xref: /titanic_50/usr/src/uts/common/fs/nfs/nfs4_vnops.c (revision 7257d1b4d25bfac0c802847390e98a464fd787ac)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 /*
27  *	Copyright 1983,1984,1985,1986,1987,1988,1989 AT&T.
28  *	All Rights Reserved
29  */
30 
31 #pragma ident	"%Z%%M%	%I%	%E% SMI"
32 
33 #include <sys/param.h>
34 #include <sys/types.h>
35 #include <sys/systm.h>
36 #include <sys/cred.h>
37 #include <sys/time.h>
38 #include <sys/vnode.h>
39 #include <sys/vfs.h>
40 #include <sys/vfs_opreg.h>
41 #include <sys/file.h>
42 #include <sys/filio.h>
43 #include <sys/uio.h>
44 #include <sys/buf.h>
45 #include <sys/mman.h>
46 #include <sys/pathname.h>
47 #include <sys/dirent.h>
48 #include <sys/debug.h>
49 #include <sys/vmsystm.h>
50 #include <sys/fcntl.h>
51 #include <sys/flock.h>
52 #include <sys/swap.h>
53 #include <sys/errno.h>
54 #include <sys/strsubr.h>
55 #include <sys/sysmacros.h>
56 #include <sys/kmem.h>
57 #include <sys/cmn_err.h>
58 #include <sys/pathconf.h>
59 #include <sys/utsname.h>
60 #include <sys/dnlc.h>
61 #include <sys/acl.h>
62 #include <sys/systeminfo.h>
63 #include <sys/policy.h>
64 #include <sys/sdt.h>
65 #include <sys/list.h>
66 #include <sys/stat.h>
67 
68 #include <rpc/types.h>
69 #include <rpc/auth.h>
70 #include <rpc/clnt.h>
71 
72 #include <nfs/nfs.h>
73 #include <nfs/nfs_clnt.h>
74 #include <nfs/nfs_acl.h>
75 #include <nfs/lm.h>
76 #include <nfs/nfs4.h>
77 #include <nfs/nfs4_kprot.h>
78 #include <nfs/rnode4.h>
79 #include <nfs/nfs4_clnt.h>
80 
81 #include <vm/hat.h>
82 #include <vm/as.h>
83 #include <vm/page.h>
84 #include <vm/pvn.h>
85 #include <vm/seg.h>
86 #include <vm/seg_map.h>
87 #include <vm/seg_kpm.h>
88 #include <vm/seg_vn.h>
89 
90 #include <fs/fs_subr.h>
91 
92 #include <sys/ddi.h>
93 #include <sys/int_fmtio.h>
94 
95 typedef struct {
96 	nfs4_ga_res_t	*di_garp;
97 	cred_t		*di_cred;
98 	hrtime_t	di_time_call;
99 } dirattr_info_t;
100 
101 typedef enum nfs4_acl_op {
102 	NFS4_ACL_GET,
103 	NFS4_ACL_SET
104 } nfs4_acl_op_t;
105 
106 static struct lm_sysid *nfs4_find_sysid(mntinfo4_t *mi);
107 
108 static void	nfs4_update_dircaches(change_info4 *, vnode_t *, vnode_t *,
109 			char *, dirattr_info_t *);
110 
111 static void	nfs4close_otw(rnode4_t *, cred_t *, nfs4_open_owner_t *,
112 		    nfs4_open_stream_t *, int *, int *, nfs4_close_type_t,
113 		    nfs4_error_t *, int *);
114 static int	nfs4_rdwrlbn(vnode_t *, page_t *, u_offset_t, size_t, int,
115 			cred_t *);
116 static int	nfs4write(vnode_t *, caddr_t, u_offset_t, int, cred_t *,
117 			stable_how4 *);
118 static int	nfs4read(vnode_t *, caddr_t, offset_t, int, size_t *,
119 			cred_t *, bool_t, struct uio *);
120 static int	nfs4setattr(vnode_t *, struct vattr *, int, cred_t *,
121 			vsecattr_t *);
122 static int	nfs4openattr(vnode_t *, vnode_t **, int, cred_t *);
123 static int	nfs4lookup(vnode_t *, char *, vnode_t **, cred_t *, int);
124 static int	nfs4lookup_xattr(vnode_t *, char *, vnode_t **, int, cred_t *);
125 static int	nfs4lookupvalidate_otw(vnode_t *, char *, vnode_t **, cred_t *);
126 static int	nfs4lookupnew_otw(vnode_t *, char *, vnode_t **, cred_t *);
127 static int	nfs4mknod(vnode_t *, char *, struct vattr *, enum vcexcl,
128 			int, vnode_t **, cred_t *);
129 static int	nfs4open_otw(vnode_t *, char *, struct vattr *, vnode_t **,
130 			cred_t *, int, int, enum createmode4, int);
131 static int	nfs4rename(vnode_t *, char *, vnode_t *, char *, cred_t *,
132 			caller_context_t *);
133 static int	nfs4rename_persistent_fh(vnode_t *, char *, vnode_t *,
134 			vnode_t *, char *, cred_t *, nfsstat4 *);
135 static int	nfs4rename_volatile_fh(vnode_t *, char *, vnode_t *,
136 			vnode_t *, char *, cred_t *, nfsstat4 *);
137 static int	do_nfs4readdir(vnode_t *, rddir4_cache *, cred_t *);
138 static void	nfs4readdir(vnode_t *, rddir4_cache *, cred_t *);
139 static int	nfs4_bio(struct buf *, stable_how4 *, cred_t *, bool_t);
140 static int	nfs4_getapage(vnode_t *, u_offset_t, size_t, uint_t *,
141 			page_t *[], size_t, struct seg *, caddr_t,
142 			enum seg_rw, cred_t *);
143 static void	nfs4_readahead(vnode_t *, u_offset_t, caddr_t, struct seg *,
144 			cred_t *);
145 static int	nfs4_sync_putapage(vnode_t *, page_t *, u_offset_t, size_t,
146 			int, cred_t *);
147 static int	nfs4_sync_pageio(vnode_t *, page_t *, u_offset_t, size_t,
148 			int, cred_t *);
149 static int	nfs4_commit(vnode_t *, offset4, count4, cred_t *);
150 static void	nfs4_set_mod(vnode_t *);
151 static void	nfs4_get_commit(vnode_t *);
152 static void	nfs4_get_commit_range(vnode_t *, u_offset_t, size_t);
153 static int	nfs4_putpage_commit(vnode_t *, offset_t, size_t, cred_t *);
154 static int	nfs4_commit_vp(vnode_t *, u_offset_t, size_t, cred_t *, int);
155 static int	nfs4_sync_commit(vnode_t *, page_t *, offset3, count3,
156 			cred_t *);
157 static void	do_nfs4_async_commit(vnode_t *, page_t *, offset3, count3,
158 			cred_t *);
159 static int	nfs4_update_attrcache(nfsstat4, nfs4_ga_res_t *,
160 			hrtime_t, vnode_t *, cred_t *);
161 static int	nfs4_open_non_reg_file(vnode_t **, int, cred_t *);
162 static int	nfs4_safelock(vnode_t *, const struct flock64 *, cred_t *);
163 static void	nfs4_register_lock_locally(vnode_t *, struct flock64 *, int,
164 			u_offset_t);
165 static int 	nfs4_lockrelease(vnode_t *, int, offset_t, cred_t *);
166 static int	nfs4_block_and_wait(clock_t *, rnode4_t *);
167 static cred_t  *state_to_cred(nfs4_open_stream_t *);
168 static int	vtoname(vnode_t *, char *, ssize_t);
169 static void	denied_to_flk(LOCK4denied *, flock64_t *, LOCKT4args *);
170 static pid_t	lo_to_pid(lock_owner4 *);
171 static void	nfs4_reinstitute_local_lock_state(vnode_t *, flock64_t *,
172 			cred_t *, nfs4_lock_owner_t *);
173 static void	push_reinstate(vnode_t *, int, flock64_t *, cred_t *,
174 			nfs4_lock_owner_t *);
175 static int 	open_and_get_osp(vnode_t *, cred_t *, nfs4_open_stream_t **);
176 static void	nfs4_delmap_callback(struct as *, void *, uint_t);
177 static void	nfs4_free_delmapcall(nfs4_delmapcall_t *);
178 static nfs4_delmapcall_t	*nfs4_init_delmapcall();
179 static int	nfs4_find_and_delete_delmapcall(rnode4_t *, int *);
180 static int	nfs4_is_acl_mask_valid(uint_t, nfs4_acl_op_t);
181 static int	nfs4_create_getsecattr_return(vsecattr_t *, vsecattr_t *,
182 			uid_t, gid_t, int);
183 
184 /*
185  * Routines that implement the setting of v4 args for the misc. ops
186  */
187 static void	nfs4args_lock_free(nfs_argop4 *);
188 static void	nfs4args_lockt_free(nfs_argop4 *);
189 static void	nfs4args_setattr(nfs_argop4 *, vattr_t *, vsecattr_t *,
190 			int, rnode4_t *, cred_t *, bitmap4, int *,
191 			nfs4_stateid_types_t *);
192 static void	nfs4args_setattr_free(nfs_argop4 *);
193 static int	nfs4args_verify(nfs_argop4 *, vattr_t *, enum nfs_opnum4,
194 			bitmap4);
195 static void	nfs4args_verify_free(nfs_argop4 *);
196 static void	nfs4args_write(nfs_argop4 *, stable_how4, rnode4_t *, cred_t *,
197 			WRITE4args **, nfs4_stateid_types_t *);
198 
199 /*
200  * These are the vnode ops functions that implement the vnode interface to
201  * the networked file system.  See more comments below at nfs4_vnodeops.
202  */
203 static int	nfs4_open(vnode_t **, int, cred_t *, caller_context_t *);
204 static int	nfs4_close(vnode_t *, int, int, offset_t, cred_t *,
205 			caller_context_t *);
206 static int	nfs4_read(vnode_t *, struct uio *, int, cred_t *,
207 			caller_context_t *);
208 static int	nfs4_write(vnode_t *, struct uio *, int, cred_t *,
209 			caller_context_t *);
210 static int	nfs4_ioctl(vnode_t *, int, intptr_t, int, cred_t *, int *,
211 			caller_context_t *);
212 static int	nfs4_setattr(vnode_t *, struct vattr *, int, cred_t *,
213 			caller_context_t *);
214 static int	nfs4_access(vnode_t *, int, int, cred_t *, caller_context_t *);
215 static int	nfs4_readlink(vnode_t *, struct uio *, cred_t *,
216 			caller_context_t *);
217 static int	nfs4_fsync(vnode_t *, int, cred_t *, caller_context_t *);
218 static int	nfs4_create(vnode_t *, char *, struct vattr *, enum vcexcl,
219 			int, vnode_t **, cred_t *, int, caller_context_t *,
220 			vsecattr_t *);
221 static int	nfs4_remove(vnode_t *, char *, cred_t *, caller_context_t *,
222 			int);
223 static int	nfs4_link(vnode_t *, vnode_t *, char *, cred_t *,
224 			caller_context_t *, int);
225 static int	nfs4_rename(vnode_t *, char *, vnode_t *, char *, cred_t *,
226 			caller_context_t *, int);
227 static int	nfs4_mkdir(vnode_t *, char *, struct vattr *, vnode_t **,
228 			cred_t *, caller_context_t *, int, vsecattr_t *);
229 static int	nfs4_rmdir(vnode_t *, char *, vnode_t *, cred_t *,
230 			caller_context_t *, int);
231 static int	nfs4_symlink(vnode_t *, char *, struct vattr *, char *,
232 			cred_t *, caller_context_t *, int);
233 static int	nfs4_readdir(vnode_t *, struct uio *, cred_t *, int *,
234 			caller_context_t *, int);
235 static int	nfs4_seek(vnode_t *, offset_t, offset_t *, caller_context_t *);
236 static int	nfs4_getpage(vnode_t *, offset_t, size_t, uint_t *,
237 			page_t *[], size_t, struct seg *, caddr_t,
238 			enum seg_rw, cred_t *, caller_context_t *);
239 static int	nfs4_putpage(vnode_t *, offset_t, size_t, int, cred_t *,
240 			caller_context_t *);
241 static int	nfs4_map(vnode_t *, offset_t, struct as *, caddr_t *, size_t,
242 			uchar_t, uchar_t, uint_t, cred_t *, caller_context_t *);
243 static int	nfs4_addmap(vnode_t *, offset_t, struct as *, caddr_t, size_t,
244 			uchar_t, uchar_t, uint_t, cred_t *, caller_context_t *);
245 static int	nfs4_cmp(vnode_t *, vnode_t *, caller_context_t *);
246 static int	nfs4_frlock(vnode_t *, int, struct flock64 *, int, offset_t,
247 			struct flk_callback *, cred_t *, caller_context_t *);
248 static int	nfs4_space(vnode_t *, int, struct flock64 *, int, offset_t,
249 			cred_t *, caller_context_t *);
250 static int	nfs4_delmap(vnode_t *, offset_t, struct as *, caddr_t, size_t,
251 			uint_t, uint_t, uint_t, cred_t *, caller_context_t *);
252 static int	nfs4_pageio(vnode_t *, page_t *, u_offset_t, size_t, int,
253 			cred_t *, caller_context_t *);
254 static void	nfs4_dispose(vnode_t *, page_t *, int, int, cred_t *,
255 			caller_context_t *);
256 static int	nfs4_setsecattr(vnode_t *, vsecattr_t *, int, cred_t *,
257 			caller_context_t *);
258 /*
259  * These vnode ops are required to be called from outside this source file,
260  * e.g. by ephemeral mount stub vnode ops, and so may not be declared
261  * as static.
262  */
263 int	nfs4_getattr(vnode_t *, struct vattr *, int, cred_t *,
264 	    caller_context_t *);
265 void	nfs4_inactive(vnode_t *, cred_t *, caller_context_t *);
266 int	nfs4_lookup(vnode_t *, char *, vnode_t **,
267 	    struct pathname *, int, vnode_t *, cred_t *,
268 	    caller_context_t *, int *, pathname_t *);
269 int	nfs4_fid(vnode_t *, fid_t *, caller_context_t *);
270 int	nfs4_rwlock(vnode_t *, int, caller_context_t *);
271 void	nfs4_rwunlock(vnode_t *, int, caller_context_t *);
272 int	nfs4_realvp(vnode_t *, vnode_t **, caller_context_t *);
273 int	nfs4_pathconf(vnode_t *, int, ulong_t *, cred_t *,
274 	    caller_context_t *);
275 int	nfs4_getsecattr(vnode_t *, vsecattr_t *, int, cred_t *,
276 	    caller_context_t *);
277 int	nfs4_shrlock(vnode_t *, int, struct shrlock *, int, cred_t *,
278 	    caller_context_t *);
279 
280 /*
281  * Used for nfs4_commit_vp() to indicate if we should
282  * wait on pending writes.
283  */
284 #define	NFS4_WRITE_NOWAIT	0
285 #define	NFS4_WRITE_WAIT		1
286 
287 #define	NFS4_BASE_WAIT_TIME 1	/* 1 second */
288 
289 /*
290  * Error flags used to pass information about certain special errors
291  * which need to be handled specially.
292  */
293 #define	NFS_EOF			-98
294 #define	NFS_VERF_MISMATCH	-97
295 
296 /*
297  * Flags used to differentiate between which operation drove the
298  * potential CLOSE OTW. (see nfs4_close_otw_if_necessary)
299  */
300 #define	NFS4_CLOSE_OP		0x1
301 #define	NFS4_DELMAP_OP		0x2
302 #define	NFS4_INACTIVE_OP	0x3
303 
304 #define	ISVDEV(t) ((t == VBLK) || (t == VCHR) || (t == VFIFO))
305 
306 /* ALIGN64 aligns the given buffer and adjust buffer size to 64 bit */
307 #define	ALIGN64(x, ptr, sz)						\
308 	x = ((uintptr_t)(ptr)) & (sizeof (uint64_t) - 1);		\
309 	if (x) {							\
310 		x = sizeof (uint64_t) - (x);				\
311 		sz -= (x);						\
312 		ptr += (x);						\
313 	}
314 
315 #ifdef DEBUG
316 int nfs4_client_attr_debug = 0;
317 int nfs4_client_state_debug = 0;
318 int nfs4_client_shadow_debug = 0;
319 int nfs4_client_lock_debug = 0;
320 int nfs4_seqid_sync = 0;
321 int nfs4_client_map_debug = 0;
322 static int nfs4_pageio_debug = 0;
323 int nfs4_client_inactive_debug = 0;
324 int nfs4_client_recov_debug = 0;
325 int nfs4_client_failover_debug = 0;
326 int nfs4_client_call_debug = 0;
327 int nfs4_client_lookup_debug = 0;
328 int nfs4_client_zone_debug = 0;
329 int nfs4_lost_rqst_debug = 0;
330 int nfs4_rdattrerr_debug = 0;
331 int nfs4_open_stream_debug = 0;
332 
333 int nfs4read_error_inject;
334 
335 static int nfs4_create_misses = 0;
336 
337 static int nfs4_readdir_cache_shorts = 0;
338 static int nfs4_readdir_readahead = 0;
339 
340 static int nfs4_bio_do_stop = 0;
341 
342 static int nfs4_lostpage = 0;	/* number of times we lost original page */
343 
344 int nfs4_mmap_debug = 0;
345 
346 static int nfs4_pathconf_cache_hits = 0;
347 static int nfs4_pathconf_cache_misses = 0;
348 
349 int nfs4close_all_cnt;
350 int nfs4close_one_debug = 0;
351 int nfs4close_notw_debug = 0;
352 
353 int denied_to_flk_debug = 0;
354 void *lockt_denied_debug;
355 
356 #endif
357 
358 /*
359  * How long to wait before trying again if OPEN_CONFIRM gets ETIMEDOUT
360  * or NFS4ERR_RESOURCE.
361  */
362 static int confirm_retry_sec = 30;
363 
364 static int nfs4_lookup_neg_cache = 1;
365 
366 /*
367  * number of pages to read ahead
368  * optimized for 100 base-T.
369  */
370 static int nfs4_nra = 4;
371 
372 static int nfs4_do_symlink_cache = 1;
373 
374 static int nfs4_pathconf_disable_cache = 0;
375 
376 /*
377  * These are the vnode ops routines which implement the vnode interface to
378  * the networked file system.  These routines just take their parameters,
379  * make them look networkish by putting the right info into interface structs,
380  * and then calling the appropriate remote routine(s) to do the work.
381  *
382  * Note on directory name lookup cacheing:  If we detect a stale fhandle,
383  * we purge the directory cache relative to that vnode.  This way, the
384  * user won't get burned by the cache repeatedly.  See <nfs/rnode4.h> for
385  * more details on rnode locking.
386  */
387 
388 struct vnodeops *nfs4_vnodeops;
389 
390 const fs_operation_def_t nfs4_vnodeops_template[] = {
391 	VOPNAME_OPEN,		{ .vop_open = nfs4_open },
392 	VOPNAME_CLOSE,		{ .vop_close = nfs4_close },
393 	VOPNAME_READ,		{ .vop_read = nfs4_read },
394 	VOPNAME_WRITE,		{ .vop_write = nfs4_write },
395 	VOPNAME_IOCTL,		{ .vop_ioctl = nfs4_ioctl },
396 	VOPNAME_GETATTR,	{ .vop_getattr = nfs4_getattr },
397 	VOPNAME_SETATTR,	{ .vop_setattr = nfs4_setattr },
398 	VOPNAME_ACCESS,		{ .vop_access = nfs4_access },
399 	VOPNAME_LOOKUP,		{ .vop_lookup = nfs4_lookup },
400 	VOPNAME_CREATE,		{ .vop_create = nfs4_create },
401 	VOPNAME_REMOVE,		{ .vop_remove = nfs4_remove },
402 	VOPNAME_LINK,		{ .vop_link = nfs4_link },
403 	VOPNAME_RENAME,		{ .vop_rename = nfs4_rename },
404 	VOPNAME_MKDIR,		{ .vop_mkdir = nfs4_mkdir },
405 	VOPNAME_RMDIR,		{ .vop_rmdir = nfs4_rmdir },
406 	VOPNAME_READDIR,	{ .vop_readdir = nfs4_readdir },
407 	VOPNAME_SYMLINK,	{ .vop_symlink = nfs4_symlink },
408 	VOPNAME_READLINK,	{ .vop_readlink = nfs4_readlink },
409 	VOPNAME_FSYNC,		{ .vop_fsync = nfs4_fsync },
410 	VOPNAME_INACTIVE,	{ .vop_inactive = nfs4_inactive },
411 	VOPNAME_FID,		{ .vop_fid = nfs4_fid },
412 	VOPNAME_RWLOCK,		{ .vop_rwlock = nfs4_rwlock },
413 	VOPNAME_RWUNLOCK,	{ .vop_rwunlock = nfs4_rwunlock },
414 	VOPNAME_SEEK,		{ .vop_seek = nfs4_seek },
415 	VOPNAME_FRLOCK,		{ .vop_frlock = nfs4_frlock },
416 	VOPNAME_SPACE,		{ .vop_space = nfs4_space },
417 	VOPNAME_REALVP,		{ .vop_realvp = nfs4_realvp },
418 	VOPNAME_GETPAGE,	{ .vop_getpage = nfs4_getpage },
419 	VOPNAME_PUTPAGE,	{ .vop_putpage = nfs4_putpage },
420 	VOPNAME_MAP,		{ .vop_map = nfs4_map },
421 	VOPNAME_ADDMAP,		{ .vop_addmap = nfs4_addmap },
422 	VOPNAME_DELMAP,		{ .vop_delmap = nfs4_delmap },
423 	/* no separate nfs4_dump */
424 	VOPNAME_DUMP,		{ .vop_dump = nfs_dump },
425 	VOPNAME_PATHCONF,	{ .vop_pathconf = nfs4_pathconf },
426 	VOPNAME_PAGEIO,		{ .vop_pageio = nfs4_pageio },
427 	VOPNAME_DISPOSE,	{ .vop_dispose = nfs4_dispose },
428 	VOPNAME_SETSECATTR,	{ .vop_setsecattr = nfs4_setsecattr },
429 	VOPNAME_GETSECATTR,	{ .vop_getsecattr = nfs4_getsecattr },
430 	VOPNAME_SHRLOCK,	{ .vop_shrlock = nfs4_shrlock },
431 	VOPNAME_VNEVENT, 	{ .vop_vnevent = fs_vnevent_support },
432 	NULL,			NULL
433 };
434 
435 /*
436  * The following are subroutines and definitions to set args or get res
437  * for the different nfsv4 ops
438  */
439 
440 void
441 nfs4args_lookup_free(nfs_argop4 *argop, int arglen)
442 {
443 	int		i;
444 
445 	for (i = 0; i < arglen; i++) {
446 		if (argop[i].argop == OP_LOOKUP) {
447 			kmem_free(
448 			    argop[i].nfs_argop4_u.oplookup.
449 			    objname.utf8string_val,
450 			    argop[i].nfs_argop4_u.oplookup.
451 			    objname.utf8string_len);
452 		}
453 	}
454 }
455 
456 static void
457 nfs4args_lock_free(nfs_argop4 *argop)
458 {
459 	locker4 *locker = &argop->nfs_argop4_u.oplock.locker;
460 
461 	if (locker->new_lock_owner == TRUE) {
462 		open_to_lock_owner4 *open_owner;
463 
464 		open_owner = &locker->locker4_u.open_owner;
465 		if (open_owner->lock_owner.owner_val != NULL) {
466 			kmem_free(open_owner->lock_owner.owner_val,
467 			    open_owner->lock_owner.owner_len);
468 		}
469 	}
470 }
471 
472 static void
473 nfs4args_lockt_free(nfs_argop4 *argop)
474 {
475 	lock_owner4 *lowner = &argop->nfs_argop4_u.oplockt.owner;
476 
477 	if (lowner->owner_val != NULL) {
478 		kmem_free(lowner->owner_val, lowner->owner_len);
479 	}
480 }
481 
482 static void
483 nfs4args_setattr(nfs_argop4 *argop, vattr_t *vap, vsecattr_t *vsap, int flags,
484     rnode4_t *rp, cred_t *cr, bitmap4 supp, int *error,
485     nfs4_stateid_types_t *sid_types)
486 {
487 	fattr4		*attr = &argop->nfs_argop4_u.opsetattr.obj_attributes;
488 	mntinfo4_t	*mi;
489 
490 	argop->argop = OP_SETATTR;
491 	/*
492 	 * The stateid is set to 0 if client is not modifying the size
493 	 * and otherwise to whatever nfs4_get_stateid() returns.
494 	 *
495 	 * XXX Note: nfs4_get_stateid() returns 0 if no lockowner and/or no
496 	 * state struct could be found for the process/file pair.  We may
497 	 * want to change this in the future (by OPENing the file).  See
498 	 * bug # 4474852.
499 	 */
500 	if (vap->va_mask & AT_SIZE) {
501 
502 		ASSERT(rp != NULL);
503 		mi = VTOMI4(RTOV4(rp));
504 
505 		argop->nfs_argop4_u.opsetattr.stateid =
506 		    nfs4_get_stateid(cr, rp, curproc->p_pidp->pid_id, mi,
507 		    OP_SETATTR, sid_types, FALSE);
508 	} else {
509 		bzero(&argop->nfs_argop4_u.opsetattr.stateid,
510 		    sizeof (stateid4));
511 	}
512 
513 	*error = vattr_to_fattr4(vap, vsap, attr, flags, OP_SETATTR, supp);
514 	if (*error)
515 		bzero(attr, sizeof (*attr));
516 }
517 
518 static void
519 nfs4args_setattr_free(nfs_argop4 *argop)
520 {
521 	nfs4_fattr4_free(&argop->nfs_argop4_u.opsetattr.obj_attributes);
522 }
523 
524 static int
525 nfs4args_verify(nfs_argop4 *argop, vattr_t *vap, enum nfs_opnum4 op,
526     bitmap4 supp)
527 {
528 	fattr4 *attr;
529 	int error = 0;
530 
531 	argop->argop = op;
532 	switch (op) {
533 	case OP_VERIFY:
534 		attr = &argop->nfs_argop4_u.opverify.obj_attributes;
535 		break;
536 	case OP_NVERIFY:
537 		attr = &argop->nfs_argop4_u.opnverify.obj_attributes;
538 		break;
539 	default:
540 		return (EINVAL);
541 	}
542 	if (!error)
543 		error = vattr_to_fattr4(vap, NULL, attr, 0, op, supp);
544 	if (error)
545 		bzero(attr, sizeof (*attr));
546 	return (error);
547 }
548 
549 static void
550 nfs4args_verify_free(nfs_argop4 *argop)
551 {
552 	switch (argop->argop) {
553 	case OP_VERIFY:
554 		nfs4_fattr4_free(&argop->nfs_argop4_u.opverify.obj_attributes);
555 		break;
556 	case OP_NVERIFY:
557 		nfs4_fattr4_free(&argop->nfs_argop4_u.opnverify.obj_attributes);
558 		break;
559 	default:
560 		break;
561 	}
562 }
563 
564 static void
565 nfs4args_write(nfs_argop4 *argop, stable_how4 stable, rnode4_t *rp, cred_t *cr,
566     WRITE4args **wargs_pp, nfs4_stateid_types_t *sid_tp)
567 {
568 	WRITE4args *wargs = &argop->nfs_argop4_u.opwrite;
569 	mntinfo4_t *mi = VTOMI4(RTOV4(rp));
570 
571 	argop->argop = OP_WRITE;
572 	wargs->stable = stable;
573 	wargs->stateid = nfs4_get_w_stateid(cr, rp, curproc->p_pidp->pid_id,
574 	    mi, OP_WRITE, sid_tp);
575 	wargs->mblk = NULL;
576 	*wargs_pp = wargs;
577 }
578 
579 void
580 nfs4args_copen_free(OPEN4cargs *open_args)
581 {
582 	if (open_args->owner.owner_val) {
583 		kmem_free(open_args->owner.owner_val,
584 		    open_args->owner.owner_len);
585 	}
586 	if ((open_args->opentype == OPEN4_CREATE) &&
587 	    (open_args->mode != EXCLUSIVE4)) {
588 		nfs4_fattr4_free(&open_args->createhow4_u.createattrs);
589 	}
590 }
591 
592 /*
593  * XXX:  This is referenced in modstubs.s
594  */
595 struct vnodeops *
596 nfs4_getvnodeops(void)
597 {
598 	return (nfs4_vnodeops);
599 }
600 
601 /*
602  * The OPEN operation opens a regular file.
603  */
604 /*ARGSUSED3*/
605 static int
606 nfs4_open(vnode_t **vpp, int flag, cred_t *cr, caller_context_t *ct)
607 {
608 	vnode_t *dvp = NULL;
609 	rnode4_t *rp, *drp;
610 	int error;
611 	int just_been_created;
612 	char fn[MAXNAMELEN];
613 
614 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4_open: "));
615 	if (nfs_zone() != VTOMI4(*vpp)->mi_zone)
616 		return (EIO);
617 	rp = VTOR4(*vpp);
618 
619 	/*
620 	 * Check to see if opening something besides a regular file;
621 	 * if so skip the OTW call
622 	 */
623 	if ((*vpp)->v_type != VREG) {
624 		error = nfs4_open_non_reg_file(vpp, flag, cr);
625 		return (error);
626 	}
627 
628 	/*
629 	 * XXX - would like a check right here to know if the file is
630 	 * executable or not, so as to skip OTW
631 	 */
632 
633 	if ((error = vtodv(*vpp, &dvp, cr, TRUE)) != 0)
634 		return (error);
635 
636 	drp = VTOR4(dvp);
637 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
638 		return (EINTR);
639 
640 	if ((error = vtoname(*vpp, fn, MAXNAMELEN)) != 0) {
641 		nfs_rw_exit(&drp->r_rwlock);
642 		return (error);
643 	}
644 
645 	/*
646 	 * See if this file has just been CREATEd.
647 	 * If so, clear the flag and update the dnlc, which was previously
648 	 * skipped in nfs4_create.
649 	 * XXX need better serilization on this.
650 	 * XXX move this into the nf4open_otw call, after we have
651 	 * XXX acquired the open owner seqid sync.
652 	 */
653 	mutex_enter(&rp->r_statev4_lock);
654 	if (rp->created_v4) {
655 		rp->created_v4 = 0;
656 		mutex_exit(&rp->r_statev4_lock);
657 
658 		dnlc_update(dvp, fn, *vpp);
659 		/* This is needed so we don't bump the open ref count */
660 		just_been_created = 1;
661 	} else {
662 		mutex_exit(&rp->r_statev4_lock);
663 		just_been_created = 0;
664 	}
665 
666 	/*
667 	 * If caller specified O_TRUNC/FTRUNC, then be sure to set
668 	 * FWRITE (to drive successful setattr(size=0) after open)
669 	 */
670 	if (flag & FTRUNC)
671 		flag |= FWRITE;
672 
673 	error = nfs4open_otw(dvp, fn, NULL, vpp, cr, 0, flag, 0,
674 	    just_been_created);
675 
676 	if (!error && !((*vpp)->v_flag & VROOT))
677 		dnlc_update(dvp, fn, *vpp);
678 
679 	nfs_rw_exit(&drp->r_rwlock);
680 
681 	/* release the hold from vtodv */
682 	VN_RELE(dvp);
683 
684 	/* exchange the shadow for the master vnode, if needed */
685 
686 	if (error == 0 && IS_SHADOW(*vpp, rp))
687 		sv_exchange(vpp);
688 
689 	return (error);
690 }
691 
692 /*
693  * See if there's a "lost open" request to be saved and recovered.
694  */
695 static void
696 nfs4open_save_lost_rqst(int error, nfs4_lost_rqst_t *lost_rqstp,
697     nfs4_open_owner_t *oop, cred_t *cr, vnode_t *vp,
698     vnode_t *dvp, OPEN4cargs *open_args)
699 {
700 	vfs_t *vfsp;
701 	char *srccfp;
702 
703 	vfsp = (dvp ? dvp->v_vfsp : vp->v_vfsp);
704 
705 	if (error != ETIMEDOUT && error != EINTR &&
706 	    !NFS4_FRC_UNMT_ERR(error, vfsp)) {
707 		lost_rqstp->lr_op = 0;
708 		return;
709 	}
710 
711 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
712 	    "nfs4open_save_lost_rqst: error %d", error));
713 
714 	lost_rqstp->lr_op = OP_OPEN;
715 
716 	/*
717 	 * The vp (if it is not NULL) and dvp are held and rele'd via
718 	 * the recovery code.  See nfs4_save_lost_rqst.
719 	 */
720 	lost_rqstp->lr_vp = vp;
721 	lost_rqstp->lr_dvp = dvp;
722 	lost_rqstp->lr_oop = oop;
723 	lost_rqstp->lr_osp = NULL;
724 	lost_rqstp->lr_lop = NULL;
725 	lost_rqstp->lr_cr = cr;
726 	lost_rqstp->lr_flk = NULL;
727 	lost_rqstp->lr_oacc = open_args->share_access;
728 	lost_rqstp->lr_odeny = open_args->share_deny;
729 	lost_rqstp->lr_oclaim = open_args->claim;
730 	if (open_args->claim == CLAIM_DELEGATE_CUR) {
731 		lost_rqstp->lr_ostateid =
732 		    open_args->open_claim4_u.delegate_cur_info.delegate_stateid;
733 		srccfp = open_args->open_claim4_u.delegate_cur_info.cfile;
734 	} else {
735 		srccfp = open_args->open_claim4_u.cfile;
736 	}
737 	lost_rqstp->lr_ofile.utf8string_len = 0;
738 	lost_rqstp->lr_ofile.utf8string_val = NULL;
739 	(void) str_to_utf8(srccfp, &lost_rqstp->lr_ofile);
740 	lost_rqstp->lr_putfirst = FALSE;
741 }
742 
743 struct nfs4_excl_time {
744 	uint32 seconds;
745 	uint32 nseconds;
746 };
747 
748 /*
749  * The OPEN operation creates and/or opens a regular file
750  *
751  * ARGSUSED
752  */
753 static int
754 nfs4open_otw(vnode_t *dvp, char *file_name, struct vattr *in_va,
755     vnode_t **vpp, cred_t *cr, int create_flag, int open_flag,
756     enum createmode4 createmode, int file_just_been_created)
757 {
758 	rnode4_t *rp;
759 	rnode4_t *drp = VTOR4(dvp);
760 	vnode_t *vp = NULL;
761 	vnode_t *vpi = *vpp;
762 	bool_t needrecov = FALSE;
763 
764 	int doqueue = 1;
765 
766 	COMPOUND4args_clnt args;
767 	COMPOUND4res_clnt res;
768 	nfs_argop4 *argop;
769 	nfs_resop4 *resop;
770 	int argoplist_size;
771 	int idx_open, idx_fattr;
772 
773 	GETFH4res *gf_res = NULL;
774 	OPEN4res *op_res = NULL;
775 	nfs4_ga_res_t *garp;
776 	fattr4 *attr = NULL;
777 	struct nfs4_excl_time verf;
778 	bool_t did_excl_setup = FALSE;
779 	int created_osp;
780 
781 	OPEN4cargs *open_args;
782 	nfs4_open_owner_t	*oop = NULL;
783 	nfs4_open_stream_t	*osp = NULL;
784 	seqid4 seqid = 0;
785 	bool_t retry_open = FALSE;
786 	nfs4_recov_state_t recov_state;
787 	nfs4_lost_rqst_t lost_rqst;
788 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
789 	hrtime_t t;
790 	int acc = 0;
791 	cred_t *cred_otw = NULL;	/* cred used to do the RPC call */
792 	cred_t *ncr = NULL;
793 
794 	nfs4_sharedfh_t *otw_sfh;
795 	nfs4_sharedfh_t *orig_sfh;
796 	int fh_differs = 0;
797 	int numops, setgid_flag;
798 	int num_bseqid_retry = NFS4_NUM_RETRY_BAD_SEQID + 1;
799 
800 	/*
801 	 * Make sure we properly deal with setting the right gid on
802 	 * a newly created file to reflect the parent's setgid bit
803 	 */
804 	setgid_flag = 0;
805 	if (create_flag && in_va) {
806 
807 		/*
808 		 * If the parent's directory has the setgid bit set
809 		 * _and_ the client was able to get a valid mapping
810 		 * for the parent dir's owner_group, we want to
811 		 * append NVERIFY(owner_group == dva.va_gid) and
812 		 * SETATTR to the CREATE compound.
813 		 */
814 		mutex_enter(&drp->r_statelock);
815 		if (drp->r_attr.va_mode & VSGID &&
816 		    drp->r_attr.va_gid != GID_NOBODY) {
817 			in_va->va_gid = drp->r_attr.va_gid;
818 			setgid_flag = 1;
819 		}
820 		mutex_exit(&drp->r_statelock);
821 	}
822 
823 	/*
824 	 * Normal/non-create compound:
825 	 * PUTFH(dfh) + OPEN(create) + GETFH + GETATTR(new)
826 	 *
827 	 * Open(create) compound no setgid:
828 	 * PUTFH(dfh) + SAVEFH + OPEN(create) + GETFH + GETATTR(new) +
829 	 * RESTOREFH + GETATTR
830 	 *
831 	 * Open(create) setgid:
832 	 * PUTFH(dfh) + OPEN(create) + GETFH + GETATTR(new) +
833 	 * SAVEFH + PUTFH(dfh) + GETATTR(dvp) + RESTOREFH +
834 	 * NVERIFY(grp) + SETATTR
835 	 */
836 	if (setgid_flag) {
837 		numops = 10;
838 		idx_open = 1;
839 		idx_fattr = 3;
840 	} else if (create_flag) {
841 		numops = 7;
842 		idx_open = 2;
843 		idx_fattr = 4;
844 	} else {
845 		numops = 4;
846 		idx_open = 1;
847 		idx_fattr = 3;
848 	}
849 
850 	args.array_len = numops;
851 	argoplist_size = numops * sizeof (nfs_argop4);
852 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
853 
854 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4open_otw: "
855 	    "open %s open flag 0x%x cred %p", file_name, open_flag,
856 	    (void *)cr));
857 
858 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
859 	if (create_flag) {
860 		/*
861 		 * We are to create a file.  Initialize the passed in vnode
862 		 * pointer.
863 		 */
864 		vpi = NULL;
865 	} else {
866 		/*
867 		 * Check to see if the client owns a read delegation and is
868 		 * trying to open for write.  If so, then return the delegation
869 		 * to avoid the server doing a cb_recall and returning DELAY.
870 		 * NB - we don't use the statev4_lock here because we'd have
871 		 * to drop the lock anyway and the result would be stale.
872 		 */
873 		if ((open_flag & FWRITE) &&
874 		    VTOR4(vpi)->r_deleg_type == OPEN_DELEGATE_READ)
875 			(void) nfs4delegreturn(VTOR4(vpi), NFS4_DR_REOPEN);
876 
877 		/*
878 		 * If the file has a delegation, then do an access check up
879 		 * front.  This avoids having to an access check later after
880 		 * we've already done start_op, which could deadlock.
881 		 */
882 		if (VTOR4(vpi)->r_deleg_type != OPEN_DELEGATE_NONE) {
883 			if (open_flag & FREAD &&
884 			    nfs4_access(vpi, VREAD, 0, cr, NULL) == 0)
885 				acc |= VREAD;
886 			if (open_flag & FWRITE &&
887 			    nfs4_access(vpi, VWRITE, 0, cr, NULL) == 0)
888 				acc |= VWRITE;
889 		}
890 	}
891 
892 	drp = VTOR4(dvp);
893 
894 	recov_state.rs_flags = 0;
895 	recov_state.rs_num_retry_despite_err = 0;
896 	cred_otw = cr;
897 
898 recov_retry:
899 	fh_differs = 0;
900 	nfs4_error_zinit(&e);
901 
902 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, vpi, &recov_state);
903 	if (e.error) {
904 		if (ncr != NULL)
905 			crfree(ncr);
906 		kmem_free(argop, argoplist_size);
907 		return (e.error);
908 	}
909 
910 	args.ctag = TAG_OPEN;
911 	args.array_len = numops;
912 	args.array = argop;
913 
914 	/* putfh directory fh */
915 	argop[0].argop = OP_CPUTFH;
916 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
917 
918 	/* OPEN: either op 1 or op 2 depending upon create/setgid flags */
919 	argop[idx_open].argop = OP_COPEN;
920 	open_args = &argop[idx_open].nfs_argop4_u.opcopen;
921 	open_args->claim = CLAIM_NULL;
922 
923 	/* name of file */
924 	open_args->open_claim4_u.cfile = file_name;
925 	open_args->owner.owner_len = 0;
926 	open_args->owner.owner_val = NULL;
927 
928 	if (create_flag) {
929 		/* CREATE a file */
930 		open_args->opentype = OPEN4_CREATE;
931 		open_args->mode = createmode;
932 		if (createmode == EXCLUSIVE4) {
933 			if (did_excl_setup == FALSE) {
934 				verf.seconds = nfs_atoi(hw_serial);
935 				if (verf.seconds != 0)
936 					verf.nseconds = newnum();
937 				else {
938 					timestruc_t now;
939 
940 					gethrestime(&now);
941 					verf.seconds = now.tv_sec;
942 					verf.nseconds = now.tv_nsec;
943 				}
944 				/*
945 				 * Since the server will use this value for the
946 				 * mtime, make sure that it can't overflow. Zero
947 				 * out the MSB. The actual value does not matter
948 				 * here, only its uniqeness.
949 				 */
950 				verf.seconds &= INT32_MAX;
951 				did_excl_setup = TRUE;
952 			}
953 
954 			/* Now copy over verifier to OPEN4args. */
955 			open_args->createhow4_u.createverf = *(uint64_t *)&verf;
956 		} else {
957 			int v_error;
958 			bitmap4 supp_attrs;
959 			servinfo4_t *svp;
960 
961 			attr = &open_args->createhow4_u.createattrs;
962 
963 			svp = drp->r_server;
964 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
965 			supp_attrs = svp->sv_supp_attrs;
966 			nfs_rw_exit(&svp->sv_lock);
967 
968 			/* GUARDED4 or UNCHECKED4 */
969 			v_error = vattr_to_fattr4(in_va, NULL, attr, 0, OP_OPEN,
970 			    supp_attrs);
971 			if (v_error) {
972 				bzero(attr, sizeof (*attr));
973 				nfs4args_copen_free(open_args);
974 				nfs4_end_op(VTOMI4(dvp), dvp, vpi,
975 				    &recov_state, FALSE);
976 				if (ncr != NULL)
977 					crfree(ncr);
978 				kmem_free(argop, argoplist_size);
979 				return (v_error);
980 			}
981 		}
982 	} else {
983 		/* NO CREATE */
984 		open_args->opentype = OPEN4_NOCREATE;
985 	}
986 
987 	if (recov_state.rs_sp != NULL) {
988 		mutex_enter(&recov_state.rs_sp->s_lock);
989 		open_args->owner.clientid = recov_state.rs_sp->clientid;
990 		mutex_exit(&recov_state.rs_sp->s_lock);
991 	} else {
992 		/* XXX should we just fail here? */
993 		open_args->owner.clientid = 0;
994 	}
995 
996 	/*
997 	 * This increments oop's ref count or creates a temporary 'just_created'
998 	 * open owner that will become valid when this OPEN/OPEN_CONFIRM call
999 	 * completes.
1000 	 */
1001 	mutex_enter(&VTOMI4(dvp)->mi_lock);
1002 
1003 	/* See if a permanent or just created open owner exists */
1004 	oop = find_open_owner_nolock(cr, NFS4_JUST_CREATED, VTOMI4(dvp));
1005 	if (!oop) {
1006 		/*
1007 		 * This open owner does not exist so create a temporary
1008 		 * just created one.
1009 		 */
1010 		oop = create_open_owner(cr, VTOMI4(dvp));
1011 		ASSERT(oop != NULL);
1012 	}
1013 	mutex_exit(&VTOMI4(dvp)->mi_lock);
1014 
1015 	/* this length never changes, do alloc before seqid sync */
1016 	open_args->owner.owner_len = sizeof (oop->oo_name);
1017 	open_args->owner.owner_val =
1018 	    kmem_alloc(open_args->owner.owner_len, KM_SLEEP);
1019 
1020 	e.error = nfs4_start_open_seqid_sync(oop, VTOMI4(dvp));
1021 	if (e.error == EAGAIN) {
1022 		open_owner_rele(oop);
1023 		nfs4args_copen_free(open_args);
1024 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, TRUE);
1025 		if (ncr != NULL) {
1026 			crfree(ncr);
1027 			ncr = NULL;
1028 		}
1029 		goto recov_retry;
1030 	}
1031 
1032 	/* Check to see if we need to do the OTW call */
1033 	if (!create_flag) {
1034 		if (!nfs4_is_otw_open_necessary(oop, open_flag, vpi,
1035 		    file_just_been_created, &e.error, acc, &recov_state)) {
1036 
1037 			/*
1038 			 * The OTW open is not necessary.  Either
1039 			 * the open can succeed without it (eg.
1040 			 * delegation, error == 0) or the open
1041 			 * must fail due to an access failure
1042 			 * (error != 0).  In either case, tidy
1043 			 * up and return.
1044 			 */
1045 
1046 			nfs4_end_open_seqid_sync(oop);
1047 			open_owner_rele(oop);
1048 			nfs4args_copen_free(open_args);
1049 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, FALSE);
1050 			if (ncr != NULL)
1051 				crfree(ncr);
1052 			kmem_free(argop, argoplist_size);
1053 			return (e.error);
1054 		}
1055 	}
1056 
1057 	bcopy(&oop->oo_name, open_args->owner.owner_val,
1058 	    open_args->owner.owner_len);
1059 
1060 	seqid = nfs4_get_open_seqid(oop) + 1;
1061 	open_args->seqid = seqid;
1062 	open_args->share_access = 0;
1063 	if (open_flag & FREAD)
1064 		open_args->share_access |= OPEN4_SHARE_ACCESS_READ;
1065 	if (open_flag & FWRITE)
1066 		open_args->share_access |= OPEN4_SHARE_ACCESS_WRITE;
1067 	open_args->share_deny = OPEN4_SHARE_DENY_NONE;
1068 
1069 
1070 
1071 	/*
1072 	 * getfh w/sanity check for idx_open/idx_fattr
1073 	 */
1074 	ASSERT((idx_open + 1) == (idx_fattr - 1));
1075 	argop[idx_open + 1].argop = OP_GETFH;
1076 
1077 	/* getattr */
1078 	argop[idx_fattr].argop = OP_GETATTR;
1079 	argop[idx_fattr].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1080 	argop[idx_fattr].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1081 
1082 	if (setgid_flag) {
1083 		vattr_t	_v;
1084 		servinfo4_t *svp;
1085 		bitmap4	supp_attrs;
1086 
1087 		svp = drp->r_server;
1088 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
1089 		supp_attrs = svp->sv_supp_attrs;
1090 		nfs_rw_exit(&svp->sv_lock);
1091 
1092 		/*
1093 		 * For setgid case, we need to:
1094 		 * 4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
1095 		 */
1096 		argop[4].argop = OP_SAVEFH;
1097 
1098 		argop[5].argop = OP_CPUTFH;
1099 		argop[5].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
1100 
1101 		argop[6].argop = OP_GETATTR;
1102 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1103 		argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1104 
1105 		argop[7].argop = OP_RESTOREFH;
1106 
1107 		/*
1108 		 * nverify
1109 		 */
1110 		_v.va_mask = AT_GID;
1111 		_v.va_gid = in_va->va_gid;
1112 		if (!(e.error = nfs4args_verify(&argop[8], &_v, OP_NVERIFY,
1113 		    supp_attrs))) {
1114 
1115 			/*
1116 			 * setattr
1117 			 *
1118 			 * We _know_ we're not messing with AT_SIZE or
1119 			 * AT_XTIME, so no need for stateid or flags.
1120 			 * Also we specify NULL rp since we're only
1121 			 * interested in setting owner_group attributes.
1122 			 */
1123 			nfs4args_setattr(&argop[9], &_v, NULL, 0, NULL, cr,
1124 			    supp_attrs, &e.error, 0);
1125 			if (e.error)
1126 				nfs4args_verify_free(&argop[8]);
1127 		}
1128 
1129 		if (e.error) {
1130 			/*
1131 			 * XXX - Revisit the last argument to nfs4_end_op()
1132 			 *	 once 5020486 is fixed.
1133 			 */
1134 			nfs4_end_open_seqid_sync(oop);
1135 			open_owner_rele(oop);
1136 			nfs4args_copen_free(open_args);
1137 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, TRUE);
1138 			if (ncr != NULL)
1139 				crfree(ncr);
1140 			kmem_free(argop, argoplist_size);
1141 			return (e.error);
1142 		}
1143 	} else if (create_flag) {
1144 		/*
1145 		 * For setgid case, we need to:
1146 		 * 4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
1147 		 */
1148 		argop[1].argop = OP_SAVEFH;
1149 
1150 		argop[5].argop = OP_RESTOREFH;
1151 
1152 		argop[6].argop = OP_GETATTR;
1153 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1154 		argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1155 	}
1156 
1157 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
1158 	    "nfs4open_otw: %s call, nm %s, rp %s",
1159 	    needrecov ? "recov" : "first", file_name,
1160 	    rnode4info(VTOR4(dvp))));
1161 
1162 	t = gethrtime();
1163 
1164 	rfs4call(VTOMI4(dvp), &args, &res, cred_otw, &doqueue, 0, &e);
1165 
1166 	if (!e.error && nfs4_need_to_bump_seqid(&res))
1167 		nfs4_set_open_seqid(seqid, oop, args.ctag);
1168 
1169 	needrecov = nfs4_needs_recovery(&e, TRUE, dvp->v_vfsp);
1170 
1171 	if (e.error || needrecov) {
1172 		bool_t abort = FALSE;
1173 
1174 		if (needrecov) {
1175 			nfs4_bseqid_entry_t *bsep = NULL;
1176 
1177 			nfs4open_save_lost_rqst(e.error, &lost_rqst, oop,
1178 			    cred_otw, vpi, dvp, open_args);
1179 
1180 			if (!e.error && res.status == NFS4ERR_BAD_SEQID) {
1181 				bsep = nfs4_create_bseqid_entry(oop, NULL,
1182 				    vpi, 0, args.ctag, open_args->seqid);
1183 				num_bseqid_retry--;
1184 			}
1185 
1186 			abort = nfs4_start_recovery(&e, VTOMI4(dvp), dvp, vpi,
1187 			    NULL, lost_rqst.lr_op == OP_OPEN ?
1188 			    &lost_rqst : NULL, OP_OPEN, bsep);
1189 
1190 			if (bsep)
1191 				kmem_free(bsep, sizeof (*bsep));
1192 			/* give up if we keep getting BAD_SEQID */
1193 			if (num_bseqid_retry == 0)
1194 				abort = TRUE;
1195 			if (abort == TRUE && e.error == 0)
1196 				e.error = geterrno4(res.status);
1197 		}
1198 		nfs4_end_open_seqid_sync(oop);
1199 		open_owner_rele(oop);
1200 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1201 		nfs4args_copen_free(open_args);
1202 		if (setgid_flag) {
1203 			nfs4args_verify_free(&argop[8]);
1204 			nfs4args_setattr_free(&argop[9]);
1205 		}
1206 		if (!e.error)
1207 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1208 		if (ncr != NULL) {
1209 			crfree(ncr);
1210 			ncr = NULL;
1211 		}
1212 		if (!needrecov || abort == TRUE || e.error == EINTR ||
1213 		    NFS4_FRC_UNMT_ERR(e.error, dvp->v_vfsp)) {
1214 			kmem_free(argop, argoplist_size);
1215 			return (e.error);
1216 		}
1217 		goto recov_retry;
1218 	}
1219 
1220 	/*
1221 	 * Will check and update lease after checking the rflag for
1222 	 * OPEN_CONFIRM in the successful OPEN call.
1223 	 */
1224 	if (res.status != NFS4_OK && res.array_len <= idx_fattr + 1) {
1225 
1226 		/*
1227 		 * XXX what if we're crossing mount points from server1:/drp
1228 		 * to server2:/drp/rp.
1229 		 */
1230 
1231 		/* Signal our end of use of the open seqid */
1232 		nfs4_end_open_seqid_sync(oop);
1233 
1234 		/*
1235 		 * This will destroy the open owner if it was just created,
1236 		 * and no one else has put a reference on it.
1237 		 */
1238 		open_owner_rele(oop);
1239 		if (create_flag && (createmode != EXCLUSIVE4) &&
1240 		    res.status == NFS4ERR_BADOWNER)
1241 			nfs4_log_badowner(VTOMI4(dvp), OP_OPEN);
1242 
1243 		e.error = geterrno4(res.status);
1244 		nfs4args_copen_free(open_args);
1245 		if (setgid_flag) {
1246 			nfs4args_verify_free(&argop[8]);
1247 			nfs4args_setattr_free(&argop[9]);
1248 		}
1249 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1250 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1251 		/*
1252 		 * If the reply is NFS4ERR_ACCESS, it may be because
1253 		 * we are root (no root net access).  If the real uid
1254 		 * is not root, then retry with the real uid instead.
1255 		 */
1256 		if (ncr != NULL) {
1257 			crfree(ncr);
1258 			ncr = NULL;
1259 		}
1260 		if (res.status == NFS4ERR_ACCESS &&
1261 		    (ncr = crnetadjust(cred_otw)) != NULL) {
1262 			cred_otw = ncr;
1263 			goto recov_retry;
1264 		}
1265 		kmem_free(argop, argoplist_size);
1266 		return (e.error);
1267 	}
1268 
1269 	resop = &res.array[idx_open];  /* open res */
1270 	op_res = &resop->nfs_resop4_u.opopen;
1271 
1272 #ifdef DEBUG
1273 	/*
1274 	 * verify attrset bitmap
1275 	 */
1276 	if (create_flag &&
1277 	    (createmode == UNCHECKED4 || createmode == GUARDED4)) {
1278 		/* make sure attrset returned is what we asked for */
1279 		/* XXX Ignore this 'error' for now */
1280 		if (attr->attrmask != op_res->attrset)
1281 			/* EMPTY */;
1282 	}
1283 #endif
1284 
1285 	if (op_res->rflags & OPEN4_RESULT_LOCKTYPE_POSIX) {
1286 		mutex_enter(&VTOMI4(dvp)->mi_lock);
1287 		VTOMI4(dvp)->mi_flags |= MI4_POSIX_LOCK;
1288 		mutex_exit(&VTOMI4(dvp)->mi_lock);
1289 	}
1290 
1291 	resop = &res.array[idx_open + 1];  /* getfh res */
1292 	gf_res = &resop->nfs_resop4_u.opgetfh;
1293 
1294 	otw_sfh = sfh4_get(&gf_res->object, VTOMI4(dvp));
1295 
1296 	/*
1297 	 * The open stateid has been updated on the server but not
1298 	 * on the client yet.  There is a path: makenfs4node->nfs4_attr_cache->
1299 	 * flush_pages->VOP_PUTPAGE->...->nfs4write where we will issue an OTW
1300 	 * WRITE call.  That, however, will use the old stateid, so go ahead
1301 	 * and upate the open stateid now, before any call to makenfs4node.
1302 	 */
1303 	if (vpi) {
1304 		nfs4_open_stream_t	*tmp_osp;
1305 		rnode4_t		*tmp_rp = VTOR4(vpi);
1306 
1307 		tmp_osp = find_open_stream(oop, tmp_rp);
1308 		if (tmp_osp) {
1309 			tmp_osp->open_stateid = op_res->stateid;
1310 			mutex_exit(&tmp_osp->os_sync_lock);
1311 			open_stream_rele(tmp_osp, tmp_rp);
1312 		}
1313 
1314 		/*
1315 		 * We must determine if the file handle given by the otw open
1316 		 * is the same as the file handle which was passed in with
1317 		 * *vpp.  This case can be reached if the file we are trying
1318 		 * to open has been removed and another file has been created
1319 		 * having the same file name.  The passed in vnode is released
1320 		 * later.
1321 		 */
1322 		orig_sfh = VTOR4(vpi)->r_fh;
1323 		fh_differs = nfs4cmpfh(&orig_sfh->sfh_fh, &otw_sfh->sfh_fh);
1324 	}
1325 
1326 	garp = &res.array[idx_fattr].nfs_resop4_u.opgetattr.ga_res;
1327 
1328 	if (create_flag || fh_differs) {
1329 		int rnode_err = 0;
1330 
1331 		vp = makenfs4node(otw_sfh, garp, dvp->v_vfsp, t, cr,
1332 		    dvp, fn_get(VTOSV(dvp)->sv_name, file_name));
1333 
1334 		if (e.error)
1335 			PURGE_ATTRCACHE4(vp);
1336 		/*
1337 		 * For the newly created vp case, make sure the rnode
1338 		 * isn't bad before using it.
1339 		 */
1340 		mutex_enter(&(VTOR4(vp))->r_statelock);
1341 		if (VTOR4(vp)->r_flags & R4RECOVERR)
1342 			rnode_err = EIO;
1343 		mutex_exit(&(VTOR4(vp))->r_statelock);
1344 
1345 		if (rnode_err) {
1346 			nfs4_end_open_seqid_sync(oop);
1347 			nfs4args_copen_free(open_args);
1348 			if (setgid_flag) {
1349 				nfs4args_verify_free(&argop[8]);
1350 				nfs4args_setattr_free(&argop[9]);
1351 			}
1352 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1353 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state,
1354 			    needrecov);
1355 			open_owner_rele(oop);
1356 			VN_RELE(vp);
1357 			if (ncr != NULL)
1358 				crfree(ncr);
1359 			sfh4_rele(&otw_sfh);
1360 			kmem_free(argop, argoplist_size);
1361 			return (EIO);
1362 		}
1363 	} else {
1364 		vp = vpi;
1365 	}
1366 	sfh4_rele(&otw_sfh);
1367 
1368 	/*
1369 	 * It seems odd to get a full set of attrs and then not update
1370 	 * the object's attrcache in the non-create case.  Create case uses
1371 	 * the attrs since makenfs4node checks to see if the attrs need to
1372 	 * be updated (and then updates them).  The non-create case should
1373 	 * update attrs also.
1374 	 */
1375 	if (! create_flag && ! fh_differs && !e.error) {
1376 		nfs4_attr_cache(vp, garp, t, cr, TRUE, NULL);
1377 	}
1378 
1379 	nfs4_error_zinit(&e);
1380 	if (op_res->rflags & OPEN4_RESULT_CONFIRM) {
1381 		/* This does not do recovery for vp explicitly. */
1382 		nfs4open_confirm(vp, &seqid, &op_res->stateid, cred_otw, FALSE,
1383 		    &retry_open, oop, FALSE, &e, &num_bseqid_retry);
1384 
1385 		if (e.error || e.stat) {
1386 			nfs4_end_open_seqid_sync(oop);
1387 			nfs4args_copen_free(open_args);
1388 			if (setgid_flag) {
1389 				nfs4args_verify_free(&argop[8]);
1390 				nfs4args_setattr_free(&argop[9]);
1391 			}
1392 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1393 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state,
1394 			    needrecov);
1395 			open_owner_rele(oop);
1396 			if (create_flag || fh_differs) {
1397 				/* rele the makenfs4node */
1398 				VN_RELE(vp);
1399 			}
1400 			if (ncr != NULL) {
1401 				crfree(ncr);
1402 				ncr = NULL;
1403 			}
1404 			if (retry_open == TRUE) {
1405 				NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
1406 				    "nfs4open_otw: retry the open since OPEN "
1407 				    "CONFIRM failed with error %d stat %d",
1408 				    e.error, e.stat));
1409 				if (create_flag && createmode == GUARDED4) {
1410 					NFS4_DEBUG(nfs4_client_recov_debug,
1411 					    (CE_NOTE, "nfs4open_otw: switch "
1412 					    "createmode from GUARDED4 to "
1413 					    "UNCHECKED4"));
1414 					createmode = UNCHECKED4;
1415 				}
1416 				goto recov_retry;
1417 			}
1418 			if (!e.error) {
1419 				if (create_flag && (createmode != EXCLUSIVE4) &&
1420 				    e.stat == NFS4ERR_BADOWNER)
1421 					nfs4_log_badowner(VTOMI4(dvp), OP_OPEN);
1422 
1423 				e.error = geterrno4(e.stat);
1424 			}
1425 			kmem_free(argop, argoplist_size);
1426 			return (e.error);
1427 		}
1428 	}
1429 
1430 	rp = VTOR4(vp);
1431 
1432 	mutex_enter(&rp->r_statev4_lock);
1433 	if (create_flag)
1434 		rp->created_v4 = 1;
1435 	mutex_exit(&rp->r_statev4_lock);
1436 
1437 	mutex_enter(&oop->oo_lock);
1438 	/* Doesn't matter if 'oo_just_created' already was set as this */
1439 	oop->oo_just_created = NFS4_PERM_CREATED;
1440 	if (oop->oo_cred_otw)
1441 		crfree(oop->oo_cred_otw);
1442 	oop->oo_cred_otw = cred_otw;
1443 	crhold(oop->oo_cred_otw);
1444 	mutex_exit(&oop->oo_lock);
1445 
1446 	/* returns with 'os_sync_lock' held */
1447 	osp = find_or_create_open_stream(oop, rp, &created_osp);
1448 	if (!osp) {
1449 		NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
1450 		    "nfs4open_otw: failed to create an open stream"));
1451 		NFS4_DEBUG(nfs4_seqid_sync, (CE_NOTE, "nfs4open_otw: "
1452 		    "signal our end of use of the open seqid"));
1453 
1454 		nfs4_end_open_seqid_sync(oop);
1455 		open_owner_rele(oop);
1456 		nfs4args_copen_free(open_args);
1457 		if (setgid_flag) {
1458 			nfs4args_verify_free(&argop[8]);
1459 			nfs4args_setattr_free(&argop[9]);
1460 		}
1461 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1462 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1463 		if (create_flag || fh_differs)
1464 			VN_RELE(vp);
1465 		if (ncr != NULL)
1466 			crfree(ncr);
1467 
1468 		kmem_free(argop, argoplist_size);
1469 		return (EINVAL);
1470 
1471 	}
1472 
1473 	osp->open_stateid = op_res->stateid;
1474 
1475 	if (open_flag & FREAD)
1476 		osp->os_share_acc_read++;
1477 	if (open_flag & FWRITE)
1478 		osp->os_share_acc_write++;
1479 	osp->os_share_deny_none++;
1480 
1481 	/*
1482 	 * Need to reset this bitfield for the possible case where we were
1483 	 * going to OTW CLOSE the file, got a non-recoverable error, and before
1484 	 * we could retry the CLOSE, OPENed the file again.
1485 	 */
1486 	ASSERT(osp->os_open_owner->oo_seqid_inuse);
1487 	osp->os_final_close = 0;
1488 	osp->os_force_close = 0;
1489 #ifdef DEBUG
1490 	if (osp->os_failed_reopen)
1491 		NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE, "nfs4open_otw:"
1492 		    " clearing os_failed_reopen for osp %p, cr %p, rp %s",
1493 		    (void *)osp, (void *)cr, rnode4info(rp)));
1494 #endif
1495 	osp->os_failed_reopen = 0;
1496 
1497 	mutex_exit(&osp->os_sync_lock);
1498 
1499 	nfs4_end_open_seqid_sync(oop);
1500 
1501 	if (created_osp && recov_state.rs_sp != NULL) {
1502 		mutex_enter(&recov_state.rs_sp->s_lock);
1503 		nfs4_inc_state_ref_count_nolock(recov_state.rs_sp, VTOMI4(dvp));
1504 		mutex_exit(&recov_state.rs_sp->s_lock);
1505 	}
1506 
1507 	/* get rid of our reference to find oop */
1508 	open_owner_rele(oop);
1509 
1510 	open_stream_rele(osp, rp);
1511 
1512 	/* accept delegation, if any */
1513 	nfs4_delegation_accept(rp, CLAIM_NULL, op_res, garp, cred_otw);
1514 
1515 	nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1516 
1517 	if (createmode == EXCLUSIVE4 &&
1518 	    (in_va->va_mask & ~(AT_GID | AT_SIZE))) {
1519 		NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4open_otw:"
1520 		    " EXCLUSIVE4: sending a SETATTR"));
1521 		/*
1522 		 * If doing an exclusive create, then generate
1523 		 * a SETATTR to set the initial attributes.
1524 		 * Try to set the mtime and the atime to the
1525 		 * server's current time.  It is somewhat
1526 		 * expected that these fields will be used to
1527 		 * store the exclusive create cookie.  If not,
1528 		 * server implementors will need to know that
1529 		 * a SETATTR will follow an exclusive create
1530 		 * and the cookie should be destroyed if
1531 		 * appropriate.
1532 		 *
1533 		 * The AT_GID and AT_SIZE bits are turned off
1534 		 * so that the SETATTR request will not attempt
1535 		 * to process these.  The gid will be set
1536 		 * separately if appropriate.  The size is turned
1537 		 * off because it is assumed that a new file will
1538 		 * be created empty and if the file wasn't empty,
1539 		 * then the exclusive create will have failed
1540 		 * because the file must have existed already.
1541 		 * Therefore, no truncate operation is needed.
1542 		 */
1543 		in_va->va_mask &= ~(AT_GID | AT_SIZE);
1544 		in_va->va_mask |= (AT_MTIME | AT_ATIME);
1545 
1546 		e.error = nfs4setattr(vp, in_va, 0, cr, NULL);
1547 		if (e.error) {
1548 			/*
1549 			 * Couldn't correct the attributes of
1550 			 * the newly created file and the
1551 			 * attributes are wrong.  Remove the
1552 			 * file and return an error to the
1553 			 * application.
1554 			 */
1555 			/* XXX will this take care of client state ? */
1556 			NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
1557 			    "nfs4open_otw: EXCLUSIVE4: error %d on SETATTR:"
1558 			    " remove file", e.error));
1559 			VN_RELE(vp);
1560 			(void) nfs4_remove(dvp, file_name, cr, NULL, 0);
1561 			/*
1562 			 * Since we've reled the vnode and removed
1563 			 * the file we now need to return the error.
1564 			 * At this point we don't want to update the
1565 			 * dircaches, call nfs4_waitfor_purge_complete
1566 			 * or set vpp to vp so we need to skip these
1567 			 * as well.
1568 			 */
1569 			goto skip_update_dircaches;
1570 		}
1571 	}
1572 
1573 	/*
1574 	 * If we created or found the correct vnode, due to create_flag or
1575 	 * fh_differs being set, then update directory cache attribute, readdir
1576 	 * and dnlc caches.
1577 	 */
1578 	if (create_flag || fh_differs) {
1579 		dirattr_info_t dinfo, *dinfop;
1580 
1581 		/*
1582 		 * Make sure getattr succeeded before using results.
1583 		 * note: op 7 is getattr(dir) for both flavors of
1584 		 * open(create).
1585 		 */
1586 		if (create_flag && res.status == NFS4_OK) {
1587 			dinfo.di_time_call = t;
1588 			dinfo.di_cred = cr;
1589 			dinfo.di_garp =
1590 			    &res.array[6].nfs_resop4_u.opgetattr.ga_res;
1591 			dinfop = &dinfo;
1592 		} else {
1593 			dinfop = NULL;
1594 		}
1595 
1596 		nfs4_update_dircaches(&op_res->cinfo, dvp, vp, file_name,
1597 		    dinfop);
1598 	}
1599 
1600 	/*
1601 	 * If the page cache for this file was flushed from actions
1602 	 * above, it was done asynchronously and if that is true,
1603 	 * there is a need to wait here for it to complete.  This must
1604 	 * be done outside of start_fop/end_fop.
1605 	 */
1606 	(void) nfs4_waitfor_purge_complete(vp);
1607 
1608 	/*
1609 	 * It is implicit that we are in the open case (create_flag == 0) since
1610 	 * fh_differs can only be set to a non-zero value in the open case.
1611 	 */
1612 	if (fh_differs != 0 && vpi != NULL)
1613 		VN_RELE(vpi);
1614 
1615 	/*
1616 	 * Be sure to set *vpp to the correct value before returning.
1617 	 */
1618 	*vpp = vp;
1619 
1620 skip_update_dircaches:
1621 
1622 	nfs4args_copen_free(open_args);
1623 	if (setgid_flag) {
1624 		nfs4args_verify_free(&argop[8]);
1625 		nfs4args_setattr_free(&argop[9]);
1626 	}
1627 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1628 
1629 	if (ncr)
1630 		crfree(ncr);
1631 	kmem_free(argop, argoplist_size);
1632 	return (e.error);
1633 }
1634 
1635 /*
1636  * Reopen an open instance.  cf. nfs4open_otw().
1637  *
1638  * Errors are returned by the nfs4_error_t parameter.
1639  * - ep->error contains an errno value or zero.
1640  * - if it is zero, ep->stat is set to an NFS status code, if any.
1641  *   If the file could not be reopened, but the caller should continue, the
1642  *   file is marked dead and no error values are returned.  If the caller
1643  *   should stop recovering open files and start over, either the ep->error
1644  *   value or ep->stat will indicate an error (either something that requires
1645  *   recovery or EAGAIN).  Note that some recovery (e.g., expired volatile
1646  *   filehandles) may be handled silently by this routine.
1647  * - if it is EINTR, ETIMEDOUT, or NFS4_FRC_UNMT_ERR, recovery for lost state
1648  *   will be started, so the caller should not do it.
1649  *
1650  * Gotos:
1651  * - kill_file : reopen failed in such a fashion to constitute marking the
1652  *    file dead and setting the open stream's 'os_failed_reopen' as 1.  This
1653  *   is for cases where recovery is not possible.
1654  * - failed_reopen : same as above, except that the file has already been
1655  *   marked dead, so no need to do it again.
1656  * - bailout : reopen failed but we are able to recover and retry the reopen -
1657  *   either within this function immediately or via the calling function.
1658  */
1659 
1660 void
1661 nfs4_reopen(vnode_t *vp, nfs4_open_stream_t *osp, nfs4_error_t *ep,
1662     open_claim_type4 claim, bool_t frc_use_claim_previous,
1663     bool_t is_recov)
1664 {
1665 	COMPOUND4args_clnt args;
1666 	COMPOUND4res_clnt res;
1667 	nfs_argop4 argop[4];
1668 	nfs_resop4 *resop;
1669 	OPEN4res *op_res = NULL;
1670 	OPEN4cargs *open_args;
1671 	GETFH4res *gf_res;
1672 	rnode4_t *rp = VTOR4(vp);
1673 	int doqueue = 1;
1674 	cred_t *cr = NULL, *cred_otw = NULL;
1675 	nfs4_open_owner_t *oop = NULL;
1676 	seqid4 seqid;
1677 	nfs4_ga_res_t *garp;
1678 	char fn[MAXNAMELEN];
1679 	nfs4_recov_state_t recov = {NULL, 0};
1680 	nfs4_lost_rqst_t lost_rqst;
1681 	mntinfo4_t *mi = VTOMI4(vp);
1682 	bool_t abort;
1683 	char *failed_msg = "";
1684 	int fh_different;
1685 	hrtime_t t;
1686 	nfs4_bseqid_entry_t *bsep = NULL;
1687 
1688 	ASSERT(nfs4_consistent_type(vp));
1689 	ASSERT(nfs_zone() == mi->mi_zone);
1690 
1691 	nfs4_error_zinit(ep);
1692 
1693 	/* this is the cred used to find the open owner */
1694 	cr = state_to_cred(osp);
1695 	if (cr == NULL) {
1696 		failed_msg = "Couldn't reopen: no cred";
1697 		goto kill_file;
1698 	}
1699 	/* use this cred for OTW operations */
1700 	cred_otw = nfs4_get_otw_cred(cr, mi, osp->os_open_owner);
1701 
1702 top:
1703 	nfs4_error_zinit(ep);
1704 
1705 	if (mi->mi_vfsp->vfs_flag & VFS_UNMOUNTED) {
1706 		/* File system has been unmounted, quit */
1707 		ep->error = EIO;
1708 		failed_msg = "Couldn't reopen: file system has been unmounted";
1709 		goto kill_file;
1710 	}
1711 
1712 	oop = osp->os_open_owner;
1713 
1714 	ASSERT(oop != NULL);
1715 	if (oop == NULL) {	/* be defensive in non-DEBUG */
1716 		failed_msg = "can't reopen: no open owner";
1717 		goto kill_file;
1718 	}
1719 	open_owner_hold(oop);
1720 
1721 	ep->error = nfs4_start_open_seqid_sync(oop, mi);
1722 	if (ep->error) {
1723 		open_owner_rele(oop);
1724 		oop = NULL;
1725 		goto bailout;
1726 	}
1727 
1728 	/*
1729 	 * If the rnode has a delegation and the delegation has been
1730 	 * recovered and the server didn't request a recall and the caller
1731 	 * didn't specifically ask for CLAIM_PREVIOUS (nfs4frlock during
1732 	 * recovery) and the rnode hasn't been marked dead, then install
1733 	 * the delegation stateid in the open stream.  Otherwise, proceed
1734 	 * with a CLAIM_PREVIOUS or CLAIM_NULL OPEN.
1735 	 */
1736 	mutex_enter(&rp->r_statev4_lock);
1737 	if (rp->r_deleg_type != OPEN_DELEGATE_NONE &&
1738 	    !rp->r_deleg_return_pending &&
1739 	    (rp->r_deleg_needs_recovery == OPEN_DELEGATE_NONE) &&
1740 	    !rp->r_deleg_needs_recall &&
1741 	    claim != CLAIM_DELEGATE_CUR && !frc_use_claim_previous &&
1742 	    !(rp->r_flags & R4RECOVERR)) {
1743 		mutex_enter(&osp->os_sync_lock);
1744 		osp->os_delegation = 1;
1745 		osp->open_stateid = rp->r_deleg_stateid;
1746 		mutex_exit(&osp->os_sync_lock);
1747 		mutex_exit(&rp->r_statev4_lock);
1748 		goto bailout;
1749 	}
1750 	mutex_exit(&rp->r_statev4_lock);
1751 
1752 	/*
1753 	 * If the file failed recovery, just quit.  This failure need not
1754 	 * affect other reopens, so don't return an error.
1755 	 */
1756 	mutex_enter(&rp->r_statelock);
1757 	if (rp->r_flags & R4RECOVERR) {
1758 		mutex_exit(&rp->r_statelock);
1759 		ep->error = 0;
1760 		goto failed_reopen;
1761 	}
1762 	mutex_exit(&rp->r_statelock);
1763 
1764 	/*
1765 	 * argop is empty here
1766 	 *
1767 	 * PUTFH, OPEN, GETATTR
1768 	 */
1769 	args.ctag = TAG_REOPEN;
1770 	args.array_len = 4;
1771 	args.array = argop;
1772 
1773 	NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
1774 	    "nfs4_reopen: file is type %d, id %s",
1775 	    vp->v_type, rnode4info(VTOR4(vp))));
1776 
1777 	argop[0].argop = OP_CPUTFH;
1778 
1779 	if (claim != CLAIM_PREVIOUS) {
1780 		/*
1781 		 * if this is a file mount then
1782 		 * use the mntinfo parentfh
1783 		 */
1784 		argop[0].nfs_argop4_u.opcputfh.sfh =
1785 		    (vp->v_flag & VROOT) ? mi->mi_srvparentfh :
1786 		    VTOSV(vp)->sv_dfh;
1787 	} else {
1788 		/* putfh fh to reopen */
1789 		argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
1790 	}
1791 
1792 	argop[1].argop = OP_COPEN;
1793 	open_args = &argop[1].nfs_argop4_u.opcopen;
1794 	open_args->claim = claim;
1795 
1796 	if (claim == CLAIM_NULL) {
1797 
1798 		if ((ep->error = vtoname(vp, fn, MAXNAMELEN)) != 0) {
1799 			nfs_cmn_err(ep->error, CE_WARN, "nfs4_reopen: vtoname "
1800 			    "failed for vp 0x%p for CLAIM_NULL with %m",
1801 			    (void *)vp);
1802 			failed_msg = "Couldn't reopen: vtoname failed for "
1803 			    "CLAIM_NULL";
1804 			/* nothing allocated yet */
1805 			goto kill_file;
1806 		}
1807 
1808 		open_args->open_claim4_u.cfile = fn;
1809 	} else if (claim == CLAIM_PREVIOUS) {
1810 
1811 		/*
1812 		 * We have two cases to deal with here:
1813 		 * 1) We're being called to reopen files in order to satisfy
1814 		 *    a lock operation request which requires us to explicitly
1815 		 *    reopen files which were opened under a delegation.  If
1816 		 *    we're in recovery, we *must* use CLAIM_PREVIOUS.  In
1817 		 *    that case, frc_use_claim_previous is TRUE and we must
1818 		 *    use the rnode's current delegation type (r_deleg_type).
1819 		 * 2) We're reopening files during some form of recovery.
1820 		 *    In this case, frc_use_claim_previous is FALSE and we
1821 		 *    use the delegation type appropriate for recovery
1822 		 *    (r_deleg_needs_recovery).
1823 		 */
1824 		mutex_enter(&rp->r_statev4_lock);
1825 		open_args->open_claim4_u.delegate_type =
1826 		    frc_use_claim_previous ?
1827 		    rp->r_deleg_type :
1828 		    rp->r_deleg_needs_recovery;
1829 		mutex_exit(&rp->r_statev4_lock);
1830 
1831 	} else if (claim == CLAIM_DELEGATE_CUR) {
1832 
1833 		if ((ep->error = vtoname(vp, fn, MAXNAMELEN)) != 0) {
1834 			nfs_cmn_err(ep->error, CE_WARN, "nfs4_reopen: vtoname "
1835 			    "failed for vp 0x%p for CLAIM_DELEGATE_CUR "
1836 			    "with %m", (void *)vp);
1837 			failed_msg = "Couldn't reopen: vtoname failed for "
1838 			    "CLAIM_DELEGATE_CUR";
1839 			/* nothing allocated yet */
1840 			goto kill_file;
1841 		}
1842 
1843 		mutex_enter(&rp->r_statev4_lock);
1844 		open_args->open_claim4_u.delegate_cur_info.delegate_stateid =
1845 		    rp->r_deleg_stateid;
1846 		mutex_exit(&rp->r_statev4_lock);
1847 
1848 		open_args->open_claim4_u.delegate_cur_info.cfile = fn;
1849 	}
1850 	open_args->opentype = OPEN4_NOCREATE;
1851 	open_args->owner.clientid = mi2clientid(mi);
1852 	open_args->owner.owner_len = sizeof (oop->oo_name);
1853 	open_args->owner.owner_val =
1854 	    kmem_alloc(open_args->owner.owner_len, KM_SLEEP);
1855 	bcopy(&oop->oo_name, open_args->owner.owner_val,
1856 	    open_args->owner.owner_len);
1857 	open_args->share_access = 0;
1858 	open_args->share_deny = 0;
1859 
1860 	mutex_enter(&osp->os_sync_lock);
1861 	NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE, "nfs4_reopen: osp %p rp "
1862 	    "%p: read acc %"PRIu64" write acc %"PRIu64": open ref count %d: "
1863 	    "mmap read %"PRIu64" mmap write %"PRIu64" claim %d ",
1864 	    (void *)osp, (void *)rp, osp->os_share_acc_read,
1865 	    osp->os_share_acc_write, osp->os_open_ref_count,
1866 	    osp->os_mmap_read, osp->os_mmap_write, claim));
1867 
1868 	if (osp->os_share_acc_read || osp->os_mmap_read)
1869 		open_args->share_access |= OPEN4_SHARE_ACCESS_READ;
1870 	if (osp->os_share_acc_write || osp->os_mmap_write)
1871 		open_args->share_access |= OPEN4_SHARE_ACCESS_WRITE;
1872 	if (osp->os_share_deny_read)
1873 		open_args->share_deny |= OPEN4_SHARE_DENY_READ;
1874 	if (osp->os_share_deny_write)
1875 		open_args->share_deny |= OPEN4_SHARE_DENY_WRITE;
1876 	mutex_exit(&osp->os_sync_lock);
1877 
1878 	seqid = nfs4_get_open_seqid(oop) + 1;
1879 	open_args->seqid = seqid;
1880 
1881 	/* Construct the getfh part of the compound */
1882 	argop[2].argop = OP_GETFH;
1883 
1884 	/* Construct the getattr part of the compound */
1885 	argop[3].argop = OP_GETATTR;
1886 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1887 	argop[3].nfs_argop4_u.opgetattr.mi = mi;
1888 
1889 	t = gethrtime();
1890 
1891 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, ep);
1892 
1893 	if (ep->error) {
1894 		if (!is_recov && !frc_use_claim_previous &&
1895 		    (ep->error == EINTR || ep->error == ETIMEDOUT ||
1896 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp))) {
1897 			nfs4open_save_lost_rqst(ep->error, &lost_rqst, oop,
1898 			    cred_otw, vp, NULL, open_args);
1899 			abort = nfs4_start_recovery(ep,
1900 			    VTOMI4(vp), vp, NULL, NULL,
1901 			    lost_rqst.lr_op == OP_OPEN ?
1902 			    &lost_rqst : NULL, OP_OPEN, NULL);
1903 			nfs4args_copen_free(open_args);
1904 			goto bailout;
1905 		}
1906 
1907 		nfs4args_copen_free(open_args);
1908 
1909 		if (ep->error == EACCES && cred_otw != cr) {
1910 			crfree(cred_otw);
1911 			cred_otw = cr;
1912 			crhold(cred_otw);
1913 			nfs4_end_open_seqid_sync(oop);
1914 			open_owner_rele(oop);
1915 			oop = NULL;
1916 			goto top;
1917 		}
1918 		if (ep->error == ETIMEDOUT)
1919 			goto bailout;
1920 		failed_msg = "Couldn't reopen: rpc error";
1921 		goto kill_file;
1922 	}
1923 
1924 	if (nfs4_need_to_bump_seqid(&res))
1925 		nfs4_set_open_seqid(seqid, oop, args.ctag);
1926 
1927 	switch (res.status) {
1928 	case NFS4_OK:
1929 		if (recov.rs_flags & NFS4_RS_DELAY_MSG) {
1930 			mutex_enter(&rp->r_statelock);
1931 			rp->r_delay_interval = 0;
1932 			mutex_exit(&rp->r_statelock);
1933 		}
1934 		break;
1935 	case NFS4ERR_BAD_SEQID:
1936 		bsep = nfs4_create_bseqid_entry(oop, NULL, vp, 0,
1937 		    args.ctag, open_args->seqid);
1938 
1939 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL,
1940 		    NULL, lost_rqst.lr_op == OP_OPEN ? &lost_rqst :
1941 		    NULL, OP_OPEN, bsep);
1942 
1943 		nfs4args_copen_free(open_args);
1944 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1945 		nfs4_end_open_seqid_sync(oop);
1946 		open_owner_rele(oop);
1947 		oop = NULL;
1948 		kmem_free(bsep, sizeof (*bsep));
1949 
1950 		goto kill_file;
1951 	case NFS4ERR_NO_GRACE:
1952 		nfs4args_copen_free(open_args);
1953 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1954 		nfs4_end_open_seqid_sync(oop);
1955 		open_owner_rele(oop);
1956 		oop = NULL;
1957 		if (claim == CLAIM_PREVIOUS) {
1958 			/*
1959 			 * Retry as a plain open. We don't need to worry about
1960 			 * checking the changeinfo: it is acceptable for a
1961 			 * client to re-open a file and continue processing
1962 			 * (in the absence of locks).
1963 			 */
1964 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
1965 			    "nfs4_reopen: CLAIM_PREVIOUS: NFS4ERR_NO_GRACE; "
1966 			    "will retry as CLAIM_NULL"));
1967 			claim = CLAIM_NULL;
1968 			nfs4_mi_kstat_inc_no_grace(mi);
1969 			goto top;
1970 		}
1971 		failed_msg =
1972 		    "Couldn't reopen: tried reclaim outside grace period. ";
1973 		goto kill_file;
1974 	case NFS4ERR_GRACE:
1975 		nfs4_set_grace_wait(mi);
1976 		nfs4args_copen_free(open_args);
1977 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1978 		nfs4_end_open_seqid_sync(oop);
1979 		open_owner_rele(oop);
1980 		oop = NULL;
1981 		ep->error = nfs4_wait_for_grace(mi, &recov);
1982 		if (ep->error != 0)
1983 			goto bailout;
1984 		goto top;
1985 	case NFS4ERR_DELAY:
1986 		nfs4_set_delay_wait(vp);
1987 		nfs4args_copen_free(open_args);
1988 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1989 		nfs4_end_open_seqid_sync(oop);
1990 		open_owner_rele(oop);
1991 		oop = NULL;
1992 		ep->error = nfs4_wait_for_delay(vp, &recov);
1993 		nfs4_mi_kstat_inc_delay(mi);
1994 		if (ep->error != 0)
1995 			goto bailout;
1996 		goto top;
1997 	case NFS4ERR_FHEXPIRED:
1998 		/* recover filehandle and retry */
1999 		abort = nfs4_start_recovery(ep,
2000 		    mi, vp, NULL, NULL, NULL, OP_OPEN, NULL);
2001 		nfs4args_copen_free(open_args);
2002 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2003 		nfs4_end_open_seqid_sync(oop);
2004 		open_owner_rele(oop);
2005 		oop = NULL;
2006 		if (abort == FALSE)
2007 			goto top;
2008 		failed_msg = "Couldn't reopen: recovery aborted";
2009 		goto kill_file;
2010 	case NFS4ERR_RESOURCE:
2011 	case NFS4ERR_STALE_CLIENTID:
2012 	case NFS4ERR_WRONGSEC:
2013 	case NFS4ERR_EXPIRED:
2014 		/*
2015 		 * Do not mark the file dead and let the calling
2016 		 * function initiate recovery.
2017 		 */
2018 		nfs4args_copen_free(open_args);
2019 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2020 		nfs4_end_open_seqid_sync(oop);
2021 		open_owner_rele(oop);
2022 		oop = NULL;
2023 		goto bailout;
2024 	case NFS4ERR_ACCESS:
2025 		if (cred_otw != cr) {
2026 			crfree(cred_otw);
2027 			cred_otw = cr;
2028 			crhold(cred_otw);
2029 			nfs4args_copen_free(open_args);
2030 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2031 			nfs4_end_open_seqid_sync(oop);
2032 			open_owner_rele(oop);
2033 			oop = NULL;
2034 			goto top;
2035 		}
2036 		/* fall through */
2037 	default:
2038 		NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
2039 		    "nfs4_reopen: r_server 0x%p, mi_curr_serv 0x%p, rnode %s",
2040 		    (void*)VTOR4(vp)->r_server, (void*)mi->mi_curr_serv,
2041 		    rnode4info(VTOR4(vp))));
2042 		failed_msg = "Couldn't reopen: NFSv4 error";
2043 		nfs4args_copen_free(open_args);
2044 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2045 		goto kill_file;
2046 	}
2047 
2048 	resop = &res.array[1];  /* open res */
2049 	op_res = &resop->nfs_resop4_u.opopen;
2050 
2051 	garp = &res.array[3].nfs_resop4_u.opgetattr.ga_res;
2052 
2053 	/*
2054 	 * Check if the path we reopened really is the same
2055 	 * file. We could end up in a situation where the file
2056 	 * was removed and a new file created with the same name.
2057 	 */
2058 	resop = &res.array[2];
2059 	gf_res = &resop->nfs_resop4_u.opgetfh;
2060 	(void) nfs_rw_enter_sig(&mi->mi_fh_lock, RW_READER, 0);
2061 	fh_different = (nfs4cmpfh(&rp->r_fh->sfh_fh, &gf_res->object) != 0);
2062 	if (fh_different) {
2063 		if (mi->mi_fh_expire_type == FH4_PERSISTENT ||
2064 		    mi->mi_fh_expire_type & FH4_NOEXPIRE_WITH_OPEN) {
2065 			/* Oops, we don't have the same file */
2066 			if (mi->mi_fh_expire_type == FH4_PERSISTENT)
2067 				failed_msg = "Couldn't reopen: Persistent "
2068 				    "file handle changed";
2069 			else
2070 				failed_msg = "Couldn't reopen: Volatile "
2071 				    "(no expire on open) file handle changed";
2072 
2073 			nfs4args_copen_free(open_args);
2074 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2075 			nfs_rw_exit(&mi->mi_fh_lock);
2076 			goto kill_file;
2077 
2078 		} else {
2079 			/*
2080 			 * We have volatile file handles that don't compare.
2081 			 * If the fids are the same then we assume that the
2082 			 * file handle expired but the rnode still refers to
2083 			 * the same file object.
2084 			 *
2085 			 * First check that we have fids or not.
2086 			 * If we don't we have a dumb server so we will
2087 			 * just assume every thing is ok for now.
2088 			 */
2089 			if (!ep->error && garp->n4g_va.va_mask & AT_NODEID &&
2090 			    rp->r_attr.va_mask & AT_NODEID &&
2091 			    rp->r_attr.va_nodeid != garp->n4g_va.va_nodeid) {
2092 				/*
2093 				 * We have fids, but they don't
2094 				 * compare. So kill the file.
2095 				 */
2096 				failed_msg =
2097 				    "Couldn't reopen: file handle changed"
2098 				    " due to mismatched fids";
2099 				nfs4args_copen_free(open_args);
2100 				(void) xdr_free(xdr_COMPOUND4res_clnt,
2101 				    (caddr_t)&res);
2102 				nfs_rw_exit(&mi->mi_fh_lock);
2103 				goto kill_file;
2104 			} else {
2105 				/*
2106 				 * We have volatile file handles that refers
2107 				 * to the same file (at least they have the
2108 				 * same fid) or we don't have fids so we
2109 				 * can't tell. :(. We'll be a kind and accepting
2110 				 * client so we'll update the rnode's file
2111 				 * handle with the otw handle.
2112 				 *
2113 				 * We need to drop mi->mi_fh_lock since
2114 				 * sh4_update acquires it. Since there is
2115 				 * only one recovery thread there is no
2116 				 * race.
2117 				 */
2118 				nfs_rw_exit(&mi->mi_fh_lock);
2119 				sfh4_update(rp->r_fh, &gf_res->object);
2120 			}
2121 		}
2122 	} else {
2123 		nfs_rw_exit(&mi->mi_fh_lock);
2124 	}
2125 
2126 	ASSERT(nfs4_consistent_type(vp));
2127 
2128 	/*
2129 	 * If the server wanted an OPEN_CONFIRM but that fails, just start
2130 	 * over.  Presumably if there is a persistent error it will show up
2131 	 * when we resend the OPEN.
2132 	 */
2133 	if (op_res->rflags & OPEN4_RESULT_CONFIRM) {
2134 		bool_t retry_open = FALSE;
2135 
2136 		nfs4open_confirm(vp, &seqid, &op_res->stateid,
2137 		    cred_otw, is_recov, &retry_open,
2138 		    oop, FALSE, ep, NULL);
2139 		if (ep->error || ep->stat) {
2140 			nfs4args_copen_free(open_args);
2141 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2142 			nfs4_end_open_seqid_sync(oop);
2143 			open_owner_rele(oop);
2144 			oop = NULL;
2145 			goto top;
2146 		}
2147 	}
2148 
2149 	mutex_enter(&osp->os_sync_lock);
2150 	osp->open_stateid = op_res->stateid;
2151 	osp->os_delegation = 0;
2152 	/*
2153 	 * Need to reset this bitfield for the possible case where we were
2154 	 * going to OTW CLOSE the file, got a non-recoverable error, and before
2155 	 * we could retry the CLOSE, OPENed the file again.
2156 	 */
2157 	ASSERT(osp->os_open_owner->oo_seqid_inuse);
2158 	osp->os_final_close = 0;
2159 	osp->os_force_close = 0;
2160 	if (claim == CLAIM_DELEGATE_CUR || claim == CLAIM_PREVIOUS)
2161 		osp->os_dc_openacc = open_args->share_access;
2162 	mutex_exit(&osp->os_sync_lock);
2163 
2164 	nfs4_end_open_seqid_sync(oop);
2165 
2166 	/* accept delegation, if any */
2167 	nfs4_delegation_accept(rp, claim, op_res, garp, cred_otw);
2168 
2169 	nfs4args_copen_free(open_args);
2170 
2171 	nfs4_attr_cache(vp, garp, t, cr, TRUE, NULL);
2172 
2173 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2174 
2175 	ASSERT(nfs4_consistent_type(vp));
2176 
2177 	open_owner_rele(oop);
2178 	crfree(cr);
2179 	crfree(cred_otw);
2180 	return;
2181 
2182 kill_file:
2183 	nfs4_fail_recov(vp, failed_msg, ep->error, ep->stat);
2184 failed_reopen:
2185 	NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
2186 	    "nfs4_reopen: setting os_failed_reopen for osp %p, cr %p, rp %s",
2187 	    (void *)osp, (void *)cr, rnode4info(rp)));
2188 	mutex_enter(&osp->os_sync_lock);
2189 	osp->os_failed_reopen = 1;
2190 	mutex_exit(&osp->os_sync_lock);
2191 bailout:
2192 	if (oop != NULL) {
2193 		nfs4_end_open_seqid_sync(oop);
2194 		open_owner_rele(oop);
2195 	}
2196 	if (cr != NULL)
2197 		crfree(cr);
2198 	if (cred_otw != NULL)
2199 		crfree(cred_otw);
2200 }
2201 
2202 /* for . and .. OPENs */
2203 /* ARGSUSED */
2204 static int
2205 nfs4_open_non_reg_file(vnode_t **vpp, int flag, cred_t *cr)
2206 {
2207 	rnode4_t *rp;
2208 	nfs4_ga_res_t gar;
2209 
2210 	ASSERT(nfs_zone() == VTOMI4(*vpp)->mi_zone);
2211 
2212 	/*
2213 	 * If close-to-open consistency checking is turned off or
2214 	 * if there is no cached data, we can avoid
2215 	 * the over the wire getattr.  Otherwise, force a
2216 	 * call to the server to get fresh attributes and to
2217 	 * check caches. This is required for close-to-open
2218 	 * consistency.
2219 	 */
2220 	rp = VTOR4(*vpp);
2221 	if (VTOMI4(*vpp)->mi_flags & MI4_NOCTO ||
2222 	    (rp->r_dir == NULL && !nfs4_has_pages(*vpp)))
2223 		return (0);
2224 
2225 	gar.n4g_va.va_mask = AT_ALL;
2226 	return (nfs4_getattr_otw(*vpp, &gar, cr, 0));
2227 }
2228 
2229 /*
2230  * CLOSE a file
2231  */
2232 /* ARGSUSED */
2233 static int
2234 nfs4_close(vnode_t *vp, int flag, int count, offset_t offset, cred_t *cr,
2235 	caller_context_t *ct)
2236 {
2237 	rnode4_t	*rp;
2238 	int		 error = 0;
2239 	int		 r_error = 0;
2240 	int		 n4error = 0;
2241 	nfs4_error_t	 e = { 0, NFS4_OK, RPC_SUCCESS };
2242 
2243 	/*
2244 	 * Remove client state for this (lockowner, file) pair.
2245 	 * Issue otw v4 call to have the server do the same.
2246 	 */
2247 
2248 	rp = VTOR4(vp);
2249 
2250 	/*
2251 	 * zone_enter(2) prevents processes from changing zones with NFS files
2252 	 * open; if we happen to get here from the wrong zone we can't do
2253 	 * anything over the wire.
2254 	 */
2255 	if (VTOMI4(vp)->mi_zone != nfs_zone()) {
2256 		/*
2257 		 * We could attempt to clean up locks, except we're sure
2258 		 * that the current process didn't acquire any locks on
2259 		 * the file: any attempt to lock a file belong to another zone
2260 		 * will fail, and one can't lock an NFS file and then change
2261 		 * zones, as that fails too.
2262 		 *
2263 		 * Returning an error here is the sane thing to do.  A
2264 		 * subsequent call to VN_RELE() which translates to a
2265 		 * nfs4_inactive() will clean up state: if the zone of the
2266 		 * vnode's origin is still alive and kicking, the inactive
2267 		 * thread will handle the request (from the correct zone), and
2268 		 * everything (minus the OTW close call) should be OK.  If the
2269 		 * zone is going away nfs4_async_inactive() will throw away
2270 		 * delegations, open streams and cached pages inline.
2271 		 */
2272 		return (EIO);
2273 	}
2274 
2275 	/*
2276 	 * If we are using local locking for this filesystem, then
2277 	 * release all of the SYSV style record locks.  Otherwise,
2278 	 * we are doing network locking and we need to release all
2279 	 * of the network locks.  All of the locks held by this
2280 	 * process on this file are released no matter what the
2281 	 * incoming reference count is.
2282 	 */
2283 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK) {
2284 		cleanlocks(vp, ttoproc(curthread)->p_pid, 0);
2285 		cleanshares(vp, ttoproc(curthread)->p_pid);
2286 	} else
2287 		e.error = nfs4_lockrelease(vp, flag, offset, cr);
2288 
2289 	if (e.error) {
2290 		struct lm_sysid *lmsid;
2291 		lmsid = nfs4_find_sysid(VTOMI4(vp));
2292 		if (lmsid == NULL) {
2293 			DTRACE_PROBE2(unknown__sysid, int, e.error,
2294 			    vnode_t *, vp);
2295 		} else {
2296 			cleanlocks(vp, ttoproc(curthread)->p_pid,
2297 			    (lm_sysidt(lmsid) | LM_SYSID_CLIENT));
2298 		}
2299 		return (e.error);
2300 	}
2301 
2302 	if (count > 1)
2303 		return (0);
2304 
2305 	/*
2306 	 * If the file has been `unlinked', then purge the
2307 	 * DNLC so that this vnode will get reycled quicker
2308 	 * and the .nfs* file on the server will get removed.
2309 	 */
2310 	if (rp->r_unldvp != NULL)
2311 		dnlc_purge_vp(vp);
2312 
2313 	/*
2314 	 * If the file was open for write and there are pages,
2315 	 * do a synchronous flush and commit of all of the
2316 	 * dirty and uncommitted pages.
2317 	 */
2318 	ASSERT(!e.error);
2319 	if ((flag & FWRITE) && nfs4_has_pages(vp))
2320 		error = nfs4_putpage_commit(vp, 0, 0, cr);
2321 
2322 	mutex_enter(&rp->r_statelock);
2323 	r_error = rp->r_error;
2324 	rp->r_error = 0;
2325 	mutex_exit(&rp->r_statelock);
2326 
2327 	/*
2328 	 * If this file type is one for which no explicit 'open' was
2329 	 * done, then bail now (ie. no need for protocol 'close'). If
2330 	 * there was an error w/the vm subsystem, return _that_ error,
2331 	 * otherwise, return any errors that may've been reported via
2332 	 * the rnode.
2333 	 */
2334 	if (vp->v_type != VREG)
2335 		return (error ? error : r_error);
2336 
2337 	/*
2338 	 * The sync putpage commit may have failed above, but since
2339 	 * we're working w/a regular file, we need to do the protocol
2340 	 * 'close' (nfs4close_one will figure out if an otw close is
2341 	 * needed or not). Report any errors _after_ doing the protocol
2342 	 * 'close'.
2343 	 */
2344 	nfs4close_one(vp, NULL, cr, flag, NULL, &e, CLOSE_NORM, 0, 0, 0);
2345 	n4error = e.error ? e.error : geterrno4(e.stat);
2346 
2347 	/*
2348 	 * Error reporting prio (Hi -> Lo)
2349 	 *
2350 	 *   i) nfs4_putpage_commit (error)
2351 	 *  ii) rnode's (r_error)
2352 	 * iii) nfs4close_one (n4error)
2353 	 */
2354 	return (error ? error : (r_error ? r_error : n4error));
2355 }
2356 
2357 /*
2358  * Initialize *lost_rqstp.
2359  */
2360 
2361 static void
2362 nfs4close_save_lost_rqst(int error, nfs4_lost_rqst_t *lost_rqstp,
2363     nfs4_open_owner_t *oop, nfs4_open_stream_t *osp, cred_t *cr,
2364     vnode_t *vp)
2365 {
2366 	if (error != ETIMEDOUT && error != EINTR &&
2367 	    !NFS4_FRC_UNMT_ERR(error, vp->v_vfsp)) {
2368 		lost_rqstp->lr_op = 0;
2369 		return;
2370 	}
2371 
2372 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
2373 	    "nfs4close_save_lost_rqst: error %d", error));
2374 
2375 	lost_rqstp->lr_op = OP_CLOSE;
2376 	/*
2377 	 * The vp is held and rele'd via the recovery code.
2378 	 * See nfs4_save_lost_rqst.
2379 	 */
2380 	lost_rqstp->lr_vp = vp;
2381 	lost_rqstp->lr_dvp = NULL;
2382 	lost_rqstp->lr_oop = oop;
2383 	lost_rqstp->lr_osp = osp;
2384 	ASSERT(osp != NULL);
2385 	ASSERT(mutex_owned(&osp->os_sync_lock));
2386 	osp->os_pending_close = 1;
2387 	lost_rqstp->lr_lop = NULL;
2388 	lost_rqstp->lr_cr = cr;
2389 	lost_rqstp->lr_flk = NULL;
2390 	lost_rqstp->lr_putfirst = FALSE;
2391 }
2392 
2393 /*
2394  * Assumes you already have the open seqid sync grabbed as well as the
2395  * 'os_sync_lock'.  Note: this will release the open seqid sync and
2396  * 'os_sync_lock' if client recovery starts.  Calling functions have to
2397  * be prepared to handle this.
2398  *
2399  * 'recov' is returned as 1 if the CLOSE operation detected client recovery
2400  * was needed and was started, and that the calling function should retry
2401  * this function; otherwise it is returned as 0.
2402  *
2403  * Errors are returned via the nfs4_error_t parameter.
2404  */
2405 static void
2406 nfs4close_otw(rnode4_t *rp, cred_t *cred_otw, nfs4_open_owner_t *oop,
2407     nfs4_open_stream_t *osp, int *recov, int *did_start_seqid_syncp,
2408     nfs4_close_type_t close_type, nfs4_error_t *ep, int *have_sync_lockp)
2409 {
2410 	COMPOUND4args_clnt args;
2411 	COMPOUND4res_clnt res;
2412 	CLOSE4args *close_args;
2413 	nfs_resop4 *resop;
2414 	nfs_argop4 argop[3];
2415 	int doqueue = 1;
2416 	mntinfo4_t *mi;
2417 	seqid4 seqid;
2418 	vnode_t *vp;
2419 	bool_t needrecov = FALSE;
2420 	nfs4_lost_rqst_t lost_rqst;
2421 	hrtime_t t;
2422 
2423 	ASSERT(nfs_zone() == VTOMI4(RTOV4(rp))->mi_zone);
2424 
2425 	ASSERT(MUTEX_HELD(&osp->os_sync_lock));
2426 
2427 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4close_otw"));
2428 
2429 	/* Only set this to 1 if recovery is started */
2430 	*recov = 0;
2431 
2432 	/* do the OTW call to close the file */
2433 
2434 	if (close_type == CLOSE_RESEND)
2435 		args.ctag = TAG_CLOSE_LOST;
2436 	else if (close_type == CLOSE_AFTER_RESEND)
2437 		args.ctag = TAG_CLOSE_UNDO;
2438 	else
2439 		args.ctag = TAG_CLOSE;
2440 
2441 	args.array_len = 3;
2442 	args.array = argop;
2443 
2444 	vp = RTOV4(rp);
2445 
2446 	mi = VTOMI4(vp);
2447 
2448 	/* putfh target fh */
2449 	argop[0].argop = OP_CPUTFH;
2450 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
2451 
2452 	argop[1].argop = OP_GETATTR;
2453 	argop[1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
2454 	argop[1].nfs_argop4_u.opgetattr.mi = mi;
2455 
2456 	argop[2].argop = OP_CLOSE;
2457 	close_args = &argop[2].nfs_argop4_u.opclose;
2458 
2459 	seqid = nfs4_get_open_seqid(oop) + 1;
2460 
2461 	close_args->seqid = seqid;
2462 	close_args->open_stateid = osp->open_stateid;
2463 
2464 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
2465 	    "nfs4close_otw: %s call, rp %s", needrecov ? "recov" : "first",
2466 	    rnode4info(rp)));
2467 
2468 	t = gethrtime();
2469 
2470 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, ep);
2471 
2472 	if (!ep->error && nfs4_need_to_bump_seqid(&res)) {
2473 		nfs4_set_open_seqid(seqid, oop, args.ctag);
2474 	}
2475 
2476 	needrecov = nfs4_needs_recovery(ep, TRUE, mi->mi_vfsp);
2477 	if (ep->error && !needrecov) {
2478 		/*
2479 		 * if there was an error and no recovery is to be done
2480 		 * then then set up the file to flush its cache if
2481 		 * needed for the next caller.
2482 		 */
2483 		mutex_enter(&rp->r_statelock);
2484 		PURGE_ATTRCACHE4_LOCKED(rp);
2485 		rp->r_flags &= ~R4WRITEMODIFIED;
2486 		mutex_exit(&rp->r_statelock);
2487 		return;
2488 	}
2489 
2490 	if (needrecov) {
2491 		bool_t abort;
2492 		nfs4_bseqid_entry_t *bsep = NULL;
2493 
2494 		if (close_type != CLOSE_RESEND)
2495 			nfs4close_save_lost_rqst(ep->error, &lost_rqst, oop,
2496 			    osp, cred_otw, vp);
2497 
2498 		if (!ep->error && res.status == NFS4ERR_BAD_SEQID)
2499 			bsep = nfs4_create_bseqid_entry(oop, NULL, vp,
2500 			    0, args.ctag, close_args->seqid);
2501 
2502 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
2503 		    "nfs4close_otw: initiating recovery. error %d "
2504 		    "res.status %d", ep->error, res.status));
2505 
2506 		/*
2507 		 * Drop the 'os_sync_lock' here so we don't hit
2508 		 * a potential recursive mutex_enter via an
2509 		 * 'open_stream_hold()'.
2510 		 */
2511 		mutex_exit(&osp->os_sync_lock);
2512 		*have_sync_lockp = 0;
2513 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL, NULL,
2514 		    (close_type != CLOSE_RESEND &&
2515 		    lost_rqst.lr_op == OP_CLOSE) ? &lost_rqst : NULL,
2516 		    OP_CLOSE, bsep);
2517 
2518 		/* drop open seq sync, and let the calling function regrab it */
2519 		nfs4_end_open_seqid_sync(oop);
2520 		*did_start_seqid_syncp = 0;
2521 
2522 		if (bsep)
2523 			kmem_free(bsep, sizeof (*bsep));
2524 		/*
2525 		 * For signals, the caller wants to quit, so don't say to
2526 		 * retry.  For forced unmount, if it's a user thread, it
2527 		 * wants to quit.  If it's a recovery thread, the retry
2528 		 * will happen higher-up on the call stack.  Either way,
2529 		 * don't say to retry.
2530 		 */
2531 		if (abort == FALSE && ep->error != EINTR &&
2532 		    !NFS4_FRC_UNMT_ERR(ep->error, mi->mi_vfsp) &&
2533 		    close_type != CLOSE_RESEND &&
2534 		    close_type != CLOSE_AFTER_RESEND)
2535 			*recov = 1;
2536 		else
2537 			*recov = 0;
2538 
2539 		if (!ep->error)
2540 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2541 		return;
2542 	}
2543 
2544 	if (res.status) {
2545 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2546 		return;
2547 	}
2548 
2549 	mutex_enter(&rp->r_statev4_lock);
2550 	rp->created_v4 = 0;
2551 	mutex_exit(&rp->r_statev4_lock);
2552 
2553 	resop = &res.array[2];
2554 	osp->open_stateid = resop->nfs_resop4_u.opclose.open_stateid;
2555 	osp->os_valid = 0;
2556 
2557 	/*
2558 	 * This removes the reference obtained at OPEN; ie, when the
2559 	 * open stream structure was created.
2560 	 *
2561 	 * We don't have to worry about calling 'open_stream_rele'
2562 	 * since we our currently holding a reference to the open
2563 	 * stream which means the count cannot go to 0 with this
2564 	 * decrement.
2565 	 */
2566 	ASSERT(osp->os_ref_count >= 2);
2567 	osp->os_ref_count--;
2568 
2569 	if (!ep->error)
2570 		nfs4_attr_cache(vp,
2571 		    &res.array[1].nfs_resop4_u.opgetattr.ga_res,
2572 		    t, cred_otw, TRUE, NULL);
2573 
2574 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4close_otw:"
2575 	    " returning %d", ep->error));
2576 
2577 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2578 }
2579 
2580 /* ARGSUSED */
2581 static int
2582 nfs4_read(vnode_t *vp, struct uio *uiop, int ioflag, cred_t *cr,
2583     caller_context_t *ct)
2584 {
2585 	rnode4_t *rp;
2586 	u_offset_t off;
2587 	offset_t diff;
2588 	uint_t on;
2589 	uint_t n;
2590 	caddr_t base;
2591 	uint_t flags;
2592 	int error;
2593 	mntinfo4_t *mi;
2594 
2595 	rp = VTOR4(vp);
2596 
2597 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
2598 
2599 	if (IS_SHADOW(vp, rp))
2600 		vp = RTOV4(rp);
2601 
2602 	if (vp->v_type != VREG)
2603 		return (EISDIR);
2604 
2605 	mi = VTOMI4(vp);
2606 
2607 	if (nfs_zone() != mi->mi_zone)
2608 		return (EIO);
2609 
2610 	if (uiop->uio_resid == 0)
2611 		return (0);
2612 
2613 	if (uiop->uio_loffset < 0 || uiop->uio_loffset + uiop->uio_resid < 0)
2614 		return (EINVAL);
2615 
2616 	mutex_enter(&rp->r_statelock);
2617 	if (rp->r_flags & R4RECOVERRP)
2618 		error = (rp->r_error ? rp->r_error : EIO);
2619 	else
2620 		error = 0;
2621 	mutex_exit(&rp->r_statelock);
2622 	if (error)
2623 		return (error);
2624 
2625 	/*
2626 	 * Bypass VM if caching has been disabled (e.g., locking) or if
2627 	 * using client-side direct I/O and the file is not mmap'd and
2628 	 * there are no cached pages.
2629 	 */
2630 	if ((vp->v_flag & VNOCACHE) ||
2631 	    (((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO)) &&
2632 	    rp->r_mapcnt == 0 && !nfs4_has_pages(vp))) {
2633 		size_t resid = 0;
2634 
2635 		return (nfs4read(vp, NULL, uiop->uio_loffset,
2636 		    uiop->uio_resid, &resid, cr, FALSE, uiop));
2637 	}
2638 
2639 	error = 0;
2640 
2641 	do {
2642 		off = uiop->uio_loffset & MAXBMASK; /* mapping offset */
2643 		on = uiop->uio_loffset & MAXBOFFSET; /* Relative offset */
2644 		n = MIN(MAXBSIZE - on, uiop->uio_resid);
2645 
2646 		if (error = nfs4_validate_caches(vp, cr))
2647 			break;
2648 
2649 		mutex_enter(&rp->r_statelock);
2650 		while (rp->r_flags & R4INCACHEPURGE) {
2651 			if (!cv_wait_sig(&rp->r_cv, &rp->r_statelock)) {
2652 				mutex_exit(&rp->r_statelock);
2653 				return (EINTR);
2654 			}
2655 		}
2656 		diff = rp->r_size - uiop->uio_loffset;
2657 		mutex_exit(&rp->r_statelock);
2658 		if (diff <= 0)
2659 			break;
2660 		if (diff < n)
2661 			n = (uint_t)diff;
2662 
2663 		if (vpm_enable) {
2664 			/*
2665 			 * Copy data.
2666 			 */
2667 			error = vpm_data_copy(vp, off + on, n, uiop,
2668 			    1, NULL, 0, S_READ);
2669 		} else {
2670 			base = segmap_getmapflt(segkmap, vp, off + on, n, 1,
2671 			    S_READ);
2672 
2673 			error = uiomove(base + on, n, UIO_READ, uiop);
2674 		}
2675 
2676 		if (!error) {
2677 			/*
2678 			 * If read a whole block or read to eof,
2679 			 * won't need this buffer again soon.
2680 			 */
2681 			mutex_enter(&rp->r_statelock);
2682 			if (n + on == MAXBSIZE ||
2683 			    uiop->uio_loffset == rp->r_size)
2684 				flags = SM_DONTNEED;
2685 			else
2686 				flags = 0;
2687 			mutex_exit(&rp->r_statelock);
2688 			if (vpm_enable) {
2689 				error = vpm_sync_pages(vp, off, n, flags);
2690 			} else {
2691 				error = segmap_release(segkmap, base, flags);
2692 			}
2693 		} else {
2694 			if (vpm_enable) {
2695 				(void) vpm_sync_pages(vp, off, n, 0);
2696 			} else {
2697 				(void) segmap_release(segkmap, base, 0);
2698 			}
2699 		}
2700 	} while (!error && uiop->uio_resid > 0);
2701 
2702 	return (error);
2703 }
2704 
2705 /* ARGSUSED */
2706 static int
2707 nfs4_write(vnode_t *vp, struct uio *uiop, int ioflag, cred_t *cr,
2708     caller_context_t *ct)
2709 {
2710 	rlim64_t limit = uiop->uio_llimit;
2711 	rnode4_t *rp;
2712 	u_offset_t off;
2713 	caddr_t base;
2714 	uint_t flags;
2715 	int remainder;
2716 	size_t n;
2717 	int on;
2718 	int error;
2719 	int resid;
2720 	u_offset_t offset;
2721 	mntinfo4_t *mi;
2722 	uint_t bsize;
2723 
2724 	rp = VTOR4(vp);
2725 
2726 	if (IS_SHADOW(vp, rp))
2727 		vp = RTOV4(rp);
2728 
2729 	if (vp->v_type != VREG)
2730 		return (EISDIR);
2731 
2732 	mi = VTOMI4(vp);
2733 
2734 	if (nfs_zone() != mi->mi_zone)
2735 		return (EIO);
2736 
2737 	if (uiop->uio_resid == 0)
2738 		return (0);
2739 
2740 	mutex_enter(&rp->r_statelock);
2741 	if (rp->r_flags & R4RECOVERRP)
2742 		error = (rp->r_error ? rp->r_error : EIO);
2743 	else
2744 		error = 0;
2745 	mutex_exit(&rp->r_statelock);
2746 	if (error)
2747 		return (error);
2748 
2749 	if (ioflag & FAPPEND) {
2750 		struct vattr va;
2751 
2752 		/*
2753 		 * Must serialize if appending.
2754 		 */
2755 		if (nfs_rw_lock_held(&rp->r_rwlock, RW_READER)) {
2756 			nfs_rw_exit(&rp->r_rwlock);
2757 			if (nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER,
2758 			    INTR(vp)))
2759 				return (EINTR);
2760 		}
2761 
2762 		va.va_mask = AT_SIZE;
2763 		error = nfs4getattr(vp, &va, cr);
2764 		if (error)
2765 			return (error);
2766 		uiop->uio_loffset = va.va_size;
2767 	}
2768 
2769 	offset = uiop->uio_loffset + uiop->uio_resid;
2770 
2771 	if (uiop->uio_loffset < (offset_t)0 || offset < 0)
2772 		return (EINVAL);
2773 
2774 	if (limit == RLIM64_INFINITY || limit > MAXOFFSET_T)
2775 		limit = MAXOFFSET_T;
2776 
2777 	/*
2778 	 * Check to make sure that the process will not exceed
2779 	 * its limit on file size.  It is okay to write up to
2780 	 * the limit, but not beyond.  Thus, the write which
2781 	 * reaches the limit will be short and the next write
2782 	 * will return an error.
2783 	 */
2784 	remainder = 0;
2785 	if (offset > uiop->uio_llimit) {
2786 		remainder = offset - uiop->uio_llimit;
2787 		uiop->uio_resid = uiop->uio_llimit - uiop->uio_loffset;
2788 		if (uiop->uio_resid <= 0) {
2789 			proc_t *p = ttoproc(curthread);
2790 
2791 			uiop->uio_resid += remainder;
2792 			mutex_enter(&p->p_lock);
2793 			(void) rctl_action(rctlproc_legacy[RLIMIT_FSIZE],
2794 			    p->p_rctls, p, RCA_UNSAFE_SIGINFO);
2795 			mutex_exit(&p->p_lock);
2796 			return (EFBIG);
2797 		}
2798 	}
2799 
2800 	/* update the change attribute, if we have a write delegation */
2801 
2802 	mutex_enter(&rp->r_statev4_lock);
2803 	if (rp->r_deleg_type == OPEN_DELEGATE_WRITE)
2804 		rp->r_deleg_change++;
2805 
2806 	mutex_exit(&rp->r_statev4_lock);
2807 
2808 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_READER, INTR4(vp)))
2809 		return (EINTR);
2810 
2811 	/*
2812 	 * Bypass VM if caching has been disabled (e.g., locking) or if
2813 	 * using client-side direct I/O and the file is not mmap'd and
2814 	 * there are no cached pages.
2815 	 */
2816 	if ((vp->v_flag & VNOCACHE) ||
2817 	    (((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO)) &&
2818 	    rp->r_mapcnt == 0 && !nfs4_has_pages(vp))) {
2819 		size_t bufsize;
2820 		int count;
2821 		u_offset_t org_offset;
2822 		stable_how4 stab_comm;
2823 nfs4_fwrite:
2824 		if (rp->r_flags & R4STALE) {
2825 			resid = uiop->uio_resid;
2826 			offset = uiop->uio_loffset;
2827 			error = rp->r_error;
2828 			goto bottom;
2829 		}
2830 
2831 		bufsize = MIN(uiop->uio_resid, mi->mi_stsize);
2832 		base = kmem_alloc(bufsize, KM_SLEEP);
2833 		do {
2834 			if (ioflag & FDSYNC)
2835 				stab_comm = DATA_SYNC4;
2836 			else
2837 				stab_comm = FILE_SYNC4;
2838 			resid = uiop->uio_resid;
2839 			offset = uiop->uio_loffset;
2840 			count = MIN(uiop->uio_resid, bufsize);
2841 			org_offset = uiop->uio_loffset;
2842 			error = uiomove(base, count, UIO_WRITE, uiop);
2843 			if (!error) {
2844 				error = nfs4write(vp, base, org_offset,
2845 				    count, cr, &stab_comm);
2846 				if (!error) {
2847 					mutex_enter(&rp->r_statelock);
2848 					if (rp->r_size < uiop->uio_loffset)
2849 						rp->r_size = uiop->uio_loffset;
2850 					mutex_exit(&rp->r_statelock);
2851 				}
2852 			}
2853 		} while (!error && uiop->uio_resid > 0);
2854 		kmem_free(base, bufsize);
2855 		goto bottom;
2856 	}
2857 
2858 	bsize = vp->v_vfsp->vfs_bsize;
2859 
2860 	do {
2861 		off = uiop->uio_loffset & MAXBMASK; /* mapping offset */
2862 		on = uiop->uio_loffset & MAXBOFFSET; /* Relative offset */
2863 		n = MIN(MAXBSIZE - on, uiop->uio_resid);
2864 
2865 		resid = uiop->uio_resid;
2866 		offset = uiop->uio_loffset;
2867 
2868 		if (rp->r_flags & R4STALE) {
2869 			error = rp->r_error;
2870 			break;
2871 		}
2872 
2873 		/*
2874 		 * Don't create dirty pages faster than they
2875 		 * can be cleaned so that the system doesn't
2876 		 * get imbalanced.  If the async queue is
2877 		 * maxed out, then wait for it to drain before
2878 		 * creating more dirty pages.  Also, wait for
2879 		 * any threads doing pagewalks in the vop_getattr
2880 		 * entry points so that they don't block for
2881 		 * long periods.
2882 		 */
2883 		mutex_enter(&rp->r_statelock);
2884 		while ((mi->mi_max_threads != 0 &&
2885 		    rp->r_awcount > 2 * mi->mi_max_threads) ||
2886 		    rp->r_gcount > 0)
2887 			cv_wait(&rp->r_cv, &rp->r_statelock);
2888 		mutex_exit(&rp->r_statelock);
2889 
2890 		if (vpm_enable) {
2891 			/*
2892 			 * It will use kpm mappings, so no need to
2893 			 * pass an address.
2894 			 */
2895 			error = writerp4(rp, NULL, n, uiop, 0);
2896 		} else  {
2897 			if (segmap_kpm) {
2898 				int pon = uiop->uio_loffset & PAGEOFFSET;
2899 				size_t pn = MIN(PAGESIZE - pon,
2900 				    uiop->uio_resid);
2901 				int pagecreate;
2902 
2903 				mutex_enter(&rp->r_statelock);
2904 				pagecreate = (pon == 0) && (pn == PAGESIZE ||
2905 				    uiop->uio_loffset + pn >= rp->r_size);
2906 				mutex_exit(&rp->r_statelock);
2907 
2908 				base = segmap_getmapflt(segkmap, vp, off + on,
2909 				    pn, !pagecreate, S_WRITE);
2910 
2911 				error = writerp4(rp, base + pon, n, uiop,
2912 				    pagecreate);
2913 
2914 			} else {
2915 				base = segmap_getmapflt(segkmap, vp, off + on,
2916 				    n, 0, S_READ);
2917 				error = writerp4(rp, base + on, n, uiop, 0);
2918 			}
2919 		}
2920 
2921 		if (!error) {
2922 			if (mi->mi_flags & MI4_NOAC)
2923 				flags = SM_WRITE;
2924 			else if ((uiop->uio_loffset % bsize) == 0 ||
2925 			    IS_SWAPVP(vp)) {
2926 				/*
2927 				 * Have written a whole block.
2928 				 * Start an asynchronous write
2929 				 * and mark the buffer to
2930 				 * indicate that it won't be
2931 				 * needed again soon.
2932 				 */
2933 				flags = SM_WRITE | SM_ASYNC | SM_DONTNEED;
2934 			} else
2935 				flags = 0;
2936 			if ((ioflag & (FSYNC|FDSYNC)) ||
2937 			    (rp->r_flags & R4OUTOFSPACE)) {
2938 				flags &= ~SM_ASYNC;
2939 				flags |= SM_WRITE;
2940 			}
2941 			if (vpm_enable) {
2942 				error = vpm_sync_pages(vp, off, n, flags);
2943 			} else {
2944 				error = segmap_release(segkmap, base, flags);
2945 			}
2946 		} else {
2947 			if (vpm_enable) {
2948 				(void) vpm_sync_pages(vp, off, n, 0);
2949 			} else {
2950 				(void) segmap_release(segkmap, base, 0);
2951 			}
2952 			/*
2953 			 * In the event that we got an access error while
2954 			 * faulting in a page for a write-only file just
2955 			 * force a write.
2956 			 */
2957 			if (error == EACCES)
2958 				goto nfs4_fwrite;
2959 		}
2960 	} while (!error && uiop->uio_resid > 0);
2961 
2962 bottom:
2963 	if (error) {
2964 		uiop->uio_resid = resid + remainder;
2965 		uiop->uio_loffset = offset;
2966 	} else {
2967 		uiop->uio_resid += remainder;
2968 
2969 		mutex_enter(&rp->r_statev4_lock);
2970 		if (rp->r_deleg_type == OPEN_DELEGATE_WRITE) {
2971 			gethrestime(&rp->r_attr.va_mtime);
2972 			rp->r_attr.va_ctime = rp->r_attr.va_mtime;
2973 		}
2974 		mutex_exit(&rp->r_statev4_lock);
2975 	}
2976 
2977 	nfs_rw_exit(&rp->r_lkserlock);
2978 
2979 	return (error);
2980 }
2981 
2982 /*
2983  * Flags are composed of {B_ASYNC, B_INVAL, B_FREE, B_DONTNEED}
2984  */
2985 static int
2986 nfs4_rdwrlbn(vnode_t *vp, page_t *pp, u_offset_t off, size_t len,
2987     int flags, cred_t *cr)
2988 {
2989 	struct buf *bp;
2990 	int error;
2991 	page_t *savepp;
2992 	uchar_t fsdata;
2993 	stable_how4 stab_comm;
2994 
2995 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
2996 	bp = pageio_setup(pp, len, vp, flags);
2997 	ASSERT(bp != NULL);
2998 
2999 	/*
3000 	 * pageio_setup should have set b_addr to 0.  This
3001 	 * is correct since we want to do I/O on a page
3002 	 * boundary.  bp_mapin will use this addr to calculate
3003 	 * an offset, and then set b_addr to the kernel virtual
3004 	 * address it allocated for us.
3005 	 */
3006 	ASSERT(bp->b_un.b_addr == 0);
3007 
3008 	bp->b_edev = 0;
3009 	bp->b_dev = 0;
3010 	bp->b_lblkno = lbtodb(off);
3011 	bp->b_file = vp;
3012 	bp->b_offset = (offset_t)off;
3013 	bp_mapin(bp);
3014 
3015 	if ((flags & (B_WRITE|B_ASYNC)) == (B_WRITE|B_ASYNC) &&
3016 	    freemem > desfree)
3017 		stab_comm = UNSTABLE4;
3018 	else
3019 		stab_comm = FILE_SYNC4;
3020 
3021 	error = nfs4_bio(bp, &stab_comm, cr, FALSE);
3022 
3023 	bp_mapout(bp);
3024 	pageio_done(bp);
3025 
3026 	if (stab_comm == UNSTABLE4)
3027 		fsdata = C_DELAYCOMMIT;
3028 	else
3029 		fsdata = C_NOCOMMIT;
3030 
3031 	savepp = pp;
3032 	do {
3033 		pp->p_fsdata = fsdata;
3034 	} while ((pp = pp->p_next) != savepp);
3035 
3036 	return (error);
3037 }
3038 
3039 /*
3040  */
3041 static int
3042 nfs4rdwr_check_osid(vnode_t *vp, nfs4_error_t *ep, cred_t *cr)
3043 {
3044 	nfs4_open_owner_t	*oop;
3045 	nfs4_open_stream_t	*osp;
3046 	rnode4_t		*rp = VTOR4(vp);
3047 	mntinfo4_t 		*mi = VTOMI4(vp);
3048 	int 			reopen_needed;
3049 
3050 	ASSERT(nfs_zone() == mi->mi_zone);
3051 
3052 
3053 	oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
3054 	if (!oop)
3055 		return (EIO);
3056 
3057 	/* returns with 'os_sync_lock' held */
3058 	osp = find_open_stream(oop, rp);
3059 	if (!osp) {
3060 		open_owner_rele(oop);
3061 		return (EIO);
3062 	}
3063 
3064 	if (osp->os_failed_reopen) {
3065 		mutex_exit(&osp->os_sync_lock);
3066 		open_stream_rele(osp, rp);
3067 		open_owner_rele(oop);
3068 		return (EIO);
3069 	}
3070 
3071 	/*
3072 	 * Determine whether a reopen is needed.  If this
3073 	 * is a delegation open stream, then the os_delegation bit
3074 	 * should be set.
3075 	 */
3076 
3077 	reopen_needed = osp->os_delegation;
3078 
3079 	mutex_exit(&osp->os_sync_lock);
3080 	open_owner_rele(oop);
3081 
3082 	if (reopen_needed) {
3083 		nfs4_error_zinit(ep);
3084 		nfs4_reopen(vp, osp, ep, CLAIM_NULL, FALSE, FALSE);
3085 		mutex_enter(&osp->os_sync_lock);
3086 		if (ep->error || ep->stat || osp->os_failed_reopen) {
3087 			mutex_exit(&osp->os_sync_lock);
3088 			open_stream_rele(osp, rp);
3089 			return (EIO);
3090 		}
3091 		mutex_exit(&osp->os_sync_lock);
3092 	}
3093 	open_stream_rele(osp, rp);
3094 
3095 	return (0);
3096 }
3097 
3098 /*
3099  * Write to file.  Writes to remote server in largest size
3100  * chunks that the server can handle.  Write is synchronous.
3101  */
3102 static int
3103 nfs4write(vnode_t *vp, caddr_t base, u_offset_t offset, int count, cred_t *cr,
3104     stable_how4 *stab_comm)
3105 {
3106 	mntinfo4_t *mi;
3107 	COMPOUND4args_clnt args;
3108 	COMPOUND4res_clnt res;
3109 	WRITE4args *wargs;
3110 	WRITE4res *wres;
3111 	nfs_argop4 argop[2];
3112 	nfs_resop4 *resop;
3113 	int tsize;
3114 	stable_how4 stable;
3115 	rnode4_t *rp;
3116 	int doqueue = 1;
3117 	bool_t needrecov;
3118 	nfs4_recov_state_t recov_state;
3119 	nfs4_stateid_types_t sid_types;
3120 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3121 	int recov;
3122 
3123 	rp = VTOR4(vp);
3124 	mi = VTOMI4(vp);
3125 
3126 	ASSERT(nfs_zone() == mi->mi_zone);
3127 
3128 	stable = *stab_comm;
3129 	*stab_comm = FILE_SYNC4;
3130 
3131 	needrecov = FALSE;
3132 	recov_state.rs_flags = 0;
3133 	recov_state.rs_num_retry_despite_err = 0;
3134 	nfs4_init_stateid_types(&sid_types);
3135 
3136 	/* Is curthread the recovery thread? */
3137 	mutex_enter(&mi->mi_lock);
3138 	recov = (mi->mi_recovthread == curthread);
3139 	mutex_exit(&mi->mi_lock);
3140 
3141 recov_retry:
3142 	args.ctag = TAG_WRITE;
3143 	args.array_len = 2;
3144 	args.array = argop;
3145 
3146 	if (!recov) {
3147 		e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3148 		    &recov_state, NULL);
3149 		if (e.error)
3150 			return (e.error);
3151 	}
3152 
3153 	/* 0. putfh target fh */
3154 	argop[0].argop = OP_CPUTFH;
3155 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3156 
3157 	/* 1. write */
3158 	nfs4args_write(&argop[1], stable, rp, cr, &wargs, &sid_types);
3159 
3160 	do {
3161 
3162 		wargs->offset = (offset4)offset;
3163 		wargs->data_val = base;
3164 
3165 		if (mi->mi_io_kstats) {
3166 			mutex_enter(&mi->mi_lock);
3167 			kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
3168 			mutex_exit(&mi->mi_lock);
3169 		}
3170 
3171 		if ((vp->v_flag & VNOCACHE) ||
3172 		    (rp->r_flags & R4DIRECTIO) ||
3173 		    (mi->mi_flags & MI4_DIRECTIO))
3174 			tsize = MIN(mi->mi_stsize, count);
3175 		else
3176 			tsize = MIN(mi->mi_curwrite, count);
3177 		wargs->data_len = (uint_t)tsize;
3178 		rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
3179 
3180 		if (mi->mi_io_kstats) {
3181 			mutex_enter(&mi->mi_lock);
3182 			kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
3183 			mutex_exit(&mi->mi_lock);
3184 		}
3185 
3186 		if (!recov) {
3187 			needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
3188 			if (e.error && !needrecov) {
3189 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3190 				    &recov_state, needrecov);
3191 				return (e.error);
3192 			}
3193 
3194 
3195 			/*
3196 			 * Do handling of OLD_STATEID outside
3197 			 * of the normal recovery framework.
3198 			 *
3199 			 * If write receives a BAD stateid error while using a
3200 			 * delegation stateid, retry using the open stateid
3201 			 * (if it exists).  If it doesn't have an open stateid,
3202 			 * reopen the * file first, then retry.
3203 			 */
3204 			if (!e.error && res.status == NFS4ERR_OLD_STATEID &&
3205 			    sid_types.cur_sid_type != SPEC_SID) {
3206 				nfs4_save_stateid(&wargs->stateid, &sid_types);
3207 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3208 				    &recov_state, needrecov);
3209 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3210 				    (caddr_t)&res);
3211 				goto recov_retry;
3212 			} else if (e.error == 0 &&
3213 			    res.status == NFS4ERR_BAD_STATEID &&
3214 			    sid_types.cur_sid_type == DEL_SID) {
3215 				nfs4_save_stateid(&wargs->stateid, &sid_types);
3216 				mutex_enter(&rp->r_statev4_lock);
3217 				rp->r_deleg_return_pending = TRUE;
3218 				mutex_exit(&rp->r_statev4_lock);
3219 				if (nfs4rdwr_check_osid(vp, &e, cr)) {
3220 					nfs4_end_fop(mi, vp, NULL, OH_WRITE,
3221 					    &recov_state, needrecov);
3222 					(void) xdr_free(xdr_COMPOUND4res_clnt,
3223 					    (caddr_t)&res);
3224 					return (EIO);
3225 				}
3226 				nfs4_end_fop(mi, vp, NULL, OH_WRITE,
3227 				    &recov_state, needrecov);
3228 				/* hold needed for nfs4delegreturn_thread */
3229 				VN_HOLD(vp);
3230 				nfs4delegreturn_async(rp,
3231 				    (NFS4_DR_PUSH|NFS4_DR_REOPEN|
3232 				    NFS4_DR_DISCARD), FALSE);
3233 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3234 				    (caddr_t)&res);
3235 				goto recov_retry;
3236 			}
3237 
3238 			if (needrecov) {
3239 				bool_t abort;
3240 
3241 				NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
3242 				    "nfs4write: client got error %d, "
3243 				    "res.status %d, so start recovery",
3244 				    e.error, res.status));
3245 
3246 				abort = nfs4_start_recovery(&e,
3247 				    VTOMI4(vp), vp, NULL, &wargs->stateid,
3248 				    NULL, OP_WRITE, NULL);
3249 				if (!e.error) {
3250 					e.error = geterrno4(res.status);
3251 					(void) xdr_free(xdr_COMPOUND4res_clnt,
3252 					    (caddr_t)&res);
3253 				}
3254 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3255 				    &recov_state, needrecov);
3256 				if (abort == FALSE)
3257 					goto recov_retry;
3258 				return (e.error);
3259 			}
3260 
3261 			if (res.status) {
3262 				e.error = geterrno4(res.status);
3263 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3264 				    (caddr_t)&res);
3265 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3266 				    &recov_state, needrecov);
3267 				return (e.error);
3268 			}
3269 
3270 			resop = &res.array[1];	/* write res */
3271 			wres = &resop->nfs_resop4_u.opwrite;
3272 
3273 			if ((int)wres->count > tsize) {
3274 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3275 				    (caddr_t)&res);
3276 
3277 				zcmn_err(getzoneid(), CE_WARN,
3278 				    "nfs4write: server wrote %u, requested "
3279 				    "was %u", (int)wres->count, tsize);
3280 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3281 				    &recov_state, needrecov);
3282 				return (EIO);
3283 			}
3284 			if (wres->committed == UNSTABLE4) {
3285 				*stab_comm = UNSTABLE4;
3286 				if (wargs->stable == DATA_SYNC4 ||
3287 				    wargs->stable == FILE_SYNC4) {
3288 					(void) xdr_free(xdr_COMPOUND4res_clnt,
3289 					    (caddr_t)&res);
3290 					zcmn_err(getzoneid(), CE_WARN,
3291 					    "nfs4write: server %s did not "
3292 					    "commit to stable storage",
3293 					    rp->r_server->sv_hostname);
3294 					nfs4_end_fop(VTOMI4(vp), vp, NULL,
3295 					    OH_WRITE, &recov_state, needrecov);
3296 					return (EIO);
3297 				}
3298 			}
3299 		}
3300 
3301 		tsize = (int)wres->count;
3302 		count -= tsize;
3303 		base += tsize;
3304 		offset += tsize;
3305 		if (mi->mi_io_kstats) {
3306 			mutex_enter(&mi->mi_lock);
3307 			KSTAT_IO_PTR(mi->mi_io_kstats)->writes++;
3308 			KSTAT_IO_PTR(mi->mi_io_kstats)->nwritten +=
3309 			    tsize;
3310 			mutex_exit(&mi->mi_lock);
3311 		}
3312 		lwp_stat_update(LWP_STAT_OUBLK, 1);
3313 		mutex_enter(&rp->r_statelock);
3314 		if (rp->r_flags & R4HAVEVERF) {
3315 			if (rp->r_writeverf != wres->writeverf) {
3316 				nfs4_set_mod(vp);
3317 				rp->r_writeverf = wres->writeverf;
3318 			}
3319 		} else {
3320 			rp->r_writeverf = wres->writeverf;
3321 			rp->r_flags |= R4HAVEVERF;
3322 		}
3323 		PURGE_ATTRCACHE4_LOCKED(rp);
3324 		rp->r_flags |= R4WRITEMODIFIED;
3325 		gethrestime(&rp->r_attr.va_mtime);
3326 		rp->r_attr.va_ctime = rp->r_attr.va_mtime;
3327 		mutex_exit(&rp->r_statelock);
3328 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3329 	} while (count);
3330 
3331 	if (!recov)
3332 		nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE, &recov_state,
3333 		    needrecov);
3334 
3335 	return (e.error);
3336 }
3337 
3338 /*
3339  * Read from a file.  Reads data in largest chunks our interface can handle.
3340  */
3341 static int
3342 nfs4read(vnode_t *vp, caddr_t base, offset_t offset, int count,
3343     size_t *residp, cred_t *cr, bool_t async, struct uio *uiop)
3344 {
3345 	mntinfo4_t *mi;
3346 	COMPOUND4args_clnt args;
3347 	COMPOUND4res_clnt res;
3348 	READ4args *rargs;
3349 	nfs_argop4 argop[2];
3350 	int tsize;
3351 	int doqueue;
3352 	rnode4_t *rp;
3353 	int data_len;
3354 	bool_t is_eof;
3355 	bool_t needrecov = FALSE;
3356 	nfs4_recov_state_t recov_state;
3357 	nfs4_stateid_types_t sid_types;
3358 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3359 
3360 	rp = VTOR4(vp);
3361 	mi = VTOMI4(vp);
3362 	doqueue = 1;
3363 
3364 	ASSERT(nfs_zone() == mi->mi_zone);
3365 
3366 	args.ctag = async ? TAG_READAHEAD : TAG_READ;
3367 
3368 	args.array_len = 2;
3369 	args.array = argop;
3370 
3371 	nfs4_init_stateid_types(&sid_types);
3372 
3373 	recov_state.rs_flags = 0;
3374 	recov_state.rs_num_retry_despite_err = 0;
3375 
3376 recov_retry:
3377 	e.error = nfs4_start_fop(mi, vp, NULL, OH_READ,
3378 	    &recov_state, NULL);
3379 	if (e.error)
3380 		return (e.error);
3381 
3382 	/* putfh target fh */
3383 	argop[0].argop = OP_CPUTFH;
3384 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3385 
3386 	/* read */
3387 	argop[1].argop = OP_READ;
3388 	rargs = &argop[1].nfs_argop4_u.opread;
3389 	rargs->stateid = nfs4_get_stateid(cr, rp, curproc->p_pidp->pid_id, mi,
3390 	    OP_READ, &sid_types, async);
3391 
3392 	do {
3393 		if (mi->mi_io_kstats) {
3394 			mutex_enter(&mi->mi_lock);
3395 			kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
3396 			mutex_exit(&mi->mi_lock);
3397 		}
3398 
3399 		NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
3400 		    "nfs4read: %s call, rp %s",
3401 		    needrecov ? "recov" : "first",
3402 		    rnode4info(rp)));
3403 
3404 		if ((vp->v_flag & VNOCACHE) ||
3405 		    (rp->r_flags & R4DIRECTIO) ||
3406 		    (mi->mi_flags & MI4_DIRECTIO))
3407 			tsize = MIN(mi->mi_tsize, count);
3408 		else
3409 			tsize = MIN(mi->mi_curread, count);
3410 		rargs->offset = (offset4)offset;
3411 		rargs->count = (count4)tsize;
3412 		rargs->res_data_val_alt = NULL;
3413 		rargs->res_mblk = NULL;
3414 		rargs->res_uiop = NULL;
3415 		rargs->res_maxsize = 0;
3416 		if (uiop)
3417 			rargs->res_uiop = uiop;
3418 		else
3419 			rargs->res_data_val_alt = base;
3420 		rargs->res_maxsize = tsize;
3421 
3422 		rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
3423 #ifdef	DEBUG
3424 		if (nfs4read_error_inject) {
3425 			res.status = nfs4read_error_inject;
3426 			nfs4read_error_inject = 0;
3427 		}
3428 #endif
3429 
3430 		if (mi->mi_io_kstats) {
3431 			mutex_enter(&mi->mi_lock);
3432 			kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
3433 			mutex_exit(&mi->mi_lock);
3434 		}
3435 
3436 		needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
3437 		if (e.error != 0 && !needrecov) {
3438 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3439 			    &recov_state, needrecov);
3440 			return (e.error);
3441 		}
3442 
3443 		/*
3444 		 * Do proper retry for OLD and BAD stateid errors outside
3445 		 * of the normal recovery framework.  There are two differences
3446 		 * between async and sync reads.  The first is that we allow
3447 		 * retry on BAD_STATEID for async reads, but not sync reads.
3448 		 * The second is that we mark the file dead for a failed
3449 		 * attempt with a special stateid for sync reads, but just
3450 		 * return EIO for async reads.
3451 		 *
3452 		 * If a sync read receives a BAD stateid error while using a
3453 		 * delegation stateid, retry using the open stateid (if it
3454 		 * exists).  If it doesn't have an open stateid, reopen the
3455 		 * file first, then retry.
3456 		 */
3457 		if (e.error == 0 && (res.status == NFS4ERR_OLD_STATEID ||
3458 		    res.status == NFS4ERR_BAD_STATEID) && async) {
3459 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3460 			    &recov_state, needrecov);
3461 			if (sid_types.cur_sid_type == SPEC_SID) {
3462 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3463 				    (caddr_t)&res);
3464 				return (EIO);
3465 			}
3466 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3467 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3468 			goto recov_retry;
3469 		} else if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3470 		    !async && sid_types.cur_sid_type != SPEC_SID) {
3471 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3472 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3473 			    &recov_state, needrecov);
3474 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3475 			goto recov_retry;
3476 		} else if (e.error == 0 && res.status == NFS4ERR_BAD_STATEID &&
3477 		    sid_types.cur_sid_type == DEL_SID) {
3478 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3479 			mutex_enter(&rp->r_statev4_lock);
3480 			rp->r_deleg_return_pending = TRUE;
3481 			mutex_exit(&rp->r_statev4_lock);
3482 			if (nfs4rdwr_check_osid(vp, &e, cr)) {
3483 				nfs4_end_fop(mi, vp, NULL, OH_READ,
3484 				    &recov_state, needrecov);
3485 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3486 				    (caddr_t)&res);
3487 				return (EIO);
3488 			}
3489 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3490 			    &recov_state, needrecov);
3491 			/* hold needed for nfs4delegreturn_thread */
3492 			VN_HOLD(vp);
3493 			nfs4delegreturn_async(rp, (NFS4_DR_PUSH|NFS4_DR_REOPEN|
3494 			    NFS4_DR_DISCARD), FALSE);
3495 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3496 			goto recov_retry;
3497 		}
3498 		if (needrecov) {
3499 			bool_t abort;
3500 
3501 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
3502 			    "nfs4read: initiating recovery\n"));
3503 
3504 			abort = nfs4_start_recovery(&e,
3505 			    mi, vp, NULL, &rargs->stateid,
3506 			    NULL, OP_READ, NULL);
3507 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3508 			    &recov_state, needrecov);
3509 			/*
3510 			 * Do not retry if we got OLD_STATEID using a special
3511 			 * stateid.  This avoids looping with a broken server.
3512 			 */
3513 			if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3514 			    sid_types.cur_sid_type == SPEC_SID)
3515 				abort = TRUE;
3516 
3517 			if (abort == FALSE) {
3518 				/*
3519 				 * Need to retry all possible stateids in
3520 				 * case the recovery error wasn't stateid
3521 				 * related or the stateids have become
3522 				 * stale (server reboot).
3523 				 */
3524 				nfs4_init_stateid_types(&sid_types);
3525 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3526 				    (caddr_t)&res);
3527 				goto recov_retry;
3528 			}
3529 
3530 			if (!e.error) {
3531 				e.error = geterrno4(res.status);
3532 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3533 				    (caddr_t)&res);
3534 			}
3535 			return (e.error);
3536 		}
3537 
3538 		if (res.status) {
3539 			e.error = geterrno4(res.status);
3540 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3541 			    &recov_state, needrecov);
3542 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3543 			return (e.error);
3544 		}
3545 
3546 		data_len = res.array[1].nfs_resop4_u.opread.data_len;
3547 		count -= data_len;
3548 		if (base)
3549 			base += data_len;
3550 		offset += data_len;
3551 		if (mi->mi_io_kstats) {
3552 			mutex_enter(&mi->mi_lock);
3553 			KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
3554 			KSTAT_IO_PTR(mi->mi_io_kstats)->nread += data_len;
3555 			mutex_exit(&mi->mi_lock);
3556 		}
3557 		lwp_stat_update(LWP_STAT_INBLK, 1);
3558 		is_eof = res.array[1].nfs_resop4_u.opread.eof;
3559 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3560 
3561 	} while (count && !is_eof);
3562 
3563 	*residp = count;
3564 
3565 	nfs4_end_fop(mi, vp, NULL, OH_READ, &recov_state, needrecov);
3566 
3567 	return (e.error);
3568 }
3569 
3570 /* ARGSUSED */
3571 static int
3572 nfs4_ioctl(vnode_t *vp, int cmd, intptr_t arg, int flag, cred_t *cr, int *rvalp,
3573 	caller_context_t *ct)
3574 {
3575 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3576 		return (EIO);
3577 	switch (cmd) {
3578 		case _FIODIRECTIO:
3579 			return (nfs4_directio(vp, (int)arg, cr));
3580 		default:
3581 			return (ENOTTY);
3582 	}
3583 }
3584 
3585 /* ARGSUSED */
3586 int
3587 nfs4_getattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3588     caller_context_t *ct)
3589 {
3590 	int error;
3591 	rnode4_t *rp = VTOR4(vp);
3592 
3593 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3594 		return (EIO);
3595 	/*
3596 	 * If it has been specified that the return value will
3597 	 * just be used as a hint, and we are only being asked
3598 	 * for size, fsid or rdevid, then return the client's
3599 	 * notion of these values without checking to make sure
3600 	 * that the attribute cache is up to date.
3601 	 * The whole point is to avoid an over the wire GETATTR
3602 	 * call.
3603 	 */
3604 	if (flags & ATTR_HINT) {
3605 		if (vap->va_mask ==
3606 		    (vap->va_mask & (AT_SIZE | AT_FSID | AT_RDEV))) {
3607 			mutex_enter(&rp->r_statelock);
3608 			if (vap->va_mask | AT_SIZE)
3609 				vap->va_size = rp->r_size;
3610 			if (vap->va_mask | AT_FSID)
3611 				vap->va_fsid = rp->r_attr.va_fsid;
3612 			if (vap->va_mask | AT_RDEV)
3613 				vap->va_rdev = rp->r_attr.va_rdev;
3614 			mutex_exit(&rp->r_statelock);
3615 			return (0);
3616 		}
3617 	}
3618 
3619 	/*
3620 	 * Only need to flush pages if asking for the mtime
3621 	 * and if there any dirty pages or any outstanding
3622 	 * asynchronous (write) requests for this file.
3623 	 */
3624 	if (vap->va_mask & AT_MTIME) {
3625 		rp = VTOR4(vp);
3626 		if (nfs4_has_pages(vp)) {
3627 			mutex_enter(&rp->r_statev4_lock);
3628 			if (rp->r_deleg_type != OPEN_DELEGATE_WRITE) {
3629 				mutex_exit(&rp->r_statev4_lock);
3630 				if (rp->r_flags & R4DIRTY ||
3631 				    rp->r_awcount > 0) {
3632 					mutex_enter(&rp->r_statelock);
3633 					rp->r_gcount++;
3634 					mutex_exit(&rp->r_statelock);
3635 					error =
3636 					    nfs4_putpage(vp, (u_offset_t)0,
3637 					    0, 0, cr, NULL);
3638 					mutex_enter(&rp->r_statelock);
3639 					if (error && (error == ENOSPC ||
3640 					    error == EDQUOT)) {
3641 						if (!rp->r_error)
3642 							rp->r_error = error;
3643 					}
3644 					if (--rp->r_gcount == 0)
3645 						cv_broadcast(&rp->r_cv);
3646 					mutex_exit(&rp->r_statelock);
3647 				}
3648 			} else {
3649 				mutex_exit(&rp->r_statev4_lock);
3650 			}
3651 		}
3652 	}
3653 	return (nfs4getattr(vp, vap, cr));
3654 }
3655 
3656 int
3657 nfs4_compare_modes(mode_t from_server, mode_t on_client)
3658 {
3659 	/*
3660 	 * If these are the only two bits cleared
3661 	 * on the server then return 0 (OK) else
3662 	 * return 1 (BAD).
3663 	 */
3664 	on_client &= ~(S_ISUID|S_ISGID);
3665 	if (on_client == from_server)
3666 		return (0);
3667 	else
3668 		return (1);
3669 }
3670 
3671 /*ARGSUSED4*/
3672 static int
3673 nfs4_setattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3674     caller_context_t *ct)
3675 {
3676 	if (vap->va_mask & AT_NOSET)
3677 		return (EINVAL);
3678 
3679 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3680 		return (EIO);
3681 
3682 	/*
3683 	 * Don't call secpolicy_vnode_setattr, the client cannot
3684 	 * use its cached attributes to make security decisions
3685 	 * as the server may be faking mode bits or mapping uid/gid.
3686 	 * Always just let the server to the checking.
3687 	 * If we provide the ability to remove basic priviledges
3688 	 * to setattr (e.g. basic without chmod) then we will
3689 	 * need to add a check here before calling the server.
3690 	 */
3691 
3692 	return (nfs4setattr(vp, vap, flags, cr, NULL));
3693 }
3694 
3695 /*
3696  * To replace the "guarded" version 3 setattr, we use two types of compound
3697  * setattr requests:
3698  * 1. The "normal" setattr, used when the size of the file isn't being
3699  *    changed - { Putfh <fh>; Setattr; Getattr }/
3700  * 2. If the size is changed, precede Setattr with: Getattr; Verify
3701  *    with only ctime as the argument. If the server ctime differs from
3702  *    what is cached on the client, the verify will fail, but we would
3703  *    already have the ctime from the preceding getattr, so just set it
3704  *    and retry. Thus the compound here is - { Putfh <fh>; Getattr; Verify;
3705  *	Setattr; Getattr }.
3706  *
3707  * The vsecattr_t * input parameter will be non-NULL if ACLs are being set in
3708  * this setattr and NULL if they are not.
3709  */
3710 static int
3711 nfs4setattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3712     vsecattr_t *vsap)
3713 {
3714 	COMPOUND4args_clnt args;
3715 	COMPOUND4res_clnt res, *resp = NULL;
3716 	nfs4_ga_res_t *garp = NULL;
3717 	int numops = 3;			/* { Putfh; Setattr; Getattr } */
3718 	nfs_argop4 argop[5];
3719 	int verify_argop = -1;
3720 	int setattr_argop = 1;
3721 	nfs_resop4 *resop;
3722 	vattr_t va;
3723 	rnode4_t *rp;
3724 	int doqueue = 1;
3725 	uint_t mask = vap->va_mask;
3726 	mode_t omode;
3727 	vsecattr_t *vsp;
3728 	timestruc_t ctime;
3729 	bool_t needrecov = FALSE;
3730 	nfs4_recov_state_t recov_state;
3731 	nfs4_stateid_types_t sid_types;
3732 	stateid4 stateid;
3733 	hrtime_t t;
3734 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3735 	servinfo4_t *svp;
3736 	bitmap4 supp_attrs;
3737 
3738 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
3739 	rp = VTOR4(vp);
3740 	nfs4_init_stateid_types(&sid_types);
3741 
3742 	/*
3743 	 * Only need to flush pages if there are any pages and
3744 	 * if the file is marked as dirty in some fashion.  The
3745 	 * file must be flushed so that we can accurately
3746 	 * determine the size of the file and the cached data
3747 	 * after the SETATTR returns.  A file is considered to
3748 	 * be dirty if it is either marked with R4DIRTY, has
3749 	 * outstanding i/o's active, or is mmap'd.  In this
3750 	 * last case, we can't tell whether there are dirty
3751 	 * pages, so we flush just to be sure.
3752 	 */
3753 	if (nfs4_has_pages(vp) &&
3754 	    ((rp->r_flags & R4DIRTY) ||
3755 	    rp->r_count > 0 ||
3756 	    rp->r_mapcnt > 0)) {
3757 		ASSERT(vp->v_type != VCHR);
3758 		e.error = nfs4_putpage(vp, (offset_t)0, 0, 0, cr, NULL);
3759 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
3760 			mutex_enter(&rp->r_statelock);
3761 			if (!rp->r_error)
3762 				rp->r_error = e.error;
3763 			mutex_exit(&rp->r_statelock);
3764 		}
3765 	}
3766 
3767 	if (mask & AT_SIZE) {
3768 		/*
3769 		 * Verification setattr compound for non-deleg AT_SIZE:
3770 		 *	{ Putfh; Getattr; Verify; Setattr; Getattr }
3771 		 * Set ctime local here (outside the do_again label)
3772 		 * so that subsequent retries (after failed VERIFY)
3773 		 * will use ctime from GETATTR results (from failed
3774 		 * verify compound) as VERIFY arg.
3775 		 * If file has delegation, then VERIFY(time_metadata)
3776 		 * is of little added value, so don't bother.
3777 		 */
3778 		mutex_enter(&rp->r_statev4_lock);
3779 		if (rp->r_deleg_type == OPEN_DELEGATE_NONE ||
3780 		    rp->r_deleg_return_pending) {
3781 			numops = 5;
3782 			ctime = rp->r_attr.va_ctime;
3783 		}
3784 		mutex_exit(&rp->r_statev4_lock);
3785 	}
3786 
3787 	recov_state.rs_flags = 0;
3788 	recov_state.rs_num_retry_despite_err = 0;
3789 
3790 	args.ctag = TAG_SETATTR;
3791 do_again:
3792 recov_retry:
3793 	setattr_argop = numops - 2;
3794 
3795 	args.array = argop;
3796 	args.array_len = numops;
3797 
3798 	e.error = nfs4_start_op(VTOMI4(vp), vp, NULL, &recov_state);
3799 	if (e.error)
3800 		return (e.error);
3801 
3802 
3803 	/* putfh target fh */
3804 	argop[0].argop = OP_CPUTFH;
3805 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3806 
3807 	if (numops == 5) {
3808 		/*
3809 		 * We only care about the ctime, but need to get mtime
3810 		 * and size for proper cache update.
3811 		 */
3812 		/* getattr */
3813 		argop[1].argop = OP_GETATTR;
3814 		argop[1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
3815 		argop[1].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
3816 
3817 		/* verify - set later in loop */
3818 		verify_argop = 2;
3819 	}
3820 
3821 	/* setattr */
3822 	svp = rp->r_server;
3823 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
3824 	supp_attrs = svp->sv_supp_attrs;
3825 	nfs_rw_exit(&svp->sv_lock);
3826 
3827 	nfs4args_setattr(&argop[setattr_argop], vap, vsap, flags, rp, cr,
3828 	    supp_attrs, &e.error, &sid_types);
3829 	stateid = argop[setattr_argop].nfs_argop4_u.opsetattr.stateid;
3830 	if (e.error) {
3831 		/* req time field(s) overflow - return immediately */
3832 		nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
3833 		nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3834 		    opsetattr.obj_attributes);
3835 		return (e.error);
3836 	}
3837 	omode = rp->r_attr.va_mode;
3838 
3839 	/* getattr */
3840 	argop[numops-1].argop = OP_GETATTR;
3841 	argop[numops-1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
3842 	/*
3843 	 * If we are setting the ACL (indicated only by vsap != NULL), request
3844 	 * the ACL in this getattr.  The ACL returned from this getattr will be
3845 	 * used in updating the ACL cache.
3846 	 */
3847 	if (vsap != NULL)
3848 		argop[numops-1].nfs_argop4_u.opgetattr.attr_request |=
3849 		    FATTR4_ACL_MASK;
3850 	argop[numops-1].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
3851 
3852 	/*
3853 	 * setattr iterates if the object size is set and the cached ctime
3854 	 * does not match the file ctime. In that case, verify the ctime first.
3855 	 */
3856 
3857 	do {
3858 		if (verify_argop != -1) {
3859 			/*
3860 			 * Verify that the ctime match before doing setattr.
3861 			 */
3862 			va.va_mask = AT_CTIME;
3863 			va.va_ctime = ctime;
3864 			svp = rp->r_server;
3865 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
3866 			supp_attrs = svp->sv_supp_attrs;
3867 			nfs_rw_exit(&svp->sv_lock);
3868 			e.error = nfs4args_verify(&argop[verify_argop], &va,
3869 			    OP_VERIFY, supp_attrs);
3870 			if (e.error) {
3871 				/* req time field(s) overflow - return */
3872 				nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3873 				    needrecov);
3874 				break;
3875 			}
3876 		}
3877 
3878 		doqueue = 1;
3879 
3880 		t = gethrtime();
3881 
3882 		rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, &e);
3883 
3884 		/*
3885 		 * Purge the access cache and ACL cache if changing either the
3886 		 * owner of the file, the group owner, or the mode.  These may
3887 		 * change the access permissions of the file, so purge old
3888 		 * information and start over again.
3889 		 */
3890 		if (mask & (AT_UID | AT_GID | AT_MODE)) {
3891 			(void) nfs4_access_purge_rp(rp);
3892 			if (rp->r_secattr != NULL) {
3893 				mutex_enter(&rp->r_statelock);
3894 				vsp = rp->r_secattr;
3895 				rp->r_secattr = NULL;
3896 				mutex_exit(&rp->r_statelock);
3897 				if (vsp != NULL)
3898 					nfs4_acl_free_cache(vsp);
3899 			}
3900 		}
3901 
3902 		/*
3903 		 * If res.array_len == numops, then everything succeeded,
3904 		 * except for possibly the final getattr.  If only the
3905 		 * last getattr failed, give up, and don't try recovery.
3906 		 */
3907 		if (res.array_len == numops) {
3908 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3909 			    needrecov);
3910 			if (! e.error)
3911 				resp = &res;
3912 			break;
3913 		}
3914 
3915 		/*
3916 		 * if either rpc call failed or completely succeeded - done
3917 		 */
3918 		needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
3919 		if (e.error) {
3920 			PURGE_ATTRCACHE4(vp);
3921 			if (!needrecov) {
3922 				nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3923 				    needrecov);
3924 				break;
3925 			}
3926 		}
3927 
3928 		/*
3929 		 * Do proper retry for OLD_STATEID outside of the normal
3930 		 * recovery framework.
3931 		 */
3932 		if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3933 		    sid_types.cur_sid_type != SPEC_SID &&
3934 		    sid_types.cur_sid_type != NO_SID) {
3935 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3936 			    needrecov);
3937 			nfs4_save_stateid(&stateid, &sid_types);
3938 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3939 			    opsetattr.obj_attributes);
3940 			if (verify_argop != -1) {
3941 				nfs4args_verify_free(&argop[verify_argop]);
3942 				verify_argop = -1;
3943 			}
3944 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3945 			goto recov_retry;
3946 		}
3947 
3948 		if (needrecov) {
3949 			bool_t abort;
3950 
3951 			abort = nfs4_start_recovery(&e,
3952 			    VTOMI4(vp), vp, NULL, NULL, NULL,
3953 			    OP_SETATTR, NULL);
3954 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3955 			    needrecov);
3956 			/*
3957 			 * Do not retry if we failed with OLD_STATEID using
3958 			 * a special stateid.  This is done to avoid looping
3959 			 * with a broken server.
3960 			 */
3961 			if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3962 			    (sid_types.cur_sid_type == SPEC_SID ||
3963 			    sid_types.cur_sid_type == NO_SID))
3964 				abort = TRUE;
3965 			if (!e.error) {
3966 				if (res.status == NFS4ERR_BADOWNER)
3967 					nfs4_log_badowner(VTOMI4(vp),
3968 					    OP_SETATTR);
3969 
3970 				e.error = geterrno4(res.status);
3971 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3972 				    (caddr_t)&res);
3973 			}
3974 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3975 			    opsetattr.obj_attributes);
3976 			if (verify_argop != -1) {
3977 				nfs4args_verify_free(&argop[verify_argop]);
3978 				verify_argop = -1;
3979 			}
3980 			if (abort == FALSE) {
3981 				/*
3982 				 * Need to retry all possible stateids in
3983 				 * case the recovery error wasn't stateid
3984 				 * related or the stateids have become
3985 				 * stale (server reboot).
3986 				 */
3987 				nfs4_init_stateid_types(&sid_types);
3988 				goto recov_retry;
3989 			}
3990 			return (e.error);
3991 		}
3992 
3993 		/*
3994 		 * Need to call nfs4_end_op before nfs4getattr to
3995 		 * avoid potential nfs4_start_op deadlock. See RFE
3996 		 * 4777612.  Calls to nfs4_invalidate_pages() and
3997 		 * nfs4_purge_stale_fh() might also generate over the
3998 		 * wire calls which my cause nfs4_start_op() deadlock.
3999 		 */
4000 		nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
4001 
4002 		/*
4003 		 * Check to update lease.
4004 		 */
4005 		resp = &res;
4006 		if (res.status == NFS4_OK) {
4007 			break;
4008 		}
4009 
4010 		/*
4011 		 * Check if verify failed to see if try again
4012 		 */
4013 		if ((verify_argop == -1) || (res.array_len != 3)) {
4014 			/*
4015 			 * can't continue...
4016 			 */
4017 			if (res.status == NFS4ERR_BADOWNER)
4018 				nfs4_log_badowner(VTOMI4(vp), OP_SETATTR);
4019 
4020 			e.error = geterrno4(res.status);
4021 		} else {
4022 			/*
4023 			 * When the verify request fails, the client ctime is
4024 			 * not in sync with the server. This is the same as
4025 			 * the version 3 "not synchronized" error, and we
4026 			 * handle it in a similar manner (XXX do we need to???).
4027 			 * Use the ctime returned in the first getattr for
4028 			 * the input to the next verify.
4029 			 * If we couldn't get the attributes, then we give up
4030 			 * because we can't complete the operation as required.
4031 			 */
4032 			garp = &res.array[1].nfs_resop4_u.opgetattr.ga_res;
4033 		}
4034 		if (e.error) {
4035 			PURGE_ATTRCACHE4(vp);
4036 			nfs4_purge_stale_fh(e.error, vp, cr);
4037 		} else {
4038 			/*
4039 			 * retry with a new verify value
4040 			 */
4041 			ctime = garp->n4g_va.va_ctime;
4042 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4043 			resp = NULL;
4044 		}
4045 		if (!e.error) {
4046 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4047 			    opsetattr.obj_attributes);
4048 			if (verify_argop != -1) {
4049 				nfs4args_verify_free(&argop[verify_argop]);
4050 				verify_argop = -1;
4051 			}
4052 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4053 			goto do_again;
4054 		}
4055 	} while (!e.error);
4056 
4057 	if (e.error) {
4058 		/*
4059 		 * If we are here, rfs4call has an irrecoverable error - return
4060 		 */
4061 		nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4062 		    opsetattr.obj_attributes);
4063 		if (verify_argop != -1) {
4064 			nfs4args_verify_free(&argop[verify_argop]);
4065 			verify_argop = -1;
4066 		}
4067 		if (resp)
4068 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
4069 		return (e.error);
4070 	}
4071 
4072 
4073 
4074 	/*
4075 	 * If changing the size of the file, invalidate
4076 	 * any local cached data which is no longer part
4077 	 * of the file.  We also possibly invalidate the
4078 	 * last page in the file.  We could use
4079 	 * pvn_vpzero(), but this would mark the page as
4080 	 * modified and require it to be written back to
4081 	 * the server for no particularly good reason.
4082 	 * This way, if we access it, then we bring it
4083 	 * back in.  A read should be cheaper than a
4084 	 * write.
4085 	 */
4086 	if (mask & AT_SIZE) {
4087 		nfs4_invalidate_pages(vp, (vap->va_size & PAGEMASK), cr);
4088 	}
4089 
4090 	/* either no error or one of the postop getattr failed */
4091 
4092 	/*
4093 	 * XXX Perform a simplified version of wcc checking. Instead of
4094 	 * have another getattr to get pre-op, just purge cache if
4095 	 * any of the ops prior to and including the getattr failed.
4096 	 * If the getattr succeeded then update the attrcache accordingly.
4097 	 */
4098 
4099 	garp = NULL;
4100 	if (res.status == NFS4_OK) {
4101 		/*
4102 		 * Last getattr
4103 		 */
4104 		resop = &res.array[numops - 1];
4105 		garp = &resop->nfs_resop4_u.opgetattr.ga_res;
4106 	}
4107 	/*
4108 	 * In certain cases, nfs4_update_attrcache() will purge the attrcache,
4109 	 * rather than filling it.  See the function itself for details.
4110 	 */
4111 	e.error = nfs4_update_attrcache(res.status, garp, t, vp, cr);
4112 	if (garp != NULL) {
4113 		if (garp->n4g_resbmap & FATTR4_ACL_MASK) {
4114 			nfs4_acl_fill_cache(rp, &garp->n4g_vsa);
4115 			vs_ace4_destroy(&garp->n4g_vsa);
4116 		} else {
4117 			if (vsap != NULL) {
4118 				/*
4119 				 * The ACL was supposed to be set and to be
4120 				 * returned in the last getattr of this
4121 				 * compound, but for some reason the getattr
4122 				 * result doesn't contain the ACL.  In this
4123 				 * case, purge the ACL cache.
4124 				 */
4125 				if (rp->r_secattr != NULL) {
4126 					mutex_enter(&rp->r_statelock);
4127 					vsp = rp->r_secattr;
4128 					rp->r_secattr = NULL;
4129 					mutex_exit(&rp->r_statelock);
4130 					if (vsp != NULL)
4131 						nfs4_acl_free_cache(vsp);
4132 				}
4133 			}
4134 		}
4135 	}
4136 
4137 	if (res.status == NFS4_OK && (mask & AT_SIZE)) {
4138 		/*
4139 		 * Set the size, rather than relying on getting it updated
4140 		 * via a GETATTR.  With delegations the client tries to
4141 		 * suppress GETATTR calls.
4142 		 */
4143 		mutex_enter(&rp->r_statelock);
4144 		rp->r_size = vap->va_size;
4145 		mutex_exit(&rp->r_statelock);
4146 	}
4147 
4148 	/*
4149 	 * Can free up request args and res
4150 	 */
4151 	nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4152 	    opsetattr.obj_attributes);
4153 	if (verify_argop != -1) {
4154 		nfs4args_verify_free(&argop[verify_argop]);
4155 		verify_argop = -1;
4156 	}
4157 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4158 
4159 	/*
4160 	 * Some servers will change the mode to clear the setuid
4161 	 * and setgid bits when changing the uid or gid.  The
4162 	 * client needs to compensate appropriately.
4163 	 */
4164 	if (mask & (AT_UID | AT_GID)) {
4165 		int terror, do_setattr;
4166 
4167 		do_setattr = 0;
4168 		va.va_mask = AT_MODE;
4169 		terror = nfs4getattr(vp, &va, cr);
4170 		if (!terror &&
4171 		    (((mask & AT_MODE) && va.va_mode != vap->va_mode) ||
4172 		    (!(mask & AT_MODE) && va.va_mode != omode))) {
4173 			va.va_mask = AT_MODE;
4174 			if (mask & AT_MODE) {
4175 				/*
4176 				 * We asked the mode to be changed and what
4177 				 * we just got from the server in getattr is
4178 				 * not what we wanted it to be, so set it now.
4179 				 */
4180 				va.va_mode = vap->va_mode;
4181 				do_setattr = 1;
4182 			} else {
4183 				/*
4184 				 * We did not ask the mode to be changed,
4185 				 * Check to see that the server just cleared
4186 				 * I_SUID and I_GUID from it. If not then
4187 				 * set mode to omode with UID/GID cleared.
4188 				 */
4189 				if (nfs4_compare_modes(va.va_mode, omode)) {
4190 					omode &= ~(S_ISUID|S_ISGID);
4191 					va.va_mode = omode;
4192 					do_setattr = 1;
4193 				}
4194 			}
4195 
4196 			if (do_setattr)
4197 				(void) nfs4setattr(vp, &va, 0, cr, NULL);
4198 		}
4199 	}
4200 
4201 	return (e.error);
4202 }
4203 
4204 /* ARGSUSED */
4205 static int
4206 nfs4_access(vnode_t *vp, int mode, int flags, cred_t *cr, caller_context_t *ct)
4207 {
4208 	COMPOUND4args_clnt args;
4209 	COMPOUND4res_clnt res;
4210 	int doqueue;
4211 	uint32_t acc, resacc, argacc;
4212 	rnode4_t *rp;
4213 	cred_t *cred, *ncr, *ncrfree = NULL;
4214 	nfs4_access_type_t cacc;
4215 	int num_ops;
4216 	nfs_argop4 argop[3];
4217 	nfs_resop4 *resop;
4218 	bool_t needrecov = FALSE, do_getattr;
4219 	nfs4_recov_state_t recov_state;
4220 	int rpc_error;
4221 	hrtime_t t;
4222 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4223 	mntinfo4_t *mi = VTOMI4(vp);
4224 
4225 	if (nfs_zone() != mi->mi_zone)
4226 		return (EIO);
4227 
4228 	acc = 0;
4229 	if (mode & VREAD)
4230 		acc |= ACCESS4_READ;
4231 	if (mode & VWRITE) {
4232 		if ((vp->v_vfsp->vfs_flag & VFS_RDONLY) && !ISVDEV(vp->v_type))
4233 			return (EROFS);
4234 		if (vp->v_type == VDIR)
4235 			acc |= ACCESS4_DELETE;
4236 		acc |= ACCESS4_MODIFY | ACCESS4_EXTEND;
4237 	}
4238 	if (mode & VEXEC) {
4239 		if (vp->v_type == VDIR)
4240 			acc |= ACCESS4_LOOKUP;
4241 		else
4242 			acc |= ACCESS4_EXECUTE;
4243 	}
4244 
4245 	if (VTOR4(vp)->r_acache != NULL) {
4246 		e.error = nfs4_validate_caches(vp, cr);
4247 		if (e.error)
4248 			return (e.error);
4249 	}
4250 
4251 	rp = VTOR4(vp);
4252 	if (vp->v_type == VDIR)
4253 		argacc = ACCESS4_READ | ACCESS4_DELETE | ACCESS4_MODIFY |
4254 		    ACCESS4_EXTEND | ACCESS4_LOOKUP;
4255 	else
4256 		argacc = ACCESS4_READ | ACCESS4_MODIFY | ACCESS4_EXTEND |
4257 		    ACCESS4_EXECUTE;
4258 	recov_state.rs_flags = 0;
4259 	recov_state.rs_num_retry_despite_err = 0;
4260 
4261 	cred = cr;
4262 	/*
4263 	 * ncr and ncrfree both initially
4264 	 * point to the memory area returned
4265 	 * by crnetadjust();
4266 	 * ncrfree not NULL when exiting means
4267 	 * that we need to release it
4268 	 */
4269 	ncr = crnetadjust(cred);
4270 	ncrfree = ncr;
4271 
4272 tryagain:
4273 	cacc = nfs4_access_check(rp, acc, cred);
4274 	if (cacc == NFS4_ACCESS_ALLOWED) {
4275 		if (ncrfree != NULL)
4276 			crfree(ncrfree);
4277 		return (0);
4278 	}
4279 	if (cacc == NFS4_ACCESS_DENIED) {
4280 		/*
4281 		 * If the cred can be adjusted, try again
4282 		 * with the new cred.
4283 		 */
4284 		if (ncr != NULL) {
4285 			cred = ncr;
4286 			ncr = NULL;
4287 			goto tryagain;
4288 		}
4289 		if (ncrfree != NULL)
4290 			crfree(ncrfree);
4291 		return (EACCES);
4292 	}
4293 
4294 recov_retry:
4295 	/*
4296 	 * Don't take with r_statev4_lock here. r_deleg_type could
4297 	 * change as soon as lock is released.  Since it is an int,
4298 	 * there is no atomicity issue.
4299 	 */
4300 	do_getattr = (rp->r_deleg_type == OPEN_DELEGATE_NONE);
4301 	num_ops = do_getattr ? 3 : 2;
4302 
4303 	args.ctag = TAG_ACCESS;
4304 
4305 	args.array_len = num_ops;
4306 	args.array = argop;
4307 
4308 	if (e.error = nfs4_start_fop(mi, vp, NULL, OH_ACCESS,
4309 	    &recov_state, NULL)) {
4310 		if (ncrfree != NULL)
4311 			crfree(ncrfree);
4312 		return (e.error);
4313 	}
4314 
4315 	/* putfh target fh */
4316 	argop[0].argop = OP_CPUTFH;
4317 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4318 
4319 	/* access */
4320 	argop[1].argop = OP_ACCESS;
4321 	argop[1].nfs_argop4_u.opaccess.access = argacc;
4322 
4323 	/* getattr */
4324 	if (do_getattr) {
4325 		argop[2].argop = OP_GETATTR;
4326 		argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4327 		argop[2].nfs_argop4_u.opgetattr.mi = mi;
4328 	}
4329 
4330 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4331 	    "nfs4_access: %s call, rp %s", needrecov ? "recov" : "first",
4332 	    rnode4info(VTOR4(vp))));
4333 
4334 	doqueue = 1;
4335 	t = gethrtime();
4336 	rfs4call(VTOMI4(vp), &args, &res, cred, &doqueue, 0, &e);
4337 	rpc_error = e.error;
4338 
4339 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4340 	if (needrecov) {
4341 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4342 		    "nfs4_access: initiating recovery\n"));
4343 
4344 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4345 		    NULL, OP_ACCESS, NULL) == FALSE) {
4346 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_ACCESS,
4347 			    &recov_state, needrecov);
4348 			if (!e.error)
4349 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4350 				    (caddr_t)&res);
4351 			goto recov_retry;
4352 		}
4353 	}
4354 	nfs4_end_fop(mi, vp, NULL, OH_ACCESS, &recov_state, needrecov);
4355 
4356 	if (e.error)
4357 		goto out;
4358 
4359 	if (res.status) {
4360 		e.error = geterrno4(res.status);
4361 		/*
4362 		 * This might generate over the wire calls throught
4363 		 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
4364 		 * here to avoid a deadlock.
4365 		 */
4366 		nfs4_purge_stale_fh(e.error, vp, cr);
4367 		goto out;
4368 	}
4369 	resop = &res.array[1];	/* access res */
4370 
4371 	resacc = resop->nfs_resop4_u.opaccess.access;
4372 
4373 	if (do_getattr) {
4374 		resop++;	/* getattr res */
4375 		nfs4_attr_cache(vp, &resop->nfs_resop4_u.opgetattr.ga_res,
4376 		    t, cr, FALSE, NULL);
4377 	}
4378 
4379 	if (!e.error) {
4380 		nfs4_access_cache(rp, argacc, resacc, cred);
4381 		/*
4382 		 * we just cached results with cred; if cred is the
4383 		 * adjusted credentials from crnetadjust, we do not want
4384 		 * to release them before exiting: hence setting ncrfree
4385 		 * to NULL
4386 		 */
4387 		if (cred != cr)
4388 			ncrfree = NULL;
4389 		/* XXX check the supported bits too? */
4390 		if ((acc & resacc) != acc) {
4391 			/*
4392 			 * The following code implements the semantic
4393 			 * that a setuid root program has *at least* the
4394 			 * permissions of the user that is running the
4395 			 * program.  See rfs3call() for more portions
4396 			 * of the implementation of this functionality.
4397 			 */
4398 			/* XXX-LP */
4399 			if (ncr != NULL) {
4400 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4401 				    (caddr_t)&res);
4402 				cred = ncr;
4403 				ncr = NULL;
4404 				goto tryagain;
4405 			}
4406 			e.error = EACCES;
4407 		}
4408 	}
4409 
4410 out:
4411 	if (!rpc_error)
4412 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4413 
4414 	if (ncrfree != NULL)
4415 		crfree(ncrfree);
4416 
4417 	return (e.error);
4418 }
4419 
4420 /* ARGSUSED */
4421 static int
4422 nfs4_readlink(vnode_t *vp, struct uio *uiop, cred_t *cr, caller_context_t *ct)
4423 {
4424 	COMPOUND4args_clnt args;
4425 	COMPOUND4res_clnt res;
4426 	int doqueue;
4427 	rnode4_t *rp;
4428 	nfs_argop4 argop[3];
4429 	nfs_resop4 *resop;
4430 	READLINK4res *lr_res;
4431 	nfs4_ga_res_t *garp;
4432 	uint_t len;
4433 	char *linkdata;
4434 	bool_t needrecov = FALSE;
4435 	nfs4_recov_state_t recov_state;
4436 	hrtime_t t;
4437 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4438 
4439 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
4440 		return (EIO);
4441 	/*
4442 	 * Can't readlink anything other than a symbolic link.
4443 	 */
4444 	if (vp->v_type != VLNK)
4445 		return (EINVAL);
4446 
4447 	rp = VTOR4(vp);
4448 	if (nfs4_do_symlink_cache && rp->r_symlink.contents != NULL) {
4449 		e.error = nfs4_validate_caches(vp, cr);
4450 		if (e.error)
4451 			return (e.error);
4452 		mutex_enter(&rp->r_statelock);
4453 		if (rp->r_symlink.contents != NULL) {
4454 			e.error = uiomove(rp->r_symlink.contents,
4455 			    rp->r_symlink.len, UIO_READ, uiop);
4456 			mutex_exit(&rp->r_statelock);
4457 			return (e.error);
4458 		}
4459 		mutex_exit(&rp->r_statelock);
4460 	}
4461 	recov_state.rs_flags = 0;
4462 	recov_state.rs_num_retry_despite_err = 0;
4463 
4464 recov_retry:
4465 	args.array_len = 3;
4466 	args.array = argop;
4467 	args.ctag = TAG_READLINK;
4468 
4469 	e.error = nfs4_start_op(VTOMI4(vp), vp, NULL, &recov_state);
4470 	if (e.error) {
4471 		return (e.error);
4472 	}
4473 
4474 	/* 0. putfh symlink fh */
4475 	argop[0].argop = OP_CPUTFH;
4476 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4477 
4478 	/* 1. readlink */
4479 	argop[1].argop = OP_READLINK;
4480 
4481 	/* 2. getattr */
4482 	argop[2].argop = OP_GETATTR;
4483 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4484 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
4485 
4486 	doqueue = 1;
4487 
4488 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4489 	    "nfs4_readlink: %s call, rp %s", needrecov ? "recov" : "first",
4490 	    rnode4info(VTOR4(vp))));
4491 
4492 	t = gethrtime();
4493 
4494 	rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, &e);
4495 
4496 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4497 	if (needrecov) {
4498 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4499 		    "nfs4_readlink: initiating recovery\n"));
4500 
4501 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4502 		    NULL, OP_READLINK, NULL) == FALSE) {
4503 			if (!e.error)
4504 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4505 				    (caddr_t)&res);
4506 
4507 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
4508 			    needrecov);
4509 			goto recov_retry;
4510 		}
4511 	}
4512 
4513 	nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
4514 
4515 	if (e.error)
4516 		return (e.error);
4517 
4518 	/*
4519 	 * There is an path in the code below which calls
4520 	 * nfs4_purge_stale_fh(), which may generate otw calls through
4521 	 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
4522 	 * here to avoid nfs4_start_op() deadlock.
4523 	 */
4524 
4525 	if (res.status && (res.array_len < args.array_len)) {
4526 		/*
4527 		 * either Putfh or Link failed
4528 		 */
4529 		e.error = geterrno4(res.status);
4530 		nfs4_purge_stale_fh(e.error, vp, cr);
4531 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4532 		return (e.error);
4533 	}
4534 
4535 	resop = &res.array[1];	/* readlink res */
4536 	lr_res = &resop->nfs_resop4_u.opreadlink;
4537 
4538 	/*
4539 	 * treat symlink names as data
4540 	 */
4541 	linkdata = utf8_to_str(&lr_res->link, &len, NULL);
4542 	if (linkdata != NULL) {
4543 		int uio_len = len - 1;
4544 		/* len includes null byte, which we won't uiomove */
4545 		e.error = uiomove(linkdata, uio_len, UIO_READ, uiop);
4546 		if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
4547 			mutex_enter(&rp->r_statelock);
4548 			if (rp->r_symlink.contents == NULL) {
4549 				rp->r_symlink.contents = linkdata;
4550 				rp->r_symlink.len = uio_len;
4551 				rp->r_symlink.size = len;
4552 				mutex_exit(&rp->r_statelock);
4553 			} else {
4554 				mutex_exit(&rp->r_statelock);
4555 				kmem_free(linkdata, len);
4556 			}
4557 		} else {
4558 			kmem_free(linkdata, len);
4559 		}
4560 	}
4561 	if (res.status == NFS4_OK) {
4562 		resop++;	/* getattr res */
4563 		garp = &resop->nfs_resop4_u.opgetattr.ga_res;
4564 	}
4565 	e.error = nfs4_update_attrcache(res.status, garp, t, vp, cr);
4566 
4567 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4568 
4569 	/*
4570 	 * The over the wire error for attempting to readlink something
4571 	 * other than a symbolic link is ENXIO.  However, we need to
4572 	 * return EINVAL instead of ENXIO, so we map it here.
4573 	 */
4574 	return (e.error == ENXIO ? EINVAL : e.error);
4575 }
4576 
4577 /*
4578  * Flush local dirty pages to stable storage on the server.
4579  *
4580  * If FNODSYNC is specified, then there is nothing to do because
4581  * metadata changes are not cached on the client before being
4582  * sent to the server.
4583  */
4584 /* ARGSUSED */
4585 static int
4586 nfs4_fsync(vnode_t *vp, int syncflag, cred_t *cr, caller_context_t *ct)
4587 {
4588 	int error;
4589 
4590 	if ((syncflag & FNODSYNC) || IS_SWAPVP(vp))
4591 		return (0);
4592 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
4593 		return (EIO);
4594 	error = nfs4_putpage_commit(vp, (offset_t)0, 0, cr);
4595 	if (!error)
4596 		error = VTOR4(vp)->r_error;
4597 	return (error);
4598 }
4599 
4600 /*
4601  * Weirdness: if the file was removed or the target of a rename
4602  * operation while it was open, it got renamed instead.  Here we
4603  * remove the renamed file.
4604  */
4605 /* ARGSUSED */
4606 void
4607 nfs4_inactive(vnode_t *vp, cred_t *cr, caller_context_t *ct)
4608 {
4609 	rnode4_t *rp;
4610 
4611 	ASSERT(vp != DNLC_NO_VNODE);
4612 
4613 	rp = VTOR4(vp);
4614 
4615 	if (IS_SHADOW(vp, rp)) {
4616 		sv_inactive(vp);
4617 		return;
4618 	}
4619 
4620 	/*
4621 	 * If this is coming from the wrong zone, we let someone in the right
4622 	 * zone take care of it asynchronously.  We can get here due to
4623 	 * VN_RELE() being called from pageout() or fsflush().  This call may
4624 	 * potentially turn into an expensive no-op if, for instance, v_count
4625 	 * gets incremented in the meantime, but it's still correct.
4626 	 */
4627 	if (nfs_zone() != VTOMI4(vp)->mi_zone) {
4628 		nfs4_async_inactive(vp, cr);
4629 		return;
4630 	}
4631 
4632 	/*
4633 	 * Some of the cleanup steps might require over-the-wire
4634 	 * operations.  Since VOP_INACTIVE can get called as a result of
4635 	 * other over-the-wire operations (e.g., an attribute cache update
4636 	 * can lead to a DNLC purge), doing those steps now would lead to a
4637 	 * nested call to the recovery framework, which can deadlock.  So
4638 	 * do any over-the-wire cleanups asynchronously, in a separate
4639 	 * thread.
4640 	 */
4641 
4642 	mutex_enter(&rp->r_os_lock);
4643 	mutex_enter(&rp->r_statelock);
4644 	mutex_enter(&rp->r_statev4_lock);
4645 
4646 	if (vp->v_type == VREG && list_head(&rp->r_open_streams) != NULL) {
4647 		mutex_exit(&rp->r_statev4_lock);
4648 		mutex_exit(&rp->r_statelock);
4649 		mutex_exit(&rp->r_os_lock);
4650 		nfs4_async_inactive(vp, cr);
4651 		return;
4652 	}
4653 
4654 	if (rp->r_deleg_type == OPEN_DELEGATE_READ ||
4655 	    rp->r_deleg_type == OPEN_DELEGATE_WRITE) {
4656 		mutex_exit(&rp->r_statev4_lock);
4657 		mutex_exit(&rp->r_statelock);
4658 		mutex_exit(&rp->r_os_lock);
4659 		nfs4_async_inactive(vp, cr);
4660 		return;
4661 	}
4662 
4663 	if (rp->r_unldvp != NULL) {
4664 		mutex_exit(&rp->r_statev4_lock);
4665 		mutex_exit(&rp->r_statelock);
4666 		mutex_exit(&rp->r_os_lock);
4667 		nfs4_async_inactive(vp, cr);
4668 		return;
4669 	}
4670 	mutex_exit(&rp->r_statev4_lock);
4671 	mutex_exit(&rp->r_statelock);
4672 	mutex_exit(&rp->r_os_lock);
4673 
4674 	rp4_addfree(rp, cr);
4675 }
4676 
4677 /*
4678  * nfs4_inactive_otw - nfs4_inactive, plus over-the-wire calls to free up
4679  * various bits of state.  The caller must not refer to vp after this call.
4680  */
4681 
4682 void
4683 nfs4_inactive_otw(vnode_t *vp, cred_t *cr)
4684 {
4685 	rnode4_t *rp = VTOR4(vp);
4686 	nfs4_recov_state_t recov_state;
4687 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4688 	vnode_t *unldvp;
4689 	char *unlname;
4690 	cred_t *unlcred;
4691 	COMPOUND4args_clnt args;
4692 	COMPOUND4res_clnt res, *resp;
4693 	nfs_argop4 argop[2];
4694 	int doqueue;
4695 #ifdef DEBUG
4696 	char *name;
4697 #endif
4698 
4699 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
4700 	ASSERT(!IS_SHADOW(vp, rp));
4701 
4702 #ifdef DEBUG
4703 	name = fn_name(VTOSV(vp)->sv_name);
4704 	NFS4_DEBUG(nfs4_client_inactive_debug, (CE_NOTE, "nfs4_inactive_otw: "
4705 	    "release vnode %s", name));
4706 	kmem_free(name, MAXNAMELEN);
4707 #endif
4708 
4709 	if (vp->v_type == VREG) {
4710 		bool_t recov_failed = FALSE;
4711 
4712 		e.error = nfs4close_all(vp, cr);
4713 		if (e.error) {
4714 			/* Check to see if recovery failed */
4715 			mutex_enter(&(VTOMI4(vp)->mi_lock));
4716 			if (VTOMI4(vp)->mi_flags & MI4_RECOV_FAIL)
4717 				recov_failed = TRUE;
4718 			mutex_exit(&(VTOMI4(vp)->mi_lock));
4719 			if (!recov_failed) {
4720 				mutex_enter(&rp->r_statelock);
4721 				if (rp->r_flags & R4RECOVERR)
4722 					recov_failed = TRUE;
4723 				mutex_exit(&rp->r_statelock);
4724 			}
4725 			if (recov_failed) {
4726 				NFS4_DEBUG(nfs4_client_recov_debug,
4727 				    (CE_NOTE, "nfs4_inactive_otw: "
4728 				    "close failed (recovery failure)"));
4729 			}
4730 		}
4731 	}
4732 
4733 redo:
4734 	if (rp->r_unldvp == NULL) {
4735 		rp4_addfree(rp, cr);
4736 		return;
4737 	}
4738 
4739 	/*
4740 	 * Save the vnode pointer for the directory where the
4741 	 * unlinked-open file got renamed, then set it to NULL
4742 	 * to prevent another thread from getting here before
4743 	 * we're done with the remove.  While we have the
4744 	 * statelock, make local copies of the pertinent rnode
4745 	 * fields.  If we weren't to do this in an atomic way, the
4746 	 * the unl* fields could become inconsistent with respect
4747 	 * to each other due to a race condition between this
4748 	 * code and nfs_remove().  See bug report 1034328.
4749 	 */
4750 	mutex_enter(&rp->r_statelock);
4751 	if (rp->r_unldvp == NULL) {
4752 		mutex_exit(&rp->r_statelock);
4753 		rp4_addfree(rp, cr);
4754 		return;
4755 	}
4756 
4757 	unldvp = rp->r_unldvp;
4758 	rp->r_unldvp = NULL;
4759 	unlname = rp->r_unlname;
4760 	rp->r_unlname = NULL;
4761 	unlcred = rp->r_unlcred;
4762 	rp->r_unlcred = NULL;
4763 	mutex_exit(&rp->r_statelock);
4764 
4765 	/*
4766 	 * If there are any dirty pages left, then flush
4767 	 * them.  This is unfortunate because they just
4768 	 * may get thrown away during the remove operation,
4769 	 * but we have to do this for correctness.
4770 	 */
4771 	if (nfs4_has_pages(vp) &&
4772 	    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
4773 		ASSERT(vp->v_type != VCHR);
4774 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr, NULL);
4775 		if (e.error) {
4776 			mutex_enter(&rp->r_statelock);
4777 			if (!rp->r_error)
4778 				rp->r_error = e.error;
4779 			mutex_exit(&rp->r_statelock);
4780 		}
4781 	}
4782 
4783 	recov_state.rs_flags = 0;
4784 	recov_state.rs_num_retry_despite_err = 0;
4785 recov_retry_remove:
4786 	/*
4787 	 * Do the remove operation on the renamed file
4788 	 */
4789 	args.ctag = TAG_INACTIVE;
4790 
4791 	/*
4792 	 * Remove ops: putfh dir; remove
4793 	 */
4794 	args.array_len = 2;
4795 	args.array = argop;
4796 
4797 	e.error = nfs4_start_op(VTOMI4(unldvp), unldvp, NULL, &recov_state);
4798 	if (e.error) {
4799 		kmem_free(unlname, MAXNAMELEN);
4800 		crfree(unlcred);
4801 		VN_RELE(unldvp);
4802 		/*
4803 		 * Try again; this time around r_unldvp will be NULL, so we'll
4804 		 * just call rp4_addfree() and return.
4805 		 */
4806 		goto redo;
4807 	}
4808 
4809 	/* putfh directory */
4810 	argop[0].argop = OP_CPUTFH;
4811 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(unldvp)->r_fh;
4812 
4813 	/* remove */
4814 	argop[1].argop = OP_CREMOVE;
4815 	argop[1].nfs_argop4_u.opcremove.ctarget = unlname;
4816 
4817 	doqueue = 1;
4818 	resp = &res;
4819 
4820 #if 0 /* notyet */
4821 	/*
4822 	 * Can't do this yet.  We may be being called from
4823 	 * dnlc_purge_XXX while that routine is holding a
4824 	 * mutex lock to the nc_rele list.  The calls to
4825 	 * nfs3_cache_wcc_data may result in calls to
4826 	 * dnlc_purge_XXX.  This will result in a deadlock.
4827 	 */
4828 	rfs4call(VTOMI4(unldvp), &args, &res, unlcred, &doqueue, 0, &e);
4829 	if (e.error) {
4830 		PURGE_ATTRCACHE4(unldvp);
4831 		resp = NULL;
4832 	} else if (res.status) {
4833 		e.error = geterrno4(res.status);
4834 		PURGE_ATTRCACHE4(unldvp);
4835 		/*
4836 		 * This code is inactive right now
4837 		 * but if made active there should
4838 		 * be a nfs4_end_op() call before
4839 		 * nfs4_purge_stale_fh to avoid start_op()
4840 		 * deadlock. See BugId: 4948726
4841 		 */
4842 		nfs4_purge_stale_fh(error, unldvp, cr);
4843 	} else {
4844 		nfs_resop4 *resop;
4845 		REMOVE4res *rm_res;
4846 
4847 		resop = &res.array[1];
4848 		rm_res = &resop->nfs_resop4_u.opremove;
4849 		/*
4850 		 * Update directory cache attribute,
4851 		 * readdir and dnlc caches.
4852 		 */
4853 		nfs4_update_dircaches(&rm_res->cinfo, unldvp, NULL, NULL, NULL);
4854 	}
4855 #else
4856 	rfs4call(VTOMI4(unldvp), &args, &res, unlcred, &doqueue, 0, &e);
4857 
4858 	PURGE_ATTRCACHE4(unldvp);
4859 #endif
4860 
4861 	if (nfs4_needs_recovery(&e, FALSE, unldvp->v_vfsp)) {
4862 		if (nfs4_start_recovery(&e, VTOMI4(unldvp), unldvp, NULL,
4863 		    NULL, NULL, OP_REMOVE, NULL) == FALSE) {
4864 			if (!e.error)
4865 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4866 				    (caddr_t)&res);
4867 			nfs4_end_op(VTOMI4(unldvp), unldvp, NULL,
4868 			    &recov_state, TRUE);
4869 			goto recov_retry_remove;
4870 		}
4871 	}
4872 	nfs4_end_op(VTOMI4(unldvp), unldvp, NULL, &recov_state, FALSE);
4873 
4874 	/*
4875 	 * Release stuff held for the remove
4876 	 */
4877 	VN_RELE(unldvp);
4878 	if (!e.error && resp)
4879 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
4880 
4881 	kmem_free(unlname, MAXNAMELEN);
4882 	crfree(unlcred);
4883 	goto redo;
4884 }
4885 
4886 /*
4887  * Remote file system operations having to do with directory manipulation.
4888  */
4889 /* ARGSUSED3 */
4890 int
4891 nfs4_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, struct pathname *pnp,
4892     int flags, vnode_t *rdir, cred_t *cr, caller_context_t *ct,
4893     int *direntflags, pathname_t *realpnp)
4894 {
4895 	int error;
4896 	vnode_t *vp, *avp = NULL;
4897 	rnode4_t *drp;
4898 
4899 	*vpp = NULL;
4900 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
4901 		return (EPERM);
4902 	/*
4903 	 * if LOOKUP_XATTR, must replace dvp (object) with
4904 	 * object's attrdir before continuing with lookup
4905 	 */
4906 	if (flags & LOOKUP_XATTR) {
4907 		error = nfs4lookup_xattr(dvp, nm, &avp, flags, cr);
4908 		if (error)
4909 			return (error);
4910 
4911 		dvp = avp;
4912 
4913 		/*
4914 		 * If lookup is for "", just return dvp now.  The attrdir
4915 		 * has already been activated (from nfs4lookup_xattr), and
4916 		 * the caller will RELE the original dvp -- not
4917 		 * the attrdir.  So, set vpp and return.
4918 		 * Currently, when the LOOKUP_XATTR flag is
4919 		 * passed to VOP_LOOKUP, the name is always empty, and
4920 		 * shortcircuiting here avoids 3 unneeded lock/unlock
4921 		 * pairs.
4922 		 *
4923 		 * If a non-empty name was provided, then it is the
4924 		 * attribute name, and it will be looked up below.
4925 		 */
4926 		if (*nm == '\0') {
4927 			*vpp = dvp;
4928 			return (0);
4929 		}
4930 
4931 		/*
4932 		 * The vfs layer never sends a name when asking for the
4933 		 * attrdir, so we should never get here (unless of course
4934 		 * name is passed at some time in future -- at which time
4935 		 * we'll blow up here).
4936 		 */
4937 		ASSERT(0);
4938 	}
4939 
4940 	drp = VTOR4(dvp);
4941 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
4942 		return (EINTR);
4943 
4944 	error = nfs4lookup(dvp, nm, vpp, cr, 0);
4945 	nfs_rw_exit(&drp->r_rwlock);
4946 
4947 	/*
4948 	 * If vnode is a device, create special vnode.
4949 	 */
4950 	if (!error && ISVDEV((*vpp)->v_type)) {
4951 		vp = *vpp;
4952 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
4953 		VN_RELE(vp);
4954 	}
4955 
4956 	return (error);
4957 }
4958 
4959 /* ARGSUSED */
4960 static int
4961 nfs4lookup_xattr(vnode_t *dvp, char *nm, vnode_t **vpp, int flags, cred_t *cr)
4962 {
4963 	int error;
4964 	rnode4_t *drp;
4965 	int cflag = ((flags & CREATE_XATTR_DIR) != 0);
4966 	mntinfo4_t *mi;
4967 
4968 	mi = VTOMI4(dvp);
4969 	if (!(mi->mi_vfsp->vfs_flag & VFS_XATTR) &&
4970 	    !vfs_has_feature(mi->mi_vfsp, VFSFT_XVATTR))
4971 		return (EINVAL);
4972 
4973 	drp = VTOR4(dvp);
4974 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
4975 		return (EINTR);
4976 
4977 	mutex_enter(&drp->r_statelock);
4978 	/*
4979 	 * If the server doesn't support xattrs just return EINVAL
4980 	 */
4981 	if (drp->r_xattr_dir == NFS4_XATTR_DIR_NOTSUPP) {
4982 		mutex_exit(&drp->r_statelock);
4983 		nfs_rw_exit(&drp->r_rwlock);
4984 		return (EINVAL);
4985 	}
4986 
4987 	/*
4988 	 * If there is a cached xattr directory entry,
4989 	 * use it as long as the attributes are valid. If the
4990 	 * attributes are not valid, take the simple approach and
4991 	 * free the cached value and re-fetch a new value.
4992 	 *
4993 	 * We don't negative entry cache for now, if we did we
4994 	 * would need to check if the file has changed on every
4995 	 * lookup. But xattrs don't exist very often and failing
4996 	 * an openattr is not much more expensive than and NVERIFY or GETATTR
4997 	 * so do an openattr over the wire for now.
4998 	 */
4999 	if (drp->r_xattr_dir != NULL) {
5000 		if (ATTRCACHE4_VALID(dvp)) {
5001 			VN_HOLD(drp->r_xattr_dir);
5002 			*vpp = drp->r_xattr_dir;
5003 			mutex_exit(&drp->r_statelock);
5004 			nfs_rw_exit(&drp->r_rwlock);
5005 			return (0);
5006 		}
5007 		VN_RELE(drp->r_xattr_dir);
5008 		drp->r_xattr_dir = NULL;
5009 	}
5010 	mutex_exit(&drp->r_statelock);
5011 
5012 	error = nfs4openattr(dvp, vpp, cflag, cr);
5013 
5014 	nfs_rw_exit(&drp->r_rwlock);
5015 
5016 	return (error);
5017 }
5018 
5019 static int
5020 nfs4lookup(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr, int skipdnlc)
5021 {
5022 	int error;
5023 	rnode4_t *drp;
5024 
5025 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5026 
5027 	/*
5028 	 * If lookup is for "", just return dvp.  Don't need
5029 	 * to send it over the wire, look it up in the dnlc,
5030 	 * or perform any access checks.
5031 	 */
5032 	if (*nm == '\0') {
5033 		VN_HOLD(dvp);
5034 		*vpp = dvp;
5035 		return (0);
5036 	}
5037 
5038 	/*
5039 	 * Can't do lookups in non-directories.
5040 	 */
5041 	if (dvp->v_type != VDIR)
5042 		return (ENOTDIR);
5043 
5044 	/*
5045 	 * If lookup is for ".", just return dvp.  Don't need
5046 	 * to send it over the wire or look it up in the dnlc,
5047 	 * just need to check access.
5048 	 */
5049 	if (nm[0] == '.' && nm[1] == '\0') {
5050 		error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5051 		if (error)
5052 			return (error);
5053 		VN_HOLD(dvp);
5054 		*vpp = dvp;
5055 		return (0);
5056 	}
5057 
5058 	drp = VTOR4(dvp);
5059 	if (!(drp->r_flags & R4LOOKUP)) {
5060 		mutex_enter(&drp->r_statelock);
5061 		drp->r_flags |= R4LOOKUP;
5062 		mutex_exit(&drp->r_statelock);
5063 	}
5064 
5065 	*vpp = NULL;
5066 	/*
5067 	 * Lookup this name in the DNLC.  If there is no entry
5068 	 * lookup over the wire.
5069 	 */
5070 	if (!skipdnlc)
5071 		*vpp = dnlc_lookup(dvp, nm);
5072 	if (*vpp == NULL) {
5073 		/*
5074 		 * We need to go over the wire to lookup the name.
5075 		 */
5076 		return (nfs4lookupnew_otw(dvp, nm, vpp, cr));
5077 	}
5078 
5079 	/*
5080 	 * We hit on the dnlc
5081 	 */
5082 	if (*vpp != DNLC_NO_VNODE ||
5083 	    (dvp->v_vfsp->vfs_flag & VFS_RDONLY)) {
5084 		/*
5085 		 * But our attrs may not be valid.
5086 		 */
5087 		if (ATTRCACHE4_VALID(dvp)) {
5088 			error = nfs4_waitfor_purge_complete(dvp);
5089 			if (error) {
5090 				VN_RELE(*vpp);
5091 				*vpp = NULL;
5092 				return (error);
5093 			}
5094 
5095 			/*
5096 			 * If after the purge completes, check to make sure
5097 			 * our attrs are still valid.
5098 			 */
5099 			if (ATTRCACHE4_VALID(dvp)) {
5100 				/*
5101 				 * If we waited for a purge we may have
5102 				 * lost our vnode so look it up again.
5103 				 */
5104 				VN_RELE(*vpp);
5105 				*vpp = dnlc_lookup(dvp, nm);
5106 				if (*vpp == NULL)
5107 					return (nfs4lookupnew_otw(dvp,
5108 					    nm, vpp, cr));
5109 
5110 				/*
5111 				 * The access cache should almost always hit
5112 				 */
5113 				error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5114 
5115 				if (error) {
5116 					VN_RELE(*vpp);
5117 					*vpp = NULL;
5118 					return (error);
5119 				}
5120 				if (*vpp == DNLC_NO_VNODE) {
5121 					VN_RELE(*vpp);
5122 					*vpp = NULL;
5123 					return (ENOENT);
5124 				}
5125 				return (0);
5126 			}
5127 		}
5128 	}
5129 
5130 	ASSERT(*vpp != NULL);
5131 
5132 	/*
5133 	 * We may have gotten here we have one of the following cases:
5134 	 *	1) vpp != DNLC_NO_VNODE, our attrs have timed out so we
5135 	 *		need to validate them.
5136 	 *	2) vpp == DNLC_NO_VNODE, a negative entry that we always
5137 	 *		must validate.
5138 	 *
5139 	 * Go to the server and check if the directory has changed, if
5140 	 * it hasn't we are done and can use the dnlc entry.
5141 	 */
5142 	return (nfs4lookupvalidate_otw(dvp, nm, vpp, cr));
5143 }
5144 
5145 /*
5146  * Go to the server and check if the directory has changed, if
5147  * it hasn't we are done and can use the dnlc entry.  If it
5148  * has changed we get a new copy of its attributes and check
5149  * the access for VEXEC, then relookup the filename and
5150  * get its filehandle and attributes.
5151  *
5152  * PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR
5153  *	if the NVERIFY failed we must
5154  *		purge the caches
5155  *		cache new attributes (will set r_time_attr_inval)
5156  *		cache new access
5157  *		recheck VEXEC access
5158  *		add name to dnlc, possibly negative
5159  *		if LOOKUP succeeded
5160  *			cache new attributes
5161  *	else
5162  *		set a new r_time_attr_inval for dvp
5163  *		check to make sure we have access
5164  *
5165  * The vpp returned is the vnode passed in if the directory is valid,
5166  * a new vnode if successful lookup, or NULL on error.
5167  */
5168 static int
5169 nfs4lookupvalidate_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5170 {
5171 	COMPOUND4args_clnt args;
5172 	COMPOUND4res_clnt res;
5173 	fattr4 *ver_fattr;
5174 	fattr4_change dchange;
5175 	int32_t *ptr;
5176 	int argoplist_size  = 7 * sizeof (nfs_argop4);
5177 	nfs_argop4 *argop;
5178 	int doqueue;
5179 	mntinfo4_t *mi;
5180 	nfs4_recov_state_t recov_state;
5181 	hrtime_t t;
5182 	int isdotdot;
5183 	vnode_t *nvp;
5184 	nfs_fh4 *fhp;
5185 	nfs4_sharedfh_t *sfhp;
5186 	nfs4_access_type_t cacc;
5187 	rnode4_t *nrp;
5188 	rnode4_t *drp = VTOR4(dvp);
5189 	nfs4_ga_res_t *garp = NULL;
5190 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5191 
5192 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5193 	ASSERT(nm != NULL);
5194 	ASSERT(nm[0] != '\0');
5195 	ASSERT(dvp->v_type == VDIR);
5196 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5197 	ASSERT(*vpp != NULL);
5198 
5199 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5200 		isdotdot = 1;
5201 		args.ctag = TAG_LOOKUP_VPARENT;
5202 	} else {
5203 		/*
5204 		 * If dvp were a stub, it should have triggered and caused
5205 		 * a mount for us to get this far.
5206 		 */
5207 		ASSERT(!RP_ISSTUB(VTOR4(dvp)));
5208 
5209 		isdotdot = 0;
5210 		args.ctag = TAG_LOOKUP_VALID;
5211 	}
5212 
5213 	mi = VTOMI4(dvp);
5214 	recov_state.rs_flags = 0;
5215 	recov_state.rs_num_retry_despite_err = 0;
5216 
5217 	nvp = NULL;
5218 
5219 	/* Save the original mount point security information */
5220 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5221 
5222 recov_retry:
5223 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5224 	    &recov_state, NULL);
5225 	if (e.error) {
5226 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5227 		VN_RELE(*vpp);
5228 		*vpp = NULL;
5229 		return (e.error);
5230 	}
5231 
5232 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5233 
5234 	/* PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR */
5235 	args.array_len = 7;
5236 	args.array = argop;
5237 
5238 	/* 0. putfh file */
5239 	argop[0].argop = OP_CPUTFH;
5240 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5241 
5242 	/* 1. nverify the change info */
5243 	argop[1].argop = OP_NVERIFY;
5244 	ver_fattr = &argop[1].nfs_argop4_u.opnverify.obj_attributes;
5245 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5246 	ver_fattr->attrlist4 = (char *)&dchange;
5247 	ptr = (int32_t *)&dchange;
5248 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5249 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5250 
5251 	/* 2. getattr directory */
5252 	argop[2].argop = OP_GETATTR;
5253 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5254 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5255 
5256 	/* 3. access directory */
5257 	argop[3].argop = OP_ACCESS;
5258 	argop[3].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5259 	    ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5260 
5261 	/* 4. lookup name */
5262 	if (isdotdot) {
5263 		argop[4].argop = OP_LOOKUPP;
5264 	} else {
5265 		argop[4].argop = OP_CLOOKUP;
5266 		argop[4].nfs_argop4_u.opclookup.cname = nm;
5267 	}
5268 
5269 	/* 5. resulting file handle */
5270 	argop[5].argop = OP_GETFH;
5271 
5272 	/* 6. resulting file attributes */
5273 	argop[6].argop = OP_GETATTR;
5274 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5275 	argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5276 
5277 	doqueue = 1;
5278 	t = gethrtime();
5279 
5280 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5281 
5282 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5283 		/*
5284 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5285 		 * from this thread, do not go thru the recovery thread since
5286 		 * we need the nm information.
5287 		 *
5288 		 * Not doing dotdot case because there is no specification
5289 		 * for (PUTFH, SECINFO "..") yet.
5290 		 */
5291 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5292 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr)))
5293 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5294 				    &recov_state, FALSE);
5295 			else
5296 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5297 				    &recov_state, TRUE);
5298 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5299 			kmem_free(argop, argoplist_size);
5300 			if (!e.error)
5301 				goto recov_retry;
5302 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5303 			VN_RELE(*vpp);
5304 			*vpp = NULL;
5305 			return (e.error);
5306 		}
5307 
5308 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5309 		    OP_LOOKUP, NULL) == FALSE) {
5310 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5311 			    &recov_state, TRUE);
5312 
5313 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5314 			kmem_free(argop, argoplist_size);
5315 			goto recov_retry;
5316 		}
5317 	}
5318 
5319 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5320 
5321 	if (e.error || res.array_len == 0) {
5322 		/*
5323 		 * If e.error isn't set, then reply has no ops (or we couldn't
5324 		 * be here).  The only legal way to reply without an op array
5325 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5326 		 * be in the reply for all other status values.
5327 		 *
5328 		 * For valid replies without an ops array, return ENOTSUP
5329 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5330 		 * return EIO -- don't trust status.
5331 		 */
5332 		if (e.error == 0)
5333 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5334 			    ENOTSUP : EIO;
5335 		VN_RELE(*vpp);
5336 		*vpp = NULL;
5337 		kmem_free(argop, argoplist_size);
5338 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5339 		return (e.error);
5340 	}
5341 
5342 	if (res.status != NFS4ERR_SAME) {
5343 		e.error = geterrno4(res.status);
5344 
5345 		/*
5346 		 * The NVERIFY "failed" so the directory has changed
5347 		 * First make sure PUTFH succeeded and NVERIFY "failed"
5348 		 * cleanly.
5349 		 */
5350 		if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5351 		    (res.array[1].nfs_resop4_u.opnverify.status != NFS4_OK)) {
5352 			nfs4_purge_stale_fh(e.error, dvp, cr);
5353 			VN_RELE(*vpp);
5354 			*vpp = NULL;
5355 			goto exit;
5356 		}
5357 
5358 		/*
5359 		 * We know the NVERIFY "failed" so we must:
5360 		 *	purge the caches (access and indirectly dnlc if needed)
5361 		 */
5362 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5363 
5364 		if (res.array[2].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5365 			nfs4_purge_stale_fh(e.error, dvp, cr);
5366 			VN_RELE(*vpp);
5367 			*vpp = NULL;
5368 			goto exit;
5369 		}
5370 
5371 		/*
5372 		 * Install new cached attributes for the directory
5373 		 */
5374 		nfs4_attr_cache(dvp,
5375 		    &res.array[2].nfs_resop4_u.opgetattr.ga_res,
5376 		    t, cr, FALSE, NULL);
5377 
5378 		if (res.array[3].nfs_resop4_u.opaccess.status != NFS4_OK) {
5379 			nfs4_purge_stale_fh(e.error, dvp, cr);
5380 			VN_RELE(*vpp);
5381 			*vpp = NULL;
5382 			e.error = geterrno4(res.status);
5383 			goto exit;
5384 		}
5385 
5386 		/*
5387 		 * Now we know the directory is valid,
5388 		 * cache new directory access
5389 		 */
5390 		nfs4_access_cache(drp,
5391 		    args.array[3].nfs_argop4_u.opaccess.access,
5392 		    res.array[3].nfs_resop4_u.opaccess.access, cr);
5393 
5394 		/*
5395 		 * recheck VEXEC access
5396 		 */
5397 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5398 		if (cacc != NFS4_ACCESS_ALLOWED) {
5399 			/*
5400 			 * Directory permissions might have been revoked
5401 			 */
5402 			if (cacc == NFS4_ACCESS_DENIED) {
5403 				e.error = EACCES;
5404 				VN_RELE(*vpp);
5405 				*vpp = NULL;
5406 				goto exit;
5407 			}
5408 
5409 			/*
5410 			 * Somehow we must not have asked for enough
5411 			 * so try a singleton ACCESS, should never happen.
5412 			 */
5413 			e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5414 			if (e.error) {
5415 				VN_RELE(*vpp);
5416 				*vpp = NULL;
5417 				goto exit;
5418 			}
5419 		}
5420 
5421 		e.error = geterrno4(res.status);
5422 		if (res.array[4].nfs_resop4_u.oplookup.status != NFS4_OK) {
5423 			/*
5424 			 * The lookup failed, probably no entry
5425 			 */
5426 			if (e.error == ENOENT && nfs4_lookup_neg_cache) {
5427 				dnlc_update(dvp, nm, DNLC_NO_VNODE);
5428 			} else {
5429 				/*
5430 				 * Might be some other error, so remove
5431 				 * the dnlc entry to make sure we start all
5432 				 * over again, next time.
5433 				 */
5434 				dnlc_remove(dvp, nm);
5435 			}
5436 			VN_RELE(*vpp);
5437 			*vpp = NULL;
5438 			goto exit;
5439 		}
5440 
5441 		if (res.array[5].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5442 			/*
5443 			 * The file exists but we can't get its fh for
5444 			 * some unknown reason.  Remove it from the dnlc
5445 			 * and error out to be safe.
5446 			 */
5447 			dnlc_remove(dvp, nm);
5448 			VN_RELE(*vpp);
5449 			*vpp = NULL;
5450 			goto exit;
5451 		}
5452 		fhp = &res.array[5].nfs_resop4_u.opgetfh.object;
5453 		if (fhp->nfs_fh4_len == 0) {
5454 			/*
5455 			 * The file exists but a bogus fh
5456 			 * some unknown reason.  Remove it from the dnlc
5457 			 * and error out to be safe.
5458 			 */
5459 			e.error = ENOENT;
5460 			dnlc_remove(dvp, nm);
5461 			VN_RELE(*vpp);
5462 			*vpp = NULL;
5463 			goto exit;
5464 		}
5465 		sfhp = sfh4_get(fhp, mi);
5466 
5467 		if (res.array[6].nfs_resop4_u.opgetattr.status == NFS4_OK)
5468 			garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
5469 
5470 		/*
5471 		 * Make the new rnode
5472 		 */
5473 		if (isdotdot) {
5474 			e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
5475 			if (e.error) {
5476 				sfh4_rele(&sfhp);
5477 				VN_RELE(*vpp);
5478 				*vpp = NULL;
5479 				goto exit;
5480 			}
5481 			/*
5482 			 * XXX if nfs4_make_dotdot uses an existing rnode
5483 			 * XXX it doesn't update the attributes.
5484 			 * XXX for now just save them again to save an OTW
5485 			 */
5486 			nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
5487 		} else {
5488 			nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
5489 			    dvp, fn_get(VTOSV(dvp)->sv_name, nm));
5490 			/*
5491 			 * If v_type == VNON, then garp was NULL because
5492 			 * the last op in the compound failed and makenfs4node
5493 			 * could not find the vnode for sfhp. It created
5494 			 * a new vnode, so we have nothing to purge here.
5495 			 */
5496 			if (nvp->v_type == VNON) {
5497 				vattr_t vattr;
5498 
5499 				vattr.va_mask = AT_TYPE;
5500 				/*
5501 				 * N.B. We've already called nfs4_end_fop above.
5502 				 */
5503 				e.error = nfs4getattr(nvp, &vattr, cr);
5504 				if (e.error) {
5505 					sfh4_rele(&sfhp);
5506 					VN_RELE(*vpp);
5507 					*vpp = NULL;
5508 					VN_RELE(nvp);
5509 					goto exit;
5510 				}
5511 				nvp->v_type = vattr.va_type;
5512 			}
5513 		}
5514 		sfh4_rele(&sfhp);
5515 
5516 		nrp = VTOR4(nvp);
5517 		mutex_enter(&nrp->r_statev4_lock);
5518 		if (!nrp->created_v4) {
5519 			mutex_exit(&nrp->r_statev4_lock);
5520 			dnlc_update(dvp, nm, nvp);
5521 		} else
5522 			mutex_exit(&nrp->r_statev4_lock);
5523 
5524 		VN_RELE(*vpp);
5525 		*vpp = nvp;
5526 	} else {
5527 		hrtime_t now;
5528 		hrtime_t delta = 0;
5529 
5530 		e.error = 0;
5531 
5532 		/*
5533 		 * Because the NVERIFY "succeeded" we know that the
5534 		 * directory attributes are still valid
5535 		 * so update r_time_attr_inval
5536 		 */
5537 		now = gethrtime();
5538 		mutex_enter(&drp->r_statelock);
5539 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
5540 			delta = now - drp->r_time_attr_saved;
5541 			if (delta < mi->mi_acdirmin)
5542 				delta = mi->mi_acdirmin;
5543 			else if (delta > mi->mi_acdirmax)
5544 				delta = mi->mi_acdirmax;
5545 		}
5546 		drp->r_time_attr_inval = now + delta;
5547 		mutex_exit(&drp->r_statelock);
5548 		dnlc_update(dvp, nm, *vpp);
5549 
5550 		/*
5551 		 * Even though we have a valid directory attr cache
5552 		 * and dnlc entry, we may not have access.
5553 		 * This should almost always hit the cache.
5554 		 */
5555 		e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5556 		if (e.error) {
5557 			VN_RELE(*vpp);
5558 			*vpp = NULL;
5559 		}
5560 
5561 		if (*vpp == DNLC_NO_VNODE) {
5562 			VN_RELE(*vpp);
5563 			*vpp = NULL;
5564 			e.error = ENOENT;
5565 		}
5566 	}
5567 
5568 exit:
5569 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5570 	kmem_free(argop, argoplist_size);
5571 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5572 	return (e.error);
5573 }
5574 
5575 /*
5576  * We need to go over the wire to lookup the name, but
5577  * while we are there verify the directory has not
5578  * changed but if it has, get new attributes and check access
5579  *
5580  * PUTFH dfh SAVEFH LOOKUP nm GETFH GETATTR RESTOREFH
5581  *					NVERIFY GETATTR ACCESS
5582  *
5583  * With the results:
5584  *	if the NVERIFY failed we must purge the caches, add new attributes,
5585  *		and cache new access.
5586  *	set a new r_time_attr_inval
5587  *	add name to dnlc, possibly negative
5588  *	if LOOKUP succeeded
5589  *		cache new attributes
5590  */
5591 static int
5592 nfs4lookupnew_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5593 {
5594 	COMPOUND4args_clnt args;
5595 	COMPOUND4res_clnt res;
5596 	fattr4 *ver_fattr;
5597 	fattr4_change dchange;
5598 	int32_t *ptr;
5599 	nfs4_ga_res_t *garp = NULL;
5600 	int argoplist_size  = 9 * sizeof (nfs_argop4);
5601 	nfs_argop4 *argop;
5602 	int doqueue;
5603 	mntinfo4_t *mi;
5604 	nfs4_recov_state_t recov_state;
5605 	hrtime_t t;
5606 	int isdotdot;
5607 	vnode_t *nvp;
5608 	nfs_fh4 *fhp;
5609 	nfs4_sharedfh_t *sfhp;
5610 	nfs4_access_type_t cacc;
5611 	rnode4_t *nrp;
5612 	rnode4_t *drp = VTOR4(dvp);
5613 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5614 
5615 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5616 	ASSERT(nm != NULL);
5617 	ASSERT(nm[0] != '\0');
5618 	ASSERT(dvp->v_type == VDIR);
5619 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5620 	ASSERT(*vpp == NULL);
5621 
5622 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5623 		isdotdot = 1;
5624 		args.ctag = TAG_LOOKUP_PARENT;
5625 	} else {
5626 		/*
5627 		 * If dvp were a stub, it should have triggered and caused
5628 		 * a mount for us to get this far.
5629 		 */
5630 		ASSERT(!RP_ISSTUB(VTOR4(dvp)));
5631 
5632 		isdotdot = 0;
5633 		args.ctag = TAG_LOOKUP;
5634 	}
5635 
5636 	mi = VTOMI4(dvp);
5637 	recov_state.rs_flags = 0;
5638 	recov_state.rs_num_retry_despite_err = 0;
5639 
5640 	nvp = NULL;
5641 
5642 	/* Save the original mount point security information */
5643 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5644 
5645 recov_retry:
5646 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5647 	    &recov_state, NULL);
5648 	if (e.error) {
5649 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5650 		return (e.error);
5651 	}
5652 
5653 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5654 
5655 	/* PUTFH SAVEFH LOOKUP GETFH GETATTR RESTOREFH NVERIFY GETATTR ACCESS */
5656 	args.array_len = 9;
5657 	args.array = argop;
5658 
5659 	/* 0. putfh file */
5660 	argop[0].argop = OP_CPUTFH;
5661 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5662 
5663 	/* 1. savefh for the nverify */
5664 	argop[1].argop = OP_SAVEFH;
5665 
5666 	/* 2. lookup name */
5667 	if (isdotdot) {
5668 		argop[2].argop = OP_LOOKUPP;
5669 	} else {
5670 		argop[2].argop = OP_CLOOKUP;
5671 		argop[2].nfs_argop4_u.opclookup.cname = nm;
5672 	}
5673 
5674 	/* 3. resulting file handle */
5675 	argop[3].argop = OP_GETFH;
5676 
5677 	/* 4. resulting file attributes */
5678 	argop[4].argop = OP_GETATTR;
5679 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5680 	argop[4].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5681 
5682 	/* 5. restorefh back the directory for the nverify */
5683 	argop[5].argop = OP_RESTOREFH;
5684 
5685 	/* 6. nverify the change info */
5686 	argop[6].argop = OP_NVERIFY;
5687 	ver_fattr = &argop[6].nfs_argop4_u.opnverify.obj_attributes;
5688 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5689 	ver_fattr->attrlist4 = (char *)&dchange;
5690 	ptr = (int32_t *)&dchange;
5691 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5692 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5693 
5694 	/* 7. getattr directory */
5695 	argop[7].argop = OP_GETATTR;
5696 	argop[7].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5697 	argop[7].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5698 
5699 	/* 8. access directory */
5700 	argop[8].argop = OP_ACCESS;
5701 	argop[8].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5702 	    ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5703 
5704 	doqueue = 1;
5705 	t = gethrtime();
5706 
5707 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5708 
5709 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5710 		/*
5711 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5712 		 * from this thread, do not go thru the recovery thread since
5713 		 * we need the nm information.
5714 		 *
5715 		 * Not doing dotdot case because there is no specification
5716 		 * for (PUTFH, SECINFO "..") yet.
5717 		 */
5718 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5719 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr)))
5720 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5721 				    &recov_state, FALSE);
5722 			else
5723 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5724 				    &recov_state, TRUE);
5725 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5726 			kmem_free(argop, argoplist_size);
5727 			if (!e.error)
5728 				goto recov_retry;
5729 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5730 			return (e.error);
5731 		}
5732 
5733 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5734 		    OP_LOOKUP, NULL) == FALSE) {
5735 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5736 			    &recov_state, TRUE);
5737 
5738 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5739 			kmem_free(argop, argoplist_size);
5740 			goto recov_retry;
5741 		}
5742 	}
5743 
5744 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5745 
5746 	if (e.error || res.array_len == 0) {
5747 		/*
5748 		 * If e.error isn't set, then reply has no ops (or we couldn't
5749 		 * be here).  The only legal way to reply without an op array
5750 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5751 		 * be in the reply for all other status values.
5752 		 *
5753 		 * For valid replies without an ops array, return ENOTSUP
5754 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5755 		 * return EIO -- don't trust status.
5756 		 */
5757 		if (e.error == 0)
5758 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5759 			    ENOTSUP : EIO;
5760 
5761 		kmem_free(argop, argoplist_size);
5762 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5763 		return (e.error);
5764 	}
5765 
5766 	e.error = geterrno4(res.status);
5767 
5768 	/*
5769 	 * The PUTFH and SAVEFH may have failed.
5770 	 */
5771 	if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5772 	    (res.array[1].nfs_resop4_u.opsavefh.status != NFS4_OK)) {
5773 		nfs4_purge_stale_fh(e.error, dvp, cr);
5774 		goto exit;
5775 	}
5776 
5777 	/*
5778 	 * Check if the file exists, if it does delay entering
5779 	 * into the dnlc until after we update the directory
5780 	 * attributes so we don't cause it to get purged immediately.
5781 	 */
5782 	if (res.array[2].nfs_resop4_u.oplookup.status != NFS4_OK) {
5783 		/*
5784 		 * The lookup failed, probably no entry
5785 		 */
5786 		if (e.error == ENOENT && nfs4_lookup_neg_cache)
5787 			dnlc_update(dvp, nm, DNLC_NO_VNODE);
5788 		goto exit;
5789 	}
5790 
5791 	if (res.array[3].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5792 		/*
5793 		 * The file exists but we can't get its fh for
5794 		 * some unknown reason. Error out to be safe.
5795 		 */
5796 		goto exit;
5797 	}
5798 
5799 	fhp = &res.array[3].nfs_resop4_u.opgetfh.object;
5800 	if (fhp->nfs_fh4_len == 0) {
5801 		/*
5802 		 * The file exists but a bogus fh
5803 		 * some unknown reason.  Error out to be safe.
5804 		 */
5805 		e.error = EIO;
5806 		goto exit;
5807 	}
5808 	sfhp = sfh4_get(fhp, mi);
5809 
5810 	if (res.array[4].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5811 		sfh4_rele(&sfhp);
5812 		goto exit;
5813 	}
5814 	garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
5815 
5816 	/*
5817 	 * The RESTOREFH may have failed
5818 	 */
5819 	if (res.array[5].nfs_resop4_u.oprestorefh.status != NFS4_OK) {
5820 		sfh4_rele(&sfhp);
5821 		e.error = EIO;
5822 		goto exit;
5823 	}
5824 
5825 	if (res.array[6].nfs_resop4_u.opnverify.status != NFS4ERR_SAME) {
5826 		/*
5827 		 * First make sure the NVERIFY failed as we expected,
5828 		 * if it didn't then be conservative and error out
5829 		 * as we can't trust the directory.
5830 		 */
5831 		if (res.array[6].nfs_resop4_u.opnverify.status != NFS4_OK) {
5832 			sfh4_rele(&sfhp);
5833 			e.error = EIO;
5834 			goto exit;
5835 		}
5836 
5837 		/*
5838 		 * We know the NVERIFY "failed" so the directory has changed,
5839 		 * so we must:
5840 		 *	purge the caches (access and indirectly dnlc if needed)
5841 		 */
5842 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5843 
5844 		if (res.array[7].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5845 			sfh4_rele(&sfhp);
5846 			goto exit;
5847 		}
5848 		nfs4_attr_cache(dvp,
5849 		    &res.array[7].nfs_resop4_u.opgetattr.ga_res,
5850 		    t, cr, FALSE, NULL);
5851 
5852 		if (res.array[8].nfs_resop4_u.opaccess.status != NFS4_OK) {
5853 			nfs4_purge_stale_fh(e.error, dvp, cr);
5854 			sfh4_rele(&sfhp);
5855 			e.error = geterrno4(res.status);
5856 			goto exit;
5857 		}
5858 
5859 		/*
5860 		 * Now we know the directory is valid,
5861 		 * cache new directory access
5862 		 */
5863 		nfs4_access_cache(drp,
5864 		    args.array[8].nfs_argop4_u.opaccess.access,
5865 		    res.array[8].nfs_resop4_u.opaccess.access, cr);
5866 
5867 		/*
5868 		 * recheck VEXEC access
5869 		 */
5870 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5871 		if (cacc != NFS4_ACCESS_ALLOWED) {
5872 			/*
5873 			 * Directory permissions might have been revoked
5874 			 */
5875 			if (cacc == NFS4_ACCESS_DENIED) {
5876 				sfh4_rele(&sfhp);
5877 				e.error = EACCES;
5878 				goto exit;
5879 			}
5880 
5881 			/*
5882 			 * Somehow we must not have asked for enough
5883 			 * so try a singleton ACCESS should never happen
5884 			 */
5885 			e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5886 			if (e.error) {
5887 				sfh4_rele(&sfhp);
5888 				goto exit;
5889 			}
5890 		}
5891 
5892 		e.error = geterrno4(res.status);
5893 	} else {
5894 		hrtime_t now;
5895 		hrtime_t delta = 0;
5896 
5897 		e.error = 0;
5898 
5899 		/*
5900 		 * Because the NVERIFY "succeeded" we know that the
5901 		 * directory attributes are still valid
5902 		 * so update r_time_attr_inval
5903 		 */
5904 		now = gethrtime();
5905 		mutex_enter(&drp->r_statelock);
5906 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
5907 			delta = now - drp->r_time_attr_saved;
5908 			if (delta < mi->mi_acdirmin)
5909 				delta = mi->mi_acdirmin;
5910 			else if (delta > mi->mi_acdirmax)
5911 				delta = mi->mi_acdirmax;
5912 		}
5913 		drp->r_time_attr_inval = now + delta;
5914 		mutex_exit(&drp->r_statelock);
5915 
5916 		/*
5917 		 * Even though we have a valid directory attr cache,
5918 		 * we may not have access.
5919 		 * This should almost always hit the cache.
5920 		 */
5921 		e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5922 		if (e.error) {
5923 			sfh4_rele(&sfhp);
5924 			goto exit;
5925 		}
5926 	}
5927 
5928 	/*
5929 	 * Now we have successfully completed the lookup, if the
5930 	 * directory has changed we now have the valid attributes.
5931 	 * We also know we have directory access.
5932 	 * Create the new rnode and insert it in the dnlc.
5933 	 */
5934 	if (isdotdot) {
5935 		e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
5936 		if (e.error) {
5937 			sfh4_rele(&sfhp);
5938 			goto exit;
5939 		}
5940 		/*
5941 		 * XXX if nfs4_make_dotdot uses an existing rnode
5942 		 * XXX it doesn't update the attributes.
5943 		 * XXX for now just save them again to save an OTW
5944 		 */
5945 		nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
5946 	} else {
5947 		nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
5948 		    dvp, fn_get(VTOSV(dvp)->sv_name, nm));
5949 	}
5950 	sfh4_rele(&sfhp);
5951 
5952 	nrp = VTOR4(nvp);
5953 	mutex_enter(&nrp->r_statev4_lock);
5954 	if (!nrp->created_v4) {
5955 		mutex_exit(&nrp->r_statev4_lock);
5956 		dnlc_update(dvp, nm, nvp);
5957 	} else
5958 		mutex_exit(&nrp->r_statev4_lock);
5959 
5960 	*vpp = nvp;
5961 
5962 exit:
5963 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5964 	kmem_free(argop, argoplist_size);
5965 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5966 	return (e.error);
5967 }
5968 
5969 #ifdef DEBUG
5970 void
5971 nfs4lookup_dump_compound(char *where, nfs_argop4 *argbase, int argcnt)
5972 {
5973 	uint_t i, len;
5974 	zoneid_t zoneid = getzoneid();
5975 	char *s;
5976 
5977 	zcmn_err(zoneid, CE_NOTE, "%s: dumping cmpd", where);
5978 	for (i = 0; i < argcnt; i++) {
5979 		nfs_argop4 *op = &argbase[i];
5980 		switch (op->argop) {
5981 		case OP_CPUTFH:
5982 		case OP_PUTFH:
5983 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putfh", i);
5984 			break;
5985 		case OP_PUTROOTFH:
5986 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putrootfh", i);
5987 			break;
5988 		case OP_CLOOKUP:
5989 			s = op->nfs_argop4_u.opclookup.cname;
5990 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
5991 			break;
5992 		case OP_LOOKUP:
5993 			s = utf8_to_str(&op->nfs_argop4_u.oplookup.objname,
5994 			    &len, NULL);
5995 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
5996 			kmem_free(s, len);
5997 			break;
5998 		case OP_LOOKUPP:
5999 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookupp ..", i);
6000 			break;
6001 		case OP_GETFH:
6002 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getfh", i);
6003 			break;
6004 		case OP_GETATTR:
6005 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getattr", i);
6006 			break;
6007 		case OP_OPENATTR:
6008 			zcmn_err(zoneid, CE_NOTE, "\t op %d, openattr", i);
6009 			break;
6010 		default:
6011 			zcmn_err(zoneid, CE_NOTE, "\t op %d, opcode %d", i,
6012 			    op->argop);
6013 			break;
6014 		}
6015 	}
6016 }
6017 #endif
6018 
6019 /*
6020  * nfs4lookup_setup - constructs a multi-lookup compound request.
6021  *
6022  * Given the path "nm1/nm2/.../nmn", the following compound requests
6023  * may be created:
6024  *
6025  * Note: Getfh is not be needed because filehandle attr is mandatory, but it
6026  * is faster, for now.
6027  *
6028  * l4_getattrs indicates the type of compound requested.
6029  *
6030  * LKP4_NO_ATTRIBUTE - no attributes (used by secinfo):
6031  *
6032  *	compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ...  Lookup {nmn} }
6033  *
6034  *   total number of ops is n + 1.
6035  *
6036  * LKP4_LAST_NAMED_ATTR - multi-component path for a named
6037  *      attribute: create lookups plus one OPENATTR/GETFH/GETATTR
6038  *      before the last component, and only get attributes
6039  *      for the last component.  Note that the second-to-last
6040  *	pathname component is XATTR_RPATH, which does NOT go
6041  *	over-the-wire as a lookup.
6042  *
6043  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Lookup {nmn-2};
6044  *		Openattr; Getfh; Getattr; Lookup {nmn}; Getfh; Getattr }
6045  *
6046  *   and total number of ops is n + 5.
6047  *
6048  * LKP4_LAST_ATTRDIR - multi-component path for the hidden named
6049  *      attribute directory: create lookups plus an OPENATTR
6050  *	replacing the last lookup.  Note that the last pathname
6051  *	component is XATTR_RPATH, which does NOT go over-the-wire
6052  *	as a lookup.
6053  *
6054  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Getfh; Getattr;
6055  *		Openattr; Getfh; Getattr }
6056  *
6057  *   and total number of ops is n + 5.
6058  *
6059  * LKP4_ALL_ATTRIBUTES - create lookups and get attributes for intermediate
6060  *	nodes too.
6061  *
6062  *	compound { Put*fh; Lookup {nm1}; Getfh; Getattr;
6063  *		Lookup {nm2}; ...  Lookup {nmn}; Getfh; Getattr }
6064  *
6065  *   and total number of ops is 3*n + 1.
6066  *
6067  * All cases: returns the index in the arg array of the final LOOKUP op, or
6068  * -1 if no LOOKUPs were used.
6069  */
6070 int
6071 nfs4lookup_setup(char *nm, lookup4_param_t *lookupargp, int needgetfh)
6072 {
6073 	enum lkp4_attr_setup l4_getattrs = lookupargp->l4_getattrs;
6074 	nfs_argop4 *argbase, *argop;
6075 	int arglen, argcnt;
6076 	int n = 1;	/* number of components */
6077 	int nga = 1;	/* number of Getattr's in request */
6078 	char c = '\0', *s, *p;
6079 	int lookup_idx = -1;
6080 	int argoplist_size;
6081 
6082 	/* set lookuparg response result to 0 */
6083 	lookupargp->resp->status = NFS4_OK;
6084 
6085 	/* skip leading "/" or "." e.g. ".//./" if there is */
6086 	for (; ; nm++) {
6087 		if (*nm != '/' && *nm != '.')
6088 			break;
6089 
6090 		/* ".." is counted as 1 component */
6091 		if (*nm == '.' && *(nm + 1) == '.')
6092 			break;
6093 	}
6094 
6095 	/*
6096 	 * Find n = number of components - nm must be null terminated
6097 	 * Skip "." components.
6098 	 */
6099 	if (*nm != '\0')
6100 		for (n = 1, s = nm; *s != '\0'; s++) {
6101 			if ((*s == '/') && (*(s + 1) != '/') &&
6102 			    (*(s + 1) != '\0') &&
6103 			    !(*(s + 1) == '.' && (*(s + 2) == '/' ||
6104 			    *(s + 2) == '\0')))
6105 				n++;
6106 		}
6107 	else
6108 		n = 0;
6109 
6110 	/*
6111 	 * nga is number of components that need Getfh+Getattr
6112 	 */
6113 	switch (l4_getattrs) {
6114 	case LKP4_NO_ATTRIBUTES:
6115 		nga = 0;
6116 		break;
6117 	case LKP4_ALL_ATTRIBUTES:
6118 		nga = n;
6119 		/*
6120 		 * Always have at least 1 getfh, getattr pair
6121 		 */
6122 		if (nga == 0)
6123 			nga++;
6124 		break;
6125 	case LKP4_LAST_ATTRDIR:
6126 	case LKP4_LAST_NAMED_ATTR:
6127 		nga = n+1;
6128 		break;
6129 	}
6130 
6131 	/*
6132 	 * If change to use the filehandle attr instead of getfh
6133 	 * the following line can be deleted.
6134 	 */
6135 	nga *= 2;
6136 
6137 	/*
6138 	 * calculate number of ops in request as
6139 	 * header + trailer + lookups + getattrs
6140 	 */
6141 	arglen = lookupargp->header_len + lookupargp->trailer_len + n + nga;
6142 
6143 	argoplist_size = arglen * sizeof (nfs_argop4);
6144 	argop = argbase = kmem_alloc(argoplist_size, KM_SLEEP);
6145 	lookupargp->argsp->array = argop;
6146 
6147 	argcnt = lookupargp->header_len;
6148 	argop += argcnt;
6149 
6150 	/*
6151 	 * loop and create a lookup op and possibly getattr/getfh for
6152 	 * each component. Skip "." components.
6153 	 */
6154 	for (s = nm; *s != '\0'; s = p) {
6155 		/*
6156 		 * Set up a pathname struct for each component if needed
6157 		 */
6158 		while (*s == '/')
6159 			s++;
6160 		if (*s == '\0')
6161 			break;
6162 
6163 		for (p = s; (*p != '/') && (*p != '\0'); p++)
6164 			;
6165 		c = *p;
6166 		*p = '\0';
6167 
6168 		if (s[0] == '.' && s[1] == '\0') {
6169 			*p = c;
6170 			continue;
6171 		}
6172 		if (l4_getattrs == LKP4_LAST_ATTRDIR &&
6173 		    strcmp(s, XATTR_RPATH) == 0) {
6174 			/* getfh XXX may not be needed in future */
6175 			argop->argop = OP_GETFH;
6176 			argop++;
6177 			argcnt++;
6178 
6179 			/* getattr */
6180 			argop->argop = OP_GETATTR;
6181 			argop->nfs_argop4_u.opgetattr.attr_request =
6182 			    lookupargp->ga_bits;
6183 			argop->nfs_argop4_u.opgetattr.mi =
6184 			    lookupargp->mi;
6185 			argop++;
6186 			argcnt++;
6187 
6188 			/* openattr */
6189 			argop->argop = OP_OPENATTR;
6190 		} else if (l4_getattrs == LKP4_LAST_NAMED_ATTR &&
6191 		    strcmp(s, XATTR_RPATH) == 0) {
6192 			/* openattr */
6193 			argop->argop = OP_OPENATTR;
6194 			argop++;
6195 			argcnt++;
6196 
6197 			/* getfh XXX may not be needed in future */
6198 			argop->argop = OP_GETFH;
6199 			argop++;
6200 			argcnt++;
6201 
6202 			/* getattr */
6203 			argop->argop = OP_GETATTR;
6204 			argop->nfs_argop4_u.opgetattr.attr_request =
6205 			    lookupargp->ga_bits;
6206 			argop->nfs_argop4_u.opgetattr.mi =
6207 			    lookupargp->mi;
6208 			argop++;
6209 			argcnt++;
6210 			*p = c;
6211 			continue;
6212 		} else if (s[0] == '.' && s[1] == '.' && s[2] == '\0') {
6213 			/* lookupp */
6214 			argop->argop = OP_LOOKUPP;
6215 		} else {
6216 			/* lookup */
6217 			argop->argop = OP_LOOKUP;
6218 			(void) str_to_utf8(s,
6219 			    &argop->nfs_argop4_u.oplookup.objname);
6220 		}
6221 		lookup_idx = argcnt;
6222 		argop++;
6223 		argcnt++;
6224 
6225 		*p = c;
6226 
6227 		if (l4_getattrs == LKP4_ALL_ATTRIBUTES) {
6228 			/* getfh XXX may not be needed in future */
6229 			argop->argop = OP_GETFH;
6230 			argop++;
6231 			argcnt++;
6232 
6233 			/* getattr */
6234 			argop->argop = OP_GETATTR;
6235 			argop->nfs_argop4_u.opgetattr.attr_request =
6236 			    lookupargp->ga_bits;
6237 			argop->nfs_argop4_u.opgetattr.mi =
6238 			    lookupargp->mi;
6239 			argop++;
6240 			argcnt++;
6241 		}
6242 	}
6243 
6244 	if ((l4_getattrs != LKP4_NO_ATTRIBUTES) &&
6245 	    ((l4_getattrs != LKP4_ALL_ATTRIBUTES) || (lookup_idx < 0))) {
6246 		if (needgetfh) {
6247 			/* stick in a post-lookup getfh */
6248 			argop->argop = OP_GETFH;
6249 			argcnt++;
6250 			argop++;
6251 		}
6252 		/* post-lookup getattr */
6253 		argop->argop = OP_GETATTR;
6254 		argop->nfs_argop4_u.opgetattr.attr_request =
6255 		    lookupargp->ga_bits;
6256 		argop->nfs_argop4_u.opgetattr.mi = lookupargp->mi;
6257 		argcnt++;
6258 	}
6259 	argcnt += lookupargp->trailer_len;	/* actual op count */
6260 	lookupargp->argsp->array_len = argcnt;
6261 	lookupargp->arglen = arglen;
6262 
6263 #ifdef DEBUG
6264 	if (nfs4_client_lookup_debug)
6265 		nfs4lookup_dump_compound("nfs4lookup_setup", argbase, argcnt);
6266 #endif
6267 
6268 	return (lookup_idx);
6269 }
6270 
6271 static int
6272 nfs4openattr(vnode_t *dvp, vnode_t **avp, int cflag, cred_t *cr)
6273 {
6274 	COMPOUND4args_clnt	args;
6275 	COMPOUND4res_clnt	res;
6276 	GETFH4res	*gf_res = NULL;
6277 	nfs_argop4	argop[4];
6278 	nfs_resop4	*resop = NULL;
6279 	nfs4_sharedfh_t *sfhp;
6280 	hrtime_t t;
6281 	nfs4_error_t	e;
6282 
6283 	rnode4_t	*drp;
6284 	int		doqueue = 1;
6285 	vnode_t		*vp;
6286 	int		needrecov = 0;
6287 	nfs4_recov_state_t recov_state;
6288 
6289 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
6290 
6291 	*avp = NULL;
6292 	recov_state.rs_flags = 0;
6293 	recov_state.rs_num_retry_despite_err = 0;
6294 
6295 recov_retry:
6296 	/* COMPOUND: putfh, openattr, getfh, getattr */
6297 	args.array_len = 4;
6298 	args.array = argop;
6299 	args.ctag = TAG_OPENATTR;
6300 
6301 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
6302 	if (e.error)
6303 		return (e.error);
6304 
6305 	drp = VTOR4(dvp);
6306 
6307 	/* putfh */
6308 	argop[0].argop = OP_CPUTFH;
6309 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6310 
6311 	/* openattr */
6312 	argop[1].argop = OP_OPENATTR;
6313 	argop[1].nfs_argop4_u.opopenattr.createdir = (cflag ? TRUE : FALSE);
6314 
6315 	/* getfh */
6316 	argop[2].argop = OP_GETFH;
6317 
6318 	/* getattr */
6319 	argop[3].argop = OP_GETATTR;
6320 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6321 	argop[3].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
6322 
6323 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
6324 	    "nfs4openattr: %s call, drp %s", needrecov ? "recov" : "first",
6325 	    rnode4info(drp)));
6326 
6327 	t = gethrtime();
6328 
6329 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
6330 
6331 	needrecov = nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp);
6332 	if (needrecov) {
6333 		bool_t abort;
6334 
6335 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
6336 		    "nfs4openattr: initiating recovery\n"));
6337 
6338 		abort = nfs4_start_recovery(&e,
6339 		    VTOMI4(dvp), dvp, NULL, NULL, NULL,
6340 		    OP_OPENATTR, NULL);
6341 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6342 		if (!e.error) {
6343 			e.error = geterrno4(res.status);
6344 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6345 		}
6346 		if (abort == FALSE)
6347 			goto recov_retry;
6348 		return (e.error);
6349 	}
6350 
6351 	if (e.error) {
6352 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6353 		return (e.error);
6354 	}
6355 
6356 	if (res.status) {
6357 		/*
6358 		 * If OTW errro is NOTSUPP, then it should be
6359 		 * translated to EINVAL.  All Solaris file system
6360 		 * implementations return EINVAL to the syscall layer
6361 		 * when the attrdir cannot be created due to an
6362 		 * implementation restriction or noxattr mount option.
6363 		 */
6364 		if (res.status == NFS4ERR_NOTSUPP) {
6365 			mutex_enter(&drp->r_statelock);
6366 			if (drp->r_xattr_dir)
6367 				VN_RELE(drp->r_xattr_dir);
6368 			VN_HOLD(NFS4_XATTR_DIR_NOTSUPP);
6369 			drp->r_xattr_dir = NFS4_XATTR_DIR_NOTSUPP;
6370 			mutex_exit(&drp->r_statelock);
6371 
6372 			e.error = EINVAL;
6373 		} else {
6374 			e.error = geterrno4(res.status);
6375 		}
6376 
6377 		if (e.error) {
6378 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6379 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
6380 			    needrecov);
6381 			return (e.error);
6382 		}
6383 	}
6384 
6385 	resop = &res.array[0];  /* putfh res */
6386 	ASSERT(resop->nfs_resop4_u.opgetfh.status == NFS4_OK);
6387 
6388 	resop = &res.array[1];  /* openattr res */
6389 	ASSERT(resop->nfs_resop4_u.opopenattr.status == NFS4_OK);
6390 
6391 	resop = &res.array[2];  /* getfh res */
6392 	gf_res = &resop->nfs_resop4_u.opgetfh;
6393 	if (gf_res->object.nfs_fh4_len == 0) {
6394 		*avp = NULL;
6395 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6396 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6397 		return (ENOENT);
6398 	}
6399 
6400 	sfhp = sfh4_get(&gf_res->object, VTOMI4(dvp));
6401 	vp = makenfs4node(sfhp, &res.array[3].nfs_resop4_u.opgetattr.ga_res,
6402 	    dvp->v_vfsp, t, cr, dvp,
6403 	    fn_get(VTOSV(dvp)->sv_name, XATTR_RPATH));
6404 	sfh4_rele(&sfhp);
6405 
6406 	if (e.error)
6407 		PURGE_ATTRCACHE4(vp);
6408 
6409 	mutex_enter(&vp->v_lock);
6410 	vp->v_flag |= V_XATTRDIR;
6411 	mutex_exit(&vp->v_lock);
6412 
6413 	*avp = vp;
6414 
6415 	mutex_enter(&drp->r_statelock);
6416 	if (drp->r_xattr_dir)
6417 		VN_RELE(drp->r_xattr_dir);
6418 	VN_HOLD(vp);
6419 	drp->r_xattr_dir = vp;
6420 
6421 	/*
6422 	 * Invalidate pathconf4 cache because r_xattr_dir is no longer
6423 	 * NULL.  xattrs could be created at any time, and we have no
6424 	 * way to update pc4_xattr_exists in the base object if/when
6425 	 * it happens.
6426 	 */
6427 	drp->r_pathconf.pc4_xattr_valid = 0;
6428 
6429 	mutex_exit(&drp->r_statelock);
6430 
6431 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6432 
6433 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6434 
6435 	return (0);
6436 }
6437 
6438 /* ARGSUSED */
6439 static int
6440 nfs4_create(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
6441 	int mode, vnode_t **vpp, cred_t *cr, int flags, caller_context_t *ct,
6442 	vsecattr_t *vsecp)
6443 {
6444 	int error;
6445 	vnode_t *vp = NULL;
6446 	rnode4_t *rp;
6447 	struct vattr vattr;
6448 	rnode4_t *drp;
6449 	vnode_t *tempvp;
6450 	enum createmode4 createmode;
6451 	bool_t must_trunc = FALSE;
6452 	int	truncating = 0;
6453 
6454 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
6455 		return (EPERM);
6456 	if (exclusive == EXCL && (dvp->v_flag & V_XATTRDIR)) {
6457 		return (EINVAL);
6458 	}
6459 
6460 	/* . and .. have special meaning in the protocol, reject them. */
6461 
6462 	if (nm[0] == '.' && (nm[1] == '\0' || (nm[1] == '.' && nm[2] == '\0')))
6463 		return (EISDIR);
6464 
6465 	drp = VTOR4(dvp);
6466 
6467 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
6468 		return (EINTR);
6469 
6470 top:
6471 	/*
6472 	 * We make a copy of the attributes because the caller does not
6473 	 * expect us to change what va points to.
6474 	 */
6475 	vattr = *va;
6476 
6477 	/*
6478 	 * If the pathname is "", then dvp is the root vnode of
6479 	 * a remote file mounted over a local directory.
6480 	 * All that needs to be done is access
6481 	 * checking and truncation.  Note that we avoid doing
6482 	 * open w/ create because the parent directory might
6483 	 * be in pseudo-fs and the open would fail.
6484 	 */
6485 	if (*nm == '\0') {
6486 		error = 0;
6487 		VN_HOLD(dvp);
6488 		vp = dvp;
6489 		must_trunc = TRUE;
6490 	} else {
6491 		/*
6492 		 * We need to go over the wire, just to be sure whether the
6493 		 * file exists or not.  Using the DNLC can be dangerous in
6494 		 * this case when making a decision regarding existence.
6495 		 */
6496 		error = nfs4lookup(dvp, nm, &vp, cr, 1);
6497 	}
6498 
6499 	if (exclusive)
6500 		createmode = EXCLUSIVE4;
6501 	else
6502 		createmode = GUARDED4;
6503 
6504 	/*
6505 	 * error would be set if the file does not exist on the
6506 	 * server, so lets go create it.
6507 	 */
6508 	if (error) {
6509 		goto create_otw;
6510 	}
6511 
6512 	/*
6513 	 * File does exist on the server
6514 	 */
6515 	if (exclusive == EXCL)
6516 		error = EEXIST;
6517 	else if (vp->v_type == VDIR && (mode & VWRITE))
6518 		error = EISDIR;
6519 	else {
6520 		/*
6521 		 * If vnode is a device, create special vnode.
6522 		 */
6523 		if (ISVDEV(vp->v_type)) {
6524 			tempvp = vp;
6525 			vp = specvp(vp, vp->v_rdev, vp->v_type, cr);
6526 			VN_RELE(tempvp);
6527 		}
6528 		if (!(error = VOP_ACCESS(vp, mode, 0, cr, ct))) {
6529 			if ((vattr.va_mask & AT_SIZE) &&
6530 			    vp->v_type == VREG) {
6531 				rp = VTOR4(vp);
6532 				/*
6533 				 * Check here for large file handled
6534 				 * by LF-unaware process (as
6535 				 * ufs_create() does)
6536 				 */
6537 				if (!(flags & FOFFMAX)) {
6538 					mutex_enter(&rp->r_statelock);
6539 					if (rp->r_size > MAXOFF32_T)
6540 						error = EOVERFLOW;
6541 					mutex_exit(&rp->r_statelock);
6542 				}
6543 
6544 				/* if error is set then we need to return */
6545 				if (error) {
6546 					nfs_rw_exit(&drp->r_rwlock);
6547 					VN_RELE(vp);
6548 					return (error);
6549 				}
6550 
6551 				if (must_trunc) {
6552 					vattr.va_mask = AT_SIZE;
6553 					error = nfs4setattr(vp, &vattr, 0, cr,
6554 					    NULL);
6555 				} else {
6556 				/*
6557 				 * we know we have a regular file that already
6558 				 * exists and we may end up truncating the file
6559 				 * as a result of the open_otw, so flush out
6560 				 * any dirty pages for this file first.
6561 				 */
6562 					if (nfs4_has_pages(vp) &&
6563 					    ((rp->r_flags & R4DIRTY) ||
6564 					    rp->r_count > 0 ||
6565 					    rp->r_mapcnt > 0)) {
6566 						error = nfs4_putpage(vp,
6567 						    (offset_t)0, 0, 0, cr, ct);
6568 						if (error && (error == ENOSPC ||
6569 						    error == EDQUOT)) {
6570 							mutex_enter(
6571 							    &rp->r_statelock);
6572 							if (!rp->r_error)
6573 								rp->r_error =
6574 								    error;
6575 							mutex_exit(
6576 							    &rp->r_statelock);
6577 						}
6578 					}
6579 					vattr.va_mask = (AT_SIZE |
6580 					    AT_TYPE | AT_MODE);
6581 					vattr.va_type = VREG;
6582 					createmode = UNCHECKED4;
6583 					truncating = 1;
6584 					goto create_otw;
6585 				}
6586 			}
6587 		}
6588 	}
6589 	nfs_rw_exit(&drp->r_rwlock);
6590 	if (error) {
6591 		VN_RELE(vp);
6592 	} else {
6593 		vnode_t *tvp;
6594 		rnode4_t *trp;
6595 		/*
6596 		 * existing file got truncated, notify.
6597 		 */
6598 		tvp = vp;
6599 		if (vp->v_type == VREG) {
6600 			trp = VTOR4(vp);
6601 			if (IS_SHADOW(vp, trp))
6602 				tvp = RTOV4(trp);
6603 		}
6604 		vnevent_create(tvp, ct);
6605 		*vpp = vp;
6606 	}
6607 	return (error);
6608 
6609 create_otw:
6610 	dnlc_remove(dvp, nm);
6611 
6612 	ASSERT(vattr.va_mask & AT_TYPE);
6613 
6614 	/*
6615 	 * If not a regular file let nfs4mknod() handle it.
6616 	 */
6617 	if (vattr.va_type != VREG) {
6618 		error = nfs4mknod(dvp, nm, &vattr, exclusive, mode, vpp, cr);
6619 		nfs_rw_exit(&drp->r_rwlock);
6620 		return (error);
6621 	}
6622 
6623 	/*
6624 	 * It _is_ a regular file.
6625 	 */
6626 	ASSERT(vattr.va_mask & AT_MODE);
6627 	if (MANDMODE(vattr.va_mode)) {
6628 		nfs_rw_exit(&drp->r_rwlock);
6629 		return (EACCES);
6630 	}
6631 
6632 	/*
6633 	 * If this happens to be a mknod of a regular file, then flags will
6634 	 * have neither FREAD or FWRITE.  However, we must set at least one
6635 	 * for the call to nfs4open_otw.  If it's open(O_CREAT) driving
6636 	 * nfs4_create, then either FREAD, FWRITE, or FRDWR has already been
6637 	 * set (based on openmode specified by app).
6638 	 */
6639 	if ((flags & (FREAD|FWRITE)) == 0)
6640 		flags |= (FREAD|FWRITE);
6641 
6642 	error = nfs4open_otw(dvp, nm, &vattr, vpp, cr, 1, flags, createmode, 0);
6643 
6644 	if (vp != NULL) {
6645 		/* if create was successful, throw away the file's pages */
6646 		if (!error && (vattr.va_mask & AT_SIZE))
6647 			nfs4_invalidate_pages(vp, (vattr.va_size & PAGEMASK),
6648 			    cr);
6649 		/* release the lookup hold */
6650 		VN_RELE(vp);
6651 		vp = NULL;
6652 	}
6653 
6654 	/*
6655 	 * validate that we opened a regular file. This handles a misbehaving
6656 	 * server that returns an incorrect FH.
6657 	 */
6658 	if ((error == 0) && *vpp && (*vpp)->v_type != VREG) {
6659 		error = EISDIR;
6660 		VN_RELE(*vpp);
6661 	}
6662 
6663 	/*
6664 	 * If this is not an exclusive create, then the CREATE
6665 	 * request will be made with the GUARDED mode set.  This
6666 	 * means that the server will return EEXIST if the file
6667 	 * exists.  The file could exist because of a retransmitted
6668 	 * request.  In this case, we recover by starting over and
6669 	 * checking to see whether the file exists.  This second
6670 	 * time through it should and a CREATE request will not be
6671 	 * sent.
6672 	 *
6673 	 * This handles the problem of a dangling CREATE request
6674 	 * which contains attributes which indicate that the file
6675 	 * should be truncated.  This retransmitted request could
6676 	 * possibly truncate valid data in the file if not caught
6677 	 * by the duplicate request mechanism on the server or if
6678 	 * not caught by other means.  The scenario is:
6679 	 *
6680 	 * Client transmits CREATE request with size = 0
6681 	 * Client times out, retransmits request.
6682 	 * Response to the first request arrives from the server
6683 	 *  and the client proceeds on.
6684 	 * Client writes data to the file.
6685 	 * The server now processes retransmitted CREATE request
6686 	 *  and truncates file.
6687 	 *
6688 	 * The use of the GUARDED CREATE request prevents this from
6689 	 * happening because the retransmitted CREATE would fail
6690 	 * with EEXIST and would not truncate the file.
6691 	 */
6692 	if (error == EEXIST && exclusive == NONEXCL) {
6693 #ifdef DEBUG
6694 		nfs4_create_misses++;
6695 #endif
6696 		goto top;
6697 	}
6698 	nfs_rw_exit(&drp->r_rwlock);
6699 	if (truncating && !error && *vpp) {
6700 		vnode_t *tvp;
6701 		rnode4_t *trp;
6702 		/*
6703 		 * existing file got truncated, notify.
6704 		 */
6705 		tvp = *vpp;
6706 		trp = VTOR4(tvp);
6707 		if (IS_SHADOW(tvp, trp))
6708 			tvp = RTOV4(trp);
6709 		vnevent_create(tvp, ct);
6710 	}
6711 	return (error);
6712 }
6713 
6714 /*
6715  * Create compound (for mkdir, mknod, symlink):
6716  * { Putfh <dfh>; Create; Getfh; Getattr }
6717  * It's okay if setattr failed to set gid - this is not considered
6718  * an error, but purge attrs in that case.
6719  */
6720 static int
6721 call_nfs4_create_req(vnode_t *dvp, char *nm, void *data, struct vattr *va,
6722     vnode_t **vpp, cred_t *cr, nfs_ftype4 type)
6723 {
6724 	int need_end_op = FALSE;
6725 	COMPOUND4args_clnt args;
6726 	COMPOUND4res_clnt res, *resp = NULL;
6727 	nfs_argop4 *argop;
6728 	nfs_resop4 *resop;
6729 	int doqueue;
6730 	mntinfo4_t *mi;
6731 	rnode4_t *drp = VTOR4(dvp);
6732 	change_info4 *cinfo;
6733 	GETFH4res *gf_res;
6734 	struct vattr vattr;
6735 	vnode_t *vp;
6736 	fattr4 *crattr;
6737 	bool_t needrecov = FALSE;
6738 	nfs4_recov_state_t recov_state;
6739 	nfs4_sharedfh_t *sfhp = NULL;
6740 	hrtime_t t;
6741 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
6742 	int numops, argoplist_size, setgid_flag, idx_create, idx_fattr;
6743 	dirattr_info_t dinfo, *dinfop;
6744 	servinfo4_t *svp;
6745 	bitmap4 supp_attrs;
6746 
6747 	ASSERT(type == NF4DIR || type == NF4LNK || type == NF4BLK ||
6748 	    type == NF4CHR || type == NF4SOCK || type == NF4FIFO);
6749 
6750 	mi = VTOMI4(dvp);
6751 
6752 	/*
6753 	 * Make sure we properly deal with setting the right gid
6754 	 * on a new directory to reflect the parent's setgid bit
6755 	 */
6756 	setgid_flag = 0;
6757 	if (type == NF4DIR) {
6758 		struct vattr dva;
6759 
6760 		va->va_mode &= ~VSGID;
6761 		dva.va_mask = AT_MODE | AT_GID;
6762 		if (VOP_GETATTR(dvp, &dva, 0, cr, NULL) == 0) {
6763 
6764 			/*
6765 			 * If the parent's directory has the setgid bit set
6766 			 * _and_ the client was able to get a valid mapping
6767 			 * for the parent dir's owner_group, we want to
6768 			 * append NVERIFY(owner_group == dva.va_gid) and
6769 			 * SETTATTR to the CREATE compound.
6770 			 */
6771 			if (mi->mi_flags & MI4_GRPID || dva.va_mode & VSGID) {
6772 				setgid_flag = 1;
6773 				va->va_mode |= VSGID;
6774 				if (dva.va_gid != GID_NOBODY) {
6775 					va->va_mask |= AT_GID;
6776 					va->va_gid = dva.va_gid;
6777 				}
6778 			}
6779 		}
6780 	}
6781 
6782 	/*
6783 	 * Create ops:
6784 	 *	0:putfh(dir) 1:savefh(dir) 2:create 3:getfh(new) 4:getattr(new)
6785 	 *	5:restorefh(dir) 6:getattr(dir)
6786 	 *
6787 	 * if (setgid)
6788 	 *	0:putfh(dir) 1:create 2:getfh(new) 3:getattr(new)
6789 	 *	4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
6790 	 *	8:nverify 9:setattr
6791 	 */
6792 	if (setgid_flag) {
6793 		numops = 10;
6794 		idx_create = 1;
6795 		idx_fattr = 3;
6796 	} else {
6797 		numops = 7;
6798 		idx_create = 2;
6799 		idx_fattr = 4;
6800 	}
6801 
6802 	ASSERT(nfs_zone() == mi->mi_zone);
6803 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp))) {
6804 		return (EINTR);
6805 	}
6806 	recov_state.rs_flags = 0;
6807 	recov_state.rs_num_retry_despite_err = 0;
6808 
6809 	argoplist_size = numops * sizeof (nfs_argop4);
6810 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
6811 
6812 recov_retry:
6813 	if (type == NF4LNK)
6814 		args.ctag = TAG_SYMLINK;
6815 	else if (type == NF4DIR)
6816 		args.ctag = TAG_MKDIR;
6817 	else
6818 		args.ctag = TAG_MKNOD;
6819 
6820 	args.array_len = numops;
6821 	args.array = argop;
6822 
6823 	if (e.error = nfs4_start_op(mi, dvp, NULL, &recov_state)) {
6824 		nfs_rw_exit(&drp->r_rwlock);
6825 		kmem_free(argop, argoplist_size);
6826 		return (e.error);
6827 	}
6828 	need_end_op = TRUE;
6829 
6830 
6831 	/* 0: putfh directory */
6832 	argop[0].argop = OP_CPUTFH;
6833 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6834 
6835 	/* 1/2: Create object */
6836 	argop[idx_create].argop = OP_CCREATE;
6837 	argop[idx_create].nfs_argop4_u.opccreate.cname = nm;
6838 	argop[idx_create].nfs_argop4_u.opccreate.type = type;
6839 	if (type == NF4LNK) {
6840 		/*
6841 		 * symlink, treat name as data
6842 		 */
6843 		ASSERT(data != NULL);
6844 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.clinkdata =
6845 		    (char *)data;
6846 	}
6847 	if (type == NF4BLK || type == NF4CHR) {
6848 		ASSERT(data != NULL);
6849 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.devdata =
6850 		    *((specdata4 *)data);
6851 	}
6852 
6853 	crattr = &argop[idx_create].nfs_argop4_u.opccreate.createattrs;
6854 
6855 	svp = drp->r_server;
6856 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
6857 	supp_attrs = svp->sv_supp_attrs;
6858 	nfs_rw_exit(&svp->sv_lock);
6859 
6860 	if (vattr_to_fattr4(va, NULL, crattr, 0, OP_CREATE, supp_attrs)) {
6861 		nfs_rw_exit(&drp->r_rwlock);
6862 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
6863 		e.error = EINVAL;
6864 		kmem_free(argop, argoplist_size);
6865 		return (e.error);
6866 	}
6867 
6868 	/* 2/3: getfh fh of created object */
6869 	ASSERT(idx_create + 1 == idx_fattr - 1);
6870 	argop[idx_create + 1].argop = OP_GETFH;
6871 
6872 	/* 3/4: getattr of new object */
6873 	argop[idx_fattr].argop = OP_GETATTR;
6874 	argop[idx_fattr].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6875 	argop[idx_fattr].nfs_argop4_u.opgetattr.mi = mi;
6876 
6877 	if (setgid_flag) {
6878 		vattr_t	_v;
6879 
6880 		argop[4].argop = OP_SAVEFH;
6881 
6882 		argop[5].argop = OP_CPUTFH;
6883 		argop[5].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6884 
6885 		argop[6].argop = OP_GETATTR;
6886 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6887 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
6888 
6889 		argop[7].argop = OP_RESTOREFH;
6890 
6891 		/*
6892 		 * nverify
6893 		 *
6894 		 * XXX - Revisit the last argument to nfs4_end_op()
6895 		 *	 once 5020486 is fixed.
6896 		 */
6897 		_v.va_mask = AT_GID;
6898 		_v.va_gid = va->va_gid;
6899 		if (e.error = nfs4args_verify(&argop[8], &_v, OP_NVERIFY,
6900 		    supp_attrs)) {
6901 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
6902 			nfs_rw_exit(&drp->r_rwlock);
6903 			nfs4_fattr4_free(crattr);
6904 			kmem_free(argop, argoplist_size);
6905 			return (e.error);
6906 		}
6907 
6908 		/*
6909 		 * setattr
6910 		 *
6911 		 * We _know_ we're not messing with AT_SIZE or AT_XTIME,
6912 		 * so no need for stateid or flags. Also we specify NULL
6913 		 * rp since we're only interested in setting owner_group
6914 		 * attributes.
6915 		 */
6916 		nfs4args_setattr(&argop[9], &_v, NULL, 0, NULL, cr, supp_attrs,
6917 		    &e.error, 0);
6918 
6919 		if (e.error) {
6920 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
6921 			nfs_rw_exit(&drp->r_rwlock);
6922 			nfs4_fattr4_free(crattr);
6923 			nfs4args_verify_free(&argop[8]);
6924 			kmem_free(argop, argoplist_size);
6925 			return (e.error);
6926 		}
6927 	} else {
6928 		argop[1].argop = OP_SAVEFH;
6929 
6930 		argop[5].argop = OP_RESTOREFH;
6931 
6932 		argop[6].argop = OP_GETATTR;
6933 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6934 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
6935 	}
6936 
6937 	dnlc_remove(dvp, nm);
6938 
6939 	doqueue = 1;
6940 	t = gethrtime();
6941 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
6942 
6943 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
6944 	if (e.error) {
6945 		PURGE_ATTRCACHE4(dvp);
6946 		if (!needrecov)
6947 			goto out;
6948 	}
6949 
6950 	if (needrecov) {
6951 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
6952 		    OP_CREATE, NULL) == FALSE) {
6953 			nfs4_end_op(mi, dvp, NULL, &recov_state,
6954 			    needrecov);
6955 			need_end_op = FALSE;
6956 			nfs4_fattr4_free(crattr);
6957 			if (setgid_flag) {
6958 				nfs4args_verify_free(&argop[8]);
6959 				nfs4args_setattr_free(&argop[9]);
6960 			}
6961 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6962 			goto recov_retry;
6963 		}
6964 	}
6965 
6966 	resp = &res;
6967 
6968 	if (res.status != NFS4_OK && res.array_len <= idx_fattr + 1) {
6969 
6970 		if (res.status == NFS4ERR_BADOWNER)
6971 			nfs4_log_badowner(mi, OP_CREATE);
6972 
6973 		e.error = geterrno4(res.status);
6974 
6975 		/*
6976 		 * This check is left over from when create was implemented
6977 		 * using a setattr op (instead of createattrs).  If the
6978 		 * putfh/create/getfh failed, the error was returned.  If
6979 		 * setattr/getattr failed, we keep going.
6980 		 *
6981 		 * It might be better to get rid of the GETFH also, and just
6982 		 * do PUTFH/CREATE/GETATTR since the FH attr is mandatory.
6983 		 * Then if any of the operations failed, we could return the
6984 		 * error now, and remove much of the error code below.
6985 		 */
6986 		if (res.array_len <= idx_fattr) {
6987 			/*
6988 			 * Either Putfh, Create or Getfh failed.
6989 			 */
6990 			PURGE_ATTRCACHE4(dvp);
6991 			/*
6992 			 * nfs4_purge_stale_fh() may generate otw calls through
6993 			 * nfs4_invalidate_pages. Hence the need to call
6994 			 * nfs4_end_op() here to avoid nfs4_start_op() deadlock.
6995 			 */
6996 			nfs4_end_op(mi, dvp, NULL, &recov_state,
6997 			    needrecov);
6998 			need_end_op = FALSE;
6999 			nfs4_purge_stale_fh(e.error, dvp, cr);
7000 			goto out;
7001 		}
7002 	}
7003 
7004 	resop = &res.array[idx_create];	/* create res */
7005 	cinfo = &resop->nfs_resop4_u.opcreate.cinfo;
7006 
7007 	resop = &res.array[idx_create + 1]; /* getfh res */
7008 	gf_res = &resop->nfs_resop4_u.opgetfh;
7009 
7010 	sfhp = sfh4_get(&gf_res->object, mi);
7011 	if (e.error) {
7012 		*vpp = vp = makenfs4node(sfhp, NULL, dvp->v_vfsp, t, cr, dvp,
7013 		    fn_get(VTOSV(dvp)->sv_name, nm));
7014 		if (vp->v_type == VNON) {
7015 			vattr.va_mask = AT_TYPE;
7016 			/*
7017 			 * Need to call nfs4_end_op before nfs4getattr to avoid
7018 			 * potential nfs4_start_op deadlock. See RFE 4777612.
7019 			 */
7020 			nfs4_end_op(mi, dvp, NULL, &recov_state,
7021 			    needrecov);
7022 			need_end_op = FALSE;
7023 			e.error = nfs4getattr(vp, &vattr, cr);
7024 			if (e.error) {
7025 				VN_RELE(vp);
7026 				*vpp = NULL;
7027 				goto out;
7028 			}
7029 			vp->v_type = vattr.va_type;
7030 		}
7031 		e.error = 0;
7032 	} else {
7033 		*vpp = vp = makenfs4node(sfhp,
7034 		    &res.array[idx_fattr].nfs_resop4_u.opgetattr.ga_res,
7035 		    dvp->v_vfsp, t, cr,
7036 		    dvp, fn_get(VTOSV(dvp)->sv_name, nm));
7037 	}
7038 
7039 	/*
7040 	 * If compound succeeded, then update dir attrs
7041 	 */
7042 	if (res.status == NFS4_OK) {
7043 		dinfo.di_garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
7044 		dinfo.di_cred = cr;
7045 		dinfo.di_time_call = t;
7046 		dinfop = &dinfo;
7047 	} else
7048 		dinfop = NULL;
7049 
7050 	/* Update directory cache attribute, readdir and dnlc caches */
7051 	nfs4_update_dircaches(cinfo, dvp, vp, nm, dinfop);
7052 
7053 out:
7054 	if (sfhp != NULL)
7055 		sfh4_rele(&sfhp);
7056 	nfs_rw_exit(&drp->r_rwlock);
7057 	nfs4_fattr4_free(crattr);
7058 	if (setgid_flag) {
7059 		nfs4args_verify_free(&argop[8]);
7060 		nfs4args_setattr_free(&argop[9]);
7061 	}
7062 	if (resp)
7063 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7064 	if (need_end_op)
7065 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
7066 
7067 	kmem_free(argop, argoplist_size);
7068 	return (e.error);
7069 }
7070 
7071 /* ARGSUSED */
7072 static int
7073 nfs4mknod(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
7074     int mode, vnode_t **vpp, cred_t *cr)
7075 {
7076 	int error;
7077 	vnode_t *vp;
7078 	nfs_ftype4 type;
7079 	specdata4 spec, *specp = NULL;
7080 
7081 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
7082 
7083 	switch (va->va_type) {
7084 	case VCHR:
7085 	case VBLK:
7086 		type = (va->va_type == VCHR) ? NF4CHR : NF4BLK;
7087 		spec.specdata1 = getmajor(va->va_rdev);
7088 		spec.specdata2 = getminor(va->va_rdev);
7089 		specp = &spec;
7090 		break;
7091 
7092 	case VFIFO:
7093 		type = NF4FIFO;
7094 		break;
7095 	case VSOCK:
7096 		type = NF4SOCK;
7097 		break;
7098 
7099 	default:
7100 		return (EINVAL);
7101 	}
7102 
7103 	error = call_nfs4_create_req(dvp, nm, specp, va, &vp, cr, type);
7104 	if (error) {
7105 		return (error);
7106 	}
7107 
7108 	/*
7109 	 * This might not be needed any more; special case to deal
7110 	 * with problematic v2/v3 servers.  Since create was unable
7111 	 * to set group correctly, not sure what hope setattr has.
7112 	 */
7113 	if (va->va_gid != VTOR4(vp)->r_attr.va_gid) {
7114 		va->va_mask = AT_GID;
7115 		(void) nfs4setattr(vp, va, 0, cr, NULL);
7116 	}
7117 
7118 	/*
7119 	 * If vnode is a device create special vnode
7120 	 */
7121 	if (ISVDEV(vp->v_type)) {
7122 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
7123 		VN_RELE(vp);
7124 	} else {
7125 		*vpp = vp;
7126 	}
7127 	return (error);
7128 }
7129 
7130 /*
7131  * Remove requires that the current fh be the target directory.
7132  * After the operation, the current fh is unchanged.
7133  * The compound op structure is:
7134  *      PUTFH(targetdir), REMOVE
7135  *
7136  * Weirdness: if the vnode to be removed is open
7137  * we rename it instead of removing it and nfs_inactive
7138  * will remove the new name.
7139  */
7140 /* ARGSUSED */
7141 static int
7142 nfs4_remove(vnode_t *dvp, char *nm, cred_t *cr, caller_context_t *ct, int flags)
7143 {
7144 	COMPOUND4args_clnt args;
7145 	COMPOUND4res_clnt res, *resp = NULL;
7146 	REMOVE4res *rm_res;
7147 	nfs_argop4 argop[3];
7148 	nfs_resop4 *resop;
7149 	vnode_t *vp;
7150 	char *tmpname;
7151 	int doqueue;
7152 	mntinfo4_t *mi;
7153 	rnode4_t *rp;
7154 	rnode4_t *drp;
7155 	int needrecov = 0;
7156 	nfs4_recov_state_t recov_state;
7157 	int isopen;
7158 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7159 	dirattr_info_t dinfo;
7160 
7161 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
7162 		return (EPERM);
7163 	drp = VTOR4(dvp);
7164 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
7165 		return (EINTR);
7166 
7167 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
7168 	if (e.error) {
7169 		nfs_rw_exit(&drp->r_rwlock);
7170 		return (e.error);
7171 	}
7172 
7173 	if (vp->v_type == VDIR) {
7174 		VN_RELE(vp);
7175 		nfs_rw_exit(&drp->r_rwlock);
7176 		return (EISDIR);
7177 	}
7178 
7179 	/*
7180 	 * First just remove the entry from the name cache, as it
7181 	 * is most likely the only entry for this vp.
7182 	 */
7183 	dnlc_remove(dvp, nm);
7184 
7185 	rp = VTOR4(vp);
7186 
7187 	/*
7188 	 * For regular file types, check to see if the file is open by looking
7189 	 * at the open streams.
7190 	 * For all other types, check the reference count on the vnode.  Since
7191 	 * they are not opened OTW they never have an open stream.
7192 	 *
7193 	 * If the file is open, rename it to .nfsXXXX.
7194 	 */
7195 	if (vp->v_type != VREG) {
7196 		/*
7197 		 * If the file has a v_count > 1 then there may be more than one
7198 		 * entry in the name cache due multiple links or an open file,
7199 		 * but we don't have the real reference count so flush all
7200 		 * possible entries.
7201 		 */
7202 		if (vp->v_count > 1)
7203 			dnlc_purge_vp(vp);
7204 
7205 		/*
7206 		 * Now we have the real reference count.
7207 		 */
7208 		isopen = vp->v_count > 1;
7209 	} else {
7210 		mutex_enter(&rp->r_os_lock);
7211 		isopen = list_head(&rp->r_open_streams) != NULL;
7212 		mutex_exit(&rp->r_os_lock);
7213 	}
7214 
7215 	mutex_enter(&rp->r_statelock);
7216 	if (isopen &&
7217 	    (rp->r_unldvp == NULL || strcmp(nm, rp->r_unlname) == 0)) {
7218 		mutex_exit(&rp->r_statelock);
7219 		tmpname = newname();
7220 		e.error = nfs4rename(dvp, nm, dvp, tmpname, cr, ct);
7221 		if (e.error)
7222 			kmem_free(tmpname, MAXNAMELEN);
7223 		else {
7224 			mutex_enter(&rp->r_statelock);
7225 			if (rp->r_unldvp == NULL) {
7226 				VN_HOLD(dvp);
7227 				rp->r_unldvp = dvp;
7228 				if (rp->r_unlcred != NULL)
7229 					crfree(rp->r_unlcred);
7230 				crhold(cr);
7231 				rp->r_unlcred = cr;
7232 				rp->r_unlname = tmpname;
7233 			} else {
7234 				kmem_free(rp->r_unlname, MAXNAMELEN);
7235 				rp->r_unlname = tmpname;
7236 			}
7237 			mutex_exit(&rp->r_statelock);
7238 		}
7239 		VN_RELE(vp);
7240 		nfs_rw_exit(&drp->r_rwlock);
7241 		return (e.error);
7242 	}
7243 	/*
7244 	 * Actually remove the file/dir
7245 	 */
7246 	mutex_exit(&rp->r_statelock);
7247 
7248 	/*
7249 	 * We need to flush any dirty pages which happen to
7250 	 * be hanging around before removing the file.
7251 	 * This shouldn't happen very often since in NFSv4
7252 	 * we should be close to open consistent.
7253 	 */
7254 	if (nfs4_has_pages(vp) &&
7255 	    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
7256 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr, ct);
7257 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
7258 			mutex_enter(&rp->r_statelock);
7259 			if (!rp->r_error)
7260 				rp->r_error = e.error;
7261 			mutex_exit(&rp->r_statelock);
7262 		}
7263 	}
7264 
7265 	mi = VTOMI4(dvp);
7266 
7267 	(void) nfs4delegreturn(rp, NFS4_DR_REOPEN);
7268 	recov_state.rs_flags = 0;
7269 	recov_state.rs_num_retry_despite_err = 0;
7270 
7271 recov_retry:
7272 	/*
7273 	 * Remove ops: putfh dir; remove
7274 	 */
7275 	args.ctag = TAG_REMOVE;
7276 	args.array_len = 3;
7277 	args.array = argop;
7278 
7279 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
7280 	if (e.error) {
7281 		nfs_rw_exit(&drp->r_rwlock);
7282 		VN_RELE(vp);
7283 		return (e.error);
7284 	}
7285 
7286 	/* putfh directory */
7287 	argop[0].argop = OP_CPUTFH;
7288 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
7289 
7290 	/* remove */
7291 	argop[1].argop = OP_CREMOVE;
7292 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
7293 
7294 	/* getattr dir */
7295 	argop[2].argop = OP_GETATTR;
7296 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7297 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
7298 
7299 	doqueue = 1;
7300 	dinfo.di_time_call = gethrtime();
7301 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
7302 
7303 	PURGE_ATTRCACHE4(vp);
7304 
7305 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
7306 	if (e.error)
7307 		PURGE_ATTRCACHE4(dvp);
7308 
7309 	if (needrecov) {
7310 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp,
7311 		    NULL, NULL, NULL, OP_REMOVE, NULL) == FALSE) {
7312 			if (!e.error)
7313 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7314 				    (caddr_t)&res);
7315 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
7316 			    needrecov);
7317 			goto recov_retry;
7318 		}
7319 	}
7320 
7321 	/*
7322 	 * Matching nfs4_end_op() for start_op() above.
7323 	 * There is a path in the code below which calls
7324 	 * nfs4_purge_stale_fh(), which may generate otw calls through
7325 	 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
7326 	 * here to avoid nfs4_start_op() deadlock.
7327 	 */
7328 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
7329 
7330 	if (!e.error) {
7331 		resp = &res;
7332 
7333 		if (res.status) {
7334 			e.error = geterrno4(res.status);
7335 			PURGE_ATTRCACHE4(dvp);
7336 			nfs4_purge_stale_fh(e.error, dvp, cr);
7337 		} else {
7338 			resop = &res.array[1];	/* remove res */
7339 			rm_res = &resop->nfs_resop4_u.opremove;
7340 
7341 			dinfo.di_garp =
7342 			    &res.array[2].nfs_resop4_u.opgetattr.ga_res;
7343 			dinfo.di_cred = cr;
7344 
7345 			/* Update directory attr, readdir and dnlc caches */
7346 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
7347 			    &dinfo);
7348 		}
7349 	}
7350 	nfs_rw_exit(&drp->r_rwlock);
7351 	if (resp)
7352 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7353 
7354 	if (e.error == 0) {
7355 		vnode_t *tvp;
7356 		rnode4_t *trp;
7357 		trp = VTOR4(vp);
7358 		tvp = vp;
7359 		if (IS_SHADOW(vp, trp))
7360 			tvp = RTOV4(trp);
7361 		vnevent_remove(tvp, dvp, nm, ct);
7362 	}
7363 	VN_RELE(vp);
7364 	return (e.error);
7365 }
7366 
7367 /*
7368  * Link requires that the current fh be the target directory and the
7369  * saved fh be the source fh. After the operation, the current fh is unchanged.
7370  * Thus the compound op structure is:
7371  *	PUTFH(file), SAVEFH, PUTFH(targetdir), LINK, RESTOREFH,
7372  *	GETATTR(file)
7373  */
7374 /* ARGSUSED */
7375 static int
7376 nfs4_link(vnode_t *tdvp, vnode_t *svp, char *tnm, cred_t *cr,
7377     caller_context_t *ct, int flags)
7378 {
7379 	COMPOUND4args_clnt args;
7380 	COMPOUND4res_clnt res, *resp = NULL;
7381 	LINK4res *ln_res;
7382 	int argoplist_size  = 7 * sizeof (nfs_argop4);
7383 	nfs_argop4 *argop;
7384 	nfs_resop4 *resop;
7385 	vnode_t *realvp, *nvp;
7386 	int doqueue;
7387 	mntinfo4_t *mi;
7388 	rnode4_t *tdrp;
7389 	bool_t needrecov = FALSE;
7390 	nfs4_recov_state_t recov_state;
7391 	hrtime_t t;
7392 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7393 	dirattr_info_t dinfo;
7394 
7395 	ASSERT(*tnm != '\0');
7396 	ASSERT(tdvp->v_type == VDIR);
7397 	ASSERT(nfs4_consistent_type(tdvp));
7398 	ASSERT(nfs4_consistent_type(svp));
7399 
7400 	if (nfs_zone() != VTOMI4(tdvp)->mi_zone)
7401 		return (EPERM);
7402 	if (VOP_REALVP(svp, &realvp, ct) == 0) {
7403 		svp = realvp;
7404 		ASSERT(nfs4_consistent_type(svp));
7405 	}
7406 
7407 	tdrp = VTOR4(tdvp);
7408 	mi = VTOMI4(svp);
7409 
7410 	if (!(mi->mi_flags & MI4_LINK)) {
7411 		return (EOPNOTSUPP);
7412 	}
7413 	recov_state.rs_flags = 0;
7414 	recov_state.rs_num_retry_despite_err = 0;
7415 
7416 	if (nfs_rw_enter_sig(&tdrp->r_rwlock, RW_WRITER, INTR4(tdvp)))
7417 		return (EINTR);
7418 
7419 recov_retry:
7420 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
7421 
7422 	args.ctag = TAG_LINK;
7423 
7424 	/*
7425 	 * Link ops: putfh fl; savefh; putfh tdir; link; getattr(dir);
7426 	 * restorefh; getattr(fl)
7427 	 */
7428 	args.array_len = 7;
7429 	args.array = argop;
7430 
7431 	e.error = nfs4_start_op(VTOMI4(svp), svp, tdvp, &recov_state);
7432 	if (e.error) {
7433 		kmem_free(argop, argoplist_size);
7434 		nfs_rw_exit(&tdrp->r_rwlock);
7435 		return (e.error);
7436 	}
7437 
7438 	/* 0. putfh file */
7439 	argop[0].argop = OP_CPUTFH;
7440 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(svp)->r_fh;
7441 
7442 	/* 1. save current fh to free up the space for the dir */
7443 	argop[1].argop = OP_SAVEFH;
7444 
7445 	/* 2. putfh targetdir */
7446 	argop[2].argop = OP_CPUTFH;
7447 	argop[2].nfs_argop4_u.opcputfh.sfh = tdrp->r_fh;
7448 
7449 	/* 3. link: current_fh is targetdir, saved_fh is source */
7450 	argop[3].argop = OP_CLINK;
7451 	argop[3].nfs_argop4_u.opclink.cnewname = tnm;
7452 
7453 	/* 4. Get attributes of dir */
7454 	argop[4].argop = OP_GETATTR;
7455 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7456 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
7457 
7458 	/* 5. If link was successful, restore current vp to file */
7459 	argop[5].argop = OP_RESTOREFH;
7460 
7461 	/* 6. Get attributes of linked object */
7462 	argop[6].argop = OP_GETATTR;
7463 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7464 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
7465 
7466 	dnlc_remove(tdvp, tnm);
7467 
7468 	doqueue = 1;
7469 	t = gethrtime();
7470 
7471 	rfs4call(VTOMI4(svp), &args, &res, cr, &doqueue, 0, &e);
7472 
7473 	needrecov = nfs4_needs_recovery(&e, FALSE, svp->v_vfsp);
7474 	if (e.error != 0 && !needrecov) {
7475 		PURGE_ATTRCACHE4(tdvp);
7476 		PURGE_ATTRCACHE4(svp);
7477 		nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7478 		goto out;
7479 	}
7480 
7481 	if (needrecov) {
7482 		bool_t abort;
7483 
7484 		abort = nfs4_start_recovery(&e, VTOMI4(svp), svp, tdvp,
7485 		    NULL, NULL, OP_LINK, NULL);
7486 		if (abort == FALSE) {
7487 			nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state,
7488 			    needrecov);
7489 			kmem_free(argop, argoplist_size);
7490 			if (!e.error)
7491 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7492 				    (caddr_t)&res);
7493 			goto recov_retry;
7494 		} else {
7495 			if (e.error != 0) {
7496 				PURGE_ATTRCACHE4(tdvp);
7497 				PURGE_ATTRCACHE4(svp);
7498 				nfs4_end_op(VTOMI4(svp), svp, tdvp,
7499 				    &recov_state, needrecov);
7500 				goto out;
7501 			}
7502 			/* fall through for res.status case */
7503 		}
7504 	}
7505 
7506 	nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7507 
7508 	resp = &res;
7509 	if (res.status) {
7510 		/* If link succeeded, then don't return error */
7511 		e.error = geterrno4(res.status);
7512 		if (res.array_len <= 4) {
7513 			/*
7514 			 * Either Putfh, Savefh, Putfh dir, or Link failed
7515 			 */
7516 			PURGE_ATTRCACHE4(svp);
7517 			PURGE_ATTRCACHE4(tdvp);
7518 			if (e.error == EOPNOTSUPP) {
7519 				mutex_enter(&mi->mi_lock);
7520 				mi->mi_flags &= ~MI4_LINK;
7521 				mutex_exit(&mi->mi_lock);
7522 			}
7523 			/* Remap EISDIR to EPERM for non-root user for SVVS */
7524 			/* XXX-LP */
7525 			if (e.error == EISDIR && crgetuid(cr) != 0)
7526 				e.error = EPERM;
7527 			goto out;
7528 		}
7529 	}
7530 
7531 	/* either no error or one of the postop getattr failed */
7532 
7533 	/*
7534 	 * XXX - if LINK succeeded, but no attrs were returned for link
7535 	 * file, purge its cache.
7536 	 *
7537 	 * XXX Perform a simplified version of wcc checking. Instead of
7538 	 * have another getattr to get pre-op, just purge cache if
7539 	 * any of the ops prior to and including the getattr failed.
7540 	 * If the getattr succeeded then update the attrcache accordingly.
7541 	 */
7542 
7543 	/*
7544 	 * update cache with link file postattrs.
7545 	 * Note: at this point resop points to link res.
7546 	 */
7547 	resop = &res.array[3];	/* link res */
7548 	ln_res = &resop->nfs_resop4_u.oplink;
7549 	if (res.status == NFS4_OK)
7550 		e.error = nfs4_update_attrcache(res.status,
7551 		    &res.array[6].nfs_resop4_u.opgetattr.ga_res,
7552 		    t, svp, cr);
7553 
7554 	/*
7555 	 * Call makenfs4node to create the new shadow vp for tnm.
7556 	 * We pass NULL attrs because we just cached attrs for
7557 	 * the src object.  All we're trying to accomplish is to
7558 	 * to create the new shadow vnode.
7559 	 */
7560 	nvp = makenfs4node(VTOR4(svp)->r_fh, NULL, tdvp->v_vfsp, t, cr,
7561 	    tdvp, fn_get(VTOSV(tdvp)->sv_name, tnm));
7562 
7563 	/* Update target cache attribute, readdir and dnlc caches */
7564 	dinfo.di_garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
7565 	dinfo.di_time_call = t;
7566 	dinfo.di_cred = cr;
7567 
7568 	nfs4_update_dircaches(&ln_res->cinfo, tdvp, nvp, tnm, &dinfo);
7569 	ASSERT(nfs4_consistent_type(tdvp));
7570 	ASSERT(nfs4_consistent_type(svp));
7571 	ASSERT(nfs4_consistent_type(nvp));
7572 	VN_RELE(nvp);
7573 
7574 	if (!e.error) {
7575 		vnode_t *tvp;
7576 		rnode4_t *trp;
7577 		/*
7578 		 * Notify the source file of this link operation.
7579 		 */
7580 		trp = VTOR4(svp);
7581 		tvp = svp;
7582 		if (IS_SHADOW(svp, trp))
7583 			tvp = RTOV4(trp);
7584 		vnevent_link(tvp, ct);
7585 	}
7586 out:
7587 	kmem_free(argop, argoplist_size);
7588 	if (resp)
7589 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7590 
7591 	nfs_rw_exit(&tdrp->r_rwlock);
7592 
7593 	return (e.error);
7594 }
7595 
7596 /* ARGSUSED */
7597 static int
7598 nfs4_rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr,
7599     caller_context_t *ct, int flags)
7600 {
7601 	vnode_t *realvp;
7602 
7603 	if (nfs_zone() != VTOMI4(odvp)->mi_zone)
7604 		return (EPERM);
7605 	if (VOP_REALVP(ndvp, &realvp, ct) == 0)
7606 		ndvp = realvp;
7607 
7608 	return (nfs4rename(odvp, onm, ndvp, nnm, cr, ct));
7609 }
7610 
7611 /*
7612  * nfs4rename does the real work of renaming in NFS Version 4.
7613  *
7614  * A file handle is considered volatile for renaming purposes if either
7615  * of the volatile bits are turned on. However, the compound may differ
7616  * based on the likelihood of the filehandle to change during rename.
7617  */
7618 static int
7619 nfs4rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr,
7620     caller_context_t *ct)
7621 {
7622 	int error;
7623 	mntinfo4_t *mi;
7624 	vnode_t *nvp = NULL;
7625 	vnode_t *ovp = NULL;
7626 	char *tmpname = NULL;
7627 	rnode4_t *rp;
7628 	rnode4_t *odrp;
7629 	rnode4_t *ndrp;
7630 	int did_link = 0;
7631 	int do_link = 1;
7632 	nfsstat4 stat = NFS4_OK;
7633 
7634 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
7635 	ASSERT(nfs4_consistent_type(odvp));
7636 	ASSERT(nfs4_consistent_type(ndvp));
7637 
7638 	if (onm[0] == '.' && (onm[1] == '\0' ||
7639 	    (onm[1] == '.' && onm[2] == '\0')))
7640 		return (EINVAL);
7641 
7642 	if (nnm[0] == '.' && (nnm[1] == '\0' ||
7643 	    (nnm[1] == '.' && nnm[2] == '\0')))
7644 		return (EINVAL);
7645 
7646 	odrp = VTOR4(odvp);
7647 	ndrp = VTOR4(ndvp);
7648 	if ((intptr_t)odrp < (intptr_t)ndrp) {
7649 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp)))
7650 			return (EINTR);
7651 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp))) {
7652 			nfs_rw_exit(&odrp->r_rwlock);
7653 			return (EINTR);
7654 		}
7655 	} else {
7656 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp)))
7657 			return (EINTR);
7658 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp))) {
7659 			nfs_rw_exit(&ndrp->r_rwlock);
7660 			return (EINTR);
7661 		}
7662 	}
7663 
7664 	/*
7665 	 * Lookup the target file.  If it exists, it needs to be
7666 	 * checked to see whether it is a mount point and whether
7667 	 * it is active (open).
7668 	 */
7669 	error = nfs4lookup(ndvp, nnm, &nvp, cr, 0);
7670 	if (!error) {
7671 		int	isactive;
7672 
7673 		ASSERT(nfs4_consistent_type(nvp));
7674 		/*
7675 		 * If this file has been mounted on, then just
7676 		 * return busy because renaming to it would remove
7677 		 * the mounted file system from the name space.
7678 		 */
7679 		if (vn_ismntpt(nvp)) {
7680 			VN_RELE(nvp);
7681 			nfs_rw_exit(&odrp->r_rwlock);
7682 			nfs_rw_exit(&ndrp->r_rwlock);
7683 			return (EBUSY);
7684 		}
7685 
7686 		/*
7687 		 * First just remove the entry from the name cache, as it
7688 		 * is most likely the only entry for this vp.
7689 		 */
7690 		dnlc_remove(ndvp, nnm);
7691 
7692 		rp = VTOR4(nvp);
7693 
7694 		if (nvp->v_type != VREG) {
7695 			/*
7696 			 * Purge the name cache of all references to this vnode
7697 			 * so that we can check the reference count to infer
7698 			 * whether it is active or not.
7699 			 */
7700 			if (nvp->v_count > 1)
7701 				dnlc_purge_vp(nvp);
7702 
7703 			isactive = nvp->v_count > 1;
7704 		} else {
7705 			mutex_enter(&rp->r_os_lock);
7706 			isactive = list_head(&rp->r_open_streams) != NULL;
7707 			mutex_exit(&rp->r_os_lock);
7708 		}
7709 
7710 		/*
7711 		 * If the vnode is active and is not a directory,
7712 		 * arrange to rename it to a
7713 		 * temporary file so that it will continue to be
7714 		 * accessible.  This implements the "unlink-open-file"
7715 		 * semantics for the target of a rename operation.
7716 		 * Before doing this though, make sure that the
7717 		 * source and target files are not already the same.
7718 		 */
7719 		if (isactive && nvp->v_type != VDIR) {
7720 			/*
7721 			 * Lookup the source name.
7722 			 */
7723 			error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7724 
7725 			/*
7726 			 * The source name *should* already exist.
7727 			 */
7728 			if (error) {
7729 				VN_RELE(nvp);
7730 				nfs_rw_exit(&odrp->r_rwlock);
7731 				nfs_rw_exit(&ndrp->r_rwlock);
7732 				return (error);
7733 			}
7734 
7735 			ASSERT(nfs4_consistent_type(ovp));
7736 
7737 			/*
7738 			 * Compare the two vnodes.  If they are the same,
7739 			 * just release all held vnodes and return success.
7740 			 */
7741 			if (VN_CMP(ovp, nvp)) {
7742 				VN_RELE(ovp);
7743 				VN_RELE(nvp);
7744 				nfs_rw_exit(&odrp->r_rwlock);
7745 				nfs_rw_exit(&ndrp->r_rwlock);
7746 				return (0);
7747 			}
7748 
7749 			/*
7750 			 * Can't mix and match directories and non-
7751 			 * directories in rename operations.  We already
7752 			 * know that the target is not a directory.  If
7753 			 * the source is a directory, return an error.
7754 			 */
7755 			if (ovp->v_type == VDIR) {
7756 				VN_RELE(ovp);
7757 				VN_RELE(nvp);
7758 				nfs_rw_exit(&odrp->r_rwlock);
7759 				nfs_rw_exit(&ndrp->r_rwlock);
7760 				return (ENOTDIR);
7761 			}
7762 link_call:
7763 			/*
7764 			 * The target file exists, is not the same as
7765 			 * the source file, and is active.  We first
7766 			 * try to Link it to a temporary filename to
7767 			 * avoid having the server removing the file
7768 			 * completely (which could cause data loss to
7769 			 * the user's POV in the event the Rename fails
7770 			 * -- see bug 1165874).
7771 			 */
7772 			/*
7773 			 * The do_link and did_link booleans are
7774 			 * introduced in the event we get NFS4ERR_FILE_OPEN
7775 			 * returned for the Rename.  Some servers can
7776 			 * not Rename over an Open file, so they return
7777 			 * this error.  The client needs to Remove the
7778 			 * newly created Link and do two Renames, just
7779 			 * as if the server didn't support LINK.
7780 			 */
7781 			tmpname = newname();
7782 			error = 0;
7783 
7784 			if (do_link) {
7785 				error = nfs4_link(ndvp, nvp, tmpname, cr,
7786 				    NULL, 0);
7787 			}
7788 			if (error == EOPNOTSUPP || !do_link) {
7789 				error = nfs4_rename(ndvp, nnm, ndvp, tmpname,
7790 				    cr, NULL, 0);
7791 				did_link = 0;
7792 			} else {
7793 				did_link = 1;
7794 			}
7795 			if (error) {
7796 				kmem_free(tmpname, MAXNAMELEN);
7797 				VN_RELE(ovp);
7798 				VN_RELE(nvp);
7799 				nfs_rw_exit(&odrp->r_rwlock);
7800 				nfs_rw_exit(&ndrp->r_rwlock);
7801 				return (error);
7802 			}
7803 
7804 			mutex_enter(&rp->r_statelock);
7805 			if (rp->r_unldvp == NULL) {
7806 				VN_HOLD(ndvp);
7807 				rp->r_unldvp = ndvp;
7808 				if (rp->r_unlcred != NULL)
7809 					crfree(rp->r_unlcred);
7810 				crhold(cr);
7811 				rp->r_unlcred = cr;
7812 				rp->r_unlname = tmpname;
7813 			} else {
7814 				if (rp->r_unlname)
7815 					kmem_free(rp->r_unlname, MAXNAMELEN);
7816 				rp->r_unlname = tmpname;
7817 			}
7818 			mutex_exit(&rp->r_statelock);
7819 		}
7820 
7821 		(void) nfs4delegreturn(VTOR4(nvp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7822 
7823 		ASSERT(nfs4_consistent_type(nvp));
7824 	}
7825 
7826 	if (ovp == NULL) {
7827 		/*
7828 		 * When renaming directories to be a subdirectory of a
7829 		 * different parent, the dnlc entry for ".." will no
7830 		 * longer be valid, so it must be removed.
7831 		 *
7832 		 * We do a lookup here to determine whether we are renaming
7833 		 * a directory and we need to check if we are renaming
7834 		 * an unlinked file.  This might have already been done
7835 		 * in previous code, so we check ovp == NULL to avoid
7836 		 * doing it twice.
7837 		 */
7838 		error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7839 		/*
7840 		 * The source name *should* already exist.
7841 		 */
7842 		if (error) {
7843 			nfs_rw_exit(&odrp->r_rwlock);
7844 			nfs_rw_exit(&ndrp->r_rwlock);
7845 			if (nvp) {
7846 				VN_RELE(nvp);
7847 			}
7848 			return (error);
7849 		}
7850 		ASSERT(ovp != NULL);
7851 		ASSERT(nfs4_consistent_type(ovp));
7852 	}
7853 
7854 	/*
7855 	 * Is the object being renamed a dir, and if so, is
7856 	 * it being renamed to a child of itself?  The underlying
7857 	 * fs should ultimately return EINVAL for this case;
7858 	 * however, buggy beta non-Solaris NFSv4 servers at
7859 	 * interop testing events have allowed this behavior,
7860 	 * and it caused our client to panic due to a recursive
7861 	 * mutex_enter in fn_move.
7862 	 *
7863 	 * The tedious locking in fn_move could be changed to
7864 	 * deal with this case, and the client could avoid the
7865 	 * panic; however, the client would just confuse itself
7866 	 * later and misbehave.  A better way to handle the broken
7867 	 * server is to detect this condition and return EINVAL
7868 	 * without ever sending the the bogus rename to the server.
7869 	 * We know the rename is invalid -- just fail it now.
7870 	 */
7871 	if (ovp->v_type == VDIR && VN_CMP(ndvp, ovp)) {
7872 		VN_RELE(ovp);
7873 		nfs_rw_exit(&odrp->r_rwlock);
7874 		nfs_rw_exit(&ndrp->r_rwlock);
7875 		if (nvp) {
7876 			VN_RELE(nvp);
7877 		}
7878 		return (EINVAL);
7879 	}
7880 
7881 	(void) nfs4delegreturn(VTOR4(ovp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7882 
7883 	/*
7884 	 * If FH4_VOL_RENAME or FH4_VOLATILE_ANY bits are set, it is
7885 	 * possible for the filehandle to change due to the rename.
7886 	 * If neither of these bits is set, but FH4_VOL_MIGRATION is set,
7887 	 * the fh will not change because of the rename, but we still need
7888 	 * to update its rnode entry with the new name for
7889 	 * an eventual fh change due to migration. The FH4_NOEXPIRE_ON_OPEN
7890 	 * has no effect on these for now, but for future improvements,
7891 	 * we might want to use it too to simplify handling of files
7892 	 * that are open with that flag on. (XXX)
7893 	 */
7894 	mi = VTOMI4(odvp);
7895 	if (NFS4_VOLATILE_FH(mi))
7896 		error = nfs4rename_volatile_fh(odvp, onm, ovp, ndvp, nnm, cr,
7897 		    &stat);
7898 	else
7899 		error = nfs4rename_persistent_fh(odvp, onm, ovp, ndvp, nnm, cr,
7900 		    &stat);
7901 
7902 	ASSERT(nfs4_consistent_type(odvp));
7903 	ASSERT(nfs4_consistent_type(ndvp));
7904 	ASSERT(nfs4_consistent_type(ovp));
7905 
7906 	if (stat == NFS4ERR_FILE_OPEN && did_link) {
7907 		do_link = 0;
7908 		/*
7909 		 * Before the 'link_call' code, we did a nfs4_lookup
7910 		 * that puts a VN_HOLD on nvp.  After the nfs4_link
7911 		 * call we call VN_RELE to match that hold.  We need
7912 		 * to place an additional VN_HOLD here since we will
7913 		 * be hitting that VN_RELE again.
7914 		 */
7915 		VN_HOLD(nvp);
7916 
7917 		(void) nfs4_remove(ndvp, tmpname, cr, NULL, 0);
7918 
7919 		/* Undo the unlinked file naming stuff we just did */
7920 		mutex_enter(&rp->r_statelock);
7921 		if (rp->r_unldvp) {
7922 			VN_RELE(ndvp);
7923 			rp->r_unldvp = NULL;
7924 			if (rp->r_unlcred != NULL)
7925 				crfree(rp->r_unlcred);
7926 			rp->r_unlcred = NULL;
7927 			/* rp->r_unlanme points to tmpname */
7928 			if (rp->r_unlname)
7929 				kmem_free(rp->r_unlname, MAXNAMELEN);
7930 			rp->r_unlname = NULL;
7931 		}
7932 		mutex_exit(&rp->r_statelock);
7933 
7934 		if (nvp) {
7935 			VN_RELE(nvp);
7936 		}
7937 		goto link_call;
7938 	}
7939 
7940 	if (error) {
7941 		VN_RELE(ovp);
7942 		nfs_rw_exit(&odrp->r_rwlock);
7943 		nfs_rw_exit(&ndrp->r_rwlock);
7944 		if (nvp) {
7945 			VN_RELE(nvp);
7946 		}
7947 		return (error);
7948 	}
7949 
7950 	/*
7951 	 * when renaming directories to be a subdirectory of a
7952 	 * different parent, the dnlc entry for ".." will no
7953 	 * longer be valid, so it must be removed
7954 	 */
7955 	rp = VTOR4(ovp);
7956 	if (ndvp != odvp) {
7957 		if (ovp->v_type == VDIR) {
7958 			dnlc_remove(ovp, "..");
7959 			if (rp->r_dir != NULL)
7960 				nfs4_purge_rddir_cache(ovp);
7961 		}
7962 	}
7963 
7964 	/*
7965 	 * If we are renaming the unlinked file, update the
7966 	 * r_unldvp and r_unlname as needed.
7967 	 */
7968 	mutex_enter(&rp->r_statelock);
7969 	if (rp->r_unldvp != NULL) {
7970 		if (strcmp(rp->r_unlname, onm) == 0) {
7971 			(void) strncpy(rp->r_unlname, nnm, MAXNAMELEN);
7972 			rp->r_unlname[MAXNAMELEN - 1] = '\0';
7973 			if (ndvp != rp->r_unldvp) {
7974 				VN_RELE(rp->r_unldvp);
7975 				rp->r_unldvp = ndvp;
7976 				VN_HOLD(ndvp);
7977 			}
7978 		}
7979 	}
7980 	mutex_exit(&rp->r_statelock);
7981 
7982 	/*
7983 	 * Notify the rename vnevents to source vnode, and to the target
7984 	 * vnode if it already existed.
7985 	 */
7986 	if (error == 0) {
7987 		vnode_t *tvp;
7988 		rnode4_t *trp;
7989 		/*
7990 		 * Notify the vnode. Each links is represented by
7991 		 * a different vnode, in nfsv4.
7992 		 */
7993 		if (nvp) {
7994 			trp = VTOR4(nvp);
7995 			tvp = nvp;
7996 			if (IS_SHADOW(nvp, trp))
7997 				tvp = RTOV4(trp);
7998 			vnevent_rename_dest(tvp, ndvp, nnm, ct);
7999 		}
8000 
8001 		/*
8002 		 * if the source and destination directory are not the
8003 		 * same notify the destination directory.
8004 		 */
8005 		if (VTOR4(odvp) != VTOR4(ndvp)) {
8006 			trp = VTOR4(ndvp);
8007 			tvp = ndvp;
8008 			if (IS_SHADOW(ndvp, trp))
8009 				tvp = RTOV4(trp);
8010 			vnevent_rename_dest_dir(tvp, ct);
8011 		}
8012 
8013 		trp = VTOR4(ovp);
8014 		tvp = ovp;
8015 		if (IS_SHADOW(ovp, trp))
8016 			tvp = RTOV4(trp);
8017 		vnevent_rename_src(tvp, odvp, onm, ct);
8018 	}
8019 
8020 	if (nvp) {
8021 		VN_RELE(nvp);
8022 	}
8023 	VN_RELE(ovp);
8024 
8025 	nfs_rw_exit(&odrp->r_rwlock);
8026 	nfs_rw_exit(&ndrp->r_rwlock);
8027 
8028 	return (error);
8029 }
8030 
8031 /*
8032  * nfs4rename_persistent does the otw portion of renaming in NFS Version 4,
8033  * when it is known that the filehandle is persistent through rename.
8034  *
8035  * Rename requires that the current fh be the target directory and the
8036  * saved fh be the source directory. After the operation, the current fh
8037  * is unchanged.
8038  * The compound op structure for persistent fh rename is:
8039  *      PUTFH(sourcdir), SAVEFH, PUTFH(targetdir), RENAME
8040  * Rather than bother with the directory postop args, we'll simply
8041  * update that a change occurred in the cache, so no post-op getattrs.
8042  */
8043 static int
8044 nfs4rename_persistent_fh(vnode_t *odvp, char *onm, vnode_t *renvp,
8045     vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
8046 {
8047 	COMPOUND4args_clnt args;
8048 	COMPOUND4res_clnt res, *resp = NULL;
8049 	nfs_argop4 *argop;
8050 	nfs_resop4 *resop;
8051 	int doqueue, argoplist_size;
8052 	mntinfo4_t *mi;
8053 	rnode4_t *odrp = VTOR4(odvp);
8054 	rnode4_t *ndrp = VTOR4(ndvp);
8055 	RENAME4res *rn_res;
8056 	bool_t needrecov;
8057 	nfs4_recov_state_t recov_state;
8058 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8059 	dirattr_info_t dinfo, *dinfop;
8060 
8061 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
8062 
8063 	recov_state.rs_flags = 0;
8064 	recov_state.rs_num_retry_despite_err = 0;
8065 
8066 	/*
8067 	 * Rename ops: putfh sdir; savefh; putfh tdir; rename; getattr tdir
8068 	 *
8069 	 * If source/target are different dirs, then append putfh(src); getattr
8070 	 */
8071 	args.array_len = (odvp == ndvp) ? 5 : 7;
8072 	argoplist_size = args.array_len * sizeof (nfs_argop4);
8073 	args.array = argop = kmem_alloc(argoplist_size, KM_SLEEP);
8074 
8075 recov_retry:
8076 	*statp = NFS4_OK;
8077 
8078 	/* No need to Lookup the file, persistent fh */
8079 	args.ctag = TAG_RENAME;
8080 
8081 	mi = VTOMI4(odvp);
8082 	e.error = nfs4_start_op(mi, odvp, ndvp, &recov_state);
8083 	if (e.error) {
8084 		kmem_free(argop, argoplist_size);
8085 		return (e.error);
8086 	}
8087 
8088 	/* 0: putfh source directory */
8089 	argop[0].argop = OP_CPUTFH;
8090 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8091 
8092 	/* 1: Save source fh to free up current for target */
8093 	argop[1].argop = OP_SAVEFH;
8094 
8095 	/* 2: putfh targetdir */
8096 	argop[2].argop = OP_CPUTFH;
8097 	argop[2].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8098 
8099 	/* 3: current_fh is targetdir, saved_fh is sourcedir */
8100 	argop[3].argop = OP_CRENAME;
8101 	argop[3].nfs_argop4_u.opcrename.coldname = onm;
8102 	argop[3].nfs_argop4_u.opcrename.cnewname = nnm;
8103 
8104 	/* 4: getattr (targetdir) */
8105 	argop[4].argop = OP_GETATTR;
8106 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8107 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
8108 
8109 	if (ndvp != odvp) {
8110 
8111 		/* 5: putfh (sourcedir) */
8112 		argop[5].argop = OP_CPUTFH;
8113 		argop[5].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8114 
8115 		/* 6: getattr (sourcedir) */
8116 		argop[6].argop = OP_GETATTR;
8117 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8118 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
8119 	}
8120 
8121 	dnlc_remove(odvp, onm);
8122 	dnlc_remove(ndvp, nnm);
8123 
8124 	doqueue = 1;
8125 	dinfo.di_time_call = gethrtime();
8126 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8127 
8128 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8129 	if (e.error) {
8130 		PURGE_ATTRCACHE4(odvp);
8131 		PURGE_ATTRCACHE4(ndvp);
8132 	} else {
8133 		*statp = res.status;
8134 	}
8135 
8136 	if (needrecov) {
8137 		if (nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8138 		    OP_RENAME, NULL) == FALSE) {
8139 			nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
8140 			if (!e.error)
8141 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8142 				    (caddr_t)&res);
8143 			goto recov_retry;
8144 		}
8145 	}
8146 
8147 	if (!e.error) {
8148 		resp = &res;
8149 		/*
8150 		 * as long as OP_RENAME
8151 		 */
8152 		if (res.status != NFS4_OK && res.array_len <= 4) {
8153 			e.error = geterrno4(res.status);
8154 			PURGE_ATTRCACHE4(odvp);
8155 			PURGE_ATTRCACHE4(ndvp);
8156 			/*
8157 			 * System V defines rename to return EEXIST, not
8158 			 * ENOTEMPTY if the target directory is not empty.
8159 			 * Over the wire, the error is NFSERR_ENOTEMPTY
8160 			 * which geterrno4 maps to ENOTEMPTY.
8161 			 */
8162 			if (e.error == ENOTEMPTY)
8163 				e.error = EEXIST;
8164 		} else {
8165 
8166 			resop = &res.array[3];	/* rename res */
8167 			rn_res = &resop->nfs_resop4_u.oprename;
8168 
8169 			if (res.status == NFS4_OK) {
8170 				/*
8171 				 * Update target attribute, readdir and dnlc
8172 				 * caches.
8173 				 */
8174 				dinfo.di_garp =
8175 				    &res.array[4].nfs_resop4_u.opgetattr.ga_res;
8176 				dinfo.di_cred = cr;
8177 				dinfop = &dinfo;
8178 			} else
8179 				dinfop = NULL;
8180 
8181 			nfs4_update_dircaches(&rn_res->target_cinfo,
8182 			    ndvp, NULL, NULL, dinfop);
8183 
8184 			/*
8185 			 * Update source attribute, readdir and dnlc caches
8186 			 *
8187 			 */
8188 			if (ndvp != odvp) {
8189 				if (dinfop)
8190 					dinfo.di_garp =
8191 					    &(res.array[6].nfs_resop4_u.
8192 					    opgetattr.ga_res);
8193 
8194 				nfs4_update_dircaches(&rn_res->source_cinfo,
8195 				    odvp, NULL, NULL, dinfop);
8196 			}
8197 
8198 			fn_move(VTOSV(renvp)->sv_name, VTOSV(ndvp)->sv_name,
8199 			    nnm);
8200 		}
8201 	}
8202 
8203 	if (resp)
8204 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8205 	nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
8206 	kmem_free(argop, argoplist_size);
8207 
8208 	return (e.error);
8209 }
8210 
8211 /*
8212  * nfs4rename_volatile_fh does the otw part of renaming in NFS Version 4, when
8213  * it is possible for the filehandle to change due to the rename.
8214  *
8215  * The compound req in this case includes a post-rename lookup and getattr
8216  * to ensure that we have the correct fh and attributes for the object.
8217  *
8218  * Rename requires that the current fh be the target directory and the
8219  * saved fh be the source directory. After the operation, the current fh
8220  * is unchanged.
8221  *
8222  * We need the new filehandle (hence a LOOKUP and GETFH) so that we can
8223  * update the filehandle for the renamed object.  We also get the old
8224  * filehandle for historical reasons; this should be taken out sometime.
8225  * This results in a rather cumbersome compound...
8226  *
8227  *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8228  *    PUTFH(targetdir), RENAME, LOOKUP(trgt), GETFH(new), GETATTR
8229  *
8230  */
8231 static int
8232 nfs4rename_volatile_fh(vnode_t *odvp, char *onm, vnode_t *ovp,
8233     vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
8234 {
8235 	COMPOUND4args_clnt args;
8236 	COMPOUND4res_clnt res, *resp = NULL;
8237 	int argoplist_size;
8238 	nfs_argop4 *argop;
8239 	nfs_resop4 *resop;
8240 	int doqueue;
8241 	mntinfo4_t *mi;
8242 	rnode4_t *odrp = VTOR4(odvp);	/* old directory */
8243 	rnode4_t *ndrp = VTOR4(ndvp);	/* new directory */
8244 	rnode4_t *orp = VTOR4(ovp);	/* object being renamed */
8245 	RENAME4res *rn_res;
8246 	GETFH4res *ngf_res;
8247 	bool_t needrecov;
8248 	nfs4_recov_state_t recov_state;
8249 	hrtime_t t;
8250 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8251 	dirattr_info_t dinfo, *dinfop = &dinfo;
8252 
8253 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
8254 
8255 	recov_state.rs_flags = 0;
8256 	recov_state.rs_num_retry_despite_err = 0;
8257 
8258 recov_retry:
8259 	*statp = NFS4_OK;
8260 
8261 	/*
8262 	 * There is a window between the RPC and updating the path and
8263 	 * filehandle stored in the rnode.  Lock out the FHEXPIRED recovery
8264 	 * code, so that it doesn't try to use the old path during that
8265 	 * window.
8266 	 */
8267 	mutex_enter(&orp->r_statelock);
8268 	while (orp->r_flags & R4RECEXPFH) {
8269 		klwp_t *lwp = ttolwp(curthread);
8270 
8271 		if (lwp != NULL)
8272 			lwp->lwp_nostop++;
8273 		if (cv_wait_sig(&orp->r_cv, &orp->r_statelock) == 0) {
8274 			mutex_exit(&orp->r_statelock);
8275 			if (lwp != NULL)
8276 				lwp->lwp_nostop--;
8277 			return (EINTR);
8278 		}
8279 		if (lwp != NULL)
8280 			lwp->lwp_nostop--;
8281 	}
8282 	orp->r_flags |= R4RECEXPFH;
8283 	mutex_exit(&orp->r_statelock);
8284 
8285 	mi = VTOMI4(odvp);
8286 
8287 	args.ctag = TAG_RENAME_VFH;
8288 	args.array_len = (odvp == ndvp) ? 10 : 12;
8289 	argoplist_size  = args.array_len * sizeof (nfs_argop4);
8290 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
8291 
8292 	/*
8293 	 * Rename ops:
8294 	 *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8295 	 *    PUTFH(targetdir), RENAME, GETATTR(targetdir)
8296 	 *    LOOKUP(trgt), GETFH(new), GETATTR,
8297 	 *
8298 	 *    if (odvp != ndvp)
8299 	 *	add putfh(sourcedir), getattr(sourcedir) }
8300 	 */
8301 	args.array = argop;
8302 
8303 	e.error = nfs4_start_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8304 	    &recov_state, NULL);
8305 	if (e.error) {
8306 		kmem_free(argop, argoplist_size);
8307 		mutex_enter(&orp->r_statelock);
8308 		orp->r_flags &= ~R4RECEXPFH;
8309 		cv_broadcast(&orp->r_cv);
8310 		mutex_exit(&orp->r_statelock);
8311 		return (e.error);
8312 	}
8313 
8314 	/* 0: putfh source directory */
8315 	argop[0].argop = OP_CPUTFH;
8316 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8317 
8318 	/* 1: Save source fh to free up current for target */
8319 	argop[1].argop = OP_SAVEFH;
8320 
8321 	/* 2: Lookup pre-rename fh of renamed object */
8322 	argop[2].argop = OP_CLOOKUP;
8323 	argop[2].nfs_argop4_u.opclookup.cname = onm;
8324 
8325 	/* 3: getfh fh of renamed object (before rename) */
8326 	argop[3].argop = OP_GETFH;
8327 
8328 	/* 4: putfh targetdir */
8329 	argop[4].argop = OP_CPUTFH;
8330 	argop[4].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8331 
8332 	/* 5: current_fh is targetdir, saved_fh is sourcedir */
8333 	argop[5].argop = OP_CRENAME;
8334 	argop[5].nfs_argop4_u.opcrename.coldname = onm;
8335 	argop[5].nfs_argop4_u.opcrename.cnewname = nnm;
8336 
8337 	/* 6: getattr of target dir (post op attrs) */
8338 	argop[6].argop = OP_GETATTR;
8339 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8340 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
8341 
8342 	/* 7: Lookup post-rename fh of renamed object */
8343 	argop[7].argop = OP_CLOOKUP;
8344 	argop[7].nfs_argop4_u.opclookup.cname = nnm;
8345 
8346 	/* 8: getfh fh of renamed object (after rename) */
8347 	argop[8].argop = OP_GETFH;
8348 
8349 	/* 9: getattr of renamed object */
8350 	argop[9].argop = OP_GETATTR;
8351 	argop[9].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8352 	argop[9].nfs_argop4_u.opgetattr.mi = mi;
8353 
8354 	/*
8355 	 * If source/target dirs are different, then get new post-op
8356 	 * attrs for source dir also.
8357 	 */
8358 	if (ndvp != odvp) {
8359 		/* 10: putfh (sourcedir) */
8360 		argop[10].argop = OP_CPUTFH;
8361 		argop[10].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8362 
8363 		/* 11: getattr (sourcedir) */
8364 		argop[11].argop = OP_GETATTR;
8365 		argop[11].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8366 		argop[11].nfs_argop4_u.opgetattr.mi = mi;
8367 	}
8368 
8369 	dnlc_remove(odvp, onm);
8370 	dnlc_remove(ndvp, nnm);
8371 
8372 	doqueue = 1;
8373 	t = gethrtime();
8374 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8375 
8376 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8377 	if (e.error) {
8378 		PURGE_ATTRCACHE4(odvp);
8379 		PURGE_ATTRCACHE4(ndvp);
8380 		if (!needrecov) {
8381 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8382 			    &recov_state, needrecov);
8383 			goto out;
8384 		}
8385 	} else {
8386 		*statp = res.status;
8387 	}
8388 
8389 	if (needrecov) {
8390 		bool_t abort;
8391 
8392 		abort = nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8393 		    OP_RENAME, NULL);
8394 		if (abort == FALSE) {
8395 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8396 			    &recov_state, needrecov);
8397 			kmem_free(argop, argoplist_size);
8398 			if (!e.error)
8399 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8400 				    (caddr_t)&res);
8401 			mutex_enter(&orp->r_statelock);
8402 			orp->r_flags &= ~R4RECEXPFH;
8403 			cv_broadcast(&orp->r_cv);
8404 			mutex_exit(&orp->r_statelock);
8405 			goto recov_retry;
8406 		} else {
8407 			if (e.error != 0) {
8408 				nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8409 				    &recov_state, needrecov);
8410 				goto out;
8411 			}
8412 			/* fall through for res.status case */
8413 		}
8414 	}
8415 
8416 	resp = &res;
8417 	/*
8418 	 * If OP_RENAME (or any prev op) failed, then return an error.
8419 	 * OP_RENAME is index 5, so if array len <= 6 we return an error.
8420 	 */
8421 	if ((res.status != NFS4_OK) && (res.array_len <= 6)) {
8422 		/*
8423 		 * Error in an op other than last Getattr
8424 		 */
8425 		e.error = geterrno4(res.status);
8426 		PURGE_ATTRCACHE4(odvp);
8427 		PURGE_ATTRCACHE4(ndvp);
8428 		/*
8429 		 * System V defines rename to return EEXIST, not
8430 		 * ENOTEMPTY if the target directory is not empty.
8431 		 * Over the wire, the error is NFSERR_ENOTEMPTY
8432 		 * which geterrno4 maps to ENOTEMPTY.
8433 		 */
8434 		if (e.error == ENOTEMPTY)
8435 			e.error = EEXIST;
8436 		nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state,
8437 		    needrecov);
8438 		goto out;
8439 	}
8440 
8441 	/* rename results */
8442 	rn_res = &res.array[5].nfs_resop4_u.oprename;
8443 
8444 	if (res.status == NFS4_OK) {
8445 		/* Update target attribute, readdir and dnlc caches */
8446 		dinfo.di_garp =
8447 		    &res.array[6].nfs_resop4_u.opgetattr.ga_res;
8448 		dinfo.di_cred = cr;
8449 		dinfo.di_time_call = t;
8450 	} else
8451 		dinfop = NULL;
8452 
8453 	/* Update source cache attribute, readdir and dnlc caches */
8454 	nfs4_update_dircaches(&rn_res->target_cinfo, ndvp, NULL, NULL, dinfop);
8455 
8456 	/* Update source cache attribute, readdir and dnlc caches */
8457 	if (ndvp != odvp) {
8458 
8459 		/*
8460 		 * If dinfop is non-NULL, then compound succeded, so
8461 		 * set di_garp to attrs for source dir.  dinfop is only
8462 		 * set to NULL when compound fails.
8463 		 */
8464 		if (dinfop)
8465 			dinfo.di_garp =
8466 			    &res.array[11].nfs_resop4_u.opgetattr.ga_res;
8467 		nfs4_update_dircaches(&rn_res->source_cinfo, odvp, NULL, NULL,
8468 		    dinfop);
8469 	}
8470 
8471 	/*
8472 	 * Update the rnode with the new component name and args,
8473 	 * and if the file handle changed, also update it with the new fh.
8474 	 * This is only necessary if the target object has an rnode
8475 	 * entry and there is no need to create one for it.
8476 	 */
8477 	resop = &res.array[8];	/* getfh new res */
8478 	ngf_res = &resop->nfs_resop4_u.opgetfh;
8479 
8480 	/*
8481 	 * Update the path and filehandle for the renamed object.
8482 	 */
8483 	nfs4rename_update(ovp, ndvp, &ngf_res->object, nnm);
8484 
8485 	nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state, needrecov);
8486 
8487 	if (res.status == NFS4_OK) {
8488 		resop++;	/* getattr res */
8489 		e.error = nfs4_update_attrcache(res.status,
8490 		    &resop->nfs_resop4_u.opgetattr.ga_res,
8491 		    t, ovp, cr);
8492 	}
8493 
8494 out:
8495 	kmem_free(argop, argoplist_size);
8496 	if (resp)
8497 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8498 	mutex_enter(&orp->r_statelock);
8499 	orp->r_flags &= ~R4RECEXPFH;
8500 	cv_broadcast(&orp->r_cv);
8501 	mutex_exit(&orp->r_statelock);
8502 
8503 	return (e.error);
8504 }
8505 
8506 /* ARGSUSED */
8507 static int
8508 nfs4_mkdir(vnode_t *dvp, char *nm, struct vattr *va, vnode_t **vpp, cred_t *cr,
8509     caller_context_t *ct, int flags, vsecattr_t *vsecp)
8510 {
8511 	int error;
8512 	vnode_t *vp;
8513 
8514 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8515 		return (EPERM);
8516 	/*
8517 	 * As ".." has special meaning and rather than send a mkdir
8518 	 * over the wire to just let the server freak out, we just
8519 	 * short circuit it here and return EEXIST
8520 	 */
8521 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8522 		return (EEXIST);
8523 
8524 	/*
8525 	 * Decision to get the right gid and setgid bit of the
8526 	 * new directory is now made in call_nfs4_create_req.
8527 	 */
8528 	va->va_mask |= AT_MODE;
8529 	error = call_nfs4_create_req(dvp, nm, NULL, va, &vp, cr, NF4DIR);
8530 	if (error)
8531 		return (error);
8532 
8533 	*vpp = vp;
8534 	return (0);
8535 }
8536 
8537 
8538 /*
8539  * rmdir is using the same remove v4 op as does remove.
8540  * Remove requires that the current fh be the target directory.
8541  * After the operation, the current fh is unchanged.
8542  * The compound op structure is:
8543  *      PUTFH(targetdir), REMOVE
8544  */
8545 /*ARGSUSED4*/
8546 static int
8547 nfs4_rmdir(vnode_t *dvp, char *nm, vnode_t *cdir, cred_t *cr,
8548     caller_context_t *ct, int flags)
8549 {
8550 	int need_end_op = FALSE;
8551 	COMPOUND4args_clnt args;
8552 	COMPOUND4res_clnt res, *resp = NULL;
8553 	REMOVE4res *rm_res;
8554 	nfs_argop4 argop[3];
8555 	nfs_resop4 *resop;
8556 	vnode_t *vp;
8557 	int doqueue;
8558 	mntinfo4_t *mi;
8559 	rnode4_t *drp;
8560 	bool_t needrecov = FALSE;
8561 	nfs4_recov_state_t recov_state;
8562 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8563 	dirattr_info_t dinfo, *dinfop;
8564 
8565 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8566 		return (EPERM);
8567 	/*
8568 	 * As ".." has special meaning and rather than send a rmdir
8569 	 * over the wire to just let the server freak out, we just
8570 	 * short circuit it here and return EEXIST
8571 	 */
8572 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8573 		return (EEXIST);
8574 
8575 	drp = VTOR4(dvp);
8576 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
8577 		return (EINTR);
8578 
8579 	/*
8580 	 * Attempt to prevent a rmdir(".") from succeeding.
8581 	 */
8582 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
8583 	if (e.error) {
8584 		nfs_rw_exit(&drp->r_rwlock);
8585 		return (e.error);
8586 	}
8587 	if (vp == cdir) {
8588 		VN_RELE(vp);
8589 		nfs_rw_exit(&drp->r_rwlock);
8590 		return (EINVAL);
8591 	}
8592 
8593 	/*
8594 	 * Since nfsv4 remove op works on both files and directories,
8595 	 * check that the removed object is indeed a directory.
8596 	 */
8597 	if (vp->v_type != VDIR) {
8598 		VN_RELE(vp);
8599 		nfs_rw_exit(&drp->r_rwlock);
8600 		return (ENOTDIR);
8601 	}
8602 
8603 	/*
8604 	 * First just remove the entry from the name cache, as it
8605 	 * is most likely an entry for this vp.
8606 	 */
8607 	dnlc_remove(dvp, nm);
8608 
8609 	/*
8610 	 * If there vnode reference count is greater than one, then
8611 	 * there may be additional references in the DNLC which will
8612 	 * need to be purged.  First, trying removing the entry for
8613 	 * the parent directory and see if that removes the additional
8614 	 * reference(s).  If that doesn't do it, then use dnlc_purge_vp
8615 	 * to completely remove any references to the directory which
8616 	 * might still exist in the DNLC.
8617 	 */
8618 	if (vp->v_count > 1) {
8619 		dnlc_remove(vp, "..");
8620 		if (vp->v_count > 1)
8621 			dnlc_purge_vp(vp);
8622 	}
8623 
8624 	mi = VTOMI4(dvp);
8625 	recov_state.rs_flags = 0;
8626 	recov_state.rs_num_retry_despite_err = 0;
8627 
8628 recov_retry:
8629 	args.ctag = TAG_RMDIR;
8630 
8631 	/*
8632 	 * Rmdir ops: putfh dir; remove
8633 	 */
8634 	args.array_len = 3;
8635 	args.array = argop;
8636 
8637 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
8638 	if (e.error) {
8639 		nfs_rw_exit(&drp->r_rwlock);
8640 		return (e.error);
8641 	}
8642 	need_end_op = TRUE;
8643 
8644 	/* putfh directory */
8645 	argop[0].argop = OP_CPUTFH;
8646 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
8647 
8648 	/* remove */
8649 	argop[1].argop = OP_CREMOVE;
8650 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
8651 
8652 	/* getattr (postop attrs for dir that contained removed dir) */
8653 	argop[2].argop = OP_GETATTR;
8654 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8655 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
8656 
8657 	dinfo.di_time_call = gethrtime();
8658 	doqueue = 1;
8659 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8660 
8661 	PURGE_ATTRCACHE4(vp);
8662 
8663 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8664 	if (e.error) {
8665 		PURGE_ATTRCACHE4(dvp);
8666 	}
8667 
8668 	if (needrecov) {
8669 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp, NULL, NULL,
8670 		    NULL, OP_REMOVE, NULL) == FALSE) {
8671 			if (!e.error)
8672 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8673 				    (caddr_t)&res);
8674 
8675 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
8676 			    needrecov);
8677 			need_end_op = FALSE;
8678 			goto recov_retry;
8679 		}
8680 	}
8681 
8682 	if (!e.error) {
8683 		resp = &res;
8684 
8685 		/*
8686 		 * Only return error if first 2 ops (OP_REMOVE or earlier)
8687 		 * failed.
8688 		 */
8689 		if (res.status != NFS4_OK && res.array_len <= 2) {
8690 			e.error = geterrno4(res.status);
8691 			PURGE_ATTRCACHE4(dvp);
8692 			nfs4_end_op(VTOMI4(dvp), dvp, NULL,
8693 			    &recov_state, needrecov);
8694 			need_end_op = FALSE;
8695 			nfs4_purge_stale_fh(e.error, dvp, cr);
8696 			/*
8697 			 * System V defines rmdir to return EEXIST, not
8698 			 * ENOTEMPTY if the directory is not empty.  Over
8699 			 * the wire, the error is NFSERR_ENOTEMPTY which
8700 			 * geterrno4 maps to ENOTEMPTY.
8701 			 */
8702 			if (e.error == ENOTEMPTY)
8703 				e.error = EEXIST;
8704 		} else {
8705 			resop = &res.array[1];	/* remove res */
8706 			rm_res = &resop->nfs_resop4_u.opremove;
8707 
8708 			if (res.status == NFS4_OK) {
8709 				resop = &res.array[2];	/* dir attrs */
8710 				dinfo.di_garp =
8711 				    &resop->nfs_resop4_u.opgetattr.ga_res;
8712 				dinfo.di_cred = cr;
8713 				dinfop = &dinfo;
8714 			} else
8715 				dinfop = NULL;
8716 
8717 			/* Update dir attribute, readdir and dnlc caches */
8718 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
8719 			    dinfop);
8720 
8721 			/* destroy rddir cache for dir that was removed */
8722 			if (VTOR4(vp)->r_dir != NULL)
8723 				nfs4_purge_rddir_cache(vp);
8724 		}
8725 	}
8726 
8727 	if (need_end_op)
8728 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
8729 
8730 	nfs_rw_exit(&drp->r_rwlock);
8731 
8732 	if (resp)
8733 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8734 
8735 	if (e.error == 0) {
8736 		vnode_t *tvp;
8737 		rnode4_t *trp;
8738 		trp = VTOR4(vp);
8739 		tvp = vp;
8740 		if (IS_SHADOW(vp, trp))
8741 			tvp = RTOV4(trp);
8742 		vnevent_rmdir(tvp, dvp, nm, ct);
8743 	}
8744 
8745 	VN_RELE(vp);
8746 
8747 	return (e.error);
8748 }
8749 
8750 /* ARGSUSED */
8751 static int
8752 nfs4_symlink(vnode_t *dvp, char *lnm, struct vattr *tva, char *tnm, cred_t *cr,
8753     caller_context_t *ct, int flags)
8754 {
8755 	int error;
8756 	vnode_t *vp;
8757 	rnode4_t *rp;
8758 	char *contents;
8759 	mntinfo4_t *mi = VTOMI4(dvp);
8760 
8761 	if (nfs_zone() != mi->mi_zone)
8762 		return (EPERM);
8763 	if (!(mi->mi_flags & MI4_SYMLINK))
8764 		return (EOPNOTSUPP);
8765 
8766 	error = call_nfs4_create_req(dvp, lnm, tnm, tva, &vp, cr, NF4LNK);
8767 	if (error)
8768 		return (error);
8769 
8770 	ASSERT(nfs4_consistent_type(vp));
8771 	rp = VTOR4(vp);
8772 	if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
8773 
8774 		contents = kmem_alloc(MAXPATHLEN, KM_SLEEP);
8775 
8776 		if (contents != NULL) {
8777 			mutex_enter(&rp->r_statelock);
8778 			if (rp->r_symlink.contents == NULL) {
8779 				rp->r_symlink.len = strlen(tnm);
8780 				bcopy(tnm, contents, rp->r_symlink.len);
8781 				rp->r_symlink.contents = contents;
8782 				rp->r_symlink.size = MAXPATHLEN;
8783 				mutex_exit(&rp->r_statelock);
8784 			} else {
8785 				mutex_exit(&rp->r_statelock);
8786 				kmem_free((void *)contents, MAXPATHLEN);
8787 			}
8788 		}
8789 	}
8790 	VN_RELE(vp);
8791 
8792 	return (error);
8793 }
8794 
8795 
8796 /*
8797  * Read directory entries.
8798  * There are some weird things to look out for here.  The uio_loffset
8799  * field is either 0 or it is the offset returned from a previous
8800  * readdir.  It is an opaque value used by the server to find the
8801  * correct directory block to read. The count field is the number
8802  * of blocks to read on the server.  This is advisory only, the server
8803  * may return only one block's worth of entries.  Entries may be compressed
8804  * on the server.
8805  */
8806 /* ARGSUSED */
8807 static int
8808 nfs4_readdir(vnode_t *vp, struct uio *uiop, cred_t *cr, int *eofp,
8809 	caller_context_t *ct, int flags)
8810 {
8811 	int error;
8812 	uint_t count;
8813 	rnode4_t *rp;
8814 	rddir4_cache *rdc;
8815 	rddir4_cache *rrdc;
8816 
8817 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
8818 		return (EIO);
8819 	rp = VTOR4(vp);
8820 
8821 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
8822 
8823 	/*
8824 	 * Make sure that the directory cache is valid.
8825 	 */
8826 	if (rp->r_dir != NULL) {
8827 		if (nfs_disable_rddir_cache != 0) {
8828 			/*
8829 			 * Setting nfs_disable_rddir_cache in /etc/system
8830 			 * allows interoperability with servers that do not
8831 			 * properly update the attributes of directories.
8832 			 * Any cached information gets purged before an
8833 			 * access is made to it.
8834 			 */
8835 			nfs4_purge_rddir_cache(vp);
8836 		}
8837 
8838 		error = nfs4_validate_caches(vp, cr);
8839 		if (error)
8840 			return (error);
8841 	}
8842 
8843 	count = MIN(uiop->uio_iov->iov_len, MAXBSIZE);
8844 
8845 	/*
8846 	 * Short circuit last readdir which always returns 0 bytes.
8847 	 * This can be done after the directory has been read through
8848 	 * completely at least once.  This will set r_direof which
8849 	 * can be used to find the value of the last cookie.
8850 	 */
8851 	mutex_enter(&rp->r_statelock);
8852 	if (rp->r_direof != NULL &&
8853 	    uiop->uio_loffset == rp->r_direof->nfs4_ncookie) {
8854 		mutex_exit(&rp->r_statelock);
8855 #ifdef DEBUG
8856 		nfs4_readdir_cache_shorts++;
8857 #endif
8858 		if (eofp)
8859 			*eofp = 1;
8860 		return (0);
8861 	}
8862 
8863 	/*
8864 	 * Look for a cache entry.  Cache entries are identified
8865 	 * by the NFS cookie value and the byte count requested.
8866 	 */
8867 	rdc = rddir4_cache_lookup(rp, uiop->uio_loffset, count);
8868 
8869 	/*
8870 	 * If rdc is NULL then the lookup resulted in an unrecoverable error.
8871 	 */
8872 	if (rdc == NULL) {
8873 		mutex_exit(&rp->r_statelock);
8874 		return (EINTR);
8875 	}
8876 
8877 	/*
8878 	 * Check to see if we need to fill this entry in.
8879 	 */
8880 	if (rdc->flags & RDDIRREQ) {
8881 		rdc->flags &= ~RDDIRREQ;
8882 		rdc->flags |= RDDIR;
8883 		mutex_exit(&rp->r_statelock);
8884 
8885 		/*
8886 		 * Do the readdir.
8887 		 */
8888 		nfs4readdir(vp, rdc, cr);
8889 
8890 		/*
8891 		 * Reacquire the lock, so that we can continue
8892 		 */
8893 		mutex_enter(&rp->r_statelock);
8894 		/*
8895 		 * The entry is now complete
8896 		 */
8897 		rdc->flags &= ~RDDIR;
8898 	}
8899 
8900 	ASSERT(!(rdc->flags & RDDIR));
8901 
8902 	/*
8903 	 * If an error occurred while attempting
8904 	 * to fill the cache entry, mark the entry invalid and
8905 	 * just return the error.
8906 	 */
8907 	if (rdc->error) {
8908 		error = rdc->error;
8909 		rdc->flags |= RDDIRREQ;
8910 		rddir4_cache_rele(rp, rdc);
8911 		mutex_exit(&rp->r_statelock);
8912 		return (error);
8913 	}
8914 
8915 	/*
8916 	 * The cache entry is complete and good,
8917 	 * copyout the dirent structs to the calling
8918 	 * thread.
8919 	 */
8920 	error = uiomove(rdc->entries, rdc->actlen, UIO_READ, uiop);
8921 
8922 	/*
8923 	 * If no error occurred during the copyout,
8924 	 * update the offset in the uio struct to
8925 	 * contain the value of the next NFS 4 cookie
8926 	 * and set the eof value appropriately.
8927 	 */
8928 	if (!error) {
8929 		uiop->uio_loffset = rdc->nfs4_ncookie;
8930 		if (eofp)
8931 			*eofp = rdc->eof;
8932 	}
8933 
8934 	/*
8935 	 * Decide whether to do readahead.  Don't if we
8936 	 * have already read to the end of directory.
8937 	 */
8938 	if (rdc->eof) {
8939 		/*
8940 		 * Make the entry the direof only if it is cached
8941 		 */
8942 		if (rdc->flags & RDDIRCACHED)
8943 			rp->r_direof = rdc;
8944 		rddir4_cache_rele(rp, rdc);
8945 		mutex_exit(&rp->r_statelock);
8946 		return (error);
8947 	}
8948 
8949 	/* Determine if a readdir readahead should be done */
8950 	if (!(rp->r_flags & R4LOOKUP)) {
8951 		rddir4_cache_rele(rp, rdc);
8952 		mutex_exit(&rp->r_statelock);
8953 		return (error);
8954 	}
8955 
8956 	/*
8957 	 * Now look for a readahead entry.
8958 	 *
8959 	 * Check to see whether we found an entry for the readahead.
8960 	 * If so, we don't need to do anything further, so free the new
8961 	 * entry if one was allocated.  Otherwise, allocate a new entry, add
8962 	 * it to the cache, and then initiate an asynchronous readdir
8963 	 * operation to fill it.
8964 	 */
8965 	rrdc = rddir4_cache_lookup(rp, rdc->nfs4_ncookie, count);
8966 
8967 	/*
8968 	 * A readdir cache entry could not be obtained for the readahead.  In
8969 	 * this case we skip the readahead and return.
8970 	 */
8971 	if (rrdc == NULL) {
8972 		rddir4_cache_rele(rp, rdc);
8973 		mutex_exit(&rp->r_statelock);
8974 		return (error);
8975 	}
8976 
8977 	/*
8978 	 * Check to see if we need to fill this entry in.
8979 	 */
8980 	if (rrdc->flags & RDDIRREQ) {
8981 		rrdc->flags &= ~RDDIRREQ;
8982 		rrdc->flags |= RDDIR;
8983 		rddir4_cache_rele(rp, rdc);
8984 		mutex_exit(&rp->r_statelock);
8985 #ifdef DEBUG
8986 		nfs4_readdir_readahead++;
8987 #endif
8988 		/*
8989 		 * Do the readdir.
8990 		 */
8991 		nfs4_async_readdir(vp, rrdc, cr, do_nfs4readdir);
8992 		return (error);
8993 	}
8994 
8995 	rddir4_cache_rele(rp, rrdc);
8996 	rddir4_cache_rele(rp, rdc);
8997 	mutex_exit(&rp->r_statelock);
8998 	return (error);
8999 }
9000 
9001 static int
9002 do_nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
9003 {
9004 	int error;
9005 	rnode4_t *rp;
9006 
9007 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
9008 
9009 	rp = VTOR4(vp);
9010 
9011 	/*
9012 	 * Obtain the readdir results for the caller.
9013 	 */
9014 	nfs4readdir(vp, rdc, cr);
9015 
9016 	mutex_enter(&rp->r_statelock);
9017 	/*
9018 	 * The entry is now complete
9019 	 */
9020 	rdc->flags &= ~RDDIR;
9021 
9022 	error = rdc->error;
9023 	if (error)
9024 		rdc->flags |= RDDIRREQ;
9025 	rddir4_cache_rele(rp, rdc);
9026 	mutex_exit(&rp->r_statelock);
9027 
9028 	return (error);
9029 }
9030 
9031 /*
9032  * Read directory entries.
9033  * There are some weird things to look out for here.  The uio_loffset
9034  * field is either 0 or it is the offset returned from a previous
9035  * readdir.  It is an opaque value used by the server to find the
9036  * correct directory block to read. The count field is the number
9037  * of blocks to read on the server.  This is advisory only, the server
9038  * may return only one block's worth of entries.  Entries may be compressed
9039  * on the server.
9040  *
9041  * Generates the following compound request:
9042  * 1. If readdir offset is zero and no dnlc entry for parent exists,
9043  *    must include a Lookupp as well. In this case, send:
9044  *    { Putfh <fh>; Readdir; Lookupp; Getfh; Getattr }
9045  * 2. Otherwise just do: { Putfh <fh>; Readdir }
9046  *
9047  * Get complete attributes and filehandles for entries if this is the
9048  * first read of the directory. Otherwise, just get fileid's.
9049  */
9050 static void
9051 nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
9052 {
9053 	COMPOUND4args_clnt args;
9054 	COMPOUND4res_clnt res;
9055 	READDIR4args *rargs;
9056 	READDIR4res_clnt *rd_res;
9057 	bitmap4 rd_bitsval;
9058 	nfs_argop4 argop[5];
9059 	nfs_resop4 *resop;
9060 	rnode4_t *rp = VTOR4(vp);
9061 	mntinfo4_t *mi = VTOMI4(vp);
9062 	int doqueue;
9063 	u_longlong_t nodeid, pnodeid;	/* id's of dir and its parents */
9064 	vnode_t *dvp;
9065 	nfs_cookie4 cookie = (nfs_cookie4)rdc->nfs4_cookie;
9066 	int num_ops, res_opcnt;
9067 	bool_t needrecov = FALSE;
9068 	nfs4_recov_state_t recov_state;
9069 	hrtime_t t;
9070 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
9071 
9072 	ASSERT(nfs_zone() == mi->mi_zone);
9073 	ASSERT(rdc->flags & RDDIR);
9074 	ASSERT(rdc->entries == NULL);
9075 
9076 	/*
9077 	 * If rp were a stub, it should have triggered and caused
9078 	 * a mount for us to get this far.
9079 	 */
9080 	ASSERT(!RP_ISSTUB(rp));
9081 
9082 	num_ops = 2;
9083 	if (cookie == (nfs_cookie4)0 || cookie == (nfs_cookie4)1) {
9084 		/*
9085 		 * Since nfsv4 readdir may not return entries for "." and "..",
9086 		 * the client must recreate them:
9087 		 * To find the correct nodeid, do the following:
9088 		 * For current node, get nodeid from dnlc.
9089 		 * - if current node is rootvp, set pnodeid to nodeid.
9090 		 * - else if parent is in the dnlc, get its nodeid from there.
9091 		 * - else add LOOKUPP+GETATTR to compound.
9092 		 */
9093 		nodeid = rp->r_attr.va_nodeid;
9094 		if (vp->v_flag & VROOT) {
9095 			pnodeid = nodeid;	/* root of mount point */
9096 		} else {
9097 			dvp = dnlc_lookup(vp, "..");
9098 			if (dvp != NULL && dvp != DNLC_NO_VNODE) {
9099 				/* parent in dnlc cache - no need for otw */
9100 				pnodeid = VTOR4(dvp)->r_attr.va_nodeid;
9101 			} else {
9102 				/*
9103 				 * parent not in dnlc cache,
9104 				 * do lookupp to get its id
9105 				 */
9106 				num_ops = 5;
9107 				pnodeid = 0; /* set later by getattr parent */
9108 			}
9109 			if (dvp)
9110 				VN_RELE(dvp);
9111 		}
9112 	}
9113 	recov_state.rs_flags = 0;
9114 	recov_state.rs_num_retry_despite_err = 0;
9115 
9116 	/* Save the original mount point security flavor */
9117 	(void) save_mnt_secinfo(mi->mi_curr_serv);
9118 
9119 recov_retry:
9120 	args.ctag = TAG_READDIR;
9121 
9122 	args.array = argop;
9123 	args.array_len = num_ops;
9124 
9125 	if (e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9126 	    &recov_state, NULL)) {
9127 		/*
9128 		 * If readdir a node that is a stub for a crossed mount point,
9129 		 * keep the original secinfo flavor for the current file
9130 		 * system, not the crossed one.
9131 		 */
9132 		(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9133 		rdc->error = e.error;
9134 		return;
9135 	}
9136 
9137 	/*
9138 	 * Determine which attrs to request for dirents.  This code
9139 	 * must be protected by nfs4_start/end_fop because of r_server
9140 	 * (which will change during failover recovery).
9141 	 *
9142 	 */
9143 	if (rp->r_flags & (R4LOOKUP | R4READDIRWATTR)) {
9144 		/*
9145 		 * Get all vattr attrs plus filehandle and rdattr_error
9146 		 */
9147 		rd_bitsval = NFS4_VATTR_MASK |
9148 		    FATTR4_RDATTR_ERROR_MASK |
9149 		    FATTR4_FILEHANDLE_MASK;
9150 
9151 		if (rp->r_flags & R4READDIRWATTR) {
9152 			mutex_enter(&rp->r_statelock);
9153 			rp->r_flags &= ~R4READDIRWATTR;
9154 			mutex_exit(&rp->r_statelock);
9155 		}
9156 	} else {
9157 		servinfo4_t *svp = rp->r_server;
9158 
9159 		/*
9160 		 * Already read directory. Use readdir with
9161 		 * no attrs (except for mounted_on_fileid) for updates.
9162 		 */
9163 		rd_bitsval = FATTR4_RDATTR_ERROR_MASK;
9164 
9165 		/*
9166 		 * request mounted on fileid if supported, else request
9167 		 * fileid.  maybe we should verify that fileid is supported
9168 		 * and request something else if not.
9169 		 */
9170 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
9171 		if (svp->sv_supp_attrs & FATTR4_MOUNTED_ON_FILEID_MASK)
9172 			rd_bitsval |= FATTR4_MOUNTED_ON_FILEID_MASK;
9173 		nfs_rw_exit(&svp->sv_lock);
9174 	}
9175 
9176 	/* putfh directory fh */
9177 	argop[0].argop = OP_CPUTFH;
9178 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
9179 
9180 	argop[1].argop = OP_READDIR;
9181 	rargs = &argop[1].nfs_argop4_u.opreaddir;
9182 	/*
9183 	 * 1 and 2 are reserved for client "." and ".." entry offset.
9184 	 * cookie 0 should be used over-the-wire to start reading at
9185 	 * the beginning of the directory excluding "." and "..".
9186 	 */
9187 	if (rdc->nfs4_cookie == 0 ||
9188 	    rdc->nfs4_cookie == 1 ||
9189 	    rdc->nfs4_cookie == 2) {
9190 		rargs->cookie = (nfs_cookie4)0;
9191 		rargs->cookieverf = 0;
9192 	} else {
9193 		rargs->cookie = (nfs_cookie4)rdc->nfs4_cookie;
9194 		mutex_enter(&rp->r_statelock);
9195 		rargs->cookieverf = rp->r_cookieverf4;
9196 		mutex_exit(&rp->r_statelock);
9197 	}
9198 	rargs->dircount = MIN(rdc->buflen, mi->mi_tsize);
9199 	rargs->maxcount = mi->mi_tsize;
9200 	rargs->attr_request = rd_bitsval;
9201 	rargs->rdc = rdc;
9202 	rargs->dvp = vp;
9203 	rargs->mi = mi;
9204 	rargs->cr = cr;
9205 
9206 
9207 	/*
9208 	 * If count < than the minimum required, we return no entries
9209 	 * and fail with EINVAL
9210 	 */
9211 	if (rargs->dircount < (DIRENT64_RECLEN(1) + DIRENT64_RECLEN(2))) {
9212 		rdc->error = EINVAL;
9213 		goto out;
9214 	}
9215 
9216 	if (args.array_len == 5) {
9217 		/*
9218 		 * Add lookupp and getattr for parent nodeid.
9219 		 */
9220 		argop[2].argop = OP_LOOKUPP;
9221 
9222 		argop[3].argop = OP_GETFH;
9223 
9224 		/* getattr parent */
9225 		argop[4].argop = OP_GETATTR;
9226 		argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
9227 		argop[4].nfs_argop4_u.opgetattr.mi = mi;
9228 	}
9229 
9230 	doqueue = 1;
9231 
9232 	if (mi->mi_io_kstats) {
9233 		mutex_enter(&mi->mi_lock);
9234 		kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
9235 		mutex_exit(&mi->mi_lock);
9236 	}
9237 
9238 	/* capture the time of this call */
9239 	rargs->t = t = gethrtime();
9240 
9241 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
9242 
9243 	if (mi->mi_io_kstats) {
9244 		mutex_enter(&mi->mi_lock);
9245 		kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
9246 		mutex_exit(&mi->mi_lock);
9247 	}
9248 
9249 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
9250 
9251 	/*
9252 	 * If RPC error occurred and it isn't an error that
9253 	 * triggers recovery, then go ahead and fail now.
9254 	 */
9255 	if (e.error != 0 && !needrecov) {
9256 		rdc->error = e.error;
9257 		goto out;
9258 	}
9259 
9260 	if (needrecov) {
9261 		bool_t abort;
9262 
9263 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
9264 		    "nfs4readdir: initiating recovery.\n"));
9265 
9266 		abort = nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
9267 		    NULL, OP_READDIR, NULL);
9268 		if (abort == FALSE) {
9269 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9270 			    &recov_state, needrecov);
9271 			if (!e.error)
9272 				(void) xdr_free(xdr_COMPOUND4res_clnt,
9273 				    (caddr_t)&res);
9274 			if (rdc->entries != NULL) {
9275 				kmem_free(rdc->entries, rdc->entlen);
9276 				rdc->entries = NULL;
9277 			}
9278 			goto recov_retry;
9279 		}
9280 
9281 		if (e.error != 0) {
9282 			rdc->error = e.error;
9283 			goto out;
9284 		}
9285 
9286 		/* fall through for res.status case */
9287 	}
9288 
9289 	res_opcnt = res.array_len;
9290 
9291 	/*
9292 	 * If compound failed first 2 ops (PUTFH+READDIR), then return
9293 	 * failure here.  Subsequent ops are for filling out dot-dot
9294 	 * dirent, and if they fail, we still want to give the caller
9295 	 * the dirents returned by (the successful) READDIR op, so we need
9296 	 * to silently ignore failure for subsequent ops (LOOKUPP+GETATTR).
9297 	 *
9298 	 * One example where PUTFH+READDIR ops would succeed but
9299 	 * LOOKUPP+GETATTR would fail would be a dir that has r perm
9300 	 * but lacks x.  In this case, a POSIX server's VOP_READDIR
9301 	 * would succeed; however, VOP_LOOKUP(..) would fail since no
9302 	 * x perm.  We need to come up with a non-vendor-specific way
9303 	 * for a POSIX server to return d_ino from dotdot's dirent if
9304 	 * client only requests mounted_on_fileid, and just say the
9305 	 * LOOKUPP succeeded and fill out the GETATTR.  However, if
9306 	 * client requested any mandatory attrs, server would be required
9307 	 * to fail the GETATTR op because it can't call VOP_LOOKUP+VOP_GETATTR
9308 	 * for dotdot.
9309 	 */
9310 
9311 	if (res.status) {
9312 		if (res_opcnt <= 2) {
9313 			e.error = geterrno4(res.status);
9314 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9315 			    &recov_state, needrecov);
9316 			nfs4_purge_stale_fh(e.error, vp, cr);
9317 			rdc->error = e.error;
9318 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9319 			if (rdc->entries != NULL) {
9320 				kmem_free(rdc->entries, rdc->entlen);
9321 				rdc->entries = NULL;
9322 			}
9323 			/*
9324 			 * If readdir a node that is a stub for a
9325 			 * crossed mount point, keep the original
9326 			 * secinfo flavor for the current file system,
9327 			 * not the crossed one.
9328 			 */
9329 			(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9330 			return;
9331 		}
9332 	}
9333 
9334 	resop = &res.array[1];	/* readdir res */
9335 	rd_res = &resop->nfs_resop4_u.opreaddirclnt;
9336 
9337 	mutex_enter(&rp->r_statelock);
9338 	rp->r_cookieverf4 = rd_res->cookieverf;
9339 	mutex_exit(&rp->r_statelock);
9340 
9341 	/*
9342 	 * For "." and ".." entries
9343 	 * e.g.
9344 	 *	seek(cookie=0) -> "." entry with d_off = 1
9345 	 *	seek(cookie=1) -> ".." entry with d_off = 2
9346 	 */
9347 	if (cookie == (nfs_cookie4) 0) {
9348 		if (rd_res->dotp)
9349 			rd_res->dotp->d_ino = nodeid;
9350 		if (rd_res->dotdotp)
9351 			rd_res->dotdotp->d_ino = pnodeid;
9352 	}
9353 	if (cookie == (nfs_cookie4) 1) {
9354 		if (rd_res->dotdotp)
9355 			rd_res->dotdotp->d_ino = pnodeid;
9356 	}
9357 
9358 
9359 	/* LOOKUPP+GETATTR attemped */
9360 	if (args.array_len == 5 && rd_res->dotdotp) {
9361 		if (res.status == NFS4_OK && res_opcnt == 5) {
9362 			nfs_fh4 *fhp;
9363 			nfs4_sharedfh_t *sfhp;
9364 			vnode_t *pvp;
9365 			nfs4_ga_res_t *garp;
9366 
9367 			resop++;	/* lookupp */
9368 			resop++;	/* getfh   */
9369 			fhp = &resop->nfs_resop4_u.opgetfh.object;
9370 
9371 			resop++;	/* getattr of parent */
9372 
9373 			/*
9374 			 * First, take care of finishing the
9375 			 * readdir results.
9376 			 */
9377 			garp = &resop->nfs_resop4_u.opgetattr.ga_res;
9378 			/*
9379 			 * The d_ino of .. must be the inode number
9380 			 * of the mounted filesystem.
9381 			 */
9382 			if (garp->n4g_va.va_mask & AT_NODEID)
9383 				rd_res->dotdotp->d_ino =
9384 				    garp->n4g_va.va_nodeid;
9385 
9386 
9387 			/*
9388 			 * Next, create the ".." dnlc entry
9389 			 */
9390 			sfhp = sfh4_get(fhp, mi);
9391 			if (!nfs4_make_dotdot(sfhp, t, vp, cr, &pvp, 0)) {
9392 				dnlc_update(vp, "..", pvp);
9393 				VN_RELE(pvp);
9394 			}
9395 			sfh4_rele(&sfhp);
9396 		}
9397 	}
9398 
9399 	if (mi->mi_io_kstats) {
9400 		mutex_enter(&mi->mi_lock);
9401 		KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
9402 		KSTAT_IO_PTR(mi->mi_io_kstats)->nread += rdc->actlen;
9403 		mutex_exit(&mi->mi_lock);
9404 	}
9405 
9406 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9407 
9408 out:
9409 	/*
9410 	 * If readdir a node that is a stub for a crossed mount point,
9411 	 * keep the original secinfo flavor for the current file system,
9412 	 * not the crossed one.
9413 	 */
9414 	(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9415 
9416 	nfs4_end_fop(mi, vp, NULL, OH_READDIR, &recov_state, needrecov);
9417 }
9418 
9419 
9420 static int
9421 nfs4_bio(struct buf *bp, stable_how4 *stab_comm, cred_t *cr, bool_t readahead)
9422 {
9423 	rnode4_t *rp = VTOR4(bp->b_vp);
9424 	int count;
9425 	int error;
9426 	cred_t *cred_otw = NULL;
9427 	offset_t offset;
9428 	nfs4_open_stream_t *osp = NULL;
9429 	bool_t first_time = TRUE;	/* first time getting otw cred */
9430 	bool_t last_time = FALSE;	/* last time getting otw cred */
9431 
9432 	ASSERT(nfs_zone() == VTOMI4(bp->b_vp)->mi_zone);
9433 
9434 	DTRACE_IO1(start, struct buf *, bp);
9435 	offset = ldbtob(bp->b_lblkno);
9436 
9437 	if (bp->b_flags & B_READ) {
9438 	read_again:
9439 		/*
9440 		 * Releases the osp, if it is provided.
9441 		 * Puts a hold on the cred_otw and the new osp (if found).
9442 		 */
9443 		cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9444 		    &first_time, &last_time);
9445 		error = bp->b_error = nfs4read(bp->b_vp, bp->b_un.b_addr,
9446 		    offset, bp->b_bcount, &bp->b_resid, cred_otw,
9447 		    readahead, NULL);
9448 		crfree(cred_otw);
9449 		if (!error) {
9450 			if (bp->b_resid) {
9451 				/*
9452 				 * Didn't get it all because we hit EOF,
9453 				 * zero all the memory beyond the EOF.
9454 				 */
9455 				/* bzero(rdaddr + */
9456 				bzero(bp->b_un.b_addr +
9457 				    bp->b_bcount - bp->b_resid, bp->b_resid);
9458 			}
9459 			mutex_enter(&rp->r_statelock);
9460 			if (bp->b_resid == bp->b_bcount &&
9461 			    offset >= rp->r_size) {
9462 				/*
9463 				 * We didn't read anything at all as we are
9464 				 * past EOF.  Return an error indicator back
9465 				 * but don't destroy the pages (yet).
9466 				 */
9467 				error = NFS_EOF;
9468 			}
9469 			mutex_exit(&rp->r_statelock);
9470 		} else if (error == EACCES && last_time == FALSE) {
9471 				goto read_again;
9472 		}
9473 	} else {
9474 		if (!(rp->r_flags & R4STALE)) {
9475 write_again:
9476 			/*
9477 			 * Releases the osp, if it is provided.
9478 			 * Puts a hold on the cred_otw and the new
9479 			 * osp (if found).
9480 			 */
9481 			cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9482 			    &first_time, &last_time);
9483 			mutex_enter(&rp->r_statelock);
9484 			count = MIN(bp->b_bcount, rp->r_size - offset);
9485 			mutex_exit(&rp->r_statelock);
9486 			if (count < 0)
9487 				cmn_err(CE_PANIC, "nfs4_bio: write count < 0");
9488 #ifdef DEBUG
9489 			if (count == 0) {
9490 				zoneid_t zoneid = getzoneid();
9491 
9492 				zcmn_err(zoneid, CE_WARN,
9493 				    "nfs4_bio: zero length write at %lld",
9494 				    offset);
9495 				zcmn_err(zoneid, CE_CONT, "flags=0x%x, "
9496 				    "b_bcount=%ld, file size=%lld",
9497 				    rp->r_flags, (long)bp->b_bcount,
9498 				    rp->r_size);
9499 				sfh4_printfhandle(VTOR4(bp->b_vp)->r_fh);
9500 				if (nfs4_bio_do_stop)
9501 					debug_enter("nfs4_bio");
9502 			}
9503 #endif
9504 			error = nfs4write(bp->b_vp, bp->b_un.b_addr, offset,
9505 			    count, cred_otw, stab_comm);
9506 			if (error == EACCES && last_time == FALSE) {
9507 				crfree(cred_otw);
9508 				goto write_again;
9509 			}
9510 			bp->b_error = error;
9511 			if (error && error != EINTR &&
9512 			    !(bp->b_vp->v_vfsp->vfs_flag & VFS_UNMOUNTED)) {
9513 				/*
9514 				 * Don't print EDQUOT errors on the console.
9515 				 * Don't print asynchronous EACCES errors.
9516 				 * Don't print EFBIG errors.
9517 				 * Print all other write errors.
9518 				 */
9519 				if (error != EDQUOT && error != EFBIG &&
9520 				    (error != EACCES ||
9521 				    !(bp->b_flags & B_ASYNC)))
9522 					nfs4_write_error(bp->b_vp,
9523 					    error, cred_otw);
9524 				/*
9525 				 * Update r_error and r_flags as appropriate.
9526 				 * If the error was ESTALE, then mark the
9527 				 * rnode as not being writeable and save
9528 				 * the error status.  Otherwise, save any
9529 				 * errors which occur from asynchronous
9530 				 * page invalidations.  Any errors occurring
9531 				 * from other operations should be saved
9532 				 * by the caller.
9533 				 */
9534 				mutex_enter(&rp->r_statelock);
9535 				if (error == ESTALE) {
9536 					rp->r_flags |= R4STALE;
9537 					if (!rp->r_error)
9538 						rp->r_error = error;
9539 				} else if (!rp->r_error &&
9540 				    (bp->b_flags &
9541 				    (B_INVAL|B_FORCE|B_ASYNC)) ==
9542 				    (B_INVAL|B_FORCE|B_ASYNC)) {
9543 					rp->r_error = error;
9544 				}
9545 				mutex_exit(&rp->r_statelock);
9546 			}
9547 			crfree(cred_otw);
9548 		} else
9549 			error = rp->r_error;
9550 	}
9551 
9552 	if (error != 0 && error != NFS_EOF)
9553 		bp->b_flags |= B_ERROR;
9554 
9555 	if (osp)
9556 		open_stream_rele(osp, rp);
9557 
9558 	DTRACE_IO1(done, struct buf *, bp);
9559 
9560 	return (error);
9561 }
9562 
9563 /* ARGSUSED */
9564 int
9565 nfs4_fid(vnode_t *vp, fid_t *fidp, caller_context_t *ct)
9566 {
9567 	return (EREMOTE);
9568 }
9569 
9570 /* ARGSUSED2 */
9571 int
9572 nfs4_rwlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9573 {
9574 	rnode4_t *rp = VTOR4(vp);
9575 
9576 	if (!write_lock) {
9577 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9578 		return (V_WRITELOCK_FALSE);
9579 	}
9580 
9581 	if ((rp->r_flags & R4DIRECTIO) ||
9582 	    (VTOMI4(vp)->mi_flags & MI4_DIRECTIO)) {
9583 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9584 		if (rp->r_mapcnt == 0 && !nfs4_has_pages(vp))
9585 			return (V_WRITELOCK_FALSE);
9586 		nfs_rw_exit(&rp->r_rwlock);
9587 	}
9588 
9589 	(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, FALSE);
9590 	return (V_WRITELOCK_TRUE);
9591 }
9592 
9593 /* ARGSUSED */
9594 void
9595 nfs4_rwunlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9596 {
9597 	rnode4_t *rp = VTOR4(vp);
9598 
9599 	nfs_rw_exit(&rp->r_rwlock);
9600 }
9601 
9602 /* ARGSUSED */
9603 static int
9604 nfs4_seek(vnode_t *vp, offset_t ooff, offset_t *noffp, caller_context_t *ct)
9605 {
9606 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9607 		return (EIO);
9608 
9609 	/*
9610 	 * Because we stuff the readdir cookie into the offset field
9611 	 * someone may attempt to do an lseek with the cookie which
9612 	 * we want to succeed.
9613 	 */
9614 	if (vp->v_type == VDIR)
9615 		return (0);
9616 	if (*noffp < 0)
9617 		return (EINVAL);
9618 	return (0);
9619 }
9620 
9621 
9622 /*
9623  * Return all the pages from [off..off+len) in file
9624  */
9625 /* ARGSUSED */
9626 static int
9627 nfs4_getpage(vnode_t *vp, offset_t off, size_t len, uint_t *protp,
9628     page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9629 	enum seg_rw rw, cred_t *cr, caller_context_t *ct)
9630 {
9631 	rnode4_t *rp;
9632 	int error;
9633 	mntinfo4_t *mi;
9634 
9635 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9636 		return (EIO);
9637 	rp = VTOR4(vp);
9638 	if (IS_SHADOW(vp, rp))
9639 		vp = RTOV4(rp);
9640 
9641 	if (vp->v_flag & VNOMAP)
9642 		return (ENOSYS);
9643 
9644 	if (protp != NULL)
9645 		*protp = PROT_ALL;
9646 
9647 	/*
9648 	 * Now validate that the caches are up to date.
9649 	 */
9650 	if (error = nfs4_validate_caches(vp, cr))
9651 		return (error);
9652 
9653 	mi = VTOMI4(vp);
9654 retry:
9655 	mutex_enter(&rp->r_statelock);
9656 
9657 	/*
9658 	 * Don't create dirty pages faster than they
9659 	 * can be cleaned so that the system doesn't
9660 	 * get imbalanced.  If the async queue is
9661 	 * maxed out, then wait for it to drain before
9662 	 * creating more dirty pages.  Also, wait for
9663 	 * any threads doing pagewalks in the vop_getattr
9664 	 * entry points so that they don't block for
9665 	 * long periods.
9666 	 */
9667 	if (rw == S_CREATE) {
9668 		while ((mi->mi_max_threads != 0 &&
9669 		    rp->r_awcount > 2 * mi->mi_max_threads) ||
9670 		    rp->r_gcount > 0)
9671 			cv_wait(&rp->r_cv, &rp->r_statelock);
9672 	}
9673 
9674 	/*
9675 	 * If we are getting called as a side effect of an nfs_write()
9676 	 * operation the local file size might not be extended yet.
9677 	 * In this case we want to be able to return pages of zeroes.
9678 	 */
9679 	if (off + len > rp->r_size + PAGEOFFSET && seg != segkmap) {
9680 		NFS4_DEBUG(nfs4_pageio_debug,
9681 		    (CE_NOTE, "getpage beyond EOF: off=%lld, "
9682 		    "len=%llu, size=%llu, attrsize =%llu", off,
9683 		    (u_longlong_t)len, rp->r_size, rp->r_attr.va_size));
9684 		mutex_exit(&rp->r_statelock);
9685 		return (EFAULT);		/* beyond EOF */
9686 	}
9687 
9688 	mutex_exit(&rp->r_statelock);
9689 
9690 	if (len <= PAGESIZE) {
9691 		error = nfs4_getapage(vp, off, len, protp, pl, plsz,
9692 		    seg, addr, rw, cr);
9693 		NFS4_DEBUG(nfs4_pageio_debug && error,
9694 		    (CE_NOTE, "getpage error %d; off=%lld, "
9695 		    "len=%lld", error, off, (u_longlong_t)len));
9696 	} else {
9697 		error = pvn_getpages(nfs4_getapage, vp, off, len, protp,
9698 		    pl, plsz, seg, addr, rw, cr);
9699 		NFS4_DEBUG(nfs4_pageio_debug && error,
9700 		    (CE_NOTE, "getpages error %d; off=%lld, "
9701 		    "len=%lld", error, off, (u_longlong_t)len));
9702 	}
9703 
9704 	switch (error) {
9705 	case NFS_EOF:
9706 		nfs4_purge_caches(vp, NFS4_NOPURGE_DNLC, cr, FALSE);
9707 		goto retry;
9708 	case ESTALE:
9709 		nfs4_purge_stale_fh(error, vp, cr);
9710 	}
9711 
9712 	return (error);
9713 }
9714 
9715 /*
9716  * Called from pvn_getpages or nfs4_getpage to get a particular page.
9717  */
9718 /* ARGSUSED */
9719 static int
9720 nfs4_getapage(vnode_t *vp, u_offset_t off, size_t len, uint_t *protp,
9721     page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9722     enum seg_rw rw, cred_t *cr)
9723 {
9724 	rnode4_t *rp;
9725 	uint_t bsize;
9726 	struct buf *bp;
9727 	page_t *pp;
9728 	u_offset_t lbn;
9729 	u_offset_t io_off;
9730 	u_offset_t blkoff;
9731 	u_offset_t rablkoff;
9732 	size_t io_len;
9733 	uint_t blksize;
9734 	int error;
9735 	int readahead;
9736 	int readahead_issued = 0;
9737 	int ra_window; /* readahead window */
9738 	page_t *pagefound;
9739 	page_t *savepp;
9740 
9741 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9742 		return (EIO);
9743 
9744 	rp = VTOR4(vp);
9745 	ASSERT(!IS_SHADOW(vp, rp));
9746 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
9747 
9748 reread:
9749 	bp = NULL;
9750 	pp = NULL;
9751 	pagefound = NULL;
9752 
9753 	if (pl != NULL)
9754 		pl[0] = NULL;
9755 
9756 	error = 0;
9757 	lbn = off / bsize;
9758 	blkoff = lbn * bsize;
9759 
9760 	/*
9761 	 * Queueing up the readahead before doing the synchronous read
9762 	 * results in a significant increase in read throughput because
9763 	 * of the increased parallelism between the async threads and
9764 	 * the process context.
9765 	 */
9766 	if ((off & ((vp->v_vfsp->vfs_bsize) - 1)) == 0 &&
9767 	    rw != S_CREATE &&
9768 	    !(vp->v_flag & VNOCACHE)) {
9769 		mutex_enter(&rp->r_statelock);
9770 
9771 		/*
9772 		 * Calculate the number of readaheads to do.
9773 		 * a) No readaheads at offset = 0.
9774 		 * b) Do maximum(nfs4_nra) readaheads when the readahead
9775 		 *    window is closed.
9776 		 * c) Do readaheads between 1 to (nfs4_nra - 1) depending
9777 		 *    upon how far the readahead window is open or close.
9778 		 * d) No readaheads if rp->r_nextr is not within the scope
9779 		 *    of the readahead window (random i/o).
9780 		 */
9781 
9782 		if (off == 0)
9783 			readahead = 0;
9784 		else if (blkoff == rp->r_nextr)
9785 			readahead = nfs4_nra;
9786 		else if (rp->r_nextr > blkoff &&
9787 		    ((ra_window = (rp->r_nextr - blkoff) / bsize)
9788 		    <= (nfs4_nra - 1)))
9789 			readahead = nfs4_nra - ra_window;
9790 		else
9791 			readahead = 0;
9792 
9793 		rablkoff = rp->r_nextr;
9794 		while (readahead > 0 && rablkoff + bsize < rp->r_size) {
9795 			mutex_exit(&rp->r_statelock);
9796 			if (nfs4_async_readahead(vp, rablkoff + bsize,
9797 			    addr + (rablkoff + bsize - off),
9798 			    seg, cr, nfs4_readahead) < 0) {
9799 				mutex_enter(&rp->r_statelock);
9800 				break;
9801 			}
9802 			readahead--;
9803 			rablkoff += bsize;
9804 			/*
9805 			 * Indicate that we did a readahead so
9806 			 * readahead offset is not updated
9807 			 * by the synchronous read below.
9808 			 */
9809 			readahead_issued = 1;
9810 			mutex_enter(&rp->r_statelock);
9811 			/*
9812 			 * set readahead offset to
9813 			 * offset of last async readahead
9814 			 * request.
9815 			 */
9816 			rp->r_nextr = rablkoff;
9817 		}
9818 		mutex_exit(&rp->r_statelock);
9819 	}
9820 
9821 again:
9822 	if ((pagefound = page_exists(vp, off)) == NULL) {
9823 		if (pl == NULL) {
9824 			(void) nfs4_async_readahead(vp, blkoff, addr, seg, cr,
9825 			    nfs4_readahead);
9826 		} else if (rw == S_CREATE) {
9827 			/*
9828 			 * Block for this page is not allocated, or the offset
9829 			 * is beyond the current allocation size, or we're
9830 			 * allocating a swap slot and the page was not found,
9831 			 * so allocate it and return a zero page.
9832 			 */
9833 			if ((pp = page_create_va(vp, off,
9834 			    PAGESIZE, PG_WAIT, seg, addr)) == NULL)
9835 				cmn_err(CE_PANIC, "nfs4_getapage: page_create");
9836 			io_len = PAGESIZE;
9837 			mutex_enter(&rp->r_statelock);
9838 			rp->r_nextr = off + PAGESIZE;
9839 			mutex_exit(&rp->r_statelock);
9840 		} else {
9841 			/*
9842 			 * Need to go to server to get a block
9843 			 */
9844 			mutex_enter(&rp->r_statelock);
9845 			if (blkoff < rp->r_size &&
9846 			    blkoff + bsize > rp->r_size) {
9847 				/*
9848 				 * If less than a block left in
9849 				 * file read less than a block.
9850 				 */
9851 				if (rp->r_size <= off) {
9852 					/*
9853 					 * Trying to access beyond EOF,
9854 					 * set up to get at least one page.
9855 					 */
9856 					blksize = off + PAGESIZE - blkoff;
9857 				} else
9858 					blksize = rp->r_size - blkoff;
9859 			} else if ((off == 0) ||
9860 			    (off != rp->r_nextr && !readahead_issued)) {
9861 				blksize = PAGESIZE;
9862 				blkoff = off; /* block = page here */
9863 			} else
9864 				blksize = bsize;
9865 			mutex_exit(&rp->r_statelock);
9866 
9867 			pp = pvn_read_kluster(vp, off, seg, addr, &io_off,
9868 			    &io_len, blkoff, blksize, 0);
9869 
9870 			/*
9871 			 * Some other thread has entered the page,
9872 			 * so just use it.
9873 			 */
9874 			if (pp == NULL)
9875 				goto again;
9876 
9877 			/*
9878 			 * Now round the request size up to page boundaries.
9879 			 * This ensures that the entire page will be
9880 			 * initialized to zeroes if EOF is encountered.
9881 			 */
9882 			io_len = ptob(btopr(io_len));
9883 
9884 			bp = pageio_setup(pp, io_len, vp, B_READ);
9885 			ASSERT(bp != NULL);
9886 
9887 			/*
9888 			 * pageio_setup should have set b_addr to 0.  This
9889 			 * is correct since we want to do I/O on a page
9890 			 * boundary.  bp_mapin will use this addr to calculate
9891 			 * an offset, and then set b_addr to the kernel virtual
9892 			 * address it allocated for us.
9893 			 */
9894 			ASSERT(bp->b_un.b_addr == 0);
9895 
9896 			bp->b_edev = 0;
9897 			bp->b_dev = 0;
9898 			bp->b_lblkno = lbtodb(io_off);
9899 			bp->b_file = vp;
9900 			bp->b_offset = (offset_t)off;
9901 			bp_mapin(bp);
9902 
9903 			/*
9904 			 * If doing a write beyond what we believe is EOF,
9905 			 * don't bother trying to read the pages from the
9906 			 * server, we'll just zero the pages here.  We
9907 			 * don't check that the rw flag is S_WRITE here
9908 			 * because some implementations may attempt a
9909 			 * read access to the buffer before copying data.
9910 			 */
9911 			mutex_enter(&rp->r_statelock);
9912 			if (io_off >= rp->r_size && seg == segkmap) {
9913 				mutex_exit(&rp->r_statelock);
9914 				bzero(bp->b_un.b_addr, io_len);
9915 			} else {
9916 				mutex_exit(&rp->r_statelock);
9917 				error = nfs4_bio(bp, NULL, cr, FALSE);
9918 			}
9919 
9920 			/*
9921 			 * Unmap the buffer before freeing it.
9922 			 */
9923 			bp_mapout(bp);
9924 			pageio_done(bp);
9925 
9926 			savepp = pp;
9927 			do {
9928 				pp->p_fsdata = C_NOCOMMIT;
9929 			} while ((pp = pp->p_next) != savepp);
9930 
9931 			if (error == NFS_EOF) {
9932 				/*
9933 				 * If doing a write system call just return
9934 				 * zeroed pages, else user tried to get pages
9935 				 * beyond EOF, return error.  We don't check
9936 				 * that the rw flag is S_WRITE here because
9937 				 * some implementations may attempt a read
9938 				 * access to the buffer before copying data.
9939 				 */
9940 				if (seg == segkmap)
9941 					error = 0;
9942 				else
9943 					error = EFAULT;
9944 			}
9945 
9946 			if (!readahead_issued && !error) {
9947 				mutex_enter(&rp->r_statelock);
9948 				rp->r_nextr = io_off + io_len;
9949 				mutex_exit(&rp->r_statelock);
9950 			}
9951 		}
9952 	}
9953 
9954 out:
9955 	if (pl == NULL)
9956 		return (error);
9957 
9958 	if (error) {
9959 		if (pp != NULL)
9960 			pvn_read_done(pp, B_ERROR);
9961 		return (error);
9962 	}
9963 
9964 	if (pagefound) {
9965 		se_t se = (rw == S_CREATE ? SE_EXCL : SE_SHARED);
9966 
9967 		/*
9968 		 * Page exists in the cache, acquire the appropriate lock.
9969 		 * If this fails, start all over again.
9970 		 */
9971 		if ((pp = page_lookup(vp, off, se)) == NULL) {
9972 #ifdef DEBUG
9973 			nfs4_lostpage++;
9974 #endif
9975 			goto reread;
9976 		}
9977 		pl[0] = pp;
9978 		pl[1] = NULL;
9979 		return (0);
9980 	}
9981 
9982 	if (pp != NULL)
9983 		pvn_plist_init(pp, pl, plsz, off, io_len, rw);
9984 
9985 	return (error);
9986 }
9987 
9988 static void
9989 nfs4_readahead(vnode_t *vp, u_offset_t blkoff, caddr_t addr, struct seg *seg,
9990     cred_t *cr)
9991 {
9992 	int error;
9993 	page_t *pp;
9994 	u_offset_t io_off;
9995 	size_t io_len;
9996 	struct buf *bp;
9997 	uint_t bsize, blksize;
9998 	rnode4_t *rp = VTOR4(vp);
9999 	page_t *savepp;
10000 
10001 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10002 
10003 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
10004 
10005 	mutex_enter(&rp->r_statelock);
10006 	if (blkoff < rp->r_size && blkoff + bsize > rp->r_size) {
10007 		/*
10008 		 * If less than a block left in file read less
10009 		 * than a block.
10010 		 */
10011 		blksize = rp->r_size - blkoff;
10012 	} else
10013 		blksize = bsize;
10014 	mutex_exit(&rp->r_statelock);
10015 
10016 	pp = pvn_read_kluster(vp, blkoff, segkmap, addr,
10017 	    &io_off, &io_len, blkoff, blksize, 1);
10018 	/*
10019 	 * The isra flag passed to the kluster function is 1, we may have
10020 	 * gotten a return value of NULL for a variety of reasons (# of free
10021 	 * pages < minfree, someone entered the page on the vnode etc). In all
10022 	 * cases, we want to punt on the readahead.
10023 	 */
10024 	if (pp == NULL)
10025 		return;
10026 
10027 	/*
10028 	 * Now round the request size up to page boundaries.
10029 	 * This ensures that the entire page will be
10030 	 * initialized to zeroes if EOF is encountered.
10031 	 */
10032 	io_len = ptob(btopr(io_len));
10033 
10034 	bp = pageio_setup(pp, io_len, vp, B_READ);
10035 	ASSERT(bp != NULL);
10036 
10037 	/*
10038 	 * pageio_setup should have set b_addr to 0.  This is correct since
10039 	 * we want to do I/O on a page boundary. bp_mapin() will use this addr
10040 	 * to calculate an offset, and then set b_addr to the kernel virtual
10041 	 * address it allocated for us.
10042 	 */
10043 	ASSERT(bp->b_un.b_addr == 0);
10044 
10045 	bp->b_edev = 0;
10046 	bp->b_dev = 0;
10047 	bp->b_lblkno = lbtodb(io_off);
10048 	bp->b_file = vp;
10049 	bp->b_offset = (offset_t)blkoff;
10050 	bp_mapin(bp);
10051 
10052 	/*
10053 	 * If doing a write beyond what we believe is EOF, don't bother trying
10054 	 * to read the pages from the server, we'll just zero the pages here.
10055 	 * We don't check that the rw flag is S_WRITE here because some
10056 	 * implementations may attempt a read access to the buffer before
10057 	 * copying data.
10058 	 */
10059 	mutex_enter(&rp->r_statelock);
10060 	if (io_off >= rp->r_size && seg == segkmap) {
10061 		mutex_exit(&rp->r_statelock);
10062 		bzero(bp->b_un.b_addr, io_len);
10063 		error = 0;
10064 	} else {
10065 		mutex_exit(&rp->r_statelock);
10066 		error = nfs4_bio(bp, NULL, cr, TRUE);
10067 		if (error == NFS_EOF)
10068 			error = 0;
10069 	}
10070 
10071 	/*
10072 	 * Unmap the buffer before freeing it.
10073 	 */
10074 	bp_mapout(bp);
10075 	pageio_done(bp);
10076 
10077 	savepp = pp;
10078 	do {
10079 		pp->p_fsdata = C_NOCOMMIT;
10080 	} while ((pp = pp->p_next) != savepp);
10081 
10082 	pvn_read_done(pp, error ? B_READ | B_ERROR : B_READ);
10083 
10084 	/*
10085 	 * In case of error set readahead offset
10086 	 * to the lowest offset.
10087 	 * pvn_read_done() calls VN_DISPOSE to destroy the pages
10088 	 */
10089 	if (error && rp->r_nextr > io_off) {
10090 		mutex_enter(&rp->r_statelock);
10091 		if (rp->r_nextr > io_off)
10092 			rp->r_nextr = io_off;
10093 		mutex_exit(&rp->r_statelock);
10094 	}
10095 }
10096 
10097 /*
10098  * Flags are composed of {B_INVAL, B_FREE, B_DONTNEED, B_FORCE}
10099  * If len == 0, do from off to EOF.
10100  *
10101  * The normal cases should be len == 0 && off == 0 (entire vp list) or
10102  * len == MAXBSIZE (from segmap_release actions), and len == PAGESIZE
10103  * (from pageout).
10104  */
10105 /* ARGSUSED */
10106 static int
10107 nfs4_putpage(vnode_t *vp, offset_t off, size_t len, int flags, cred_t *cr,
10108 	caller_context_t *ct)
10109 {
10110 	int error;
10111 	rnode4_t *rp;
10112 
10113 	ASSERT(cr != NULL);
10114 
10115 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
10116 		return (EIO);
10117 
10118 	rp = VTOR4(vp);
10119 	if (IS_SHADOW(vp, rp))
10120 		vp = RTOV4(rp);
10121 
10122 	/*
10123 	 * XXX - Why should this check be made here?
10124 	 */
10125 	if (vp->v_flag & VNOMAP)
10126 		return (ENOSYS);
10127 
10128 	if (len == 0 && !(flags & B_INVAL) &&
10129 	    (vp->v_vfsp->vfs_flag & VFS_RDONLY))
10130 		return (0);
10131 
10132 	mutex_enter(&rp->r_statelock);
10133 	rp->r_count++;
10134 	mutex_exit(&rp->r_statelock);
10135 	error = nfs4_putpages(vp, off, len, flags, cr);
10136 	mutex_enter(&rp->r_statelock);
10137 	rp->r_count--;
10138 	cv_broadcast(&rp->r_cv);
10139 	mutex_exit(&rp->r_statelock);
10140 
10141 	return (error);
10142 }
10143 
10144 /*
10145  * Write out a single page, possibly klustering adjacent dirty pages.
10146  */
10147 int
10148 nfs4_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp, size_t *lenp,
10149     int flags, cred_t *cr)
10150 {
10151 	u_offset_t io_off;
10152 	u_offset_t lbn_off;
10153 	u_offset_t lbn;
10154 	size_t io_len;
10155 	uint_t bsize;
10156 	int error;
10157 	rnode4_t *rp;
10158 
10159 	ASSERT(!(vp->v_vfsp->vfs_flag & VFS_RDONLY));
10160 	ASSERT(pp != NULL);
10161 	ASSERT(cr != NULL);
10162 	ASSERT((flags & B_ASYNC) || nfs_zone() == VTOMI4(vp)->mi_zone);
10163 
10164 	rp = VTOR4(vp);
10165 	ASSERT(rp->r_count > 0);
10166 	ASSERT(!IS_SHADOW(vp, rp));
10167 
10168 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
10169 	lbn = pp->p_offset / bsize;
10170 	lbn_off = lbn * bsize;
10171 
10172 	/*
10173 	 * Find a kluster that fits in one block, or in
10174 	 * one page if pages are bigger than blocks.  If
10175 	 * there is less file space allocated than a whole
10176 	 * page, we'll shorten the i/o request below.
10177 	 */
10178 	pp = pvn_write_kluster(vp, pp, &io_off, &io_len, lbn_off,
10179 	    roundup(bsize, PAGESIZE), flags);
10180 
10181 	/*
10182 	 * pvn_write_kluster shouldn't have returned a page with offset
10183 	 * behind the original page we were given.  Verify that.
10184 	 */
10185 	ASSERT((pp->p_offset / bsize) >= lbn);
10186 
10187 	/*
10188 	 * Now pp will have the list of kept dirty pages marked for
10189 	 * write back.  It will also handle invalidation and freeing
10190 	 * of pages that are not dirty.  Check for page length rounding
10191 	 * problems.
10192 	 */
10193 	if (io_off + io_len > lbn_off + bsize) {
10194 		ASSERT((io_off + io_len) - (lbn_off + bsize) < PAGESIZE);
10195 		io_len = lbn_off + bsize - io_off;
10196 	}
10197 	/*
10198 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10199 	 * consistent value of r_size. R4MODINPROGRESS is set in writerp4().
10200 	 * When R4MODINPROGRESS is set it indicates that a uiomove() is in
10201 	 * progress and the r_size has not been made consistent with the
10202 	 * new size of the file. When the uiomove() completes the r_size is
10203 	 * updated and the R4MODINPROGRESS flag is cleared.
10204 	 *
10205 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10206 	 * consistent value of r_size. Without this handshaking, it is
10207 	 * possible that nfs4_bio() picks  up the old value of r_size
10208 	 * before the uiomove() in writerp4() completes. This will result
10209 	 * in the write through nfs4_bio() being dropped.
10210 	 *
10211 	 * More precisely, there is a window between the time the uiomove()
10212 	 * completes and the time the r_size is updated. If a VOP_PUTPAGE()
10213 	 * operation intervenes in this window, the page will be picked up,
10214 	 * because it is dirty (it will be unlocked, unless it was
10215 	 * pagecreate'd). When the page is picked up as dirty, the dirty
10216 	 * bit is reset (pvn_getdirty()). In nfs4write(), r_size is
10217 	 * checked. This will still be the old size. Therefore the page will
10218 	 * not be written out. When segmap_release() calls VOP_PUTPAGE(),
10219 	 * the page will be found to be clean and the write will be dropped.
10220 	 */
10221 	if (rp->r_flags & R4MODINPROGRESS) {
10222 		mutex_enter(&rp->r_statelock);
10223 		if ((rp->r_flags & R4MODINPROGRESS) &&
10224 		    rp->r_modaddr + MAXBSIZE > io_off &&
10225 		    rp->r_modaddr < io_off + io_len) {
10226 			page_t *plist;
10227 			/*
10228 			 * A write is in progress for this region of the file.
10229 			 * If we did not detect R4MODINPROGRESS here then this
10230 			 * path through nfs_putapage() would eventually go to
10231 			 * nfs4_bio() and may not write out all of the data
10232 			 * in the pages. We end up losing data. So we decide
10233 			 * to set the modified bit on each page in the page
10234 			 * list and mark the rnode with R4DIRTY. This write
10235 			 * will be restarted at some later time.
10236 			 */
10237 			plist = pp;
10238 			while (plist != NULL) {
10239 				pp = plist;
10240 				page_sub(&plist, pp);
10241 				hat_setmod(pp);
10242 				page_io_unlock(pp);
10243 				page_unlock(pp);
10244 			}
10245 			rp->r_flags |= R4DIRTY;
10246 			mutex_exit(&rp->r_statelock);
10247 			if (offp)
10248 				*offp = io_off;
10249 			if (lenp)
10250 				*lenp = io_len;
10251 			return (0);
10252 		}
10253 		mutex_exit(&rp->r_statelock);
10254 	}
10255 
10256 	if (flags & B_ASYNC) {
10257 		error = nfs4_async_putapage(vp, pp, io_off, io_len, flags, cr,
10258 		    nfs4_sync_putapage);
10259 	} else
10260 		error = nfs4_sync_putapage(vp, pp, io_off, io_len, flags, cr);
10261 
10262 	if (offp)
10263 		*offp = io_off;
10264 	if (lenp)
10265 		*lenp = io_len;
10266 	return (error);
10267 }
10268 
10269 static int
10270 nfs4_sync_putapage(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
10271     int flags, cred_t *cr)
10272 {
10273 	int error;
10274 	rnode4_t *rp;
10275 
10276 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10277 
10278 	flags |= B_WRITE;
10279 
10280 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
10281 
10282 	rp = VTOR4(vp);
10283 
10284 	if ((error == ENOSPC || error == EDQUOT || error == EFBIG ||
10285 	    error == EACCES) &&
10286 	    (flags & (B_INVAL|B_FORCE)) != (B_INVAL|B_FORCE)) {
10287 		if (!(rp->r_flags & R4OUTOFSPACE)) {
10288 			mutex_enter(&rp->r_statelock);
10289 			rp->r_flags |= R4OUTOFSPACE;
10290 			mutex_exit(&rp->r_statelock);
10291 		}
10292 		flags |= B_ERROR;
10293 		pvn_write_done(pp, flags);
10294 		/*
10295 		 * If this was not an async thread, then try again to
10296 		 * write out the pages, but this time, also destroy
10297 		 * them whether or not the write is successful.  This
10298 		 * will prevent memory from filling up with these
10299 		 * pages and destroying them is the only alternative
10300 		 * if they can't be written out.
10301 		 *
10302 		 * Don't do this if this is an async thread because
10303 		 * when the pages are unlocked in pvn_write_done,
10304 		 * some other thread could have come along, locked
10305 		 * them, and queued for an async thread.  It would be
10306 		 * possible for all of the async threads to be tied
10307 		 * up waiting to lock the pages again and they would
10308 		 * all already be locked and waiting for an async
10309 		 * thread to handle them.  Deadlock.
10310 		 */
10311 		if (!(flags & B_ASYNC)) {
10312 			error = nfs4_putpage(vp, io_off, io_len,
10313 			    B_INVAL | B_FORCE, cr, NULL);
10314 		}
10315 	} else {
10316 		if (error)
10317 			flags |= B_ERROR;
10318 		else if (rp->r_flags & R4OUTOFSPACE) {
10319 			mutex_enter(&rp->r_statelock);
10320 			rp->r_flags &= ~R4OUTOFSPACE;
10321 			mutex_exit(&rp->r_statelock);
10322 		}
10323 		pvn_write_done(pp, flags);
10324 		if (freemem < desfree)
10325 			(void) nfs4_commit_vp(vp, (u_offset_t)0, 0, cr,
10326 			    NFS4_WRITE_NOWAIT);
10327 	}
10328 
10329 	return (error);
10330 }
10331 
10332 #ifdef DEBUG
10333 int nfs4_force_open_before_mmap = 0;
10334 #endif
10335 
10336 /* ARGSUSED */
10337 static int
10338 nfs4_map(vnode_t *vp, offset_t off, struct as *as, caddr_t *addrp,
10339     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
10340     caller_context_t *ct)
10341 {
10342 	struct segvn_crargs vn_a;
10343 	int error = 0;
10344 	rnode4_t *rp = VTOR4(vp);
10345 	mntinfo4_t *mi = VTOMI4(vp);
10346 
10347 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10348 		return (EIO);
10349 
10350 	if (vp->v_flag & VNOMAP)
10351 		return (ENOSYS);
10352 
10353 	if (off < 0 || (off + len) < 0)
10354 		return (ENXIO);
10355 
10356 	if (vp->v_type != VREG)
10357 		return (ENODEV);
10358 
10359 	/*
10360 	 * If the file is delegated to the client don't do anything.
10361 	 * If the file is not delegated, then validate the data cache.
10362 	 */
10363 	mutex_enter(&rp->r_statev4_lock);
10364 	if (rp->r_deleg_type == OPEN_DELEGATE_NONE) {
10365 		mutex_exit(&rp->r_statev4_lock);
10366 		error = nfs4_validate_caches(vp, cr);
10367 		if (error)
10368 			return (error);
10369 	} else {
10370 		mutex_exit(&rp->r_statev4_lock);
10371 	}
10372 
10373 	/*
10374 	 * Check to see if the vnode is currently marked as not cachable.
10375 	 * This means portions of the file are locked (through VOP_FRLOCK).
10376 	 * In this case the map request must be refused.  We use
10377 	 * rp->r_lkserlock to avoid a race with concurrent lock requests.
10378 	 */
10379 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_READER, INTR4(vp)))
10380 		return (EINTR);
10381 
10382 	if (vp->v_flag & VNOCACHE) {
10383 		error = EAGAIN;
10384 		goto done;
10385 	}
10386 
10387 	/*
10388 	 * Don't allow concurrent locks and mapping if mandatory locking is
10389 	 * enabled.
10390 	 */
10391 	if (flk_has_remote_locks(vp)) {
10392 		struct vattr va;
10393 		va.va_mask = AT_MODE;
10394 		error = nfs4getattr(vp, &va, cr);
10395 		if (error != 0)
10396 			goto done;
10397 		if (MANDLOCK(vp, va.va_mode)) {
10398 			error = EAGAIN;
10399 			goto done;
10400 		}
10401 	}
10402 
10403 	/*
10404 	 * It is possible that the rnode has a lost lock request that we
10405 	 * are still trying to recover, and that the request conflicts with
10406 	 * this map request.
10407 	 *
10408 	 * An alternative approach would be for nfs4_safemap() to consider
10409 	 * queued lock requests when deciding whether to set or clear
10410 	 * VNOCACHE.  This would require the frlock code path to call
10411 	 * nfs4_safemap() after enqueing a lost request.
10412 	 */
10413 	if (nfs4_map_lost_lock_conflict(vp)) {
10414 		error = EAGAIN;
10415 		goto done;
10416 	}
10417 
10418 	as_rangelock(as);
10419 	error = choose_addr(as, addrp, len, off, ADDR_VACALIGN, flags);
10420 	if (error != 0) {
10421 		as_rangeunlock(as);
10422 		goto done;
10423 	}
10424 
10425 	if (vp->v_type == VREG) {
10426 		/*
10427 		 * We need to retrieve the open stream
10428 		 */
10429 		nfs4_open_stream_t	*osp = NULL;
10430 		nfs4_open_owner_t	*oop = NULL;
10431 
10432 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10433 		if (oop != NULL) {
10434 			/* returns with 'os_sync_lock' held */
10435 			osp = find_open_stream(oop, rp);
10436 			open_owner_rele(oop);
10437 		}
10438 		if (osp == NULL) {
10439 #ifdef DEBUG
10440 			if (nfs4_force_open_before_mmap) {
10441 				error = EIO;
10442 				goto done;
10443 			}
10444 #endif
10445 			/* returns with 'os_sync_lock' held */
10446 			error = open_and_get_osp(vp, cr, &osp);
10447 			if (osp == NULL) {
10448 				NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10449 				    "nfs4_map: we tried to OPEN the file "
10450 				    "but again no osp, so fail with EIO"));
10451 				goto done;
10452 			}
10453 		}
10454 
10455 		if (osp->os_failed_reopen) {
10456 			mutex_exit(&osp->os_sync_lock);
10457 			open_stream_rele(osp, rp);
10458 			NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
10459 			    "nfs4_map: os_failed_reopen set on "
10460 			    "osp %p, cr %p, rp %s", (void *)osp,
10461 			    (void *)cr, rnode4info(rp)));
10462 			error = EIO;
10463 			goto done;
10464 		}
10465 		mutex_exit(&osp->os_sync_lock);
10466 		open_stream_rele(osp, rp);
10467 	}
10468 
10469 	vn_a.vp = vp;
10470 	vn_a.offset = off;
10471 	vn_a.type = (flags & MAP_TYPE);
10472 	vn_a.prot = (uchar_t)prot;
10473 	vn_a.maxprot = (uchar_t)maxprot;
10474 	vn_a.flags = (flags & ~MAP_TYPE);
10475 	vn_a.cred = cr;
10476 	vn_a.amp = NULL;
10477 	vn_a.szc = 0;
10478 	vn_a.lgrp_mem_policy_flags = 0;
10479 
10480 	error = as_map(as, *addrp, len, segvn_create, &vn_a);
10481 	as_rangeunlock(as);
10482 
10483 done:
10484 	nfs_rw_exit(&rp->r_lkserlock);
10485 	return (error);
10486 }
10487 
10488 /*
10489  * We're most likely dealing with a kernel module that likes to READ
10490  * and mmap without OPENing the file (ie: lookup/read/mmap), so lets
10491  * officially OPEN the file to create the necessary client state
10492  * for bookkeeping of os_mmap_read/write counts.
10493  *
10494  * Since VOP_MAP only passes in a pointer to the vnode rather than
10495  * a double pointer, we can't handle the case where nfs4open_otw()
10496  * returns a different vnode than the one passed into VOP_MAP (since
10497  * VOP_DELMAP will not see the vnode nfs4open_otw used).  In this case,
10498  * we return NULL and let nfs4_map() fail.  Note: the only case where
10499  * this should happen is if the file got removed and replaced with the
10500  * same name on the server (in addition to the fact that we're trying
10501  * to VOP_MAP withouth VOP_OPENing the file in the first place).
10502  */
10503 static int
10504 open_and_get_osp(vnode_t *map_vp, cred_t *cr, nfs4_open_stream_t **ospp)
10505 {
10506 	rnode4_t		*rp, *drp;
10507 	vnode_t			*dvp, *open_vp;
10508 	char			file_name[MAXNAMELEN];
10509 	int			just_created;
10510 	nfs4_open_stream_t	*osp;
10511 	nfs4_open_owner_t	*oop;
10512 	int			error;
10513 
10514 	*ospp = NULL;
10515 	open_vp = map_vp;
10516 
10517 	rp = VTOR4(open_vp);
10518 	if ((error = vtodv(open_vp, &dvp, cr, TRUE)) != 0)
10519 		return (error);
10520 	drp = VTOR4(dvp);
10521 
10522 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp))) {
10523 		VN_RELE(dvp);
10524 		return (EINTR);
10525 	}
10526 
10527 	if ((error = vtoname(open_vp, file_name, MAXNAMELEN)) != 0) {
10528 		nfs_rw_exit(&drp->r_rwlock);
10529 		VN_RELE(dvp);
10530 		return (error);
10531 	}
10532 
10533 	mutex_enter(&rp->r_statev4_lock);
10534 	if (rp->created_v4) {
10535 		rp->created_v4 = 0;
10536 		mutex_exit(&rp->r_statev4_lock);
10537 
10538 		dnlc_update(dvp, file_name, open_vp);
10539 		/* This is needed so we don't bump the open ref count */
10540 		just_created = 1;
10541 	} else {
10542 		mutex_exit(&rp->r_statev4_lock);
10543 		just_created = 0;
10544 	}
10545 
10546 	VN_HOLD(map_vp);
10547 
10548 	error = nfs4open_otw(dvp, file_name, NULL, &open_vp, cr, 0, FREAD, 0,
10549 	    just_created);
10550 	if (error) {
10551 		nfs_rw_exit(&drp->r_rwlock);
10552 		VN_RELE(dvp);
10553 		VN_RELE(map_vp);
10554 		return (error);
10555 	}
10556 
10557 	nfs_rw_exit(&drp->r_rwlock);
10558 	VN_RELE(dvp);
10559 
10560 	/*
10561 	 * If nfs4open_otw() returned a different vnode then "undo"
10562 	 * the open and return failure to the caller.
10563 	 */
10564 	if (!VN_CMP(open_vp, map_vp)) {
10565 		nfs4_error_t e;
10566 
10567 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10568 		    "open returned a different vnode"));
10569 		/*
10570 		 * If there's an error, ignore it,
10571 		 * and let VOP_INACTIVE handle it.
10572 		 */
10573 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10574 		    CLOSE_NORM, 0, 0, 0);
10575 		VN_RELE(map_vp);
10576 		return (EIO);
10577 	}
10578 
10579 	VN_RELE(map_vp);
10580 
10581 	oop = find_open_owner(cr, NFS4_PERM_CREATED, VTOMI4(open_vp));
10582 	if (!oop) {
10583 		nfs4_error_t e;
10584 
10585 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10586 		    "no open owner"));
10587 		/*
10588 		 * If there's an error, ignore it,
10589 		 * and let VOP_INACTIVE handle it.
10590 		 */
10591 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10592 		    CLOSE_NORM, 0, 0, 0);
10593 		return (EIO);
10594 	}
10595 	osp = find_open_stream(oop, rp);
10596 	open_owner_rele(oop);
10597 	*ospp = osp;
10598 	return (0);
10599 }
10600 
10601 /*
10602  * Please be aware that when this function is called, the address space write
10603  * a_lock is held.  Do not put over the wire calls in this function.
10604  */
10605 /* ARGSUSED */
10606 static int
10607 nfs4_addmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
10608     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
10609     caller_context_t *ct)
10610 {
10611 	rnode4_t		*rp;
10612 	int			error = 0;
10613 	mntinfo4_t		*mi;
10614 
10615 	mi = VTOMI4(vp);
10616 	rp = VTOR4(vp);
10617 
10618 	if (nfs_zone() != mi->mi_zone)
10619 		return (EIO);
10620 	if (vp->v_flag & VNOMAP)
10621 		return (ENOSYS);
10622 
10623 	/*
10624 	 * Need to hold rwlock while incrementing the mapcnt so that
10625 	 * mmap'ing can be serialized with writes so that the caching
10626 	 * can be handled correctly.
10627 	 *
10628 	 * Don't need to update the open stream first, since this
10629 	 * mmap can't add any additional share access that isn't
10630 	 * already contained in the open stream (for the case where we
10631 	 * open/mmap/only update rp->r_mapcnt/server reboots/reopen doesn't
10632 	 * take into account os_mmap_read[write] counts).
10633 	 */
10634 	if (nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, INTR(vp)))
10635 		return (EINTR);
10636 	atomic_add_long((ulong_t *)&rp->r_mapcnt, btopr(len));
10637 	nfs_rw_exit(&rp->r_rwlock);
10638 
10639 	if (vp->v_type == VREG) {
10640 		/*
10641 		 * We need to retrieve the open stream and update the counts.
10642 		 * If there is no open stream here, something is wrong.
10643 		 */
10644 		nfs4_open_stream_t	*osp = NULL;
10645 		nfs4_open_owner_t	*oop = NULL;
10646 
10647 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10648 		if (oop != NULL) {
10649 			/* returns with 'os_sync_lock' held */
10650 			osp = find_open_stream(oop, rp);
10651 			open_owner_rele(oop);
10652 		}
10653 		if (osp == NULL) {
10654 			NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10655 			    "nfs4_addmap: we should have an osp"
10656 			    "but we don't, so fail with EIO"));
10657 			error = EIO;
10658 			goto out;
10659 		}
10660 
10661 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "nfs4_addmap: osp %p,"
10662 		    " pages %ld, prot 0x%x", (void *)osp, btopr(len), prot));
10663 
10664 		/*
10665 		 * Update the map count in the open stream.
10666 		 * This is necessary in the case where we
10667 		 * open/mmap/close/, then the server reboots, and we
10668 		 * attempt to reopen.  If the mmap doesn't add share
10669 		 * access then we send an invalid reopen with
10670 		 * access = NONE.
10671 		 *
10672 		 * We need to specifically check each PROT_* so a mmap
10673 		 * call of (PROT_WRITE | PROT_EXEC) will ensure us both
10674 		 * read and write access.  A simple comparison of prot
10675 		 * to ~PROT_WRITE to determine read access is insufficient
10676 		 * since prot can be |= with PROT_USER, etc.
10677 		 */
10678 
10679 		/*
10680 		 * Unless we're MAP_SHARED, no sense in adding os_mmap_write
10681 		 */
10682 		if ((flags & MAP_SHARED) && (maxprot & PROT_WRITE))
10683 			osp->os_mmap_write += btopr(len);
10684 		if (maxprot & PROT_READ)
10685 			osp->os_mmap_read += btopr(len);
10686 		if (maxprot & PROT_EXEC)
10687 			osp->os_mmap_read += btopr(len);
10688 		/*
10689 		 * Ensure that os_mmap_read gets incremented, even if
10690 		 * maxprot were to look like PROT_NONE.
10691 		 */
10692 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
10693 		    !(maxprot & PROT_EXEC))
10694 			osp->os_mmap_read += btopr(len);
10695 		osp->os_mapcnt += btopr(len);
10696 		mutex_exit(&osp->os_sync_lock);
10697 		open_stream_rele(osp, rp);
10698 	}
10699 
10700 out:
10701 	/*
10702 	 * If we got an error, then undo our
10703 	 * incrementing of 'r_mapcnt'.
10704 	 */
10705 
10706 	if (error) {
10707 		atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(len));
10708 		ASSERT(rp->r_mapcnt >= 0);
10709 	}
10710 	return (error);
10711 }
10712 
10713 /* ARGSUSED */
10714 static int
10715 nfs4_cmp(vnode_t *vp1, vnode_t *vp2, caller_context_t *ct)
10716 {
10717 
10718 	return (VTOR4(vp1) == VTOR4(vp2));
10719 }
10720 
10721 /* ARGSUSED */
10722 static int
10723 nfs4_frlock(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
10724     offset_t offset, struct flk_callback *flk_cbp, cred_t *cr,
10725     caller_context_t *ct)
10726 {
10727 	int rc;
10728 	u_offset_t start, end;
10729 	rnode4_t *rp;
10730 	int error = 0, intr = INTR4(vp);
10731 	nfs4_error_t e;
10732 
10733 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10734 		return (EIO);
10735 
10736 	/* check for valid cmd parameter */
10737 	if (cmd != F_GETLK && cmd != F_SETLK && cmd != F_SETLKW)
10738 		return (EINVAL);
10739 
10740 	/* Verify l_type. */
10741 	switch (bfp->l_type) {
10742 	case F_RDLCK:
10743 		if (cmd != F_GETLK && !(flag & FREAD))
10744 			return (EBADF);
10745 		break;
10746 	case F_WRLCK:
10747 		if (cmd != F_GETLK && !(flag & FWRITE))
10748 			return (EBADF);
10749 		break;
10750 	case F_UNLCK:
10751 		intr = 0;
10752 		break;
10753 
10754 	default:
10755 		return (EINVAL);
10756 	}
10757 
10758 	/* check the validity of the lock range */
10759 	if (rc = flk_convert_lock_data(vp, bfp, &start, &end, offset))
10760 		return (rc);
10761 	if (rc = flk_check_lock_data(start, end, MAXEND))
10762 		return (rc);
10763 
10764 	/*
10765 	 * If the filesystem is mounted using local locking, pass the
10766 	 * request off to the local locking code.
10767 	 */
10768 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK || vp->v_type != VREG) {
10769 		if (cmd == F_SETLK || cmd == F_SETLKW) {
10770 			/*
10771 			 * For complete safety, we should be holding
10772 			 * r_lkserlock.  However, we can't call
10773 			 * nfs4_safelock and then fs_frlock while
10774 			 * holding r_lkserlock, so just invoke
10775 			 * nfs4_safelock and expect that this will
10776 			 * catch enough of the cases.
10777 			 */
10778 			if (!nfs4_safelock(vp, bfp, cr))
10779 				return (EAGAIN);
10780 		}
10781 		return (fs_frlock(vp, cmd, bfp, flag, offset, flk_cbp, cr, ct));
10782 	}
10783 
10784 	rp = VTOR4(vp);
10785 
10786 	/*
10787 	 * Check whether the given lock request can proceed, given the
10788 	 * current file mappings.
10789 	 */
10790 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_WRITER, intr))
10791 		return (EINTR);
10792 	if (cmd == F_SETLK || cmd == F_SETLKW) {
10793 		if (!nfs4_safelock(vp, bfp, cr)) {
10794 			rc = EAGAIN;
10795 			goto done;
10796 		}
10797 	}
10798 
10799 	/*
10800 	 * Flush the cache after waiting for async I/O to finish.  For new
10801 	 * locks, this is so that the process gets the latest bits from the
10802 	 * server.  For unlocks, this is so that other clients see the
10803 	 * latest bits once the file has been unlocked.  If currently dirty
10804 	 * pages can't be flushed, then don't allow a lock to be set.  But
10805 	 * allow unlocks to succeed, to avoid having orphan locks on the
10806 	 * server.
10807 	 */
10808 	if (cmd != F_GETLK) {
10809 		mutex_enter(&rp->r_statelock);
10810 		while (rp->r_count > 0) {
10811 			if (intr) {
10812 				klwp_t *lwp = ttolwp(curthread);
10813 
10814 				if (lwp != NULL)
10815 					lwp->lwp_nostop++;
10816 				if (cv_wait_sig(&rp->r_cv,
10817 				    &rp->r_statelock) == 0) {
10818 					if (lwp != NULL)
10819 						lwp->lwp_nostop--;
10820 					rc = EINTR;
10821 					break;
10822 				}
10823 				if (lwp != NULL)
10824 					lwp->lwp_nostop--;
10825 				} else
10826 					cv_wait(&rp->r_cv, &rp->r_statelock);
10827 		}
10828 		mutex_exit(&rp->r_statelock);
10829 		if (rc != 0)
10830 			goto done;
10831 		error = nfs4_putpage(vp, (offset_t)0, 0, B_INVAL, cr, ct);
10832 		if (error) {
10833 			if (error == ENOSPC || error == EDQUOT) {
10834 				mutex_enter(&rp->r_statelock);
10835 				if (!rp->r_error)
10836 					rp->r_error = error;
10837 				mutex_exit(&rp->r_statelock);
10838 			}
10839 			if (bfp->l_type != F_UNLCK) {
10840 				rc = ENOLCK;
10841 				goto done;
10842 			}
10843 		}
10844 	}
10845 
10846 	/*
10847 	 * Call the lock manager to do the real work of contacting
10848 	 * the server and obtaining the lock.
10849 	 */
10850 	nfs4frlock(NFS4_LCK_CTYPE_NORM, vp, cmd, bfp, flag, offset,
10851 	    cr, &e, NULL, NULL);
10852 	rc = e.error;
10853 
10854 	if (rc == 0)
10855 		nfs4_lockcompletion(vp, cmd);
10856 
10857 done:
10858 	nfs_rw_exit(&rp->r_lkserlock);
10859 
10860 	return (rc);
10861 }
10862 
10863 /*
10864  * Free storage space associated with the specified vnode.  The portion
10865  * to be freed is specified by bfp->l_start and bfp->l_len (already
10866  * normalized to a "whence" of 0).
10867  *
10868  * This is an experimental facility whose continued existence is not
10869  * guaranteed.  Currently, we only support the special case
10870  * of l_len == 0, meaning free to end of file.
10871  */
10872 /* ARGSUSED */
10873 static int
10874 nfs4_space(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
10875     offset_t offset, cred_t *cr, caller_context_t *ct)
10876 {
10877 	int error;
10878 
10879 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10880 		return (EIO);
10881 	ASSERT(vp->v_type == VREG);
10882 	if (cmd != F_FREESP)
10883 		return (EINVAL);
10884 
10885 	error = convoff(vp, bfp, 0, offset);
10886 	if (!error) {
10887 		ASSERT(bfp->l_start >= 0);
10888 		if (bfp->l_len == 0) {
10889 			struct vattr va;
10890 
10891 			va.va_mask = AT_SIZE;
10892 			va.va_size = bfp->l_start;
10893 			error = nfs4setattr(vp, &va, 0, cr, NULL);
10894 		} else
10895 			error = EINVAL;
10896 	}
10897 
10898 	return (error);
10899 }
10900 
10901 /* ARGSUSED */
10902 int
10903 nfs4_realvp(vnode_t *vp, vnode_t **vpp, caller_context_t *ct)
10904 {
10905 	rnode4_t *rp;
10906 	rp = VTOR4(vp);
10907 
10908 	if (vp->v_type == VREG && IS_SHADOW(vp, rp)) {
10909 		vp = RTOV4(rp);
10910 	}
10911 	*vpp = vp;
10912 	return (0);
10913 }
10914 
10915 /*
10916  * Setup and add an address space callback to do the work of the delmap call.
10917  * The callback will (and must be) deleted in the actual callback function.
10918  *
10919  * This is done in order to take care of the problem that we have with holding
10920  * the address space's a_lock for a long period of time (e.g. if the NFS server
10921  * is down).  Callbacks will be executed in the address space code while the
10922  * a_lock is not held.  Holding the address space's a_lock causes things such
10923  * as ps and fork to hang because they are trying to acquire this lock as well.
10924  */
10925 /* ARGSUSED */
10926 static int
10927 nfs4_delmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
10928     size_t len, uint_t prot, uint_t maxprot, uint_t flags, cred_t *cr,
10929     caller_context_t *ct)
10930 {
10931 	int			caller_found;
10932 	int			error;
10933 	rnode4_t		*rp;
10934 	nfs4_delmap_args_t	*dmapp;
10935 	nfs4_delmapcall_t	*delmap_call;
10936 
10937 	if (vp->v_flag & VNOMAP)
10938 		return (ENOSYS);
10939 
10940 	/*
10941 	 * A process may not change zones if it has NFS pages mmap'ed
10942 	 * in, so we can't legitimately get here from the wrong zone.
10943 	 */
10944 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10945 
10946 	rp = VTOR4(vp);
10947 
10948 	/*
10949 	 * The way that the address space of this process deletes its mapping
10950 	 * of this file is via the following call chains:
10951 	 * - as_free()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
10952 	 * - as_unmap()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
10953 	 *
10954 	 * With the use of address space callbacks we are allowed to drop the
10955 	 * address space lock, a_lock, while executing the NFS operations that
10956 	 * need to go over the wire.  Returning EAGAIN to the caller of this
10957 	 * function is what drives the execution of the callback that we add
10958 	 * below.  The callback will be executed by the address space code
10959 	 * after dropping the a_lock.  When the callback is finished, since
10960 	 * we dropped the a_lock, it must be re-acquired and segvn_unmap()
10961 	 * is called again on the same segment to finish the rest of the work
10962 	 * that needs to happen during unmapping.
10963 	 *
10964 	 * This action of calling back into the segment driver causes
10965 	 * nfs4_delmap() to get called again, but since the callback was
10966 	 * already executed at this point, it already did the work and there
10967 	 * is nothing left for us to do.
10968 	 *
10969 	 * To Summarize:
10970 	 * - The first time nfs4_delmap is called by the current thread is when
10971 	 * we add the caller associated with this delmap to the delmap caller
10972 	 * list, add the callback, and return EAGAIN.
10973 	 * - The second time in this call chain when nfs4_delmap is called we
10974 	 * will find this caller in the delmap caller list and realize there
10975 	 * is no more work to do thus removing this caller from the list and
10976 	 * returning the error that was set in the callback execution.
10977 	 */
10978 	caller_found = nfs4_find_and_delete_delmapcall(rp, &error);
10979 	if (caller_found) {
10980 		/*
10981 		 * 'error' is from the actual delmap operations.  To avoid
10982 		 * hangs, we need to handle the return of EAGAIN differently
10983 		 * since this is what drives the callback execution.
10984 		 * In this case, we don't want to return EAGAIN and do the
10985 		 * callback execution because there are none to execute.
10986 		 */
10987 		if (error == EAGAIN)
10988 			return (0);
10989 		else
10990 			return (error);
10991 	}
10992 
10993 	/* current caller was not in the list */
10994 	delmap_call = nfs4_init_delmapcall();
10995 
10996 	mutex_enter(&rp->r_statelock);
10997 	list_insert_tail(&rp->r_indelmap, delmap_call);
10998 	mutex_exit(&rp->r_statelock);
10999 
11000 	dmapp = kmem_alloc(sizeof (nfs4_delmap_args_t), KM_SLEEP);
11001 
11002 	dmapp->vp = vp;
11003 	dmapp->off = off;
11004 	dmapp->addr = addr;
11005 	dmapp->len = len;
11006 	dmapp->prot = prot;
11007 	dmapp->maxprot = maxprot;
11008 	dmapp->flags = flags;
11009 	dmapp->cr = cr;
11010 	dmapp->caller = delmap_call;
11011 
11012 	error = as_add_callback(as, nfs4_delmap_callback, dmapp,
11013 	    AS_UNMAP_EVENT, addr, len, KM_SLEEP);
11014 
11015 	return (error ? error : EAGAIN);
11016 }
11017 
11018 static nfs4_delmapcall_t *
11019 nfs4_init_delmapcall()
11020 {
11021 	nfs4_delmapcall_t	*delmap_call;
11022 
11023 	delmap_call = kmem_alloc(sizeof (nfs4_delmapcall_t), KM_SLEEP);
11024 	delmap_call->call_id = curthread;
11025 	delmap_call->error = 0;
11026 
11027 	return (delmap_call);
11028 }
11029 
11030 static void
11031 nfs4_free_delmapcall(nfs4_delmapcall_t *delmap_call)
11032 {
11033 	kmem_free(delmap_call, sizeof (nfs4_delmapcall_t));
11034 }
11035 
11036 /*
11037  * Searches for the current delmap caller (based on curthread) in the list of
11038  * callers.  If it is found, we remove it and free the delmap caller.
11039  * Returns:
11040  *      0 if the caller wasn't found
11041  *      1 if the caller was found, removed and freed.  *errp will be set
11042  *	to what the result of the delmap was.
11043  */
11044 static int
11045 nfs4_find_and_delete_delmapcall(rnode4_t *rp, int *errp)
11046 {
11047 	nfs4_delmapcall_t	*delmap_call;
11048 
11049 	/*
11050 	 * If the list doesn't exist yet, we create it and return
11051 	 * that the caller wasn't found.  No list = no callers.
11052 	 */
11053 	mutex_enter(&rp->r_statelock);
11054 	if (!(rp->r_flags & R4DELMAPLIST)) {
11055 		/* The list does not exist */
11056 		list_create(&rp->r_indelmap, sizeof (nfs4_delmapcall_t),
11057 		    offsetof(nfs4_delmapcall_t, call_node));
11058 		rp->r_flags |= R4DELMAPLIST;
11059 		mutex_exit(&rp->r_statelock);
11060 		return (0);
11061 	} else {
11062 		/* The list exists so search it */
11063 		for (delmap_call = list_head(&rp->r_indelmap);
11064 		    delmap_call != NULL;
11065 		    delmap_call = list_next(&rp->r_indelmap, delmap_call)) {
11066 			if (delmap_call->call_id == curthread) {
11067 				/* current caller is in the list */
11068 				*errp = delmap_call->error;
11069 				list_remove(&rp->r_indelmap, delmap_call);
11070 				mutex_exit(&rp->r_statelock);
11071 				nfs4_free_delmapcall(delmap_call);
11072 				return (1);
11073 			}
11074 		}
11075 	}
11076 	mutex_exit(&rp->r_statelock);
11077 	return (0);
11078 }
11079 
11080 /*
11081  * Remove some pages from an mmap'd vnode.  Just update the
11082  * count of pages.  If doing close-to-open, then flush and
11083  * commit all of the pages associated with this file.
11084  * Otherwise, start an asynchronous page flush to write out
11085  * any dirty pages.  This will also associate a credential
11086  * with the rnode which can be used to write the pages.
11087  */
11088 /* ARGSUSED */
11089 static void
11090 nfs4_delmap_callback(struct as *as, void *arg, uint_t event)
11091 {
11092 	nfs4_error_t		e = { 0, NFS4_OK, RPC_SUCCESS };
11093 	rnode4_t		*rp;
11094 	mntinfo4_t		*mi;
11095 	nfs4_delmap_args_t	*dmapp = (nfs4_delmap_args_t *)arg;
11096 
11097 	rp = VTOR4(dmapp->vp);
11098 	mi = VTOMI4(dmapp->vp);
11099 
11100 	atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(dmapp->len));
11101 	ASSERT(rp->r_mapcnt >= 0);
11102 
11103 	/*
11104 	 * Initiate a page flush and potential commit if there are
11105 	 * pages, the file system was not mounted readonly, the segment
11106 	 * was mapped shared, and the pages themselves were writeable.
11107 	 */
11108 	if (nfs4_has_pages(dmapp->vp) &&
11109 	    !(dmapp->vp->v_vfsp->vfs_flag & VFS_RDONLY) &&
11110 	    dmapp->flags == MAP_SHARED && (dmapp->maxprot & PROT_WRITE)) {
11111 		mutex_enter(&rp->r_statelock);
11112 		rp->r_flags |= R4DIRTY;
11113 		mutex_exit(&rp->r_statelock);
11114 		e.error = nfs4_putpage_commit(dmapp->vp, dmapp->off,
11115 		    dmapp->len, dmapp->cr);
11116 		if (!e.error) {
11117 			mutex_enter(&rp->r_statelock);
11118 			e.error = rp->r_error;
11119 			rp->r_error = 0;
11120 			mutex_exit(&rp->r_statelock);
11121 		}
11122 	} else
11123 		e.error = 0;
11124 
11125 	if ((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO))
11126 		(void) nfs4_putpage(dmapp->vp, dmapp->off, dmapp->len,
11127 		    B_INVAL, dmapp->cr, NULL);
11128 
11129 	if (e.error) {
11130 		e.stat = puterrno4(e.error);
11131 		nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
11132 		    OP_COMMIT, FALSE, NULL, 0, dmapp->vp);
11133 		dmapp->caller->error = e.error;
11134 	}
11135 
11136 	/* Check to see if we need to close the file */
11137 
11138 	if (dmapp->vp->v_type == VREG) {
11139 		nfs4close_one(dmapp->vp, NULL, dmapp->cr, 0, NULL, &e,
11140 		    CLOSE_DELMAP, dmapp->len, dmapp->maxprot, dmapp->flags);
11141 
11142 		if (e.error != 0 || e.stat != NFS4_OK) {
11143 			/*
11144 			 * Since it is possible that e.error == 0 and
11145 			 * e.stat != NFS4_OK (and vice versa),
11146 			 * we do the proper checking in order to get both
11147 			 * e.error and e.stat reporting the correct info.
11148 			 */
11149 			if (e.stat == NFS4_OK)
11150 				e.stat = puterrno4(e.error);
11151 			if (e.error == 0)
11152 				e.error = geterrno4(e.stat);
11153 
11154 			nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
11155 			    OP_CLOSE, FALSE, NULL, 0, dmapp->vp);
11156 			dmapp->caller->error = e.error;
11157 		}
11158 	}
11159 
11160 	(void) as_delete_callback(as, arg);
11161 	kmem_free(dmapp, sizeof (nfs4_delmap_args_t));
11162 }
11163 
11164 
11165 static uint_t
11166 fattr4_maxfilesize_to_bits(uint64_t ll)
11167 {
11168 	uint_t l = 1;
11169 
11170 	if (ll == 0) {
11171 		return (0);
11172 	}
11173 
11174 	if (ll & 0xffffffff00000000) {
11175 		l += 32; ll >>= 32;
11176 	}
11177 	if (ll & 0xffff0000) {
11178 		l += 16; ll >>= 16;
11179 	}
11180 	if (ll & 0xff00) {
11181 		l += 8; ll >>= 8;
11182 	}
11183 	if (ll & 0xf0) {
11184 		l += 4; ll >>= 4;
11185 	}
11186 	if (ll & 0xc) {
11187 		l += 2; ll >>= 2;
11188 	}
11189 	if (ll & 0x2) {
11190 		l += 1;
11191 	}
11192 	return (l);
11193 }
11194 
11195 /* ARGSUSED */
11196 int
11197 nfs4_pathconf(vnode_t *vp, int cmd, ulong_t *valp, cred_t *cr,
11198 	caller_context_t *ct)
11199 {
11200 	int error;
11201 	hrtime_t t;
11202 	rnode4_t *rp;
11203 	nfs4_ga_res_t gar;
11204 	nfs4_ga_ext_res_t ger;
11205 
11206 	gar.n4g_ext_res = &ger;
11207 
11208 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
11209 		return (EIO);
11210 	if (cmd == _PC_PATH_MAX || cmd == _PC_SYMLINK_MAX) {
11211 		*valp = MAXPATHLEN;
11212 		return (0);
11213 	}
11214 	if (cmd == _PC_ACL_ENABLED) {
11215 		*valp = _ACL_ACE_ENABLED;
11216 		return (0);
11217 	}
11218 
11219 	rp = VTOR4(vp);
11220 	if (cmd == _PC_XATTR_EXISTS) {
11221 		/*
11222 		 * Eventually should attempt small client readdir before
11223 		 * going otw with GETATTR(FATTR4_NAMED_ATTR).  For now
11224 		 * just drive the OTW getattr.  This is required because
11225 		 * _PC_XATTR_EXISTS can only return true if attributes
11226 		 * exist -- simply checking for existence of the attrdir
11227 		 * is not sufficient.
11228 		 *
11229 		 * pc4_xattr_valid can be only be trusted when r_xattr_dir
11230 		 * is NULL.  Once the xadir vp exists, we can create xattrs,
11231 		 * and we don't have any way to update the "base" object's
11232 		 * pc4_xattr_exists from the xattr or xadir.  Maybe FEM
11233 		 * could help out.
11234 		 */
11235 		if (ATTRCACHE4_VALID(vp) && rp->r_pathconf.pc4_xattr_valid &&
11236 		    rp->r_xattr_dir == NULL) {
11237 			*valp = rp->r_pathconf.pc4_xattr_exists;
11238 			return (0);
11239 		}
11240 	} else {  /* OLD CODE */
11241 		if (ATTRCACHE4_VALID(vp)) {
11242 			mutex_enter(&rp->r_statelock);
11243 			if (rp->r_pathconf.pc4_cache_valid) {
11244 				error = 0;
11245 				switch (cmd) {
11246 				case _PC_FILESIZEBITS:
11247 					*valp =
11248 					    rp->r_pathconf.pc4_filesizebits;
11249 					break;
11250 				case _PC_LINK_MAX:
11251 					*valp =
11252 					    rp->r_pathconf.pc4_link_max;
11253 					break;
11254 				case _PC_NAME_MAX:
11255 					*valp =
11256 					    rp->r_pathconf.pc4_name_max;
11257 					break;
11258 				case _PC_CHOWN_RESTRICTED:
11259 					*valp =
11260 					    rp->r_pathconf.pc4_chown_restricted;
11261 					break;
11262 				case _PC_NO_TRUNC:
11263 					*valp =
11264 					    rp->r_pathconf.pc4_no_trunc;
11265 					break;
11266 				default:
11267 					error = EINVAL;
11268 					break;
11269 				}
11270 				mutex_exit(&rp->r_statelock);
11271 #ifdef DEBUG
11272 				nfs4_pathconf_cache_hits++;
11273 #endif
11274 				return (error);
11275 			}
11276 			mutex_exit(&rp->r_statelock);
11277 		}
11278 	}
11279 #ifdef DEBUG
11280 	nfs4_pathconf_cache_misses++;
11281 #endif
11282 
11283 	t = gethrtime();
11284 
11285 	error = nfs4_attr_otw(vp, TAG_PATHCONF, &gar, NFS4_PATHCONF_MASK, cr);
11286 
11287 	if (error) {
11288 		mutex_enter(&rp->r_statelock);
11289 		rp->r_pathconf.pc4_cache_valid = FALSE;
11290 		rp->r_pathconf.pc4_xattr_valid = FALSE;
11291 		mutex_exit(&rp->r_statelock);
11292 		return (error);
11293 	}
11294 
11295 	/* interpret the max filesize */
11296 	gar.n4g_ext_res->n4g_pc4.pc4_filesizebits =
11297 	    fattr4_maxfilesize_to_bits(gar.n4g_ext_res->n4g_maxfilesize);
11298 
11299 	/* Store the attributes we just received */
11300 	nfs4_attr_cache(vp, &gar, t, cr, TRUE, NULL);
11301 
11302 	switch (cmd) {
11303 	case _PC_FILESIZEBITS:
11304 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_filesizebits;
11305 		break;
11306 	case _PC_LINK_MAX:
11307 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_link_max;
11308 		break;
11309 	case _PC_NAME_MAX:
11310 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_name_max;
11311 		break;
11312 	case _PC_CHOWN_RESTRICTED:
11313 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_chown_restricted;
11314 		break;
11315 	case _PC_NO_TRUNC:
11316 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_no_trunc;
11317 		break;
11318 	case _PC_XATTR_EXISTS:
11319 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_xattr_exists;
11320 		break;
11321 	default:
11322 		return (EINVAL);
11323 	}
11324 
11325 	return (0);
11326 }
11327 
11328 /*
11329  * Called by async thread to do synchronous pageio. Do the i/o, wait
11330  * for it to complete, and cleanup the page list when done.
11331  */
11332 static int
11333 nfs4_sync_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11334     int flags, cred_t *cr)
11335 {
11336 	int error;
11337 
11338 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11339 
11340 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11341 	if (flags & B_READ)
11342 		pvn_read_done(pp, (error ? B_ERROR : 0) | flags);
11343 	else
11344 		pvn_write_done(pp, (error ? B_ERROR : 0) | flags);
11345 	return (error);
11346 }
11347 
11348 /* ARGSUSED */
11349 static int
11350 nfs4_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11351 	int flags, cred_t *cr, caller_context_t *ct)
11352 {
11353 	int error;
11354 	rnode4_t *rp;
11355 
11356 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
11357 		return (EIO);
11358 
11359 	if (pp == NULL)
11360 		return (EINVAL);
11361 
11362 	rp = VTOR4(vp);
11363 	mutex_enter(&rp->r_statelock);
11364 	rp->r_count++;
11365 	mutex_exit(&rp->r_statelock);
11366 
11367 	if (flags & B_ASYNC) {
11368 		error = nfs4_async_pageio(vp, pp, io_off, io_len, flags, cr,
11369 		    nfs4_sync_pageio);
11370 	} else
11371 		error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11372 	mutex_enter(&rp->r_statelock);
11373 	rp->r_count--;
11374 	cv_broadcast(&rp->r_cv);
11375 	mutex_exit(&rp->r_statelock);
11376 	return (error);
11377 }
11378 
11379 /* ARGSUSED */
11380 static void
11381 nfs4_dispose(vnode_t *vp, page_t *pp, int fl, int dn, cred_t *cr,
11382 	caller_context_t *ct)
11383 {
11384 	int error;
11385 	rnode4_t *rp;
11386 	page_t *plist;
11387 	page_t *pptr;
11388 	offset3 offset;
11389 	count3 len;
11390 	k_sigset_t smask;
11391 
11392 	/*
11393 	 * We should get called with fl equal to either B_FREE or
11394 	 * B_INVAL.  Any other value is illegal.
11395 	 *
11396 	 * The page that we are either supposed to free or destroy
11397 	 * should be exclusive locked and its io lock should not
11398 	 * be held.
11399 	 */
11400 	ASSERT(fl == B_FREE || fl == B_INVAL);
11401 	ASSERT((PAGE_EXCL(pp) && !page_iolock_assert(pp)) || panicstr);
11402 
11403 	rp = VTOR4(vp);
11404 
11405 	/*
11406 	 * If the page doesn't need to be committed or we shouldn't
11407 	 * even bother attempting to commit it, then just make sure
11408 	 * that the p_fsdata byte is clear and then either free or
11409 	 * destroy the page as appropriate.
11410 	 */
11411 	if (pp->p_fsdata == C_NOCOMMIT || (rp->r_flags & R4STALE)) {
11412 		pp->p_fsdata = C_NOCOMMIT;
11413 		if (fl == B_FREE)
11414 			page_free(pp, dn);
11415 		else
11416 			page_destroy(pp, dn);
11417 		return;
11418 	}
11419 
11420 	/*
11421 	 * If there is a page invalidation operation going on, then
11422 	 * if this is one of the pages being destroyed, then just
11423 	 * clear the p_fsdata byte and then either free or destroy
11424 	 * the page as appropriate.
11425 	 */
11426 	mutex_enter(&rp->r_statelock);
11427 	if ((rp->r_flags & R4TRUNCATE) && pp->p_offset >= rp->r_truncaddr) {
11428 		mutex_exit(&rp->r_statelock);
11429 		pp->p_fsdata = C_NOCOMMIT;
11430 		if (fl == B_FREE)
11431 			page_free(pp, dn);
11432 		else
11433 			page_destroy(pp, dn);
11434 		return;
11435 	}
11436 
11437 	/*
11438 	 * If we are freeing this page and someone else is already
11439 	 * waiting to do a commit, then just unlock the page and
11440 	 * return.  That other thread will take care of commiting
11441 	 * this page.  The page can be freed sometime after the
11442 	 * commit has finished.  Otherwise, if the page is marked
11443 	 * as delay commit, then we may be getting called from
11444 	 * pvn_write_done, one page at a time.   This could result
11445 	 * in one commit per page, so we end up doing lots of small
11446 	 * commits instead of fewer larger commits.  This is bad,
11447 	 * we want do as few commits as possible.
11448 	 */
11449 	if (fl == B_FREE) {
11450 		if (rp->r_flags & R4COMMITWAIT) {
11451 			page_unlock(pp);
11452 			mutex_exit(&rp->r_statelock);
11453 			return;
11454 		}
11455 		if (pp->p_fsdata == C_DELAYCOMMIT) {
11456 			pp->p_fsdata = C_COMMIT;
11457 			page_unlock(pp);
11458 			mutex_exit(&rp->r_statelock);
11459 			return;
11460 		}
11461 	}
11462 
11463 	/*
11464 	 * Check to see if there is a signal which would prevent an
11465 	 * attempt to commit the pages from being successful.  If so,
11466 	 * then don't bother with all of the work to gather pages and
11467 	 * generate the unsuccessful RPC.  Just return from here and
11468 	 * let the page be committed at some later time.
11469 	 */
11470 	sigintr(&smask, VTOMI4(vp)->mi_flags & MI4_INT);
11471 	if (ttolwp(curthread) != NULL && ISSIG(curthread, JUSTLOOKING)) {
11472 		sigunintr(&smask);
11473 		page_unlock(pp);
11474 		mutex_exit(&rp->r_statelock);
11475 		return;
11476 	}
11477 	sigunintr(&smask);
11478 
11479 	/*
11480 	 * We are starting to need to commit pages, so let's try
11481 	 * to commit as many as possible at once to reduce the
11482 	 * overhead.
11483 	 *
11484 	 * Set the `commit inprogress' state bit.  We must
11485 	 * first wait until any current one finishes.  Then
11486 	 * we initialize the c_pages list with this page.
11487 	 */
11488 	while (rp->r_flags & R4COMMIT) {
11489 		rp->r_flags |= R4COMMITWAIT;
11490 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
11491 		rp->r_flags &= ~R4COMMITWAIT;
11492 	}
11493 	rp->r_flags |= R4COMMIT;
11494 	mutex_exit(&rp->r_statelock);
11495 	ASSERT(rp->r_commit.c_pages == NULL);
11496 	rp->r_commit.c_pages = pp;
11497 	rp->r_commit.c_commbase = (offset3)pp->p_offset;
11498 	rp->r_commit.c_commlen = PAGESIZE;
11499 
11500 	/*
11501 	 * Gather together all other pages which can be committed.
11502 	 * They will all be chained off r_commit.c_pages.
11503 	 */
11504 	nfs4_get_commit(vp);
11505 
11506 	/*
11507 	 * Clear the `commit inprogress' status and disconnect
11508 	 * the list of pages to be committed from the rnode.
11509 	 * At this same time, we also save the starting offset
11510 	 * and length of data to be committed on the server.
11511 	 */
11512 	plist = rp->r_commit.c_pages;
11513 	rp->r_commit.c_pages = NULL;
11514 	offset = rp->r_commit.c_commbase;
11515 	len = rp->r_commit.c_commlen;
11516 	mutex_enter(&rp->r_statelock);
11517 	rp->r_flags &= ~R4COMMIT;
11518 	cv_broadcast(&rp->r_commit.c_cv);
11519 	mutex_exit(&rp->r_statelock);
11520 
11521 	if (curproc == proc_pageout || curproc == proc_fsflush ||
11522 	    nfs_zone() != VTOMI4(vp)->mi_zone) {
11523 		nfs4_async_commit(vp, plist, offset, len,
11524 		    cr, do_nfs4_async_commit);
11525 		return;
11526 	}
11527 
11528 	/*
11529 	 * Actually generate the COMMIT op over the wire operation.
11530 	 */
11531 	error = nfs4_commit(vp, (offset4)offset, (count4)len, cr);
11532 
11533 	/*
11534 	 * If we got an error during the commit, just unlock all
11535 	 * of the pages.  The pages will get retransmitted to the
11536 	 * server during a putpage operation.
11537 	 */
11538 	if (error) {
11539 		while (plist != NULL) {
11540 			pptr = plist;
11541 			page_sub(&plist, pptr);
11542 			page_unlock(pptr);
11543 		}
11544 		return;
11545 	}
11546 
11547 	/*
11548 	 * We've tried as hard as we can to commit the data to stable
11549 	 * storage on the server.  We just unlock the rest of the pages
11550 	 * and clear the commit required state.  They will be put
11551 	 * onto the tail of the cachelist if they are nolonger
11552 	 * mapped.
11553 	 */
11554 	while (plist != pp) {
11555 		pptr = plist;
11556 		page_sub(&plist, pptr);
11557 		pptr->p_fsdata = C_NOCOMMIT;
11558 		page_unlock(pptr);
11559 	}
11560 
11561 	/*
11562 	 * It is possible that nfs4_commit didn't return error but
11563 	 * some other thread has modified the page we are going
11564 	 * to free/destroy.
11565 	 *    In this case we need to rewrite the page. Do an explicit check
11566 	 * before attempting to free/destroy the page. If modified, needs to
11567 	 * be rewritten so unlock the page and return.
11568 	 */
11569 	if (hat_ismod(pp)) {
11570 		pp->p_fsdata = C_NOCOMMIT;
11571 		page_unlock(pp);
11572 		return;
11573 	}
11574 
11575 	/*
11576 	 * Now, as appropriate, either free or destroy the page
11577 	 * that we were called with.
11578 	 */
11579 	pp->p_fsdata = C_NOCOMMIT;
11580 	if (fl == B_FREE)
11581 		page_free(pp, dn);
11582 	else
11583 		page_destroy(pp, dn);
11584 }
11585 
11586 /*
11587  * Commit requires that the current fh be the file written to.
11588  * The compound op structure is:
11589  *      PUTFH(file), COMMIT
11590  */
11591 static int
11592 nfs4_commit(vnode_t *vp, offset4 offset, count4 count, cred_t *cr)
11593 {
11594 	COMPOUND4args_clnt args;
11595 	COMPOUND4res_clnt res;
11596 	COMMIT4res *cm_res;
11597 	nfs_argop4 argop[2];
11598 	nfs_resop4 *resop;
11599 	int doqueue;
11600 	mntinfo4_t *mi;
11601 	rnode4_t *rp;
11602 	cred_t *cred_otw = NULL;
11603 	bool_t needrecov = FALSE;
11604 	nfs4_recov_state_t recov_state;
11605 	nfs4_open_stream_t *osp = NULL;
11606 	bool_t first_time = TRUE;	/* first time getting OTW cred */
11607 	bool_t last_time = FALSE;	/* last time getting OTW cred */
11608 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
11609 
11610 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11611 
11612 	rp = VTOR4(vp);
11613 
11614 	mi = VTOMI4(vp);
11615 	recov_state.rs_flags = 0;
11616 	recov_state.rs_num_retry_despite_err = 0;
11617 get_commit_cred:
11618 	/*
11619 	 * Releases the osp, if a valid open stream is provided.
11620 	 * Puts a hold on the cred_otw and the new osp (if found).
11621 	 */
11622 	cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
11623 	    &first_time, &last_time);
11624 	args.ctag = TAG_COMMIT;
11625 recov_retry:
11626 	/*
11627 	 * Commit ops: putfh file; commit
11628 	 */
11629 	args.array_len = 2;
11630 	args.array = argop;
11631 
11632 	e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11633 	    &recov_state, NULL);
11634 	if (e.error) {
11635 		crfree(cred_otw);
11636 		if (osp != NULL)
11637 			open_stream_rele(osp, rp);
11638 		return (e.error);
11639 	}
11640 
11641 	/* putfh directory */
11642 	argop[0].argop = OP_CPUTFH;
11643 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
11644 
11645 	/* commit */
11646 	argop[1].argop = OP_COMMIT;
11647 	argop[1].nfs_argop4_u.opcommit.offset = offset;
11648 	argop[1].nfs_argop4_u.opcommit.count = count;
11649 
11650 	doqueue = 1;
11651 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, &e);
11652 
11653 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
11654 	if (!needrecov && e.error) {
11655 		nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state,
11656 		    needrecov);
11657 		crfree(cred_otw);
11658 		if (e.error == EACCES && last_time == FALSE)
11659 			goto get_commit_cred;
11660 		if (osp != NULL)
11661 			open_stream_rele(osp, rp);
11662 		return (e.error);
11663 	}
11664 
11665 	if (needrecov) {
11666 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
11667 		    NULL, OP_COMMIT, NULL) == FALSE) {
11668 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11669 			    &recov_state, needrecov);
11670 			if (!e.error)
11671 				(void) xdr_free(xdr_COMPOUND4res_clnt,
11672 				    (caddr_t)&res);
11673 			goto recov_retry;
11674 		}
11675 		if (e.error) {
11676 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11677 			    &recov_state, needrecov);
11678 			crfree(cred_otw);
11679 			if (osp != NULL)
11680 				open_stream_rele(osp, rp);
11681 			return (e.error);
11682 		}
11683 		/* fall through for res.status case */
11684 	}
11685 
11686 	if (res.status) {
11687 		e.error = geterrno4(res.status);
11688 		if (e.error == EACCES && last_time == FALSE) {
11689 			crfree(cred_otw);
11690 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11691 			    &recov_state, needrecov);
11692 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11693 			goto get_commit_cred;
11694 		}
11695 		/*
11696 		 * Can't do a nfs4_purge_stale_fh here because this
11697 		 * can cause a deadlock.  nfs4_commit can
11698 		 * be called from nfs4_dispose which can be called
11699 		 * indirectly via pvn_vplist_dirty.  nfs4_purge_stale_fh
11700 		 * can call back to pvn_vplist_dirty.
11701 		 */
11702 		if (e.error == ESTALE) {
11703 			mutex_enter(&rp->r_statelock);
11704 			rp->r_flags |= R4STALE;
11705 			if (!rp->r_error)
11706 				rp->r_error = e.error;
11707 			mutex_exit(&rp->r_statelock);
11708 			PURGE_ATTRCACHE4(vp);
11709 		} else {
11710 			mutex_enter(&rp->r_statelock);
11711 			if (!rp->r_error)
11712 				rp->r_error = e.error;
11713 			mutex_exit(&rp->r_statelock);
11714 		}
11715 	} else {
11716 		ASSERT(rp->r_flags & R4HAVEVERF);
11717 		resop = &res.array[1];	/* commit res */
11718 		cm_res = &resop->nfs_resop4_u.opcommit;
11719 		mutex_enter(&rp->r_statelock);
11720 		if (cm_res->writeverf == rp->r_writeverf) {
11721 			mutex_exit(&rp->r_statelock);
11722 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11723 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11724 			    &recov_state, needrecov);
11725 			crfree(cred_otw);
11726 			if (osp != NULL)
11727 				open_stream_rele(osp, rp);
11728 			return (0);
11729 		}
11730 		nfs4_set_mod(vp);
11731 		rp->r_writeverf = cm_res->writeverf;
11732 		mutex_exit(&rp->r_statelock);
11733 		e.error = NFS_VERF_MISMATCH;
11734 	}
11735 
11736 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11737 	nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state, needrecov);
11738 	crfree(cred_otw);
11739 	if (osp != NULL)
11740 		open_stream_rele(osp, rp);
11741 
11742 	return (e.error);
11743 }
11744 
11745 static void
11746 nfs4_set_mod(vnode_t *vp)
11747 {
11748 	page_t *pp;
11749 	kmutex_t *vphm;
11750 	rnode4_t *rp;
11751 
11752 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11753 
11754 	/* make sure we're looking at the master vnode, not a shadow */
11755 
11756 	rp = VTOR4(vp);
11757 	if (IS_SHADOW(vp, rp))
11758 		vp = RTOV4(rp);
11759 
11760 	vphm = page_vnode_mutex(vp);
11761 	mutex_enter(vphm);
11762 	/*
11763 	 * If there are no pages associated with this vnode, then
11764 	 * just return.
11765 	 */
11766 	if ((pp = vp->v_pages) == NULL) {
11767 		mutex_exit(vphm);
11768 		return;
11769 	}
11770 
11771 	do {
11772 		if (pp->p_fsdata != C_NOCOMMIT) {
11773 			hat_setmod(pp);
11774 			pp->p_fsdata = C_NOCOMMIT;
11775 		}
11776 	} while ((pp = pp->p_vpnext) != vp->v_pages);
11777 	mutex_exit(vphm);
11778 }
11779 
11780 /*
11781  * This function is used to gather a page list of the pages which
11782  * can be committed on the server.
11783  *
11784  * The calling thread must have set R4COMMIT.  This bit is used to
11785  * serialize access to the commit structure in the rnode.  As long
11786  * as the thread has set R4COMMIT, then it can manipulate the commit
11787  * structure without requiring any other locks.
11788  *
11789  * When this function is called from nfs4_dispose() the page passed
11790  * into nfs4_dispose() will be SE_EXCL locked, and so this function
11791  * will skip it. This is not a problem since we initially add the
11792  * page to the r_commit page list.
11793  *
11794  */
11795 static void
11796 nfs4_get_commit(vnode_t *vp)
11797 {
11798 	rnode4_t *rp;
11799 	page_t *pp;
11800 	kmutex_t *vphm;
11801 
11802 	rp = VTOR4(vp);
11803 
11804 	ASSERT(rp->r_flags & R4COMMIT);
11805 
11806 	/* make sure we're looking at the master vnode, not a shadow */
11807 
11808 	if (IS_SHADOW(vp, rp))
11809 		vp = RTOV4(rp);
11810 
11811 	vphm = page_vnode_mutex(vp);
11812 	mutex_enter(vphm);
11813 
11814 	/*
11815 	 * If there are no pages associated with this vnode, then
11816 	 * just return.
11817 	 */
11818 	if ((pp = vp->v_pages) == NULL) {
11819 		mutex_exit(vphm);
11820 		return;
11821 	}
11822 
11823 	/*
11824 	 * Step through all of the pages associated with this vnode
11825 	 * looking for pages which need to be committed.
11826 	 */
11827 	do {
11828 		/*
11829 		 * First short-cut everything (without the page_lock)
11830 		 * and see if this page does not need to be committed
11831 		 * or is modified if so then we'll just skip it.
11832 		 */
11833 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp))
11834 			continue;
11835 
11836 		/*
11837 		 * Attempt to lock the page.  If we can't, then
11838 		 * someone else is messing with it or we have been
11839 		 * called from nfs4_dispose and this is the page that
11840 		 * nfs4_dispose was called with.. anyway just skip it.
11841 		 */
11842 		if (!page_trylock(pp, SE_EXCL))
11843 			continue;
11844 
11845 		/*
11846 		 * Lets check again now that we have the page lock.
11847 		 */
11848 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
11849 			page_unlock(pp);
11850 			continue;
11851 		}
11852 
11853 		/* this had better not be a free page */
11854 		ASSERT(PP_ISFREE(pp) == 0);
11855 
11856 		/*
11857 		 * The page needs to be committed and we locked it.
11858 		 * Update the base and length parameters and add it
11859 		 * to r_pages.
11860 		 */
11861 		if (rp->r_commit.c_pages == NULL) {
11862 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11863 			rp->r_commit.c_commlen = PAGESIZE;
11864 		} else if (pp->p_offset < rp->r_commit.c_commbase) {
11865 			rp->r_commit.c_commlen = rp->r_commit.c_commbase -
11866 			    (offset3)pp->p_offset + rp->r_commit.c_commlen;
11867 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11868 		} else if ((rp->r_commit.c_commbase + rp->r_commit.c_commlen)
11869 		    <= pp->p_offset) {
11870 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
11871 			    rp->r_commit.c_commbase + PAGESIZE;
11872 		}
11873 		page_add(&rp->r_commit.c_pages, pp);
11874 	} while ((pp = pp->p_vpnext) != vp->v_pages);
11875 
11876 	mutex_exit(vphm);
11877 }
11878 
11879 /*
11880  * This routine is used to gather together a page list of the pages
11881  * which are to be committed on the server.  This routine must not
11882  * be called if the calling thread holds any locked pages.
11883  *
11884  * The calling thread must have set R4COMMIT.  This bit is used to
11885  * serialize access to the commit structure in the rnode.  As long
11886  * as the thread has set R4COMMIT, then it can manipulate the commit
11887  * structure without requiring any other locks.
11888  */
11889 static void
11890 nfs4_get_commit_range(vnode_t *vp, u_offset_t soff, size_t len)
11891 {
11892 
11893 	rnode4_t *rp;
11894 	page_t *pp;
11895 	u_offset_t end;
11896 	u_offset_t off;
11897 	ASSERT(len != 0);
11898 	rp = VTOR4(vp);
11899 	ASSERT(rp->r_flags & R4COMMIT);
11900 
11901 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11902 
11903 	/* make sure we're looking at the master vnode, not a shadow */
11904 
11905 	if (IS_SHADOW(vp, rp))
11906 		vp = RTOV4(rp);
11907 
11908 	/*
11909 	 * If there are no pages associated with this vnode, then
11910 	 * just return.
11911 	 */
11912 	if ((pp = vp->v_pages) == NULL)
11913 		return;
11914 	/*
11915 	 * Calculate the ending offset.
11916 	 */
11917 	end = soff + len;
11918 	for (off = soff; off < end; off += PAGESIZE) {
11919 		/*
11920 		 * Lookup each page by vp, offset.
11921 		 */
11922 		if ((pp = page_lookup_nowait(vp, off, SE_EXCL)) == NULL)
11923 			continue;
11924 		/*
11925 		 * If this page does not need to be committed or is
11926 		 * modified, then just skip it.
11927 		 */
11928 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
11929 			page_unlock(pp);
11930 			continue;
11931 		}
11932 
11933 		ASSERT(PP_ISFREE(pp) == 0);
11934 		/*
11935 		 * The page needs to be committed and we locked it.
11936 		 * Update the base and length parameters and add it
11937 		 * to r_pages.
11938 		 */
11939 		if (rp->r_commit.c_pages == NULL) {
11940 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11941 			rp->r_commit.c_commlen = PAGESIZE;
11942 		} else {
11943 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
11944 			    rp->r_commit.c_commbase + PAGESIZE;
11945 		}
11946 		page_add(&rp->r_commit.c_pages, pp);
11947 	}
11948 }
11949 
11950 /*
11951  * Called from nfs4_close(), nfs4_fsync() and nfs4_delmap().
11952  * Flushes and commits data to the server.
11953  */
11954 static int
11955 nfs4_putpage_commit(vnode_t *vp, offset_t poff, size_t plen, cred_t *cr)
11956 {
11957 	int error;
11958 	verifier4 write_verf;
11959 	rnode4_t *rp = VTOR4(vp);
11960 
11961 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11962 
11963 	/*
11964 	 * Flush the data portion of the file and then commit any
11965 	 * portions which need to be committed.  This may need to
11966 	 * be done twice if the server has changed state since
11967 	 * data was last written.  The data will need to be
11968 	 * rewritten to the server and then a new commit done.
11969 	 *
11970 	 * In fact, this may need to be done several times if the
11971 	 * server is having problems and crashing while we are
11972 	 * attempting to do this.
11973 	 */
11974 
11975 top:
11976 	/*
11977 	 * Do a flush based on the poff and plen arguments.  This
11978 	 * will synchronously write out any modified pages in the
11979 	 * range specified by (poff, plen). This starts all of the
11980 	 * i/o operations which will be waited for in the next
11981 	 * call to nfs4_putpage
11982 	 */
11983 
11984 	mutex_enter(&rp->r_statelock);
11985 	write_verf = rp->r_writeverf;
11986 	mutex_exit(&rp->r_statelock);
11987 
11988 	error = nfs4_putpage(vp, poff, plen, B_ASYNC, cr, NULL);
11989 	if (error == EAGAIN)
11990 		error = 0;
11991 
11992 	/*
11993 	 * Do a flush based on the poff and plen arguments.  This
11994 	 * will synchronously write out any modified pages in the
11995 	 * range specified by (poff, plen) and wait until all of
11996 	 * the asynchronous i/o's in that range are done as well.
11997 	 */
11998 	if (!error)
11999 		error = nfs4_putpage(vp, poff, plen, 0, cr, NULL);
12000 
12001 	if (error)
12002 		return (error);
12003 
12004 	mutex_enter(&rp->r_statelock);
12005 	if (rp->r_writeverf != write_verf) {
12006 		mutex_exit(&rp->r_statelock);
12007 		goto top;
12008 	}
12009 	mutex_exit(&rp->r_statelock);
12010 
12011 	/*
12012 	 * Now commit any pages which might need to be committed.
12013 	 * If the error, NFS_VERF_MISMATCH, is returned, then
12014 	 * start over with the flush operation.
12015 	 */
12016 	error = nfs4_commit_vp(vp, poff, plen, cr, NFS4_WRITE_WAIT);
12017 
12018 	if (error == NFS_VERF_MISMATCH)
12019 		goto top;
12020 
12021 	return (error);
12022 }
12023 
12024 /*
12025  * nfs4_commit_vp()  will wait for other pending commits and
12026  * will either commit the whole file or a range, plen dictates
12027  * if we commit whole file. a value of zero indicates the whole
12028  * file. Called from nfs4_putpage_commit() or nfs4_sync_putapage()
12029  */
12030 static int
12031 nfs4_commit_vp(vnode_t *vp, u_offset_t poff, size_t plen,
12032     cred_t *cr, int wait_on_writes)
12033 {
12034 	rnode4_t *rp;
12035 	page_t *plist;
12036 	offset3 offset;
12037 	count3 len;
12038 
12039 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12040 
12041 	rp = VTOR4(vp);
12042 
12043 	/*
12044 	 *  before we gather commitable pages make
12045 	 *  sure there are no outstanding async writes
12046 	 */
12047 	if (rp->r_count && wait_on_writes == NFS4_WRITE_WAIT) {
12048 		mutex_enter(&rp->r_statelock);
12049 		while (rp->r_count > 0) {
12050 			cv_wait(&rp->r_cv, &rp->r_statelock);
12051 		}
12052 		mutex_exit(&rp->r_statelock);
12053 	}
12054 
12055 	/*
12056 	 * Set the `commit inprogress' state bit.  We must
12057 	 * first wait until any current one finishes.
12058 	 */
12059 	mutex_enter(&rp->r_statelock);
12060 	while (rp->r_flags & R4COMMIT) {
12061 		rp->r_flags |= R4COMMITWAIT;
12062 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
12063 		rp->r_flags &= ~R4COMMITWAIT;
12064 	}
12065 	rp->r_flags |= R4COMMIT;
12066 	mutex_exit(&rp->r_statelock);
12067 
12068 	/*
12069 	 * Gather all of the pages which need to be
12070 	 * committed.
12071 	 */
12072 	if (plen == 0)
12073 		nfs4_get_commit(vp);
12074 	else
12075 		nfs4_get_commit_range(vp, poff, plen);
12076 
12077 	/*
12078 	 * Clear the `commit inprogress' bit and disconnect the
12079 	 * page list which was gathered by nfs4_get_commit.
12080 	 */
12081 	plist = rp->r_commit.c_pages;
12082 	rp->r_commit.c_pages = NULL;
12083 	offset = rp->r_commit.c_commbase;
12084 	len = rp->r_commit.c_commlen;
12085 	mutex_enter(&rp->r_statelock);
12086 	rp->r_flags &= ~R4COMMIT;
12087 	cv_broadcast(&rp->r_commit.c_cv);
12088 	mutex_exit(&rp->r_statelock);
12089 
12090 	/*
12091 	 * If any pages need to be committed, commit them and
12092 	 * then unlock them so that they can be freed some
12093 	 * time later.
12094 	 */
12095 	if (plist == NULL)
12096 		return (0);
12097 
12098 	/*
12099 	 * No error occurred during the flush portion
12100 	 * of this operation, so now attempt to commit
12101 	 * the data to stable storage on the server.
12102 	 *
12103 	 * This will unlock all of the pages on the list.
12104 	 */
12105 	return (nfs4_sync_commit(vp, plist, offset, len, cr));
12106 }
12107 
12108 static int
12109 nfs4_sync_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
12110     cred_t *cr)
12111 {
12112 	int error;
12113 	page_t *pp;
12114 
12115 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12116 
12117 	error = nfs4_commit(vp, (offset4)offset, (count3)count, cr);
12118 
12119 	/*
12120 	 * If we got an error, then just unlock all of the pages
12121 	 * on the list.
12122 	 */
12123 	if (error) {
12124 		while (plist != NULL) {
12125 			pp = plist;
12126 			page_sub(&plist, pp);
12127 			page_unlock(pp);
12128 		}
12129 		return (error);
12130 	}
12131 	/*
12132 	 * We've tried as hard as we can to commit the data to stable
12133 	 * storage on the server.  We just unlock the pages and clear
12134 	 * the commit required state.  They will get freed later.
12135 	 */
12136 	while (plist != NULL) {
12137 		pp = plist;
12138 		page_sub(&plist, pp);
12139 		pp->p_fsdata = C_NOCOMMIT;
12140 		page_unlock(pp);
12141 	}
12142 
12143 	return (error);
12144 }
12145 
12146 static void
12147 do_nfs4_async_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
12148     cred_t *cr)
12149 {
12150 
12151 	(void) nfs4_sync_commit(vp, plist, offset, count, cr);
12152 }
12153 
12154 /*ARGSUSED*/
12155 static int
12156 nfs4_setsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr,
12157 	caller_context_t *ct)
12158 {
12159 	int		error = 0;
12160 	mntinfo4_t	*mi;
12161 	vattr_t		va;
12162 	vsecattr_t	nfsace4_vsap;
12163 
12164 	mi = VTOMI4(vp);
12165 	if (nfs_zone() != mi->mi_zone)
12166 		return (EIO);
12167 	if (mi->mi_flags & MI4_ACL) {
12168 		/* if we have a delegation, return it */
12169 		if (VTOR4(vp)->r_deleg_type != OPEN_DELEGATE_NONE)
12170 			(void) nfs4delegreturn(VTOR4(vp),
12171 			    NFS4_DR_REOPEN|NFS4_DR_PUSH);
12172 
12173 		error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask,
12174 		    NFS4_ACL_SET);
12175 		if (error) /* EINVAL */
12176 			return (error);
12177 
12178 		if (vsecattr->vsa_mask & (VSA_ACL | VSA_DFACL)) {
12179 			/*
12180 			 * These are aclent_t type entries.
12181 			 */
12182 			error = vs_aent_to_ace4(vsecattr, &nfsace4_vsap,
12183 			    vp->v_type == VDIR, FALSE);
12184 			if (error)
12185 				return (error);
12186 		} else {
12187 			/*
12188 			 * These are ace_t type entries.
12189 			 */
12190 			error = vs_acet_to_ace4(vsecattr, &nfsace4_vsap,
12191 			    FALSE);
12192 			if (error)
12193 				return (error);
12194 		}
12195 		bzero(&va, sizeof (va));
12196 		error = nfs4setattr(vp, &va, flag, cr, &nfsace4_vsap);
12197 		vs_ace4_destroy(&nfsace4_vsap);
12198 		return (error);
12199 	}
12200 	return (ENOSYS);
12201 }
12202 
12203 /* ARGSUSED */
12204 int
12205 nfs4_getsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr,
12206 	caller_context_t *ct)
12207 {
12208 	int		error;
12209 	mntinfo4_t	*mi;
12210 	nfs4_ga_res_t	gar;
12211 	rnode4_t	*rp = VTOR4(vp);
12212 
12213 	mi = VTOMI4(vp);
12214 	if (nfs_zone() != mi->mi_zone)
12215 		return (EIO);
12216 
12217 	bzero(&gar, sizeof (gar));
12218 	gar.n4g_vsa.vsa_mask = vsecattr->vsa_mask;
12219 
12220 	/*
12221 	 * vsecattr->vsa_mask holds the original acl request mask.
12222 	 * This is needed when determining what to return.
12223 	 * (See: nfs4_create_getsecattr_return())
12224 	 */
12225 	error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask, NFS4_ACL_GET);
12226 	if (error) /* EINVAL */
12227 		return (error);
12228 
12229 	if (mi->mi_flags & MI4_ACL) {
12230 		/*
12231 		 * Check if the data is cached and the cache is valid.  If it
12232 		 * is we don't go over the wire.
12233 		 */
12234 		if (rp->r_secattr != NULL && ATTRCACHE4_VALID(vp)) {
12235 			mutex_enter(&rp->r_statelock);
12236 			if (rp->r_secattr != NULL) {
12237 				error = nfs4_create_getsecattr_return(
12238 				    rp->r_secattr, vsecattr, rp->r_attr.va_uid,
12239 				    rp->r_attr.va_gid,
12240 				    vp->v_type == VDIR);
12241 				if (!error) { /* error == 0 - Success! */
12242 					mutex_exit(&rp->r_statelock);
12243 					return (error);
12244 				}
12245 			}
12246 			mutex_exit(&rp->r_statelock);
12247 		}
12248 
12249 		/*
12250 		 * The getattr otw call will always get both the acl, in
12251 		 * the form of a list of nfsace4's, and the number of acl
12252 		 * entries; independent of the value of gar.n4g_vsa.vsa_mask.
12253 		 */
12254 		gar.n4g_va.va_mask = AT_ALL;
12255 		error =  nfs4_getattr_otw(vp, &gar, cr, 1);
12256 		if (error) {
12257 			vs_ace4_destroy(&gar.n4g_vsa);
12258 			if (error == ENOTSUP || error == EOPNOTSUPP)
12259 				error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12260 			return (error);
12261 		}
12262 
12263 		if (!(gar.n4g_resbmap & FATTR4_ACL_MASK)) {
12264 			/*
12265 			 * No error was returned, but according to the response
12266 			 * bitmap, neither was an acl.
12267 			 */
12268 			vs_ace4_destroy(&gar.n4g_vsa);
12269 			error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12270 			return (error);
12271 		}
12272 
12273 		/*
12274 		 * Update the cache with the ACL.
12275 		 */
12276 		nfs4_acl_fill_cache(rp, &gar.n4g_vsa);
12277 
12278 		error = nfs4_create_getsecattr_return(&gar.n4g_vsa,
12279 		    vsecattr, gar.n4g_va.va_uid, gar.n4g_va.va_gid,
12280 		    vp->v_type == VDIR);
12281 		vs_ace4_destroy(&gar.n4g_vsa);
12282 		if ((error) && (vsecattr->vsa_mask &
12283 		    (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) &&
12284 		    (error != EACCES)) {
12285 			error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12286 		}
12287 		return (error);
12288 	}
12289 	error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12290 	return (error);
12291 }
12292 
12293 /*
12294  * The function returns:
12295  * 	- 0 (zero) if the passed in "acl_mask" is a valid request.
12296  * 	- EINVAL if the passed in "acl_mask" is an invalid request.
12297  *
12298  * In the case of getting an acl (op == NFS4_ACL_GET) the mask is invalid if:
12299  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12300  *
12301  * In the case of setting an acl (op == NFS4_ACL_SET) the mask is invalid if:
12302  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12303  * - We have a count field set without the corresponding acl field set. (e.g. -
12304  * VSA_ACECNT is set, but VSA_ACE is not)
12305  */
12306 static int
12307 nfs4_is_acl_mask_valid(uint_t acl_mask, nfs4_acl_op_t op)
12308 {
12309 	/* Shortcut the masks that are always valid. */
12310 	if (acl_mask == (VSA_ACE | VSA_ACECNT))
12311 		return (0);
12312 	if (acl_mask == (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT))
12313 		return (0);
12314 
12315 	if (acl_mask & (VSA_ACE | VSA_ACECNT)) {
12316 		/*
12317 		 * We can't have any VSA_ACL type stuff in the mask now.
12318 		 */
12319 		if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12320 		    VSA_DFACLCNT))
12321 			return (EINVAL);
12322 
12323 		if (op == NFS4_ACL_SET) {
12324 			if ((acl_mask & VSA_ACECNT) && !(acl_mask & VSA_ACE))
12325 				return (EINVAL);
12326 		}
12327 	}
12328 
12329 	if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) {
12330 		/*
12331 		 * We can't have any VSA_ACE type stuff in the mask now.
12332 		 */
12333 		if (acl_mask & (VSA_ACE | VSA_ACECNT))
12334 			return (EINVAL);
12335 
12336 		if (op == NFS4_ACL_SET) {
12337 			if ((acl_mask & VSA_ACLCNT) && !(acl_mask & VSA_ACL))
12338 				return (EINVAL);
12339 
12340 			if ((acl_mask & VSA_DFACLCNT) &&
12341 			    !(acl_mask & VSA_DFACL))
12342 				return (EINVAL);
12343 		}
12344 	}
12345 	return (0);
12346 }
12347 
12348 /*
12349  * The theory behind creating the correct getsecattr return is simply this:
12350  * "Don't return anything that the caller is not expecting to have to free."
12351  */
12352 static int
12353 nfs4_create_getsecattr_return(vsecattr_t *filled_vsap, vsecattr_t *vsap,
12354     uid_t uid, gid_t gid, int isdir)
12355 {
12356 	int error = 0;
12357 	/* Save the mask since the translators modify it. */
12358 	uint_t	orig_mask = vsap->vsa_mask;
12359 
12360 	if (orig_mask & (VSA_ACE | VSA_ACECNT)) {
12361 		error = vs_ace4_to_acet(filled_vsap, vsap, uid, gid,
12362 		    FALSE, ((orig_mask & VSA_ACE) ? FALSE : TRUE));
12363 
12364 		if (error)
12365 			return (error);
12366 
12367 		/*
12368 		 * If the caller only asked for the ace count (VSA_ACECNT)
12369 		 * don't give them the full acl (VSA_ACE), free it.
12370 		 */
12371 		if (!orig_mask & VSA_ACE) {
12372 			if (vsap->vsa_aclentp != NULL) {
12373 				kmem_free(vsap->vsa_aclentp,
12374 				    vsap->vsa_aclcnt * sizeof (ace_t));
12375 				vsap->vsa_aclentp = NULL;
12376 			}
12377 		}
12378 		vsap->vsa_mask = orig_mask;
12379 
12380 	} else if (orig_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12381 	    VSA_DFACLCNT)) {
12382 		error = vs_ace4_to_aent(filled_vsap, vsap, uid, gid,
12383 		    isdir, FALSE,
12384 		    ((orig_mask & (VSA_ACL | VSA_DFACL)) ? FALSE : TRUE));
12385 
12386 		if (error)
12387 			return (error);
12388 
12389 		/*
12390 		 * If the caller only asked for the acl count (VSA_ACLCNT)
12391 		 * and/or the default acl count (VSA_DFACLCNT) don't give them
12392 		 * the acl (VSA_ACL) or default acl (VSA_DFACL), free it.
12393 		 */
12394 		if (!orig_mask & VSA_ACL) {
12395 			if (vsap->vsa_aclentp != NULL) {
12396 				kmem_free(vsap->vsa_aclentp,
12397 				    vsap->vsa_aclcnt * sizeof (aclent_t));
12398 				vsap->vsa_aclentp = NULL;
12399 			}
12400 		}
12401 
12402 		if (!orig_mask & VSA_DFACL) {
12403 			if (vsap->vsa_dfaclentp != NULL) {
12404 				kmem_free(vsap->vsa_dfaclentp,
12405 				    vsap->vsa_dfaclcnt * sizeof (aclent_t));
12406 				vsap->vsa_dfaclentp = NULL;
12407 			}
12408 		}
12409 		vsap->vsa_mask = orig_mask;
12410 	}
12411 	return (0);
12412 }
12413 
12414 /* ARGSUSED */
12415 int
12416 nfs4_shrlock(vnode_t *vp, int cmd, struct shrlock *shr, int flag, cred_t *cr,
12417     caller_context_t *ct)
12418 {
12419 	int error;
12420 
12421 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
12422 		return (EIO);
12423 	/*
12424 	 * check for valid cmd parameter
12425 	 */
12426 	if (cmd != F_SHARE && cmd != F_UNSHARE && cmd != F_HASREMOTELOCKS)
12427 		return (EINVAL);
12428 
12429 	/*
12430 	 * Check access permissions
12431 	 */
12432 	if ((cmd & F_SHARE) &&
12433 	    (((shr->s_access & F_RDACC) && (flag & FREAD) == 0) ||
12434 	    (shr->s_access == F_WRACC && (flag & FWRITE) == 0)))
12435 		return (EBADF);
12436 
12437 	/*
12438 	 * If the filesystem is mounted using local locking, pass the
12439 	 * request off to the local share code.
12440 	 */
12441 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK)
12442 		return (fs_shrlock(vp, cmd, shr, flag, cr, ct));
12443 
12444 	switch (cmd) {
12445 	case F_SHARE:
12446 	case F_UNSHARE:
12447 		/*
12448 		 * This will be properly implemented later,
12449 		 * see RFE: 4823948 .
12450 		 */
12451 		error = EAGAIN;
12452 		break;
12453 
12454 	case F_HASREMOTELOCKS:
12455 		/*
12456 		 * NFS client can't store remote locks itself
12457 		 */
12458 		shr->s_access = 0;
12459 		error = 0;
12460 		break;
12461 
12462 	default:
12463 		error = EINVAL;
12464 		break;
12465 	}
12466 
12467 	return (error);
12468 }
12469 
12470 /*
12471  * Common code called by directory ops to update the attrcache
12472  */
12473 static int
12474 nfs4_update_attrcache(nfsstat4 status, nfs4_ga_res_t *garp,
12475     hrtime_t t, vnode_t *vp, cred_t *cr)
12476 {
12477 	int error = 0;
12478 
12479 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12480 
12481 	if (status != NFS4_OK) {
12482 		/* getattr not done or failed */
12483 		PURGE_ATTRCACHE4(vp);
12484 		return (error);
12485 	}
12486 
12487 	if (garp) {
12488 		nfs4_attr_cache(vp, garp, t, cr, FALSE, NULL);
12489 	} else {
12490 		PURGE_ATTRCACHE4(vp);
12491 	}
12492 	return (error);
12493 }
12494 
12495 /*
12496  * Update directory caches for directory modification ops (link, rename, etc.)
12497  * When dinfo is NULL, manage dircaches in the old way.
12498  */
12499 static void
12500 nfs4_update_dircaches(change_info4 *cinfo, vnode_t *dvp, vnode_t *vp, char *nm,
12501     dirattr_info_t *dinfo)
12502 {
12503 	rnode4_t	*drp = VTOR4(dvp);
12504 
12505 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
12506 
12507 	/* Purge rddir cache for dir since it changed */
12508 	if (drp->r_dir != NULL)
12509 		nfs4_purge_rddir_cache(dvp);
12510 
12511 	/*
12512 	 * If caller provided dinfo, then use it to manage dir caches.
12513 	 */
12514 	if (dinfo != NULL) {
12515 		if (vp != NULL) {
12516 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12517 			if (!VTOR4(vp)->created_v4) {
12518 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12519 				dnlc_update(dvp, nm, vp);
12520 			} else {
12521 				/*
12522 				 * XXX don't update if the created_v4 flag is
12523 				 * set
12524 				 */
12525 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12526 				NFS4_DEBUG(nfs4_client_state_debug,
12527 				    (CE_NOTE, "nfs4_update_dircaches: "
12528 				    "don't update dnlc: created_v4 flag"));
12529 			}
12530 		}
12531 
12532 		nfs4_attr_cache(dvp, dinfo->di_garp, dinfo->di_time_call,
12533 		    dinfo->di_cred, FALSE, cinfo);
12534 
12535 		return;
12536 	}
12537 
12538 	/*
12539 	 * Caller didn't provide dinfo, then check change_info4 to update DNLC.
12540 	 * Since caller modified dir but didn't receive post-dirmod-op dir
12541 	 * attrs, the dir's attrs must be purged.
12542 	 *
12543 	 * XXX this check and dnlc update/purge should really be atomic,
12544 	 * XXX but can't use rnode statelock because it'll deadlock in
12545 	 * XXX dnlc_purge_vp, however, the risk is minimal even if a race
12546 	 * XXX does occur.
12547 	 *
12548 	 * XXX We also may want to check that atomic is true in the
12549 	 * XXX change_info struct. If it is not, the change_info may
12550 	 * XXX reflect changes by more than one clients which means that
12551 	 * XXX our cache may not be valid.
12552 	 */
12553 	PURGE_ATTRCACHE4(dvp);
12554 	if (drp->r_change == cinfo->before) {
12555 		/* no changes took place in the directory prior to our link */
12556 		if (vp != NULL) {
12557 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12558 			if (!VTOR4(vp)->created_v4) {
12559 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12560 				dnlc_update(dvp, nm, vp);
12561 			} else {
12562 				/*
12563 				 * XXX dont' update if the created_v4 flag
12564 				 * is set
12565 				 */
12566 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12567 				NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
12568 				    "nfs4_update_dircaches: don't"
12569 				    " update dnlc: created_v4 flag"));
12570 			}
12571 		}
12572 	} else {
12573 		/* Another client modified directory - purge its dnlc cache */
12574 		dnlc_purge_vp(dvp);
12575 	}
12576 }
12577 
12578 /*
12579  * The OPEN_CONFIRM operation confirms the sequence number used in OPENing a
12580  * file.
12581  *
12582  * The 'reopening_file' boolean should be set to TRUE if we are reopening this
12583  * file (ie: client recovery) and otherwise set to FALSE.
12584  *
12585  * 'nfs4_start/end_op' should have been called by the proper (ie: not recovery
12586  * initiated) calling functions.
12587  *
12588  * 'resend' is set to TRUE if this is a OPEN_CONFIRM issued as a result
12589  * of resending a 'lost' open request.
12590  *
12591  * 'num_bseqid_retryp' makes sure we don't loop forever on a broken
12592  * server that hands out BAD_SEQID on open confirm.
12593  *
12594  * Errors are returned via the nfs4_error_t parameter.
12595  */
12596 void
12597 nfs4open_confirm(vnode_t *vp, seqid4 *seqid, stateid4 *stateid, cred_t *cr,
12598     bool_t reopening_file, bool_t *retry_open, nfs4_open_owner_t *oop,
12599     bool_t resend, nfs4_error_t *ep, int *num_bseqid_retryp)
12600 {
12601 	COMPOUND4args_clnt args;
12602 	COMPOUND4res_clnt res;
12603 	nfs_argop4 argop[2];
12604 	nfs_resop4 *resop;
12605 	int doqueue = 1;
12606 	mntinfo4_t *mi;
12607 	OPEN_CONFIRM4args *open_confirm_args;
12608 	int needrecov;
12609 
12610 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12611 #if DEBUG
12612 	mutex_enter(&oop->oo_lock);
12613 	ASSERT(oop->oo_seqid_inuse);
12614 	mutex_exit(&oop->oo_lock);
12615 #endif
12616 
12617 recov_retry_confirm:
12618 	nfs4_error_zinit(ep);
12619 	*retry_open = FALSE;
12620 
12621 	if (resend)
12622 		args.ctag = TAG_OPEN_CONFIRM_LOST;
12623 	else
12624 		args.ctag = TAG_OPEN_CONFIRM;
12625 
12626 	args.array_len = 2;
12627 	args.array = argop;
12628 
12629 	/* putfh target fh */
12630 	argop[0].argop = OP_CPUTFH;
12631 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
12632 
12633 	argop[1].argop = OP_OPEN_CONFIRM;
12634 	open_confirm_args = &argop[1].nfs_argop4_u.opopen_confirm;
12635 
12636 	(*seqid) += 1;
12637 	open_confirm_args->seqid = *seqid;
12638 	open_confirm_args->open_stateid = *stateid;
12639 
12640 	mi = VTOMI4(vp);
12641 
12642 	rfs4call(mi, &args, &res, cr, &doqueue, 0, ep);
12643 
12644 	if (!ep->error && nfs4_need_to_bump_seqid(&res)) {
12645 		nfs4_set_open_seqid((*seqid), oop, args.ctag);
12646 	}
12647 
12648 	needrecov = nfs4_needs_recovery(ep, FALSE, mi->mi_vfsp);
12649 	if (!needrecov && ep->error)
12650 		return;
12651 
12652 	if (needrecov) {
12653 		bool_t abort = FALSE;
12654 
12655 		if (reopening_file == FALSE) {
12656 			nfs4_bseqid_entry_t *bsep = NULL;
12657 
12658 			if (!ep->error && res.status == NFS4ERR_BAD_SEQID)
12659 				bsep = nfs4_create_bseqid_entry(oop, NULL,
12660 				    vp, 0, args.ctag,
12661 				    open_confirm_args->seqid);
12662 
12663 			abort = nfs4_start_recovery(ep, VTOMI4(vp), vp,
12664 			    NULL, NULL, NULL, OP_OPEN_CONFIRM, bsep);
12665 			if (bsep) {
12666 				kmem_free(bsep, sizeof (*bsep));
12667 				if (num_bseqid_retryp &&
12668 				    --(*num_bseqid_retryp) == 0)
12669 					abort = TRUE;
12670 			}
12671 		}
12672 		if ((ep->error == ETIMEDOUT ||
12673 		    res.status == NFS4ERR_RESOURCE) &&
12674 		    abort == FALSE && resend == FALSE) {
12675 			if (!ep->error)
12676 				(void) xdr_free(xdr_COMPOUND4res_clnt,
12677 				    (caddr_t)&res);
12678 
12679 			delay(SEC_TO_TICK(confirm_retry_sec));
12680 			goto recov_retry_confirm;
12681 		}
12682 		/* State may have changed so retry the entire OPEN op */
12683 		if (abort == FALSE)
12684 			*retry_open = TRUE;
12685 		else
12686 			*retry_open = FALSE;
12687 		if (!ep->error)
12688 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12689 		return;
12690 	}
12691 
12692 	if (res.status) {
12693 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12694 		return;
12695 	}
12696 
12697 	resop = &res.array[1];  /* open confirm res */
12698 	bcopy(&resop->nfs_resop4_u.opopen_confirm.open_stateid,
12699 	    stateid, sizeof (*stateid));
12700 
12701 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12702 }
12703 
12704 /*
12705  * Return the credentials associated with a client state object.  The
12706  * caller is responsible for freeing the credentials.
12707  */
12708 
12709 static cred_t *
12710 state_to_cred(nfs4_open_stream_t *osp)
12711 {
12712 	cred_t *cr;
12713 
12714 	/*
12715 	 * It's ok to not lock the open stream and open owner to get
12716 	 * the oo_cred since this is only written once (upon creation)
12717 	 * and will not change.
12718 	 */
12719 	cr = osp->os_open_owner->oo_cred;
12720 	crhold(cr);
12721 
12722 	return (cr);
12723 }
12724 
12725 /*
12726  * nfs4_find_sysid
12727  *
12728  * Find the sysid for the knetconfig associated with the given mi.
12729  */
12730 static struct lm_sysid *
12731 nfs4_find_sysid(mntinfo4_t *mi)
12732 {
12733 	ASSERT(nfs_zone() == mi->mi_zone);
12734 
12735 	/*
12736 	 * Switch from RDMA knconf to original mount knconf
12737 	 */
12738 	return (lm_get_sysid(ORIG_KNCONF(mi), &mi->mi_curr_serv->sv_addr,
12739 	    mi->mi_curr_serv->sv_hostname, NULL));
12740 }
12741 
12742 #ifdef DEBUG
12743 /*
12744  * Return a string version of the call type for easy reading.
12745  */
12746 static char *
12747 nfs4frlock_get_call_type(nfs4_lock_call_type_t ctype)
12748 {
12749 	switch (ctype) {
12750 	case NFS4_LCK_CTYPE_NORM:
12751 		return ("NORMAL");
12752 	case NFS4_LCK_CTYPE_RECLAIM:
12753 		return ("RECLAIM");
12754 	case NFS4_LCK_CTYPE_RESEND:
12755 		return ("RESEND");
12756 	case NFS4_LCK_CTYPE_REINSTATE:
12757 		return ("REINSTATE");
12758 	default:
12759 		cmn_err(CE_PANIC, "nfs4frlock_get_call_type: got illegal "
12760 		    "type %d", ctype);
12761 		return ("");
12762 	}
12763 }
12764 #endif
12765 
12766 /*
12767  * Map the frlock cmd and lock type to the NFSv4 over-the-wire lock type
12768  * Unlock requests don't have an over-the-wire locktype, so we just return
12769  * something non-threatening.
12770  */
12771 
12772 static nfs_lock_type4
12773 flk_to_locktype(int cmd, int l_type)
12774 {
12775 	ASSERT(l_type == F_RDLCK || l_type == F_WRLCK || l_type == F_UNLCK);
12776 
12777 	switch (l_type) {
12778 	case F_UNLCK:
12779 		return (READ_LT);
12780 	case F_RDLCK:
12781 		if (cmd == F_SETLK)
12782 			return (READ_LT);
12783 		else
12784 			return (READW_LT);
12785 	case F_WRLCK:
12786 		if (cmd == F_SETLK)
12787 			return (WRITE_LT);
12788 		else
12789 			return (WRITEW_LT);
12790 	}
12791 	panic("flk_to_locktype");
12792 	/*NOTREACHED*/
12793 }
12794 
12795 /*
12796  * Do some preliminary checks for nfs4frlock.
12797  */
12798 static int
12799 nfs4frlock_validate_args(int cmd, flock64_t *flk, int flag, vnode_t *vp,
12800     u_offset_t offset)
12801 {
12802 	int error = 0;
12803 
12804 	/*
12805 	 * If we are setting a lock, check that the file is opened
12806 	 * with the correct mode.
12807 	 */
12808 	if (cmd == F_SETLK || cmd == F_SETLKW) {
12809 		if ((flk->l_type == F_RDLCK && (flag & FREAD) == 0) ||
12810 		    (flk->l_type == F_WRLCK && (flag & FWRITE) == 0)) {
12811 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12812 			    "nfs4frlock_validate_args: file was opened with "
12813 			    "incorrect mode"));
12814 			return (EBADF);
12815 		}
12816 	}
12817 
12818 	/* Convert the offset. It may need to be restored before returning. */
12819 	if (error = convoff(vp, flk, 0, offset)) {
12820 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12821 		    "nfs4frlock_validate_args: convoff  =>  error= %d\n",
12822 		    error));
12823 		return (error);
12824 	}
12825 
12826 	return (error);
12827 }
12828 
12829 /*
12830  * Set the flock64's lm_sysid for nfs4frlock.
12831  */
12832 static int
12833 nfs4frlock_get_sysid(struct lm_sysid **lspp, vnode_t *vp, flock64_t *flk)
12834 {
12835 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12836 
12837 	/* Find the lm_sysid */
12838 	*lspp = nfs4_find_sysid(VTOMI4(vp));
12839 
12840 	if (*lspp == NULL) {
12841 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12842 		    "nfs4frlock_get_sysid: no sysid, return ENOLCK"));
12843 		return (ENOLCK);
12844 	}
12845 
12846 	flk->l_sysid = lm_sysidt(*lspp);
12847 
12848 	return (0);
12849 }
12850 
12851 /*
12852  * Do the remaining preliminary setup for nfs4frlock.
12853  */
12854 static void
12855 nfs4frlock_pre_setup(clock_t *tick_delayp, nfs4_recov_state_t *recov_statep,
12856     flock64_t *flk, short *whencep, vnode_t *vp, cred_t *search_cr,
12857     cred_t **cred_otw)
12858 {
12859 	/*
12860 	 * set tick_delay to the base delay time.
12861 	 * (NFS4_BASE_WAIT_TIME is in secs)
12862 	 */
12863 
12864 	*tick_delayp = drv_usectohz(NFS4_BASE_WAIT_TIME * 1000 * 1000);
12865 
12866 	/*
12867 	 * If lock is relative to EOF, we need the newest length of the
12868 	 * file. Therefore invalidate the ATTR_CACHE.
12869 	 */
12870 
12871 	*whencep = flk->l_whence;
12872 
12873 	if (*whencep == 2)		/* SEEK_END */
12874 		PURGE_ATTRCACHE4(vp);
12875 
12876 	recov_statep->rs_flags = 0;
12877 	recov_statep->rs_num_retry_despite_err = 0;
12878 	*cred_otw = nfs4_get_otw_cred(search_cr, VTOMI4(vp), NULL);
12879 }
12880 
12881 /*
12882  * Initialize and allocate the data structures necessary for
12883  * the nfs4frlock call.
12884  * Allocates argsp's op array, frees up the saved_rqstpp if there is one.
12885  */
12886 static void
12887 nfs4frlock_call_init(COMPOUND4args_clnt *argsp, COMPOUND4args_clnt **argspp,
12888     nfs_argop4 **argopp, nfs4_op_hint_t *op_hintp, flock64_t *flk, int cmd,
12889     bool_t *retry, bool_t *did_start_fop, COMPOUND4res_clnt **respp,
12890     bool_t *skip_get_err, nfs4_lost_rqst_t *lost_rqstp)
12891 {
12892 	int		argoplist_size;
12893 	int		num_ops = 2;
12894 
12895 	*retry = FALSE;
12896 	*did_start_fop = FALSE;
12897 	*skip_get_err = FALSE;
12898 	lost_rqstp->lr_op = 0;
12899 	argoplist_size  = num_ops * sizeof (nfs_argop4);
12900 	/* fill array with zero */
12901 	*argopp = kmem_zalloc(argoplist_size, KM_SLEEP);
12902 
12903 	*argspp = argsp;
12904 	*respp = NULL;
12905 
12906 	argsp->array_len = num_ops;
12907 	argsp->array = *argopp;
12908 
12909 	/* initialize in case of error; will get real value down below */
12910 	argsp->ctag = TAG_NONE;
12911 
12912 	if ((cmd == F_SETLK || cmd == F_SETLKW) && flk->l_type == F_UNLCK)
12913 		*op_hintp = OH_LOCKU;
12914 	else
12915 		*op_hintp = OH_OTHER;
12916 }
12917 
12918 /*
12919  * Call the nfs4_start_fop() for nfs4frlock, if necessary.  Assign
12920  * the proper nfs4_server_t for this instance of nfs4frlock.
12921  * Returns 0 (success) or an errno value.
12922  */
12923 static int
12924 nfs4frlock_start_call(nfs4_lock_call_type_t ctype, vnode_t *vp,
12925     nfs4_op_hint_t op_hint, nfs4_recov_state_t *recov_statep,
12926     bool_t *did_start_fop, bool_t *startrecovp)
12927 {
12928 	int error = 0;
12929 	rnode4_t *rp;
12930 
12931 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12932 
12933 	if (ctype == NFS4_LCK_CTYPE_NORM) {
12934 		error = nfs4_start_fop(VTOMI4(vp), vp, NULL, op_hint,
12935 		    recov_statep, startrecovp);
12936 		if (error)
12937 			return (error);
12938 		*did_start_fop = TRUE;
12939 	} else {
12940 		*did_start_fop = FALSE;
12941 		*startrecovp = FALSE;
12942 	}
12943 
12944 	if (!error) {
12945 		rp = VTOR4(vp);
12946 
12947 		/* If the file failed recovery, just quit. */
12948 		mutex_enter(&rp->r_statelock);
12949 		if (rp->r_flags & R4RECOVERR) {
12950 			error = EIO;
12951 		}
12952 		mutex_exit(&rp->r_statelock);
12953 	}
12954 
12955 	return (error);
12956 }
12957 
12958 /*
12959  * Setup the LOCK4/LOCKU4 arguments for resending a lost lock request.  A
12960  * resend nfs4frlock call is initiated by the recovery framework.
12961  * Acquires the lop and oop seqid synchronization.
12962  */
12963 static void
12964 nfs4frlock_setup_resend_lock_args(nfs4_lost_rqst_t *resend_rqstp,
12965     COMPOUND4args_clnt *argsp, nfs_argop4 *argop, nfs4_lock_owner_t **lopp,
12966     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
12967     LOCK4args **lock_argsp, LOCKU4args **locku_argsp)
12968 {
12969 	mntinfo4_t *mi = VTOMI4(resend_rqstp->lr_vp);
12970 	int error;
12971 
12972 	NFS4_DEBUG((nfs4_lost_rqst_debug || nfs4_client_lock_debug),
12973 	    (CE_NOTE,
12974 	    "nfs4frlock_setup_resend_lock_args: have lost lock to resend"));
12975 	ASSERT(resend_rqstp != NULL);
12976 	ASSERT(resend_rqstp->lr_op == OP_LOCK ||
12977 	    resend_rqstp->lr_op == OP_LOCKU);
12978 
12979 	*oopp = resend_rqstp->lr_oop;
12980 	if (resend_rqstp->lr_oop) {
12981 		open_owner_hold(resend_rqstp->lr_oop);
12982 		error = nfs4_start_open_seqid_sync(resend_rqstp->lr_oop, mi);
12983 		ASSERT(error == 0);	/* recov thread always succeeds */
12984 	}
12985 
12986 	/* Must resend this lost lock/locku request. */
12987 	ASSERT(resend_rqstp->lr_lop != NULL);
12988 	*lopp = resend_rqstp->lr_lop;
12989 	lock_owner_hold(resend_rqstp->lr_lop);
12990 	error = nfs4_start_lock_seqid_sync(resend_rqstp->lr_lop, mi);
12991 	ASSERT(error == 0);	/* recov thread always succeeds */
12992 
12993 	*ospp = resend_rqstp->lr_osp;
12994 	if (*ospp)
12995 		open_stream_hold(resend_rqstp->lr_osp);
12996 
12997 	if (resend_rqstp->lr_op == OP_LOCK) {
12998 		LOCK4args *lock_args;
12999 
13000 		argop->argop = OP_LOCK;
13001 		*lock_argsp = lock_args = &argop->nfs_argop4_u.oplock;
13002 		lock_args->locktype = resend_rqstp->lr_locktype;
13003 		lock_args->reclaim =
13004 		    (resend_rqstp->lr_ctype == NFS4_LCK_CTYPE_RECLAIM);
13005 		lock_args->offset = resend_rqstp->lr_flk->l_start;
13006 		lock_args->length = resend_rqstp->lr_flk->l_len;
13007 		if (lock_args->length == 0)
13008 			lock_args->length = ~lock_args->length;
13009 		nfs4_setup_lock_args(*lopp, *oopp, *ospp,
13010 		    mi2clientid(mi), &lock_args->locker);
13011 
13012 		switch (resend_rqstp->lr_ctype) {
13013 		case NFS4_LCK_CTYPE_RESEND:
13014 			argsp->ctag = TAG_LOCK_RESEND;
13015 			break;
13016 		case NFS4_LCK_CTYPE_REINSTATE:
13017 			argsp->ctag = TAG_LOCK_REINSTATE;
13018 			break;
13019 		case NFS4_LCK_CTYPE_RECLAIM:
13020 			argsp->ctag = TAG_LOCK_RECLAIM;
13021 			break;
13022 		default:
13023 			argsp->ctag = TAG_LOCK_UNKNOWN;
13024 			break;
13025 		}
13026 	} else {
13027 		LOCKU4args *locku_args;
13028 		nfs4_lock_owner_t *lop = resend_rqstp->lr_lop;
13029 
13030 		argop->argop = OP_LOCKU;
13031 		*locku_argsp = locku_args = &argop->nfs_argop4_u.oplocku;
13032 		locku_args->locktype = READ_LT;
13033 		locku_args->seqid = lop->lock_seqid + 1;
13034 		mutex_enter(&lop->lo_lock);
13035 		locku_args->lock_stateid = lop->lock_stateid;
13036 		mutex_exit(&lop->lo_lock);
13037 		locku_args->offset = resend_rqstp->lr_flk->l_start;
13038 		locku_args->length = resend_rqstp->lr_flk->l_len;
13039 		if (locku_args->length == 0)
13040 			locku_args->length = ~locku_args->length;
13041 
13042 		switch (resend_rqstp->lr_ctype) {
13043 		case NFS4_LCK_CTYPE_RESEND:
13044 			argsp->ctag = TAG_LOCKU_RESEND;
13045 			break;
13046 		case NFS4_LCK_CTYPE_REINSTATE:
13047 			argsp->ctag = TAG_LOCKU_REINSTATE;
13048 			break;
13049 		default:
13050 			argsp->ctag = TAG_LOCK_UNKNOWN;
13051 			break;
13052 		}
13053 	}
13054 }
13055 
13056 /*
13057  * Setup the LOCKT4 arguments.
13058  */
13059 static void
13060 nfs4frlock_setup_lockt_args(nfs4_lock_call_type_t ctype, nfs_argop4 *argop,
13061     LOCKT4args **lockt_argsp, COMPOUND4args_clnt *argsp, flock64_t *flk,
13062     rnode4_t *rp)
13063 {
13064 	LOCKT4args *lockt_args;
13065 
13066 	ASSERT(nfs_zone() == VTOMI4(RTOV4(rp))->mi_zone);
13067 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13068 	argop->argop = OP_LOCKT;
13069 	argsp->ctag = TAG_LOCKT;
13070 	lockt_args = &argop->nfs_argop4_u.oplockt;
13071 
13072 	/*
13073 	 * The locktype will be READ_LT unless it's
13074 	 * a write lock. We do this because the Solaris
13075 	 * system call allows the combination of
13076 	 * F_UNLCK and F_GETLK* and so in that case the
13077 	 * unlock is mapped to a read.
13078 	 */
13079 	if (flk->l_type == F_WRLCK)
13080 		lockt_args->locktype = WRITE_LT;
13081 	else
13082 		lockt_args->locktype = READ_LT;
13083 
13084 	lockt_args->owner.clientid = mi2clientid(VTOMI4(RTOV4(rp)));
13085 	/* set the lock owner4 args */
13086 	nfs4_setlockowner_args(&lockt_args->owner, rp,
13087 	    ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pidp->pid_id :
13088 	    flk->l_pid);
13089 	lockt_args->offset = flk->l_start;
13090 	lockt_args->length = flk->l_len;
13091 	if (flk->l_len == 0)
13092 		lockt_args->length = ~lockt_args->length;
13093 
13094 	*lockt_argsp = lockt_args;
13095 }
13096 
13097 /*
13098  * If the client is holding a delegation, and the open stream to be used
13099  * with this lock request is a delegation open stream, then re-open the stream.
13100  * Sets the nfs4_error_t to all zeros unless the open stream has already
13101  * failed a reopen or we couldn't find the open stream.  NFS4ERR_DELAY
13102  * means the caller should retry (like a recovery retry).
13103  */
13104 static void
13105 nfs4frlock_check_deleg(vnode_t *vp, nfs4_error_t *ep, cred_t *cr, int lt)
13106 {
13107 	open_delegation_type4	dt;
13108 	bool_t			reopen_needed, force;
13109 	nfs4_open_stream_t	*osp;
13110 	open_claim_type4 	oclaim;
13111 	rnode4_t		*rp = VTOR4(vp);
13112 	mntinfo4_t		*mi = VTOMI4(vp);
13113 
13114 	ASSERT(nfs_zone() == mi->mi_zone);
13115 
13116 	nfs4_error_zinit(ep);
13117 
13118 	mutex_enter(&rp->r_statev4_lock);
13119 	dt = rp->r_deleg_type;
13120 	mutex_exit(&rp->r_statev4_lock);
13121 
13122 	if (dt != OPEN_DELEGATE_NONE) {
13123 		nfs4_open_owner_t	*oop;
13124 
13125 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
13126 		if (!oop) {
13127 			ep->stat = NFS4ERR_IO;
13128 			return;
13129 		}
13130 		/* returns with 'os_sync_lock' held */
13131 		osp = find_open_stream(oop, rp);
13132 		if (!osp) {
13133 			open_owner_rele(oop);
13134 			ep->stat = NFS4ERR_IO;
13135 			return;
13136 		}
13137 
13138 		if (osp->os_failed_reopen) {
13139 			NFS4_DEBUG((nfs4_open_stream_debug ||
13140 			    nfs4_client_lock_debug), (CE_NOTE,
13141 			    "nfs4frlock_check_deleg: os_failed_reopen set "
13142 			    "for osp %p, cr %p, rp %s", (void *)osp,
13143 			    (void *)cr, rnode4info(rp)));
13144 			mutex_exit(&osp->os_sync_lock);
13145 			open_stream_rele(osp, rp);
13146 			open_owner_rele(oop);
13147 			ep->stat = NFS4ERR_IO;
13148 			return;
13149 		}
13150 
13151 		/*
13152 		 * Determine whether a reopen is needed.  If this
13153 		 * is a delegation open stream, then send the open
13154 		 * to the server to give visibility to the open owner.
13155 		 * Even if it isn't a delegation open stream, we need
13156 		 * to check if the previous open CLAIM_DELEGATE_CUR
13157 		 * was sufficient.
13158 		 */
13159 
13160 		reopen_needed = osp->os_delegation ||
13161 		    ((lt == F_RDLCK &&
13162 		    !(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_READ)) ||
13163 		    (lt == F_WRLCK &&
13164 		    !(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_WRITE)));
13165 
13166 		mutex_exit(&osp->os_sync_lock);
13167 		open_owner_rele(oop);
13168 
13169 		if (reopen_needed) {
13170 			/*
13171 			 * Always use CLAIM_PREVIOUS after server reboot.
13172 			 * The server will reject CLAIM_DELEGATE_CUR if
13173 			 * it is used during the grace period.
13174 			 */
13175 			mutex_enter(&mi->mi_lock);
13176 			if (mi->mi_recovflags & MI4R_SRV_REBOOT) {
13177 				oclaim = CLAIM_PREVIOUS;
13178 				force = TRUE;
13179 			} else {
13180 				oclaim = CLAIM_DELEGATE_CUR;
13181 				force = FALSE;
13182 			}
13183 			mutex_exit(&mi->mi_lock);
13184 
13185 			nfs4_reopen(vp, osp, ep, oclaim, force, FALSE);
13186 			if (ep->error == EAGAIN) {
13187 				nfs4_error_zinit(ep);
13188 				ep->stat = NFS4ERR_DELAY;
13189 			}
13190 		}
13191 		open_stream_rele(osp, rp);
13192 		osp = NULL;
13193 	}
13194 }
13195 
13196 /*
13197  * Setup the LOCKU4 arguments.
13198  * Returns errors via the nfs4_error_t.
13199  * NFS4_OK		no problems.  *go_otwp is TRUE if call should go
13200  *			over-the-wire.  The caller must release the
13201  *			reference on *lopp.
13202  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13203  * (other)		unrecoverable error.
13204  */
13205 static void
13206 nfs4frlock_setup_locku_args(nfs4_lock_call_type_t ctype, nfs_argop4 *argop,
13207     LOCKU4args **locku_argsp, flock64_t *flk,
13208     nfs4_lock_owner_t **lopp, nfs4_error_t *ep, COMPOUND4args_clnt *argsp,
13209     vnode_t *vp, int flag, u_offset_t offset, cred_t *cr,
13210     bool_t *skip_get_err, bool_t *go_otwp)
13211 {
13212 	nfs4_lock_owner_t	*lop = NULL;
13213 	LOCKU4args		*locku_args;
13214 	pid_t			pid;
13215 	bool_t			is_spec = FALSE;
13216 	rnode4_t		*rp = VTOR4(vp);
13217 
13218 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13219 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13220 
13221 	nfs4frlock_check_deleg(vp, ep, cr, F_UNLCK);
13222 	if (ep->error || ep->stat)
13223 		return;
13224 
13225 	argop->argop = OP_LOCKU;
13226 	if (ctype == NFS4_LCK_CTYPE_REINSTATE)
13227 		argsp->ctag = TAG_LOCKU_REINSTATE;
13228 	else
13229 		argsp->ctag = TAG_LOCKU;
13230 	locku_args = &argop->nfs_argop4_u.oplocku;
13231 	*locku_argsp = locku_args;
13232 
13233 	/*
13234 	 * XXX what should locku_args->locktype be?
13235 	 * setting to ALWAYS be READ_LT so at least
13236 	 * it is a valid locktype.
13237 	 */
13238 
13239 	locku_args->locktype = READ_LT;
13240 
13241 	pid = ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pidp->pid_id :
13242 	    flk->l_pid;
13243 
13244 	/*
13245 	 * Get the lock owner stateid.  If no lock owner
13246 	 * exists, return success.
13247 	 */
13248 	lop = find_lock_owner(rp, pid, LOWN_ANY);
13249 	*lopp = lop;
13250 	if (lop && CLNT_ISSPECIAL(&lop->lock_stateid))
13251 		is_spec = TRUE;
13252 	if (!lop || is_spec) {
13253 		/*
13254 		 * No lock owner so no locks to unlock.
13255 		 * Return success.  If there was a failed
13256 		 * reclaim earlier, the lock might still be
13257 		 * registered with the local locking code,
13258 		 * so notify it of the unlock.
13259 		 *
13260 		 * If the lockowner is using a special stateid,
13261 		 * then the original lock request (that created
13262 		 * this lockowner) was never successful, so we
13263 		 * have no lock to undo OTW.
13264 		 */
13265 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13266 		    "nfs4frlock_setup_locku_args: LOCKU: no lock owner "
13267 		    "(%ld) so return success", (long)pid));
13268 
13269 		if (ctype == NFS4_LCK_CTYPE_NORM)
13270 			flk->l_pid = curproc->p_pid;
13271 		nfs4_register_lock_locally(vp, flk, flag, offset);
13272 		/*
13273 		 * Release our hold and NULL out so final_cleanup
13274 		 * doesn't try to end a lock seqid sync we
13275 		 * never started.
13276 		 */
13277 		if (is_spec) {
13278 			lock_owner_rele(lop);
13279 			*lopp = NULL;
13280 		}
13281 		*skip_get_err = TRUE;
13282 		*go_otwp = FALSE;
13283 		return;
13284 	}
13285 
13286 	ep->error = nfs4_start_lock_seqid_sync(lop, VTOMI4(vp));
13287 	if (ep->error == EAGAIN) {
13288 		lock_owner_rele(lop);
13289 		*lopp = NULL;
13290 		return;
13291 	}
13292 
13293 	mutex_enter(&lop->lo_lock);
13294 	locku_args->lock_stateid = lop->lock_stateid;
13295 	mutex_exit(&lop->lo_lock);
13296 	locku_args->seqid = lop->lock_seqid + 1;
13297 
13298 	/* leave the ref count on lop, rele after RPC call */
13299 
13300 	locku_args->offset = flk->l_start;
13301 	locku_args->length = flk->l_len;
13302 	if (flk->l_len == 0)
13303 		locku_args->length = ~locku_args->length;
13304 
13305 	*go_otwp = TRUE;
13306 }
13307 
13308 /*
13309  * Setup the LOCK4 arguments.
13310  *
13311  * Returns errors via the nfs4_error_t.
13312  * NFS4_OK		no problems
13313  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13314  * (other)		unrecoverable error
13315  */
13316 static void
13317 nfs4frlock_setup_lock_args(nfs4_lock_call_type_t ctype, LOCK4args **lock_argsp,
13318     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13319     nfs4_lock_owner_t **lopp, nfs_argop4 *argop, COMPOUND4args_clnt *argsp,
13320     flock64_t *flk, int cmd, vnode_t *vp, cred_t *cr, nfs4_error_t *ep)
13321 {
13322 	LOCK4args		*lock_args;
13323 	nfs4_open_owner_t	*oop = NULL;
13324 	nfs4_open_stream_t	*osp = NULL;
13325 	nfs4_lock_owner_t	*lop = NULL;
13326 	pid_t			pid;
13327 	rnode4_t		*rp = VTOR4(vp);
13328 
13329 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13330 
13331 	nfs4frlock_check_deleg(vp, ep, cr, flk->l_type);
13332 	if (ep->error || ep->stat != NFS4_OK)
13333 		return;
13334 
13335 	argop->argop = OP_LOCK;
13336 	if (ctype == NFS4_LCK_CTYPE_NORM)
13337 		argsp->ctag = TAG_LOCK;
13338 	else if (ctype == NFS4_LCK_CTYPE_RECLAIM)
13339 		argsp->ctag = TAG_RELOCK;
13340 	else
13341 		argsp->ctag = TAG_LOCK_REINSTATE;
13342 	lock_args = &argop->nfs_argop4_u.oplock;
13343 	lock_args->locktype = flk_to_locktype(cmd, flk->l_type);
13344 	lock_args->reclaim = ctype == NFS4_LCK_CTYPE_RECLAIM ? 1 : 0;
13345 	/*
13346 	 * Get the lock owner.  If no lock owner exists,
13347 	 * create a 'temporary' one and grab the open seqid
13348 	 * synchronization (which puts a hold on the open
13349 	 * owner and open stream).
13350 	 * This also grabs the lock seqid synchronization.
13351 	 */
13352 	pid = ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pid : flk->l_pid;
13353 	ep->stat =
13354 	    nfs4_find_or_create_lock_owner(pid, rp, cr, &oop, &osp, &lop);
13355 
13356 	if (ep->stat != NFS4_OK)
13357 		goto out;
13358 
13359 	nfs4_setup_lock_args(lop, oop, osp, mi2clientid(VTOMI4(vp)),
13360 	    &lock_args->locker);
13361 
13362 	lock_args->offset = flk->l_start;
13363 	lock_args->length = flk->l_len;
13364 	if (flk->l_len == 0)
13365 		lock_args->length = ~lock_args->length;
13366 	*lock_argsp = lock_args;
13367 out:
13368 	*oopp = oop;
13369 	*ospp = osp;
13370 	*lopp = lop;
13371 }
13372 
13373 /*
13374  * After we get the reply from the server, record the proper information
13375  * for possible resend lock requests.
13376  *
13377  * Allocates memory for the saved_rqstp if we have a lost lock to save.
13378  */
13379 static void
13380 nfs4frlock_save_lost_rqst(nfs4_lock_call_type_t ctype, int error,
13381     nfs_lock_type4 locktype, nfs4_open_owner_t *oop,
13382     nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop, flock64_t *flk,
13383     nfs4_lost_rqst_t *lost_rqstp, cred_t *cr, vnode_t *vp)
13384 {
13385 	bool_t unlock = (flk->l_type == F_UNLCK);
13386 
13387 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13388 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM ||
13389 	    ctype == NFS4_LCK_CTYPE_REINSTATE);
13390 
13391 	if (error != 0 && !unlock) {
13392 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13393 		    nfs4_client_lock_debug), (CE_NOTE,
13394 		    "nfs4frlock_save_lost_rqst: set lo_pending_rqsts to 1 "
13395 		    " for lop %p", (void *)lop));
13396 		ASSERT(lop != NULL);
13397 		mutex_enter(&lop->lo_lock);
13398 		lop->lo_pending_rqsts = 1;
13399 		mutex_exit(&lop->lo_lock);
13400 	}
13401 
13402 	lost_rqstp->lr_putfirst = FALSE;
13403 	lost_rqstp->lr_op = 0;
13404 
13405 	/*
13406 	 * For lock/locku requests, we treat EINTR as ETIMEDOUT for
13407 	 * recovery purposes so that the lock request that was sent
13408 	 * can be saved and re-issued later.  Ditto for EIO from a forced
13409 	 * unmount.  This is done to have the client's local locking state
13410 	 * match the v4 server's state; that is, the request was
13411 	 * potentially received and accepted by the server but the client
13412 	 * thinks it was not.
13413 	 */
13414 	if (error == ETIMEDOUT || error == EINTR ||
13415 	    NFS4_FRC_UNMT_ERR(error, vp->v_vfsp)) {
13416 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13417 		    nfs4_client_lock_debug), (CE_NOTE,
13418 		    "nfs4frlock_save_lost_rqst: got a lost %s lock for "
13419 		    "lop %p oop %p osp %p", unlock ? "LOCKU" : "LOCK",
13420 		    (void *)lop, (void *)oop, (void *)osp));
13421 		if (unlock)
13422 			lost_rqstp->lr_op = OP_LOCKU;
13423 		else {
13424 			lost_rqstp->lr_op = OP_LOCK;
13425 			lost_rqstp->lr_locktype = locktype;
13426 		}
13427 		/*
13428 		 * Objects are held and rele'd via the recovery code.
13429 		 * See nfs4_save_lost_rqst.
13430 		 */
13431 		lost_rqstp->lr_vp = vp;
13432 		lost_rqstp->lr_dvp = NULL;
13433 		lost_rqstp->lr_oop = oop;
13434 		lost_rqstp->lr_osp = osp;
13435 		lost_rqstp->lr_lop = lop;
13436 		lost_rqstp->lr_cr = cr;
13437 		switch (ctype) {
13438 		case NFS4_LCK_CTYPE_NORM:
13439 			flk->l_pid = ttoproc(curthread)->p_pid;
13440 			lost_rqstp->lr_ctype = NFS4_LCK_CTYPE_RESEND;
13441 			break;
13442 		case NFS4_LCK_CTYPE_REINSTATE:
13443 			lost_rqstp->lr_putfirst = TRUE;
13444 			lost_rqstp->lr_ctype = ctype;
13445 			break;
13446 		default:
13447 			break;
13448 		}
13449 		lost_rqstp->lr_flk = flk;
13450 	}
13451 }
13452 
13453 /*
13454  * Update lop's seqid.  Also update the seqid stored in a resend request,
13455  * if any.  (Some recovery errors increment the seqid, and we may have to
13456  * send the resend request again.)
13457  */
13458 
13459 static void
13460 nfs4frlock_bump_seqid(LOCK4args *lock_args, LOCKU4args *locku_args,
13461     nfs4_open_owner_t *oop, nfs4_lock_owner_t *lop, nfs4_tag_type_t tag_type)
13462 {
13463 	if (lock_args) {
13464 		if (lock_args->locker.new_lock_owner == TRUE)
13465 			nfs4_get_and_set_next_open_seqid(oop, tag_type);
13466 		else {
13467 			ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13468 			nfs4_set_lock_seqid(lop->lock_seqid + 1, lop);
13469 		}
13470 	} else if (locku_args) {
13471 		ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13472 		nfs4_set_lock_seqid(lop->lock_seqid +1, lop);
13473 	}
13474 }
13475 
13476 /*
13477  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13478  * COMPOUND4 args/res for calls that need to retry.
13479  * Switches the *cred_otwp to base_cr.
13480  */
13481 static void
13482 nfs4frlock_check_access(vnode_t *vp, nfs4_op_hint_t op_hint,
13483     nfs4_recov_state_t *recov_statep, int needrecov, bool_t *did_start_fop,
13484     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp, int error,
13485     nfs4_lock_owner_t **lopp, nfs4_open_owner_t **oopp,
13486     nfs4_open_stream_t **ospp, cred_t *base_cr, cred_t **cred_otwp)
13487 {
13488 	nfs4_open_owner_t	*oop = *oopp;
13489 	nfs4_open_stream_t	*osp = *ospp;
13490 	nfs4_lock_owner_t	*lop = *lopp;
13491 	nfs_argop4		*argop = (*argspp)->array;
13492 
13493 	if (*did_start_fop) {
13494 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13495 		    needrecov);
13496 		*did_start_fop = FALSE;
13497 	}
13498 	ASSERT((*argspp)->array_len == 2);
13499 	if (argop[1].argop == OP_LOCK)
13500 		nfs4args_lock_free(&argop[1]);
13501 	else if (argop[1].argop == OP_LOCKT)
13502 		nfs4args_lockt_free(&argop[1]);
13503 	kmem_free(argop, 2 * sizeof (nfs_argop4));
13504 	if (!error)
13505 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13506 	*argspp = NULL;
13507 	*respp = NULL;
13508 
13509 	if (lop) {
13510 		nfs4_end_lock_seqid_sync(lop);
13511 		lock_owner_rele(lop);
13512 		*lopp = NULL;
13513 	}
13514 
13515 	/* need to free up the reference on osp for lock args */
13516 	if (osp != NULL) {
13517 		open_stream_rele(osp, VTOR4(vp));
13518 		*ospp = NULL;
13519 	}
13520 
13521 	/* need to free up the reference on oop for lock args */
13522 	if (oop != NULL) {
13523 		nfs4_end_open_seqid_sync(oop);
13524 		open_owner_rele(oop);
13525 		*oopp = NULL;
13526 	}
13527 
13528 	crfree(*cred_otwp);
13529 	*cred_otwp = base_cr;
13530 	crhold(*cred_otwp);
13531 }
13532 
13533 /*
13534  * Function to process the client's recovery for nfs4frlock.
13535  * Returns TRUE if we should retry the lock request; FALSE otherwise.
13536  *
13537  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13538  * COMPOUND4 args/res for calls that need to retry.
13539  *
13540  * Note: the rp's r_lkserlock is *not* dropped during this path.
13541  */
13542 static bool_t
13543 nfs4frlock_recovery(int needrecov, nfs4_error_t *ep,
13544     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13545     LOCK4args *lock_args, LOCKU4args *locku_args,
13546     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13547     nfs4_lock_owner_t **lopp, rnode4_t *rp, vnode_t *vp,
13548     nfs4_recov_state_t *recov_statep, nfs4_op_hint_t op_hint,
13549     bool_t *did_start_fop, nfs4_lost_rqst_t *lost_rqstp, flock64_t *flk)
13550 {
13551 	nfs4_open_owner_t	*oop = *oopp;
13552 	nfs4_open_stream_t	*osp = *ospp;
13553 	nfs4_lock_owner_t	*lop = *lopp;
13554 
13555 	bool_t abort, retry;
13556 
13557 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13558 	ASSERT((*argspp) != NULL);
13559 	ASSERT((*respp) != NULL);
13560 	if (lock_args || locku_args)
13561 		ASSERT(lop != NULL);
13562 
13563 	NFS4_DEBUG((nfs4_client_lock_debug || nfs4_client_recov_debug),
13564 	    (CE_NOTE, "nfs4frlock_recovery: initiating recovery\n"));
13565 
13566 	retry = TRUE;
13567 	abort = FALSE;
13568 	if (needrecov) {
13569 		nfs4_bseqid_entry_t *bsep = NULL;
13570 		nfs_opnum4 op;
13571 
13572 		op = lock_args ? OP_LOCK : locku_args ? OP_LOCKU : OP_LOCKT;
13573 
13574 		if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID) {
13575 			seqid4 seqid;
13576 
13577 			if (lock_args) {
13578 				if (lock_args->locker.new_lock_owner == TRUE)
13579 					seqid = lock_args->locker.locker4_u.
13580 					    open_owner.open_seqid;
13581 				else
13582 					seqid = lock_args->locker.locker4_u.
13583 					    lock_owner.lock_seqid;
13584 			} else if (locku_args) {
13585 				seqid = locku_args->seqid;
13586 			} else {
13587 				seqid = 0;
13588 			}
13589 
13590 			bsep = nfs4_create_bseqid_entry(oop, lop, vp,
13591 			    flk->l_pid, (*argspp)->ctag, seqid);
13592 		}
13593 
13594 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL, NULL,
13595 		    (lost_rqstp && (lost_rqstp->lr_op == OP_LOCK ||
13596 		    lost_rqstp->lr_op == OP_LOCKU)) ? lost_rqstp :
13597 		    NULL, op, bsep);
13598 
13599 		if (bsep)
13600 			kmem_free(bsep, sizeof (*bsep));
13601 	}
13602 
13603 	/*
13604 	 * Return that we do not want to retry the request for 3 cases:
13605 	 * 1. If we received EINTR or are bailing out because of a forced
13606 	 *    unmount, we came into this code path just for the sake of
13607 	 *    initiating recovery, we now need to return the error.
13608 	 * 2. If we have aborted recovery.
13609 	 * 3. We received NFS4ERR_BAD_SEQID.
13610 	 */
13611 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp) ||
13612 	    abort == TRUE || (ep->error == 0 && ep->stat == NFS4ERR_BAD_SEQID))
13613 		retry = FALSE;
13614 
13615 	if (*did_start_fop == TRUE) {
13616 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13617 		    needrecov);
13618 		*did_start_fop = FALSE;
13619 	}
13620 
13621 	if (retry == TRUE) {
13622 		nfs_argop4	*argop;
13623 
13624 		argop = (*argspp)->array;
13625 		ASSERT((*argspp)->array_len == 2);
13626 
13627 		if (argop[1].argop == OP_LOCK)
13628 			nfs4args_lock_free(&argop[1]);
13629 		else if (argop[1].argop == OP_LOCKT)
13630 			nfs4args_lockt_free(&argop[1]);
13631 		kmem_free(argop, 2 * sizeof (nfs_argop4));
13632 		if (!ep->error)
13633 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13634 		*respp = NULL;
13635 		*argspp = NULL;
13636 	}
13637 
13638 	if (lop != NULL) {
13639 		nfs4_end_lock_seqid_sync(lop);
13640 		lock_owner_rele(lop);
13641 	}
13642 
13643 	*lopp = NULL;
13644 
13645 	/* need to free up the reference on osp for lock args */
13646 	if (osp != NULL) {
13647 		open_stream_rele(osp, rp);
13648 		*ospp = NULL;
13649 	}
13650 
13651 	/* need to free up the reference on oop for lock args */
13652 	if (oop != NULL) {
13653 		nfs4_end_open_seqid_sync(oop);
13654 		open_owner_rele(oop);
13655 		*oopp = NULL;
13656 	}
13657 
13658 	return (retry);
13659 }
13660 
13661 /*
13662  * Handles the successful reply from the server for nfs4frlock.
13663  */
13664 static void
13665 nfs4frlock_results_ok(nfs4_lock_call_type_t ctype, int cmd, flock64_t *flk,
13666     vnode_t *vp, int flag, u_offset_t offset,
13667     nfs4_lost_rqst_t *resend_rqstp)
13668 {
13669 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13670 	if ((cmd == F_SETLK || cmd == F_SETLKW) &&
13671 	    (flk->l_type == F_RDLCK || flk->l_type == F_WRLCK)) {
13672 		if (ctype == NFS4_LCK_CTYPE_NORM) {
13673 			flk->l_pid = ttoproc(curthread)->p_pid;
13674 			/*
13675 			 * We do not register lost locks locally in
13676 			 * the 'resend' case since the user/application
13677 			 * doesn't think we have the lock.
13678 			 */
13679 			ASSERT(!resend_rqstp);
13680 			nfs4_register_lock_locally(vp, flk, flag, offset);
13681 		}
13682 	}
13683 }
13684 
13685 /*
13686  * Handle the DENIED reply from the server for nfs4frlock.
13687  * Returns TRUE if we should retry the request; FALSE otherwise.
13688  *
13689  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13690  * COMPOUND4 args/res for calls that need to retry.  Can also
13691  * drop and regrab the r_lkserlock.
13692  */
13693 static bool_t
13694 nfs4frlock_results_denied(nfs4_lock_call_type_t ctype, LOCK4args *lock_args,
13695     LOCKT4args *lockt_args, nfs4_open_owner_t **oopp,
13696     nfs4_open_stream_t **ospp, nfs4_lock_owner_t **lopp, int cmd,
13697     vnode_t *vp, flock64_t *flk, nfs4_op_hint_t op_hint,
13698     nfs4_recov_state_t *recov_statep, int needrecov,
13699     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13700     clock_t *tick_delayp, short *whencep, int *errorp,
13701     nfs_resop4 *resop, cred_t *cr, bool_t *did_start_fop,
13702     bool_t *skip_get_err)
13703 {
13704 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13705 
13706 	if (lock_args) {
13707 		nfs4_open_owner_t	*oop = *oopp;
13708 		nfs4_open_stream_t	*osp = *ospp;
13709 		nfs4_lock_owner_t	*lop = *lopp;
13710 		int			intr;
13711 
13712 		/*
13713 		 * Blocking lock needs to sleep and retry from the request.
13714 		 *
13715 		 * Do not block and wait for 'resend' or 'reinstate'
13716 		 * lock requests, just return the error.
13717 		 *
13718 		 * Note: reclaim requests have cmd == F_SETLK, not F_SETLKW.
13719 		 */
13720 		if (cmd == F_SETLKW) {
13721 			rnode4_t *rp = VTOR4(vp);
13722 			nfs_argop4 *argop = (*argspp)->array;
13723 
13724 			ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13725 
13726 			nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
13727 			    recov_statep, needrecov);
13728 			*did_start_fop = FALSE;
13729 			ASSERT((*argspp)->array_len == 2);
13730 			if (argop[1].argop == OP_LOCK)
13731 				nfs4args_lock_free(&argop[1]);
13732 			else if (argop[1].argop == OP_LOCKT)
13733 				nfs4args_lockt_free(&argop[1]);
13734 			kmem_free(argop, 2 * sizeof (nfs_argop4));
13735 			if (*respp)
13736 				(void) xdr_free(xdr_COMPOUND4res_clnt,
13737 				    (caddr_t)*respp);
13738 			*argspp = NULL;
13739 			*respp = NULL;
13740 			nfs4_end_lock_seqid_sync(lop);
13741 			lock_owner_rele(lop);
13742 			*lopp = NULL;
13743 			if (osp != NULL) {
13744 				open_stream_rele(osp, rp);
13745 				*ospp = NULL;
13746 			}
13747 			if (oop != NULL) {
13748 				nfs4_end_open_seqid_sync(oop);
13749 				open_owner_rele(oop);
13750 				*oopp = NULL;
13751 			}
13752 
13753 			nfs_rw_exit(&rp->r_lkserlock);
13754 
13755 			intr = nfs4_block_and_wait(tick_delayp, rp);
13756 
13757 			if (intr) {
13758 				(void) nfs_rw_enter_sig(&rp->r_lkserlock,
13759 				    RW_WRITER, FALSE);
13760 				*errorp = EINTR;
13761 				return (FALSE);
13762 			}
13763 
13764 			(void) nfs_rw_enter_sig(&rp->r_lkserlock,
13765 			    RW_WRITER, FALSE);
13766 
13767 			/*
13768 			 * Make sure we are still safe to lock with
13769 			 * regards to mmapping.
13770 			 */
13771 			if (!nfs4_safelock(vp, flk, cr)) {
13772 				*errorp = EAGAIN;
13773 				return (FALSE);
13774 			}
13775 
13776 			return (TRUE);
13777 		}
13778 		if (ctype == NFS4_LCK_CTYPE_NORM)
13779 			*errorp = EAGAIN;
13780 		*skip_get_err = TRUE;
13781 		flk->l_whence = 0;
13782 		*whencep = 0;
13783 		return (FALSE);
13784 	} else if (lockt_args) {
13785 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13786 		    "nfs4frlock_results_denied: OP_LOCKT DENIED"));
13787 
13788 		denied_to_flk(&resop->nfs_resop4_u.oplockt.denied,
13789 		    flk, lockt_args);
13790 
13791 		/* according to NLM code */
13792 		*errorp = 0;
13793 		*whencep = 0;
13794 		*skip_get_err = TRUE;
13795 		return (FALSE);
13796 	}
13797 	return (FALSE);
13798 }
13799 
13800 /*
13801  * Handles all NFS4 errors besides NFS4_OK and NFS4ERR_DENIED for nfs4frlock.
13802  */
13803 static void
13804 nfs4frlock_results_default(COMPOUND4res_clnt *resp, int *errorp)
13805 {
13806 	switch (resp->status) {
13807 	case NFS4ERR_ACCESS:
13808 	case NFS4ERR_ADMIN_REVOKED:
13809 	case NFS4ERR_BADHANDLE:
13810 	case NFS4ERR_BAD_RANGE:
13811 	case NFS4ERR_BAD_SEQID:
13812 	case NFS4ERR_BAD_STATEID:
13813 	case NFS4ERR_BADXDR:
13814 	case NFS4ERR_DEADLOCK:
13815 	case NFS4ERR_DELAY:
13816 	case NFS4ERR_EXPIRED:
13817 	case NFS4ERR_FHEXPIRED:
13818 	case NFS4ERR_GRACE:
13819 	case NFS4ERR_INVAL:
13820 	case NFS4ERR_ISDIR:
13821 	case NFS4ERR_LEASE_MOVED:
13822 	case NFS4ERR_LOCK_NOTSUPP:
13823 	case NFS4ERR_LOCK_RANGE:
13824 	case NFS4ERR_MOVED:
13825 	case NFS4ERR_NOFILEHANDLE:
13826 	case NFS4ERR_NO_GRACE:
13827 	case NFS4ERR_OLD_STATEID:
13828 	case NFS4ERR_OPENMODE:
13829 	case NFS4ERR_RECLAIM_BAD:
13830 	case NFS4ERR_RECLAIM_CONFLICT:
13831 	case NFS4ERR_RESOURCE:
13832 	case NFS4ERR_SERVERFAULT:
13833 	case NFS4ERR_STALE:
13834 	case NFS4ERR_STALE_CLIENTID:
13835 	case NFS4ERR_STALE_STATEID:
13836 		return;
13837 	default:
13838 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13839 		    "nfs4frlock_results_default: got unrecognizable "
13840 		    "res.status %d", resp->status));
13841 		*errorp = NFS4ERR_INVAL;
13842 	}
13843 }
13844 
13845 /*
13846  * The lock request was successful, so update the client's state.
13847  */
13848 static void
13849 nfs4frlock_update_state(LOCK4args *lock_args, LOCKU4args *locku_args,
13850     LOCKT4args *lockt_args, nfs_resop4 *resop, nfs4_lock_owner_t *lop,
13851     vnode_t *vp, flock64_t *flk, cred_t *cr,
13852     nfs4_lost_rqst_t *resend_rqstp)
13853 {
13854 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13855 
13856 	if (lock_args) {
13857 		LOCK4res *lock_res;
13858 
13859 		lock_res = &resop->nfs_resop4_u.oplock;
13860 		/* update the stateid with server's response */
13861 
13862 		if (lock_args->locker.new_lock_owner == TRUE) {
13863 			mutex_enter(&lop->lo_lock);
13864 			lop->lo_just_created = NFS4_PERM_CREATED;
13865 			mutex_exit(&lop->lo_lock);
13866 		}
13867 
13868 		nfs4_set_lock_stateid(lop, lock_res->LOCK4res_u.lock_stateid);
13869 
13870 		/*
13871 		 * If the lock was the result of a resending a lost
13872 		 * request, we've synched up the stateid and seqid
13873 		 * with the server, but now the server might be out of sync
13874 		 * with what the application thinks it has for locks.
13875 		 * Clean that up here.  It's unclear whether we should do
13876 		 * this even if the filesystem has been forcibly unmounted.
13877 		 * For most servers, it's probably wasted effort, but
13878 		 * RFC3530 lets servers require that unlocks exactly match
13879 		 * the locks that are held.
13880 		 */
13881 		if (resend_rqstp != NULL &&
13882 		    resend_rqstp->lr_ctype != NFS4_LCK_CTYPE_REINSTATE) {
13883 			nfs4_reinstitute_local_lock_state(vp, flk, cr, lop);
13884 		} else {
13885 			flk->l_whence = 0;
13886 		}
13887 	} else if (locku_args) {
13888 		LOCKU4res *locku_res;
13889 
13890 		locku_res = &resop->nfs_resop4_u.oplocku;
13891 
13892 		/* Update the stateid with the server's response */
13893 		nfs4_set_lock_stateid(lop, locku_res->lock_stateid);
13894 	} else if (lockt_args) {
13895 		/* Switch the lock type to express success, see fcntl */
13896 		flk->l_type = F_UNLCK;
13897 		flk->l_whence = 0;
13898 	}
13899 }
13900 
13901 /*
13902  * Do final cleanup before exiting nfs4frlock.
13903  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13904  * COMPOUND4 args/res for calls that haven't already.
13905  */
13906 static void
13907 nfs4frlock_final_cleanup(nfs4_lock_call_type_t ctype, COMPOUND4args_clnt *argsp,
13908     COMPOUND4res_clnt *resp, vnode_t *vp, nfs4_op_hint_t op_hint,
13909     nfs4_recov_state_t *recov_statep, int needrecov, nfs4_open_owner_t *oop,
13910     nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop, flock64_t *flk,
13911     short whence, u_offset_t offset, struct lm_sysid *ls,
13912     int *errorp, LOCK4args *lock_args, LOCKU4args *locku_args,
13913     bool_t did_start_fop, bool_t skip_get_err,
13914     cred_t *cred_otw, cred_t *cred)
13915 {
13916 	mntinfo4_t	*mi = VTOMI4(vp);
13917 	rnode4_t	*rp = VTOR4(vp);
13918 	int		error = *errorp;
13919 	nfs_argop4	*argop;
13920 
13921 	ASSERT(nfs_zone() == mi->mi_zone);
13922 	/*
13923 	 * The client recovery code wants the raw status information,
13924 	 * so don't map the NFS status code to an errno value for
13925 	 * non-normal call types.
13926 	 */
13927 	if (ctype == NFS4_LCK_CTYPE_NORM) {
13928 		if (*errorp == 0 && resp != NULL && skip_get_err == FALSE)
13929 			*errorp = geterrno4(resp->status);
13930 		if (did_start_fop == TRUE)
13931 			nfs4_end_fop(mi, vp, NULL, op_hint, recov_statep,
13932 			    needrecov);
13933 
13934 		/*
13935 		 * We've established a new lock on the server, so invalidate
13936 		 * the pages associated with the vnode to get the most up to
13937 		 * date pages from the server after acquiring the lock. We
13938 		 * want to be sure that the read operation gets the newest data.
13939 		 * N.B.
13940 		 * We used to do this in nfs4frlock_results_ok but that doesn't
13941 		 * work since VOP_PUTPAGE can call nfs4_commit which calls
13942 		 * nfs4_start_fop. We flush the pages below after calling
13943 		 * nfs4_end_fop above
13944 		 */
13945 		if (!error && resp && resp->status == NFS4_OK) {
13946 			int error;
13947 
13948 			error = VOP_PUTPAGE(vp, (u_offset_t)0,
13949 			    0, B_INVAL, cred, NULL);
13950 
13951 			if (error && (error == ENOSPC || error == EDQUOT)) {
13952 				rnode4_t *rp = VTOR4(vp);
13953 
13954 				mutex_enter(&rp->r_statelock);
13955 				if (!rp->r_error)
13956 					rp->r_error = error;
13957 				mutex_exit(&rp->r_statelock);
13958 			}
13959 		}
13960 	}
13961 	if (argsp) {
13962 		ASSERT(argsp->array_len == 2);
13963 		argop = argsp->array;
13964 		if (argop[1].argop == OP_LOCK)
13965 			nfs4args_lock_free(&argop[1]);
13966 		else if (argop[1].argop == OP_LOCKT)
13967 			nfs4args_lockt_free(&argop[1]);
13968 		kmem_free(argop, 2 * sizeof (nfs_argop4));
13969 		if (resp)
13970 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
13971 	}
13972 
13973 	/* free the reference on the lock owner */
13974 	if (lop != NULL) {
13975 		nfs4_end_lock_seqid_sync(lop);
13976 		lock_owner_rele(lop);
13977 	}
13978 
13979 	/* need to free up the reference on osp for lock args */
13980 	if (osp != NULL)
13981 		open_stream_rele(osp, rp);
13982 
13983 	/* need to free up the reference on oop for lock args */
13984 	if (oop != NULL) {
13985 		nfs4_end_open_seqid_sync(oop);
13986 		open_owner_rele(oop);
13987 	}
13988 
13989 	(void) convoff(vp, flk, whence, offset);
13990 
13991 	lm_rel_sysid(ls);
13992 
13993 	/*
13994 	 * Record debug information in the event we get EINVAL.
13995 	 */
13996 	mutex_enter(&mi->mi_lock);
13997 	if (*errorp == EINVAL && (lock_args || locku_args) &&
13998 	    (!(mi->mi_flags & MI4_POSIX_LOCK))) {
13999 		if (!(mi->mi_flags & MI4_LOCK_DEBUG)) {
14000 			zcmn_err(getzoneid(), CE_NOTE,
14001 			    "%s operation failed with "
14002 			    "EINVAL probably since the server, %s,"
14003 			    " doesn't support POSIX style locking",
14004 			    lock_args ? "LOCK" : "LOCKU",
14005 			    mi->mi_curr_serv->sv_hostname);
14006 			mi->mi_flags |= MI4_LOCK_DEBUG;
14007 		}
14008 	}
14009 	mutex_exit(&mi->mi_lock);
14010 
14011 	if (cred_otw)
14012 		crfree(cred_otw);
14013 }
14014 
14015 /*
14016  * This calls the server and the local locking code.
14017  *
14018  * Client locks are registerred locally by oring the sysid with
14019  * LM_SYSID_CLIENT. The server registers locks locally using just the sysid.
14020  * We need to distinguish between the two to avoid collision in case one
14021  * machine is used as both client and server.
14022  *
14023  * Blocking lock requests will continually retry to acquire the lock
14024  * forever.
14025  *
14026  * The ctype is defined as follows:
14027  * NFS4_LCK_CTYPE_NORM: normal lock request.
14028  *
14029  * NFS4_LCK_CTYPE_RECLAIM:  bypass the usual calls for synchronizing with client
14030  * recovery, get the pid from flk instead of curproc, and don't reregister
14031  * the lock locally.
14032  *
14033  * NFS4_LCK_CTYPE_RESEND: same as NFS4_LCK_CTYPE_RECLAIM, with the addition
14034  * that we will use the information passed in via resend_rqstp to setup the
14035  * lock/locku request.  This resend is the exact same request as the 'lost
14036  * lock', and is initiated by the recovery framework. A successful resend
14037  * request can initiate one or more reinstate requests.
14038  *
14039  * NFS4_LCK_CTYPE_REINSTATE: same as NFS4_LCK_CTYPE_RESEND, except that it
14040  * does not trigger additional reinstate requests.  This lock call type is
14041  * set for setting the v4 server's locking state back to match what the
14042  * client's local locking state is in the event of a received 'lost lock'.
14043  *
14044  * Errors are returned via the nfs4_error_t parameter.
14045  */
14046 void
14047 nfs4frlock(nfs4_lock_call_type_t ctype, vnode_t *vp, int cmd, flock64_t *flk,
14048     int flag, u_offset_t offset, cred_t *cr, nfs4_error_t *ep,
14049     nfs4_lost_rqst_t *resend_rqstp, int *did_reclaimp)
14050 {
14051 	COMPOUND4args_clnt	args, *argsp = NULL;
14052 	COMPOUND4res_clnt	res, *resp = NULL;
14053 	nfs_argop4	*argop;
14054 	nfs_resop4	*resop;
14055 	rnode4_t	*rp;
14056 	int		doqueue = 1;
14057 	clock_t		tick_delay;  /* delay in clock ticks */
14058 	struct lm_sysid	*ls;
14059 	LOCK4args	*lock_args = NULL;
14060 	LOCKU4args	*locku_args = NULL;
14061 	LOCKT4args	*lockt_args = NULL;
14062 	nfs4_open_owner_t *oop = NULL;
14063 	nfs4_open_stream_t *osp = NULL;
14064 	nfs4_lock_owner_t *lop = NULL;
14065 	bool_t		needrecov = FALSE;
14066 	nfs4_recov_state_t recov_state;
14067 	short		whence;
14068 	nfs4_op_hint_t	op_hint;
14069 	nfs4_lost_rqst_t lost_rqst;
14070 	bool_t		retry = FALSE;
14071 	bool_t		did_start_fop = FALSE;
14072 	bool_t		skip_get_err = FALSE;
14073 	cred_t		*cred_otw = NULL;
14074 	bool_t		recovonly;	/* just queue request */
14075 	int		frc_no_reclaim = 0;
14076 #ifdef DEBUG
14077 	char *name;
14078 #endif
14079 
14080 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14081 
14082 #ifdef DEBUG
14083 	name = fn_name(VTOSV(vp)->sv_name);
14084 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4frlock: "
14085 	    "%s: cmd %d, type %d, offset %llu, start %"PRIx64", "
14086 	    "length %"PRIu64", pid %d, sysid %d, call type %s, "
14087 	    "resend request %s", name, cmd, flk->l_type, offset, flk->l_start,
14088 	    flk->l_len, ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pid :
14089 	    flk->l_pid, flk->l_sysid, nfs4frlock_get_call_type(ctype),
14090 	    resend_rqstp ? "TRUE" : "FALSE"));
14091 	kmem_free(name, MAXNAMELEN);
14092 #endif
14093 
14094 	nfs4_error_zinit(ep);
14095 	ep->error = nfs4frlock_validate_args(cmd, flk, flag, vp, offset);
14096 	if (ep->error)
14097 		return;
14098 	ep->error = nfs4frlock_get_sysid(&ls, vp, flk);
14099 	if (ep->error)
14100 		return;
14101 	nfs4frlock_pre_setup(&tick_delay, &recov_state, flk, &whence,
14102 	    vp, cr, &cred_otw);
14103 
14104 recov_retry:
14105 	nfs4frlock_call_init(&args, &argsp, &argop, &op_hint, flk, cmd,
14106 	    &retry, &did_start_fop, &resp, &skip_get_err, &lost_rqst);
14107 	rp = VTOR4(vp);
14108 
14109 	ep->error = nfs4frlock_start_call(ctype, vp, op_hint, &recov_state,
14110 	    &did_start_fop, &recovonly);
14111 
14112 	if (ep->error)
14113 		goto out;
14114 
14115 	if (recovonly) {
14116 		/*
14117 		 * Leave the request for the recovery system to deal with.
14118 		 */
14119 		ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
14120 		ASSERT(cmd != F_GETLK);
14121 		ASSERT(flk->l_type == F_UNLCK);
14122 
14123 		nfs4_error_init(ep, EINTR);
14124 		needrecov = TRUE;
14125 		lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14126 		if (lop != NULL) {
14127 			nfs4frlock_save_lost_rqst(ctype, ep->error, READ_LT,
14128 			    NULL, NULL, lop, flk, &lost_rqst, cr, vp);
14129 			(void) nfs4_start_recovery(ep,
14130 			    VTOMI4(vp), vp, NULL, NULL,
14131 			    (lost_rqst.lr_op == OP_LOCK ||
14132 			    lost_rqst.lr_op == OP_LOCKU) ?
14133 			    &lost_rqst : NULL, OP_LOCKU, NULL);
14134 			lock_owner_rele(lop);
14135 			lop = NULL;
14136 		}
14137 		flk->l_pid = curproc->p_pid;
14138 		nfs4_register_lock_locally(vp, flk, flag, offset);
14139 		goto out;
14140 	}
14141 
14142 	/* putfh directory fh */
14143 	argop[0].argop = OP_CPUTFH;
14144 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
14145 
14146 	/*
14147 	 * Set up the over-the-wire arguments and get references to the
14148 	 * open owner, etc.
14149 	 */
14150 
14151 	if (ctype == NFS4_LCK_CTYPE_RESEND ||
14152 	    ctype == NFS4_LCK_CTYPE_REINSTATE) {
14153 		nfs4frlock_setup_resend_lock_args(resend_rqstp, argsp,
14154 		    &argop[1], &lop, &oop, &osp, &lock_args, &locku_args);
14155 	} else {
14156 		bool_t go_otw = TRUE;
14157 
14158 		ASSERT(resend_rqstp == NULL);
14159 
14160 		switch (cmd) {
14161 		case F_GETLK:
14162 		case F_O_GETLK:
14163 			nfs4frlock_setup_lockt_args(ctype, &argop[1],
14164 			    &lockt_args, argsp, flk, rp);
14165 			break;
14166 		case F_SETLKW:
14167 		case F_SETLK:
14168 			if (flk->l_type == F_UNLCK)
14169 				nfs4frlock_setup_locku_args(ctype,
14170 				    &argop[1], &locku_args, flk,
14171 				    &lop, ep, argsp,
14172 				    vp, flag, offset, cr,
14173 				    &skip_get_err, &go_otw);
14174 			else
14175 				nfs4frlock_setup_lock_args(ctype,
14176 				    &lock_args, &oop, &osp, &lop, &argop[1],
14177 				    argsp, flk, cmd, vp, cr, ep);
14178 
14179 			if (ep->error)
14180 				goto out;
14181 
14182 			switch (ep->stat) {
14183 			case NFS4_OK:
14184 				break;
14185 			case NFS4ERR_DELAY:
14186 				/* recov thread never gets this error */
14187 				ASSERT(resend_rqstp == NULL);
14188 				ASSERT(did_start_fop);
14189 
14190 				nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
14191 				    &recov_state, TRUE);
14192 				did_start_fop = FALSE;
14193 				if (argop[1].argop == OP_LOCK)
14194 					nfs4args_lock_free(&argop[1]);
14195 				else if (argop[1].argop == OP_LOCKT)
14196 					nfs4args_lockt_free(&argop[1]);
14197 				kmem_free(argop, 2 * sizeof (nfs_argop4));
14198 				argsp = NULL;
14199 				goto recov_retry;
14200 			default:
14201 				ep->error = EIO;
14202 				goto out;
14203 			}
14204 			break;
14205 		default:
14206 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14207 			    "nfs4_frlock: invalid cmd %d", cmd));
14208 			ep->error = EINVAL;
14209 			goto out;
14210 		}
14211 
14212 		if (!go_otw)
14213 			goto out;
14214 	}
14215 
14216 	/* XXX should we use the local reclock as a cache ? */
14217 	/*
14218 	 * Unregister the lock with the local locking code before
14219 	 * contacting the server.  This avoids a potential race where
14220 	 * another process gets notified that it has been granted a lock
14221 	 * before we can unregister ourselves locally.
14222 	 */
14223 	if ((cmd == F_SETLK || cmd == F_SETLKW) && flk->l_type == F_UNLCK) {
14224 		if (ctype == NFS4_LCK_CTYPE_NORM)
14225 			flk->l_pid = ttoproc(curthread)->p_pid;
14226 		nfs4_register_lock_locally(vp, flk, flag, offset);
14227 	}
14228 
14229 	/*
14230 	 * Send the server the lock request.  Continually loop with a delay
14231 	 * if get error NFS4ERR_DENIED (for blocking locks) or NFS4ERR_GRACE.
14232 	 */
14233 	resp = &res;
14234 
14235 	NFS4_DEBUG((nfs4_client_call_debug || nfs4_client_lock_debug),
14236 	    (CE_NOTE,
14237 	    "nfs4frlock: %s call, rp %s", needrecov ? "recov" : "first",
14238 	    rnode4info(rp)));
14239 
14240 	if (lock_args && frc_no_reclaim) {
14241 		ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14242 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14243 		    "nfs4frlock: frc_no_reclaim: clearing reclaim"));
14244 		lock_args->reclaim = FALSE;
14245 		if (did_reclaimp)
14246 			*did_reclaimp = 0;
14247 	}
14248 
14249 	/*
14250 	 * Do the OTW call.
14251 	 */
14252 	rfs4call(VTOMI4(vp), argsp, resp, cred_otw, &doqueue, 0, ep);
14253 
14254 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14255 	    "nfs4frlock: error %d, status %d", ep->error, resp->status));
14256 
14257 	needrecov = nfs4_needs_recovery(ep, TRUE, vp->v_vfsp);
14258 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14259 	    "nfs4frlock: needrecov %d", needrecov));
14260 
14261 	if (ep->error == 0 && nfs4_need_to_bump_seqid(resp))
14262 		nfs4frlock_bump_seqid(lock_args, locku_args, oop, lop,
14263 		    args.ctag);
14264 
14265 	/*
14266 	 * Check if one of these mutually exclusive error cases has
14267 	 * happened:
14268 	 *   need to swap credentials due to access error
14269 	 *   recovery is needed
14270 	 *   different error (only known case is missing Kerberos ticket)
14271 	 */
14272 
14273 	if ((ep->error == EACCES ||
14274 	    (ep->error == 0 && resp->status == NFS4ERR_ACCESS)) &&
14275 	    cred_otw != cr) {
14276 		nfs4frlock_check_access(vp, op_hint, &recov_state, needrecov,
14277 		    &did_start_fop, &argsp, &resp, ep->error, &lop, &oop, &osp,
14278 		    cr, &cred_otw);
14279 		goto recov_retry;
14280 	}
14281 
14282 	if (needrecov) {
14283 		/*
14284 		 * LOCKT requests don't need to recover from lost
14285 		 * requests since they don't create/modify state.
14286 		 */
14287 		if ((ep->error == EINTR ||
14288 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) &&
14289 		    lockt_args)
14290 			goto out;
14291 		/*
14292 		 * Do not attempt recovery for requests initiated by
14293 		 * the recovery framework.  Let the framework redrive them.
14294 		 */
14295 		if (ctype != NFS4_LCK_CTYPE_NORM)
14296 			goto out;
14297 		else {
14298 			ASSERT(resend_rqstp == NULL);
14299 		}
14300 
14301 		nfs4frlock_save_lost_rqst(ctype, ep->error,
14302 		    flk_to_locktype(cmd, flk->l_type),
14303 		    oop, osp, lop, flk, &lost_rqst, cred_otw, vp);
14304 
14305 		retry = nfs4frlock_recovery(needrecov, ep, &argsp,
14306 		    &resp, lock_args, locku_args, &oop, &osp, &lop,
14307 		    rp, vp, &recov_state, op_hint, &did_start_fop,
14308 		    cmd != F_GETLK ? &lost_rqst : NULL, flk);
14309 
14310 		if (retry) {
14311 			ASSERT(oop == NULL);
14312 			ASSERT(osp == NULL);
14313 			ASSERT(lop == NULL);
14314 			goto recov_retry;
14315 		}
14316 		goto out;
14317 	}
14318 
14319 	/*
14320 	 * Bail out if have reached this point with ep->error set. Can
14321 	 * happen if (ep->error == EACCES && !needrecov && cred_otw == cr).
14322 	 * This happens if Kerberos ticket has expired or has been
14323 	 * destroyed.
14324 	 */
14325 	if (ep->error != 0)
14326 		goto out;
14327 
14328 	/*
14329 	 * Process the reply.
14330 	 */
14331 	switch (resp->status) {
14332 	case NFS4_OK:
14333 		resop = &resp->array[1];
14334 		nfs4frlock_results_ok(ctype, cmd, flk, vp, flag, offset,
14335 		    resend_rqstp);
14336 		/*
14337 		 * Have a successful lock operation, now update state.
14338 		 */
14339 		nfs4frlock_update_state(lock_args, locku_args, lockt_args,
14340 		    resop, lop, vp, flk, cr, resend_rqstp);
14341 		break;
14342 
14343 	case NFS4ERR_DENIED:
14344 		resop = &resp->array[1];
14345 		retry = nfs4frlock_results_denied(ctype, lock_args, lockt_args,
14346 		    &oop, &osp, &lop, cmd, vp, flk, op_hint,
14347 		    &recov_state, needrecov, &argsp, &resp,
14348 		    &tick_delay, &whence, &ep->error, resop, cr,
14349 		    &did_start_fop, &skip_get_err);
14350 
14351 		if (retry) {
14352 			ASSERT(oop == NULL);
14353 			ASSERT(osp == NULL);
14354 			ASSERT(lop == NULL);
14355 			goto recov_retry;
14356 		}
14357 		break;
14358 	/*
14359 	 * If the server won't let us reclaim, fall-back to trying to lock
14360 	 * the file from scratch. Code elsewhere will check the changeinfo
14361 	 * to ensure the file hasn't been changed.
14362 	 */
14363 	case NFS4ERR_NO_GRACE:
14364 		if (lock_args && lock_args->reclaim == TRUE) {
14365 			ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14366 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14367 			    "nfs4frlock: reclaim: NFS4ERR_NO_GRACE"));
14368 			frc_no_reclaim = 1;
14369 			/* clean up before retrying */
14370 			needrecov = 0;
14371 			(void) nfs4frlock_recovery(needrecov, ep, &argsp, &resp,
14372 			    lock_args, locku_args, &oop, &osp, &lop, rp, vp,
14373 			    &recov_state, op_hint, &did_start_fop, NULL, flk);
14374 			goto recov_retry;
14375 		}
14376 		/* FALLTHROUGH */
14377 
14378 	default:
14379 		nfs4frlock_results_default(resp, &ep->error);
14380 		break;
14381 	}
14382 out:
14383 	/*
14384 	 * Process and cleanup from error.  Make interrupted unlock
14385 	 * requests look successful, since they will be handled by the
14386 	 * client recovery code.
14387 	 */
14388 	nfs4frlock_final_cleanup(ctype, argsp, resp, vp, op_hint, &recov_state,
14389 	    needrecov, oop, osp, lop, flk, whence, offset, ls, &ep->error,
14390 	    lock_args, locku_args, did_start_fop,
14391 	    skip_get_err, cred_otw, cr);
14392 
14393 	if (ep->error == EINTR && flk->l_type == F_UNLCK &&
14394 	    (cmd == F_SETLK || cmd == F_SETLKW))
14395 		ep->error = 0;
14396 }
14397 
14398 /*
14399  * nfs4_safelock:
14400  *
14401  * Return non-zero if the given lock request can be handled without
14402  * violating the constraints on concurrent mapping and locking.
14403  */
14404 
14405 static int
14406 nfs4_safelock(vnode_t *vp, const struct flock64 *bfp, cred_t *cr)
14407 {
14408 	rnode4_t *rp = VTOR4(vp);
14409 	struct vattr va;
14410 	int error;
14411 
14412 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14413 	ASSERT(rp->r_mapcnt >= 0);
14414 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock %s: "
14415 	    "(%"PRIx64", %"PRIx64"); mapcnt = %ld", bfp->l_type == F_WRLCK ?
14416 	    "write" : bfp->l_type == F_RDLCK ? "read" : "unlock",
14417 	    bfp->l_start, bfp->l_len, rp->r_mapcnt));
14418 
14419 	if (rp->r_mapcnt == 0)
14420 		return (1);		/* always safe if not mapped */
14421 
14422 	/*
14423 	 * If the file is already mapped and there are locks, then they
14424 	 * should be all safe locks.  So adding or removing a lock is safe
14425 	 * as long as the new request is safe (i.e., whole-file, meaning
14426 	 * length and starting offset are both zero).
14427 	 */
14428 
14429 	if (bfp->l_start != 0 || bfp->l_len != 0) {
14430 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14431 		    "cannot lock a memory mapped file unless locking the "
14432 		    "entire file: start %"PRIx64", len %"PRIx64,
14433 		    bfp->l_start, bfp->l_len));
14434 		return (0);
14435 	}
14436 
14437 	/* mandatory locking and mapping don't mix */
14438 	va.va_mask = AT_MODE;
14439 	error = VOP_GETATTR(vp, &va, 0, cr, NULL);
14440 	if (error != 0) {
14441 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14442 		    "getattr error %d", error));
14443 		return (0);		/* treat errors conservatively */
14444 	}
14445 	if (MANDLOCK(vp, va.va_mode)) {
14446 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14447 		    "cannot mandatory lock and mmap a file"));
14448 		return (0);
14449 	}
14450 
14451 	return (1);
14452 }
14453 
14454 
14455 /*
14456  * Register the lock locally within Solaris.
14457  * As the client, we "or" the sysid with LM_SYSID_CLIENT when
14458  * recording locks locally.
14459  *
14460  * This should handle conflicts/cooperation with NFS v2/v3 since all locks
14461  * are registered locally.
14462  */
14463 void
14464 nfs4_register_lock_locally(vnode_t *vp, struct flock64 *flk, int flag,
14465     u_offset_t offset)
14466 {
14467 	int oldsysid;
14468 	int error;
14469 #ifdef DEBUG
14470 	char *name;
14471 #endif
14472 
14473 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14474 
14475 #ifdef DEBUG
14476 	name = fn_name(VTOSV(vp)->sv_name);
14477 	NFS4_DEBUG(nfs4_client_lock_debug,
14478 	    (CE_NOTE, "nfs4_register_lock_locally: %s: type %d, "
14479 	    "start %"PRIx64", length %"PRIx64", pid %ld, sysid %d",
14480 	    name, flk->l_type, flk->l_start, flk->l_len, (long)flk->l_pid,
14481 	    flk->l_sysid));
14482 	kmem_free(name, MAXNAMELEN);
14483 #endif
14484 
14485 	/* register the lock with local locking */
14486 	oldsysid = flk->l_sysid;
14487 	flk->l_sysid |= LM_SYSID_CLIENT;
14488 	error = reclock(vp, flk, SETFLCK, flag, offset, NULL);
14489 #ifdef DEBUG
14490 	if (error != 0) {
14491 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14492 		    "nfs4_register_lock_locally: could not register with"
14493 		    " local locking"));
14494 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14495 		    "error %d, vp 0x%p, pid %d, sysid 0x%x",
14496 		    error, (void *)vp, flk->l_pid, flk->l_sysid));
14497 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14498 		    "type %d off 0x%" PRIx64 " len 0x%" PRIx64,
14499 		    flk->l_type, flk->l_start, flk->l_len));
14500 		(void) reclock(vp, flk, 0, flag, offset, NULL);
14501 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14502 		    "blocked by pid %d sysid 0x%x type %d "
14503 		    "off 0x%" PRIx64 " len 0x%" PRIx64,
14504 		    flk->l_pid, flk->l_sysid, flk->l_type, flk->l_start,
14505 		    flk->l_len));
14506 	}
14507 #endif
14508 	flk->l_sysid = oldsysid;
14509 }
14510 
14511 /*
14512  * nfs4_lockrelease:
14513  *
14514  * Release any locks on the given vnode that are held by the current
14515  * process.  Also removes the lock owner (if one exists) from the rnode's
14516  * list.
14517  */
14518 static int
14519 nfs4_lockrelease(vnode_t *vp, int flag, offset_t offset, cred_t *cr)
14520 {
14521 	flock64_t ld;
14522 	int ret, error;
14523 	rnode4_t *rp;
14524 	nfs4_lock_owner_t *lop;
14525 	nfs4_recov_state_t recov_state;
14526 	mntinfo4_t *mi;
14527 	bool_t possible_orphan = FALSE;
14528 	bool_t recovonly;
14529 
14530 	ASSERT((uintptr_t)vp > KERNELBASE);
14531 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14532 
14533 	rp = VTOR4(vp);
14534 	mi = VTOMI4(vp);
14535 
14536 	/*
14537 	 * If we have not locked anything then we can
14538 	 * just return since we have no work to do.
14539 	 */
14540 	if (rp->r_lo_head.lo_next_rnode == &rp->r_lo_head) {
14541 		return (0);
14542 	}
14543 
14544 	/*
14545 	 * We need to comprehend that another thread may
14546 	 * kick off recovery and the lock_owner we have stashed
14547 	 * in lop might be invalid so we should NOT cache it
14548 	 * locally!
14549 	 */
14550 	recov_state.rs_flags = 0;
14551 	recov_state.rs_num_retry_despite_err = 0;
14552 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14553 	    &recovonly);
14554 	if (error) {
14555 		mutex_enter(&rp->r_statelock);
14556 		rp->r_flags |= R4LODANGLERS;
14557 		mutex_exit(&rp->r_statelock);
14558 		return (error);
14559 	}
14560 
14561 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14562 
14563 	/*
14564 	 * Check if the lock owner might have a lock (request was sent but
14565 	 * no response was received).  Also check if there are any remote
14566 	 * locks on the file.  (In theory we shouldn't have to make this
14567 	 * second check if there's no lock owner, but for now we'll be
14568 	 * conservative and do it anyway.)  If either condition is true,
14569 	 * send an unlock for the entire file to the server.
14570 	 *
14571 	 * Note that no explicit synchronization is needed here.  At worst,
14572 	 * flk_has_remote_locks() will return a false positive, in which case
14573 	 * the unlock call wastes time but doesn't harm correctness.
14574 	 */
14575 
14576 	if (lop) {
14577 		mutex_enter(&lop->lo_lock);
14578 		possible_orphan = lop->lo_pending_rqsts;
14579 		mutex_exit(&lop->lo_lock);
14580 		lock_owner_rele(lop);
14581 	}
14582 
14583 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14584 
14585 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14586 	    "nfs4_lockrelease: possible orphan %d, remote locks %d, for "
14587 	    "lop %p.", possible_orphan, flk_has_remote_locks(vp),
14588 	    (void *)lop));
14589 
14590 	if (possible_orphan || flk_has_remote_locks(vp)) {
14591 		ld.l_type = F_UNLCK;    /* set to unlock entire file */
14592 		ld.l_whence = 0;	/* unlock from start of file */
14593 		ld.l_start = 0;
14594 		ld.l_len = 0;		/* do entire file */
14595 
14596 		ret = VOP_FRLOCK(vp, F_SETLK, &ld, flag, offset, NULL,
14597 		    cr, NULL);
14598 
14599 		if (ret != 0) {
14600 			/*
14601 			 * If VOP_FRLOCK fails, make sure we unregister
14602 			 * local locks before we continue.
14603 			 */
14604 			ld.l_pid = ttoproc(curthread)->p_pid;
14605 			nfs4_register_lock_locally(vp, &ld, flag, offset);
14606 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14607 			    "nfs4_lockrelease: lock release error on vp"
14608 			    " %p: error %d.\n", (void *)vp, ret));
14609 		}
14610 	}
14611 
14612 	recov_state.rs_flags = 0;
14613 	recov_state.rs_num_retry_despite_err = 0;
14614 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14615 	    &recovonly);
14616 	if (error) {
14617 		mutex_enter(&rp->r_statelock);
14618 		rp->r_flags |= R4LODANGLERS;
14619 		mutex_exit(&rp->r_statelock);
14620 		return (error);
14621 	}
14622 
14623 	/*
14624 	 * So, here we're going to need to retrieve the lock-owner
14625 	 * again (in case recovery has done a switch-a-roo) and
14626 	 * remove it because we can.
14627 	 */
14628 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14629 
14630 	if (lop) {
14631 		nfs4_rnode_remove_lock_owner(rp, lop);
14632 		lock_owner_rele(lop);
14633 	}
14634 
14635 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14636 	return (0);
14637 }
14638 
14639 /*
14640  * Wait for 'tick_delay' clock ticks.
14641  * Implement exponential backoff until hit the lease_time of this nfs4_server.
14642  * NOTE: lock_lease_time is in seconds.
14643  *
14644  * XXX For future improvements, should implement a waiting queue scheme.
14645  */
14646 static int
14647 nfs4_block_and_wait(clock_t *tick_delay, rnode4_t *rp)
14648 {
14649 	long milliseconds_delay;
14650 	time_t lock_lease_time;
14651 
14652 	/* wait tick_delay clock ticks or siginteruptus */
14653 	if (delay_sig(*tick_delay)) {
14654 		return (EINTR);
14655 	}
14656 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_block_and_wait: "
14657 	    "reissue the lock request: blocked for %ld clock ticks: %ld "
14658 	    "milliseconds", *tick_delay, drv_hztousec(*tick_delay) / 1000));
14659 
14660 	/* get the lease time */
14661 	lock_lease_time = r2lease_time(rp);
14662 
14663 	/* drv_hztousec converts ticks to microseconds */
14664 	milliseconds_delay = drv_hztousec(*tick_delay) / 1000;
14665 	if (milliseconds_delay < lock_lease_time * 1000) {
14666 		*tick_delay = 2 * *tick_delay;
14667 		if (drv_hztousec(*tick_delay) > lock_lease_time * 1000 * 1000)
14668 			*tick_delay = drv_usectohz(lock_lease_time*1000*1000);
14669 	}
14670 	return (0);
14671 }
14672 
14673 
14674 void
14675 nfs4_vnops_init(void)
14676 {
14677 }
14678 
14679 void
14680 nfs4_vnops_fini(void)
14681 {
14682 }
14683 
14684 /*
14685  * Return a reference to the directory (parent) vnode for a given vnode,
14686  * using the saved pathname information and the directory file handle.  The
14687  * caller is responsible for disposing of the reference.
14688  * Returns zero or an errno value.
14689  *
14690  * Caller should set need_start_op to FALSE if it is the recovery
14691  * thread, or if a start_fop has already been done.  Otherwise, TRUE.
14692  */
14693 int
14694 vtodv(vnode_t *vp, vnode_t **dvpp, cred_t *cr, bool_t need_start_op)
14695 {
14696 	svnode_t *svnp;
14697 	vnode_t *dvp = NULL;
14698 	servinfo4_t *svp;
14699 	nfs4_fname_t *mfname;
14700 	int error;
14701 
14702 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14703 
14704 	if (vp->v_flag & VROOT) {
14705 		nfs4_sharedfh_t *sfh;
14706 		nfs_fh4 fh;
14707 		mntinfo4_t *mi;
14708 
14709 		ASSERT(vp->v_type == VREG);
14710 
14711 		mi = VTOMI4(vp);
14712 		svp = mi->mi_curr_serv;
14713 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14714 		fh.nfs_fh4_len = svp->sv_pfhandle.fh_len;
14715 		fh.nfs_fh4_val = svp->sv_pfhandle.fh_buf;
14716 		sfh = sfh4_get(&fh, VTOMI4(vp));
14717 		nfs_rw_exit(&svp->sv_lock);
14718 		mfname = mi->mi_fname;
14719 		fn_hold(mfname);
14720 		dvp = makenfs4node_by_fh(sfh, NULL, &mfname, NULL, mi, cr, 0);
14721 		sfh4_rele(&sfh);
14722 
14723 		if (dvp->v_type == VNON)
14724 			dvp->v_type = VDIR;
14725 		*dvpp = dvp;
14726 		return (0);
14727 	}
14728 
14729 	svnp = VTOSV(vp);
14730 
14731 	if (svnp == NULL) {
14732 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14733 		    "shadow node is NULL"));
14734 		return (EINVAL);
14735 	}
14736 
14737 	if (svnp->sv_name == NULL || svnp->sv_dfh == NULL) {
14738 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14739 		    "shadow node name or dfh val == NULL"));
14740 		return (EINVAL);
14741 	}
14742 
14743 	error = nfs4_make_dotdot(svnp->sv_dfh, 0, vp, cr, &dvp,
14744 	    (int)need_start_op);
14745 	if (error != 0) {
14746 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14747 		    "nfs4_make_dotdot returned %d", error));
14748 		return (error);
14749 	}
14750 	if (!dvp) {
14751 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14752 		    "nfs4_make_dotdot returned a NULL dvp"));
14753 		return (EIO);
14754 	}
14755 	if (dvp->v_type == VNON)
14756 		dvp->v_type = VDIR;
14757 	ASSERT(dvp->v_type == VDIR);
14758 	if (VTOR4(vp)->r_flags & R4ISXATTR) {
14759 		mutex_enter(&dvp->v_lock);
14760 		dvp->v_flag |= V_XATTRDIR;
14761 		mutex_exit(&dvp->v_lock);
14762 	}
14763 	*dvpp = dvp;
14764 	return (0);
14765 }
14766 
14767 /*
14768  * Copy the (final) component name of vp to fnamep.  maxlen is the maximum
14769  * length that fnamep can accept, including the trailing null.
14770  * Returns 0 if okay, returns an errno value if there was a problem.
14771  */
14772 
14773 int
14774 vtoname(vnode_t *vp, char *fnamep, ssize_t maxlen)
14775 {
14776 	char *fn;
14777 	int err = 0;
14778 	servinfo4_t *svp;
14779 	svnode_t *shvp;
14780 
14781 	/*
14782 	 * If the file being opened has VROOT set, then this is
14783 	 * a "file" mount.  sv_name will not be interesting, so
14784 	 * go back to the servinfo4 to get the original mount
14785 	 * path and strip off all but the final edge.  Otherwise
14786 	 * just return the name from the shadow vnode.
14787 	 */
14788 
14789 	if (vp->v_flag & VROOT) {
14790 
14791 		svp = VTOMI4(vp)->mi_curr_serv;
14792 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14793 
14794 		fn = strrchr(svp->sv_path, '/');
14795 		if (fn == NULL)
14796 			err = EINVAL;
14797 		else
14798 			fn++;
14799 	} else {
14800 		shvp = VTOSV(vp);
14801 		fn = fn_name(shvp->sv_name);
14802 	}
14803 
14804 	if (err == 0)
14805 		if (strlen(fn) < maxlen)
14806 			(void) strcpy(fnamep, fn);
14807 		else
14808 			err = ENAMETOOLONG;
14809 
14810 	if (vp->v_flag & VROOT)
14811 		nfs_rw_exit(&svp->sv_lock);
14812 	else
14813 		kmem_free(fn, MAXNAMELEN);
14814 
14815 	return (err);
14816 }
14817 
14818 /*
14819  * Bookkeeping for a close that doesn't need to go over the wire.
14820  * *have_lockp is set to 0 if 'os_sync_lock' is released; otherwise
14821  * it is left at 1.
14822  */
14823 void
14824 nfs4close_notw(vnode_t *vp, nfs4_open_stream_t *osp, int *have_lockp)
14825 {
14826 	rnode4_t		*rp;
14827 	mntinfo4_t		*mi;
14828 
14829 	mi = VTOMI4(vp);
14830 	rp = VTOR4(vp);
14831 
14832 	NFS4_DEBUG(nfs4close_notw_debug, (CE_NOTE, "nfs4close_notw: "
14833 	    "rp=%p osp=%p", (void *)rp, (void *)osp));
14834 	ASSERT(nfs_zone() == mi->mi_zone);
14835 	ASSERT(mutex_owned(&osp->os_sync_lock));
14836 	ASSERT(*have_lockp);
14837 
14838 	if (!osp->os_valid ||
14839 	    osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
14840 		return;
14841 	}
14842 
14843 	/*
14844 	 * This removes the reference obtained at OPEN; ie,
14845 	 * when the open stream structure was created.
14846 	 *
14847 	 * We don't have to worry about calling 'open_stream_rele'
14848 	 * since we our currently holding a reference to this
14849 	 * open stream which means the count can not go to 0 with
14850 	 * this decrement.
14851 	 */
14852 	ASSERT(osp->os_ref_count >= 2);
14853 	osp->os_ref_count--;
14854 	osp->os_valid = 0;
14855 	mutex_exit(&osp->os_sync_lock);
14856 	*have_lockp = 0;
14857 
14858 	nfs4_dec_state_ref_count(mi);
14859 }
14860 
14861 /*
14862  * Close all remaining open streams on the rnode.  These open streams
14863  * could be here because:
14864  * - The close attempted at either close or delmap failed
14865  * - Some kernel entity did VOP_OPEN but never did VOP_CLOSE
14866  * - Someone did mknod on a regular file but never opened it
14867  */
14868 int
14869 nfs4close_all(vnode_t *vp, cred_t *cr)
14870 {
14871 	nfs4_open_stream_t *osp;
14872 	int error;
14873 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
14874 	rnode4_t *rp;
14875 
14876 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14877 
14878 	error = 0;
14879 	rp = VTOR4(vp);
14880 
14881 	/*
14882 	 * At this point, all we know is that the last time
14883 	 * someone called vn_rele, the count was 1.  Since then,
14884 	 * the vnode could have been re-activated.  We want to
14885 	 * loop through the open streams and close each one, but
14886 	 * we have to be careful since once we release the rnode
14887 	 * hash bucket lock, someone else is free to come in and
14888 	 * re-activate the rnode and add new open streams.  The
14889 	 * strategy is take the rnode hash bucket lock, verify that
14890 	 * the count is still 1, grab the open stream off the
14891 	 * head of the list and mark it invalid, then release the
14892 	 * rnode hash bucket lock and proceed with that open stream.
14893 	 * This is ok because nfs4close_one() will acquire the proper
14894 	 * open/create to close/destroy synchronization for open
14895 	 * streams, and will ensure that if someone has reopened
14896 	 * the open stream after we've dropped the hash bucket lock
14897 	 * then we'll just simply return without destroying the
14898 	 * open stream.
14899 	 * Repeat until the list is empty.
14900 	 */
14901 
14902 	for (;;) {
14903 
14904 		/* make sure vnode hasn't been reactivated */
14905 		rw_enter(&rp->r_hashq->r_lock, RW_READER);
14906 		mutex_enter(&vp->v_lock);
14907 		if (vp->v_count > 1) {
14908 			mutex_exit(&vp->v_lock);
14909 			rw_exit(&rp->r_hashq->r_lock);
14910 			break;
14911 		}
14912 		/*
14913 		 * Grabbing r_os_lock before releasing v_lock prevents
14914 		 * a window where the rnode/open stream could get
14915 		 * reactivated (and os_force_close set to 0) before we
14916 		 * had a chance to set os_force_close to 1.
14917 		 */
14918 		mutex_enter(&rp->r_os_lock);
14919 		mutex_exit(&vp->v_lock);
14920 
14921 		osp = list_head(&rp->r_open_streams);
14922 		if (!osp) {
14923 			/* nothing left to CLOSE OTW, so return */
14924 			mutex_exit(&rp->r_os_lock);
14925 			rw_exit(&rp->r_hashq->r_lock);
14926 			break;
14927 		}
14928 
14929 		mutex_enter(&rp->r_statev4_lock);
14930 		/* the file can't still be mem mapped */
14931 		ASSERT(rp->r_mapcnt == 0);
14932 		if (rp->created_v4)
14933 			rp->created_v4 = 0;
14934 		mutex_exit(&rp->r_statev4_lock);
14935 
14936 		/*
14937 		 * Grab a ref on this open stream; nfs4close_one
14938 		 * will mark it as invalid
14939 		 */
14940 		mutex_enter(&osp->os_sync_lock);
14941 		osp->os_ref_count++;
14942 		osp->os_force_close = 1;
14943 		mutex_exit(&osp->os_sync_lock);
14944 		mutex_exit(&rp->r_os_lock);
14945 		rw_exit(&rp->r_hashq->r_lock);
14946 
14947 		nfs4close_one(vp, osp, cr, 0, NULL, &e, CLOSE_FORCE, 0, 0, 0);
14948 
14949 		/* Update error if it isn't already non-zero */
14950 		if (error == 0) {
14951 			if (e.error)
14952 				error = e.error;
14953 			else if (e.stat)
14954 				error = geterrno4(e.stat);
14955 		}
14956 
14957 #ifdef	DEBUG
14958 		nfs4close_all_cnt++;
14959 #endif
14960 		/* Release the ref on osp acquired above. */
14961 		open_stream_rele(osp, rp);
14962 
14963 		/* Proceed to the next open stream, if any */
14964 	}
14965 	return (error);
14966 }
14967 
14968 /*
14969  * nfs4close_one - close one open stream for a file if needed.
14970  *
14971  * "close_type" indicates which close path this is:
14972  * CLOSE_NORM: close initiated via VOP_CLOSE.
14973  * CLOSE_DELMAP: close initiated via VOP_DELMAP.
14974  * CLOSE_FORCE: close initiated via VOP_INACTIVE.  This path forces
14975  *	the close and release of client state for this open stream
14976  *	(unless someone else has the open stream open).
14977  * CLOSE_RESEND: indicates the request is a replay of an earlier request
14978  *	(e.g., due to abort because of a signal).
14979  * CLOSE_AFTER_RESEND: close initiated to "undo" a successful resent OPEN.
14980  *
14981  * CLOSE_RESEND and CLOSE_AFTER_RESEND will not attempt to retry after client
14982  * recovery.  Instead, the caller is expected to deal with retries.
14983  *
14984  * The caller can either pass in the osp ('provided_osp') or not.
14985  *
14986  * 'access_bits' represents the access we are closing/downgrading.
14987  *
14988  * 'len', 'prot', and 'mmap_flags' are used for CLOSE_DELMAP.  'len' is the
14989  * number of bytes we are unmapping, 'maxprot' is the mmap protection, and
14990  * 'mmap_flags' tells us the type of sharing (MAP_PRIVATE or MAP_SHARED).
14991  *
14992  * Errors are returned via the nfs4_error_t.
14993  */
14994 void
14995 nfs4close_one(vnode_t *vp, nfs4_open_stream_t *provided_osp, cred_t *cr,
14996     int access_bits, nfs4_lost_rqst_t *lrp, nfs4_error_t *ep,
14997     nfs4_close_type_t close_type, size_t len, uint_t maxprot,
14998     uint_t mmap_flags)
14999 {
15000 	nfs4_open_owner_t *oop;
15001 	nfs4_open_stream_t *osp = NULL;
15002 	int retry = 0;
15003 	int num_retries = NFS4_NUM_RECOV_RETRIES;
15004 	rnode4_t *rp;
15005 	mntinfo4_t *mi;
15006 	nfs4_recov_state_t recov_state;
15007 	cred_t *cred_otw = NULL;
15008 	bool_t recovonly = FALSE;
15009 	int isrecov;
15010 	int force_close;
15011 	int close_failed = 0;
15012 	int did_dec_count = 0;
15013 	int did_start_op = 0;
15014 	int did_force_recovlock = 0;
15015 	int did_start_seqid_sync = 0;
15016 	int have_sync_lock = 0;
15017 
15018 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
15019 
15020 	NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE, "closing vp %p osp %p, "
15021 	    "lrp %p, close type %d len %ld prot %x mmap flags %x bits %x",
15022 	    (void *)vp, (void *)provided_osp, (void *)lrp, close_type,
15023 	    len, maxprot, mmap_flags, access_bits));
15024 
15025 	nfs4_error_zinit(ep);
15026 	rp = VTOR4(vp);
15027 	mi = VTOMI4(vp);
15028 	isrecov = (close_type == CLOSE_RESEND ||
15029 	    close_type == CLOSE_AFTER_RESEND);
15030 
15031 	/*
15032 	 * First get the open owner.
15033 	 */
15034 	if (!provided_osp) {
15035 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
15036 	} else {
15037 		oop = provided_osp->os_open_owner;
15038 		ASSERT(oop != NULL);
15039 		open_owner_hold(oop);
15040 	}
15041 
15042 	if (!oop) {
15043 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15044 		    "nfs4close_one: no oop, rp %p, mi %p, cr %p, osp %p, "
15045 		    "close type %d", (void *)rp, (void *)mi, (void *)cr,
15046 		    (void *)provided_osp, close_type));
15047 		ep->error = EIO;
15048 		goto out;
15049 	}
15050 
15051 	cred_otw = nfs4_get_otw_cred(cr, mi, oop);
15052 recov_retry:
15053 	osp = NULL;
15054 	close_failed = 0;
15055 	force_close = (close_type == CLOSE_FORCE);
15056 	retry = 0;
15057 	did_start_op = 0;
15058 	did_force_recovlock = 0;
15059 	did_start_seqid_sync = 0;
15060 	have_sync_lock = 0;
15061 	recovonly = FALSE;
15062 	recov_state.rs_flags = 0;
15063 	recov_state.rs_num_retry_despite_err = 0;
15064 
15065 	/*
15066 	 * Second synchronize with recovery.
15067 	 */
15068 	if (!isrecov) {
15069 		ep->error = nfs4_start_fop(mi, vp, NULL, OH_CLOSE,
15070 		    &recov_state, &recovonly);
15071 		if (!ep->error) {
15072 			did_start_op = 1;
15073 		} else {
15074 			close_failed = 1;
15075 			/*
15076 			 * If we couldn't get start_fop, but have to
15077 			 * cleanup state, then at least acquire the
15078 			 * mi_recovlock so we can synchronize with
15079 			 * recovery.
15080 			 */
15081 			if (close_type == CLOSE_FORCE) {
15082 				(void) nfs_rw_enter_sig(&mi->mi_recovlock,
15083 				    RW_READER, FALSE);
15084 				did_force_recovlock = 1;
15085 			} else
15086 				goto out;
15087 		}
15088 	}
15089 
15090 	/*
15091 	 * We cannot attempt to get the open seqid sync if nfs4_start_fop
15092 	 * set 'recovonly' to TRUE since most likely this is due to
15093 	 * reovery being active (MI4_RECOV_ACTIV).  If recovery is active,
15094 	 * nfs4_start_open_seqid_sync() will fail with EAGAIN asking us
15095 	 * to retry, causing us to loop until recovery finishes.  Plus we
15096 	 * don't need protection over the open seqid since we're not going
15097 	 * OTW, hence don't need to use the seqid.
15098 	 */
15099 	if (recovonly == FALSE) {
15100 		/* need to grab the open owner sync before 'os_sync_lock' */
15101 		ep->error = nfs4_start_open_seqid_sync(oop, mi);
15102 		if (ep->error == EAGAIN) {
15103 			ASSERT(!isrecov);
15104 			if (did_start_op)
15105 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15106 				    &recov_state, TRUE);
15107 			if (did_force_recovlock)
15108 				nfs_rw_exit(&mi->mi_recovlock);
15109 			goto recov_retry;
15110 		}
15111 		did_start_seqid_sync = 1;
15112 	}
15113 
15114 	/*
15115 	 * Third get an open stream and acquire 'os_sync_lock' to
15116 	 * sychronize the opening/creating of an open stream with the
15117 	 * closing/destroying of an open stream.
15118 	 */
15119 	if (!provided_osp) {
15120 		/* returns with 'os_sync_lock' held */
15121 		osp = find_open_stream(oop, rp);
15122 		if (!osp) {
15123 			ep->error = EIO;
15124 			goto out;
15125 		}
15126 	} else {
15127 		osp = provided_osp;
15128 		open_stream_hold(osp);
15129 		mutex_enter(&osp->os_sync_lock);
15130 	}
15131 	have_sync_lock = 1;
15132 
15133 	ASSERT(oop == osp->os_open_owner);
15134 
15135 	/*
15136 	 * Fourth, do any special pre-OTW CLOSE processing
15137 	 * based on the specific close type.
15138 	 */
15139 	if ((close_type == CLOSE_NORM || close_type == CLOSE_AFTER_RESEND) &&
15140 	    !did_dec_count) {
15141 		ASSERT(osp->os_open_ref_count > 0);
15142 		osp->os_open_ref_count--;
15143 		did_dec_count = 1;
15144 		if (osp->os_open_ref_count == 0)
15145 			osp->os_final_close = 1;
15146 	}
15147 
15148 	if (close_type == CLOSE_FORCE) {
15149 		/* see if somebody reopened the open stream. */
15150 		if (!osp->os_force_close) {
15151 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
15152 			    "nfs4close_one: skip CLOSE_FORCE as osp %p "
15153 			    "was reopened, vp %p", (void *)osp, (void *)vp));
15154 			ep->error = 0;
15155 			ep->stat = NFS4_OK;
15156 			goto out;
15157 		}
15158 
15159 		if (!osp->os_final_close && !did_dec_count) {
15160 			osp->os_open_ref_count--;
15161 			did_dec_count = 1;
15162 		}
15163 
15164 		/*
15165 		 * We can't depend on os_open_ref_count being 0 due to the
15166 		 * way executables are opened (VN_RELE to match a VOP_OPEN).
15167 		 */
15168 #ifdef	NOTYET
15169 		ASSERT(osp->os_open_ref_count == 0);
15170 #endif
15171 		if (osp->os_open_ref_count != 0) {
15172 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
15173 			    "nfs4close_one: should panic here on an "
15174 			    "ASSERT(osp->os_open_ref_count == 0). Ignoring "
15175 			    "since this is probably the exec problem."));
15176 
15177 			osp->os_open_ref_count = 0;
15178 		}
15179 
15180 		/*
15181 		 * There is the possibility that nfs4close_one()
15182 		 * for close_type == CLOSE_DELMAP couldn't find the
15183 		 * open stream, thus couldn't decrement its os_mapcnt;
15184 		 * therefore we can't use this ASSERT yet.
15185 		 */
15186 #ifdef	NOTYET
15187 		ASSERT(osp->os_mapcnt == 0);
15188 #endif
15189 		osp->os_mapcnt = 0;
15190 	}
15191 
15192 	if (close_type == CLOSE_DELMAP && !did_dec_count) {
15193 		ASSERT(osp->os_mapcnt >= btopr(len));
15194 
15195 		if ((mmap_flags & MAP_SHARED) && (maxprot & PROT_WRITE))
15196 			osp->os_mmap_write -= btopr(len);
15197 		if (maxprot & PROT_READ)
15198 			osp->os_mmap_read -= btopr(len);
15199 		if (maxprot & PROT_EXEC)
15200 			osp->os_mmap_read -= btopr(len);
15201 		/* mirror the PROT_NONE check in nfs4_addmap() */
15202 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
15203 		    !(maxprot & PROT_EXEC))
15204 			osp->os_mmap_read -= btopr(len);
15205 		osp->os_mapcnt -= btopr(len);
15206 		did_dec_count = 1;
15207 	}
15208 
15209 	if (recovonly) {
15210 		nfs4_lost_rqst_t lost_rqst;
15211 
15212 		/* request should not already be in recovery queue */
15213 		ASSERT(lrp == NULL);
15214 		nfs4_error_init(ep, EINTR);
15215 		nfs4close_save_lost_rqst(ep->error, &lost_rqst, oop,
15216 		    osp, cred_otw, vp);
15217 		mutex_exit(&osp->os_sync_lock);
15218 		have_sync_lock = 0;
15219 		(void) nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15220 		    lost_rqst.lr_op == OP_CLOSE ?
15221 		    &lost_rqst : NULL, OP_CLOSE, NULL);
15222 		close_failed = 1;
15223 		force_close = 0;
15224 		goto close_cleanup;
15225 	}
15226 
15227 	/*
15228 	 * If a previous OTW call got NFS4ERR_BAD_SEQID, then
15229 	 * we stopped operating on the open owner's <old oo_name, old seqid>
15230 	 * space, which means we stopped operating on the open stream
15231 	 * too.  So don't go OTW (as the seqid is likely bad, and the
15232 	 * stateid could be stale, potentially triggering a false
15233 	 * setclientid), and just clean up the client's internal state.
15234 	 */
15235 	if (osp->os_orig_oo_name != oop->oo_name) {
15236 		NFS4_DEBUG(nfs4close_one_debug || nfs4_client_recov_debug,
15237 		    (CE_NOTE, "nfs4close_one: skip OTW close for osp %p "
15238 		    "oop %p due to bad seqid (orig oo_name %" PRIx64 " current "
15239 		    "oo_name %" PRIx64")",
15240 		    (void *)osp, (void *)oop, osp->os_orig_oo_name,
15241 		    oop->oo_name));
15242 		close_failed = 1;
15243 	}
15244 
15245 	/* If the file failed recovery, just quit. */
15246 	mutex_enter(&rp->r_statelock);
15247 	if (rp->r_flags & R4RECOVERR) {
15248 		close_failed = 1;
15249 	}
15250 	mutex_exit(&rp->r_statelock);
15251 
15252 	/*
15253 	 * If the force close path failed to obtain start_fop
15254 	 * then skip the OTW close and just remove the state.
15255 	 */
15256 	if (close_failed)
15257 		goto close_cleanup;
15258 
15259 	/*
15260 	 * Fifth, check to see if there are still mapped pages or other
15261 	 * opens using this open stream.  If there are then we can't
15262 	 * close yet but we can see if an OPEN_DOWNGRADE is necessary.
15263 	 */
15264 	if (osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
15265 		nfs4_lost_rqst_t	new_lost_rqst;
15266 		bool_t			needrecov = FALSE;
15267 		cred_t			*odg_cred_otw = NULL;
15268 		seqid4			open_dg_seqid = 0;
15269 
15270 		if (osp->os_delegation) {
15271 			/*
15272 			 * If this open stream was never OPENed OTW then we
15273 			 * surely can't DOWNGRADE it (especially since the
15274 			 * osp->open_stateid is really a delegation stateid
15275 			 * when os_delegation is 1).
15276 			 */
15277 			if (access_bits & FREAD)
15278 				osp->os_share_acc_read--;
15279 			if (access_bits & FWRITE)
15280 				osp->os_share_acc_write--;
15281 			osp->os_share_deny_none--;
15282 			nfs4_error_zinit(ep);
15283 			goto out;
15284 		}
15285 		nfs4_open_downgrade(access_bits, 0, oop, osp, vp, cr,
15286 		    lrp, ep, &odg_cred_otw, &open_dg_seqid);
15287 		needrecov = nfs4_needs_recovery(ep, TRUE, mi->mi_vfsp);
15288 		if (needrecov && !isrecov) {
15289 			bool_t abort;
15290 			nfs4_bseqid_entry_t *bsep = NULL;
15291 
15292 			if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID)
15293 				bsep = nfs4_create_bseqid_entry(oop, NULL,
15294 				    vp, 0,
15295 				    lrp ? TAG_OPEN_DG_LOST : TAG_OPEN_DG,
15296 				    open_dg_seqid);
15297 
15298 			nfs4open_dg_save_lost_rqst(ep->error, &new_lost_rqst,
15299 			    oop, osp, odg_cred_otw, vp, access_bits, 0);
15300 			mutex_exit(&osp->os_sync_lock);
15301 			have_sync_lock = 0;
15302 			abort = nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15303 			    new_lost_rqst.lr_op == OP_OPEN_DOWNGRADE ?
15304 			    &new_lost_rqst : NULL, OP_OPEN_DOWNGRADE,
15305 			    bsep);
15306 			if (odg_cred_otw)
15307 				crfree(odg_cred_otw);
15308 			if (bsep)
15309 				kmem_free(bsep, sizeof (*bsep));
15310 
15311 			if (abort == TRUE)
15312 				goto out;
15313 
15314 			if (did_start_seqid_sync) {
15315 				nfs4_end_open_seqid_sync(oop);
15316 				did_start_seqid_sync = 0;
15317 			}
15318 			open_stream_rele(osp, rp);
15319 
15320 			if (did_start_op)
15321 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15322 				    &recov_state, FALSE);
15323 			if (did_force_recovlock)
15324 				nfs_rw_exit(&mi->mi_recovlock);
15325 
15326 			goto recov_retry;
15327 		} else {
15328 			if (odg_cred_otw)
15329 				crfree(odg_cred_otw);
15330 		}
15331 		goto out;
15332 	}
15333 
15334 	/*
15335 	 * If this open stream was created as the results of an open
15336 	 * while holding a delegation, then just release it; no need
15337 	 * to do an OTW close.  Otherwise do a "normal" OTW close.
15338 	 */
15339 	if (osp->os_delegation) {
15340 		nfs4close_notw(vp, osp, &have_sync_lock);
15341 		nfs4_error_zinit(ep);
15342 		goto out;
15343 	}
15344 
15345 	/*
15346 	 * If this stream is not valid, we're done.
15347 	 */
15348 	if (!osp->os_valid) {
15349 		nfs4_error_zinit(ep);
15350 		goto out;
15351 	}
15352 
15353 	/*
15354 	 * Last open or mmap ref has vanished, need to do an OTW close.
15355 	 * First check to see if a close is still necessary.
15356 	 */
15357 	if (osp->os_failed_reopen) {
15358 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15359 		    "don't close OTW osp %p since reopen failed.",
15360 		    (void *)osp));
15361 		/*
15362 		 * Reopen of the open stream failed, hence the
15363 		 * stateid of the open stream is invalid/stale, and
15364 		 * sending this OTW would incorrectly cause another
15365 		 * round of recovery.  In this case, we need to set
15366 		 * the 'os_valid' bit to 0 so another thread doesn't
15367 		 * come in and re-open this open stream before
15368 		 * this "closing" thread cleans up state (decrementing
15369 		 * the nfs4_server_t's state_ref_count and decrementing
15370 		 * the os_ref_count).
15371 		 */
15372 		osp->os_valid = 0;
15373 		/*
15374 		 * This removes the reference obtained at OPEN; ie,
15375 		 * when the open stream structure was created.
15376 		 *
15377 		 * We don't have to worry about calling 'open_stream_rele'
15378 		 * since we our currently holding a reference to this
15379 		 * open stream which means the count can not go to 0 with
15380 		 * this decrement.
15381 		 */
15382 		ASSERT(osp->os_ref_count >= 2);
15383 		osp->os_ref_count--;
15384 		nfs4_error_zinit(ep);
15385 		close_failed = 0;
15386 		goto close_cleanup;
15387 	}
15388 
15389 	ASSERT(osp->os_ref_count > 1);
15390 
15391 	/*
15392 	 * Sixth, try the CLOSE OTW.
15393 	 */
15394 	nfs4close_otw(rp, cred_otw, oop, osp, &retry, &did_start_seqid_sync,
15395 	    close_type, ep, &have_sync_lock);
15396 
15397 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) {
15398 		/*
15399 		 * Let the recovery thread be responsible for
15400 		 * removing the state for CLOSE.
15401 		 */
15402 		close_failed = 1;
15403 		force_close = 0;
15404 		retry = 0;
15405 	}
15406 
15407 	/* See if we need to retry with a different cred */
15408 	if ((ep->error == EACCES ||
15409 	    (ep->error == 0 && ep->stat == NFS4ERR_ACCESS)) &&
15410 	    cred_otw != cr) {
15411 		crfree(cred_otw);
15412 		cred_otw = cr;
15413 		crhold(cred_otw);
15414 		retry = 1;
15415 	}
15416 
15417 	if (ep->error || ep->stat)
15418 		close_failed = 1;
15419 
15420 	if (retry && !isrecov && num_retries-- > 0) {
15421 		if (have_sync_lock) {
15422 			mutex_exit(&osp->os_sync_lock);
15423 			have_sync_lock = 0;
15424 		}
15425 		if (did_start_seqid_sync) {
15426 			nfs4_end_open_seqid_sync(oop);
15427 			did_start_seqid_sync = 0;
15428 		}
15429 		open_stream_rele(osp, rp);
15430 
15431 		if (did_start_op)
15432 			nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15433 			    &recov_state, FALSE);
15434 		if (did_force_recovlock)
15435 			nfs_rw_exit(&mi->mi_recovlock);
15436 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15437 		    "nfs4close_one: need to retry the close "
15438 		    "operation"));
15439 		goto recov_retry;
15440 	}
15441 close_cleanup:
15442 	/*
15443 	 * Seventh and lastly, process our results.
15444 	 */
15445 	if (close_failed && force_close) {
15446 		/*
15447 		 * It's ok to drop and regrab the 'os_sync_lock' since
15448 		 * nfs4close_notw() will recheck to make sure the
15449 		 * "close"/removal of state should happen.
15450 		 */
15451 		if (!have_sync_lock) {
15452 			mutex_enter(&osp->os_sync_lock);
15453 			have_sync_lock = 1;
15454 		}
15455 		/*
15456 		 * This is last call, remove the ref on the open
15457 		 * stream created by open and clean everything up.
15458 		 */
15459 		osp->os_pending_close = 0;
15460 		nfs4close_notw(vp, osp, &have_sync_lock);
15461 		nfs4_error_zinit(ep);
15462 	}
15463 
15464 	if (!close_failed) {
15465 		if (have_sync_lock) {
15466 			osp->os_pending_close = 0;
15467 			mutex_exit(&osp->os_sync_lock);
15468 			have_sync_lock = 0;
15469 		} else {
15470 			mutex_enter(&osp->os_sync_lock);
15471 			osp->os_pending_close = 0;
15472 			mutex_exit(&osp->os_sync_lock);
15473 		}
15474 		if (did_start_op && recov_state.rs_sp != NULL) {
15475 			mutex_enter(&recov_state.rs_sp->s_lock);
15476 			nfs4_dec_state_ref_count_nolock(recov_state.rs_sp, mi);
15477 			mutex_exit(&recov_state.rs_sp->s_lock);
15478 		} else {
15479 			nfs4_dec_state_ref_count(mi);
15480 		}
15481 		nfs4_error_zinit(ep);
15482 	}
15483 
15484 out:
15485 	if (have_sync_lock)
15486 		mutex_exit(&osp->os_sync_lock);
15487 	if (did_start_op)
15488 		nfs4_end_fop(mi, vp, NULL, OH_CLOSE, &recov_state,
15489 		    recovonly ? TRUE : FALSE);
15490 	if (did_force_recovlock)
15491 		nfs_rw_exit(&mi->mi_recovlock);
15492 	if (cred_otw)
15493 		crfree(cred_otw);
15494 	if (osp)
15495 		open_stream_rele(osp, rp);
15496 	if (oop) {
15497 		if (did_start_seqid_sync)
15498 			nfs4_end_open_seqid_sync(oop);
15499 		open_owner_rele(oop);
15500 	}
15501 }
15502 
15503 /*
15504  * Convert information returned by the server in the LOCK4denied
15505  * structure to the form required by fcntl.
15506  */
15507 static void
15508 denied_to_flk(LOCK4denied *lockt_denied, flock64_t *flk, LOCKT4args *lockt_args)
15509 {
15510 	nfs4_lo_name_t *lo;
15511 
15512 #ifdef	DEBUG
15513 	if (denied_to_flk_debug) {
15514 		lockt_denied_debug = lockt_denied;
15515 		debug_enter("lockt_denied");
15516 	}
15517 #endif
15518 
15519 	flk->l_type = lockt_denied->locktype == READ_LT ? F_RDLCK : F_WRLCK;
15520 	flk->l_whence = 0;	/* aka SEEK_SET */
15521 	flk->l_start = lockt_denied->offset;
15522 	flk->l_len = lockt_denied->length;
15523 
15524 	/*
15525 	 * If the blocking clientid matches our client id, then we can
15526 	 * interpret the lockowner (since we built it).  If not, then
15527 	 * fabricate a sysid and pid.  Note that the l_sysid field
15528 	 * in *flk already has the local sysid.
15529 	 */
15530 
15531 	if (lockt_denied->owner.clientid == lockt_args->owner.clientid) {
15532 
15533 		if (lockt_denied->owner.owner_len == sizeof (*lo)) {
15534 			lo = (nfs4_lo_name_t *)
15535 			    lockt_denied->owner.owner_val;
15536 
15537 			flk->l_pid = lo->ln_pid;
15538 		} else {
15539 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15540 			    "denied_to_flk: bad lock owner length\n"));
15541 
15542 			flk->l_pid = lo_to_pid(&lockt_denied->owner);
15543 		}
15544 	} else {
15545 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15546 		"denied_to_flk: foreign clientid\n"));
15547 
15548 		/*
15549 		 * Construct a new sysid which should be different from
15550 		 * sysids of other systems.
15551 		 */
15552 
15553 		flk->l_sysid++;
15554 		flk->l_pid = lo_to_pid(&lockt_denied->owner);
15555 	}
15556 }
15557 
15558 static pid_t
15559 lo_to_pid(lock_owner4 *lop)
15560 {
15561 	pid_t pid = 0;
15562 	uchar_t *cp;
15563 	int i;
15564 
15565 	cp = (uchar_t *)&lop->clientid;
15566 
15567 	for (i = 0; i < sizeof (lop->clientid); i++)
15568 		pid += (pid_t)*cp++;
15569 
15570 	cp = (uchar_t *)lop->owner_val;
15571 
15572 	for (i = 0; i < lop->owner_len; i++)
15573 		pid += (pid_t)*cp++;
15574 
15575 	return (pid);
15576 }
15577 
15578 /*
15579  * Given a lock pointer, returns the length of that lock.
15580  * "end" is the last locked offset the "l_len" covers from
15581  * the start of the lock.
15582  */
15583 static off64_t
15584 lock_to_end(flock64_t *lock)
15585 {
15586 	off64_t lock_end;
15587 
15588 	if (lock->l_len == 0)
15589 		lock_end = (off64_t)MAXEND;
15590 	else
15591 		lock_end = lock->l_start + lock->l_len - 1;
15592 
15593 	return (lock_end);
15594 }
15595 
15596 /*
15597  * Given the end of a lock, it will return you the length "l_len" for that lock.
15598  */
15599 static off64_t
15600 end_to_len(off64_t start, off64_t end)
15601 {
15602 	off64_t lock_len;
15603 
15604 	ASSERT(end >= start);
15605 	if (end == MAXEND)
15606 		lock_len = 0;
15607 	else
15608 		lock_len = end - start + 1;
15609 
15610 	return (lock_len);
15611 }
15612 
15613 /*
15614  * On given end for a lock it determines if it is the last locked offset
15615  * or not, if so keeps it as is, else adds one to return the length for
15616  * valid start.
15617  */
15618 static off64_t
15619 start_check(off64_t x)
15620 {
15621 	if (x == MAXEND)
15622 		return (x);
15623 	else
15624 		return (x + 1);
15625 }
15626 
15627 /*
15628  * See if these two locks overlap, and if so return 1;
15629  * otherwise, return 0.
15630  */
15631 static int
15632 locks_intersect(flock64_t *llfp, flock64_t *curfp)
15633 {
15634 	off64_t llfp_end, curfp_end;
15635 
15636 	llfp_end = lock_to_end(llfp);
15637 	curfp_end = lock_to_end(curfp);
15638 
15639 	if (((llfp_end >= curfp->l_start) &&
15640 	    (llfp->l_start <= curfp->l_start)) ||
15641 	    ((curfp->l_start <= llfp->l_start) && (curfp_end >= llfp->l_start)))
15642 		return (1);
15643 	return (0);
15644 }
15645 
15646 /*
15647  * Determine what the intersecting lock region is, and add that to the
15648  * 'nl_llpp' locklist in increasing order (by l_start).
15649  */
15650 static void
15651 nfs4_add_lock_range(flock64_t *lost_flp, flock64_t *local_flp,
15652     locklist_t **nl_llpp, vnode_t *vp)
15653 {
15654 	locklist_t *intersect_llp, *tmp_fllp, *cur_fllp;
15655 	off64_t lost_flp_end, local_flp_end, len, start;
15656 
15657 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range:"));
15658 
15659 	if (!locks_intersect(lost_flp, local_flp))
15660 		return;
15661 
15662 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15663 	    "locks intersect"));
15664 
15665 	lost_flp_end = lock_to_end(lost_flp);
15666 	local_flp_end = lock_to_end(local_flp);
15667 
15668 	/* Find the starting point of the intersecting region */
15669 	if (local_flp->l_start > lost_flp->l_start)
15670 		start = local_flp->l_start;
15671 	else
15672 		start = lost_flp->l_start;
15673 
15674 	/* Find the lenght of the intersecting region */
15675 	if (lost_flp_end < local_flp_end)
15676 		len = end_to_len(start, lost_flp_end);
15677 	else
15678 		len = end_to_len(start, local_flp_end);
15679 
15680 	/*
15681 	 * Prepare the flock structure for the intersection found and insert
15682 	 * it into the new list in increasing l_start order. This list contains
15683 	 * intersections of locks registered by the client with the local host
15684 	 * and the lost lock.
15685 	 * The lock type of this lock is the same as that of the local_flp.
15686 	 */
15687 	intersect_llp = (locklist_t *)kmem_alloc(sizeof (locklist_t), KM_SLEEP);
15688 	intersect_llp->ll_flock.l_start = start;
15689 	intersect_llp->ll_flock.l_len = len;
15690 	intersect_llp->ll_flock.l_type = local_flp->l_type;
15691 	intersect_llp->ll_flock.l_pid = local_flp->l_pid;
15692 	intersect_llp->ll_flock.l_sysid = local_flp->l_sysid;
15693 	intersect_llp->ll_flock.l_whence = 0;	/* aka SEEK_SET */
15694 	intersect_llp->ll_vp = vp;
15695 
15696 	tmp_fllp = *nl_llpp;
15697 	cur_fllp = NULL;
15698 	while (tmp_fllp != NULL && tmp_fllp->ll_flock.l_start <
15699 	    intersect_llp->ll_flock.l_start) {
15700 			cur_fllp = tmp_fllp;
15701 			tmp_fllp = tmp_fllp->ll_next;
15702 	}
15703 	if (cur_fllp == NULL) {
15704 		/* first on the list */
15705 		intersect_llp->ll_next = *nl_llpp;
15706 		*nl_llpp = intersect_llp;
15707 	} else {
15708 		intersect_llp->ll_next = cur_fllp->ll_next;
15709 		cur_fllp->ll_next = intersect_llp;
15710 	}
15711 
15712 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15713 	    "created lock region: start %"PRIx64" end %"PRIx64" : %s\n",
15714 	    intersect_llp->ll_flock.l_start,
15715 	    intersect_llp->ll_flock.l_start + intersect_llp->ll_flock.l_len,
15716 	    intersect_llp->ll_flock.l_type == F_RDLCK ? "READ" : "WRITE"));
15717 }
15718 
15719 /*
15720  * Our local locking current state is potentially different than
15721  * what the NFSv4 server thinks we have due to a lost lock that was
15722  * resent and then received.  We need to reset our "NFSv4" locking
15723  * state to match the current local locking state for this pid since
15724  * that is what the user/application sees as what the world is.
15725  *
15726  * We cannot afford to drop the open/lock seqid sync since then we can
15727  * get confused about what the current local locking state "is" versus
15728  * "was".
15729  *
15730  * If we are unable to fix up the locks, we send SIGLOST to the affected
15731  * process.  This is not done if the filesystem has been forcibly
15732  * unmounted, in case the process has already exited and a new process
15733  * exists with the same pid.
15734  */
15735 static void
15736 nfs4_reinstitute_local_lock_state(vnode_t *vp, flock64_t *lost_flp, cred_t *cr,
15737     nfs4_lock_owner_t *lop)
15738 {
15739 	locklist_t *locks, *llp, *ri_llp, *tmp_llp;
15740 	mntinfo4_t *mi = VTOMI4(vp);
15741 	const int cmd = F_SETLK;
15742 	off64_t cur_start, llp_ll_flock_end, lost_flp_end;
15743 	flock64_t ul_fl;
15744 
15745 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15746 	    "nfs4_reinstitute_local_lock_state"));
15747 
15748 	/*
15749 	 * Find active locks for this vp from the local locking code.
15750 	 * Scan through this list and find out the locks that intersect with
15751 	 * the lost lock. Once we find the lock that intersects, add the
15752 	 * intersection area as a new lock to a new list "ri_llp". The lock
15753 	 * type of the intersection region lock added to ri_llp is the same
15754 	 * as that found in the active lock list, "list". The intersecting
15755 	 * region locks are added to ri_llp in increasing l_start order.
15756 	 */
15757 	ASSERT(nfs_zone() == mi->mi_zone);
15758 
15759 	locks = flk_active_locks_for_vp(vp);
15760 	ri_llp = NULL;
15761 
15762 	for (llp = locks; llp != NULL; llp = llp->ll_next) {
15763 		ASSERT(llp->ll_vp == vp);
15764 		/*
15765 		 * Pick locks that belong to this pid/lockowner
15766 		 */
15767 		if (llp->ll_flock.l_pid != lost_flp->l_pid)
15768 			continue;
15769 
15770 		nfs4_add_lock_range(lost_flp, &llp->ll_flock, &ri_llp, vp);
15771 	}
15772 
15773 	/*
15774 	 * Now we have the list of intersections with the lost lock. These are
15775 	 * the locks that were/are active before the server replied to the
15776 	 * last/lost lock. Issue these locks to the server here. Playing these
15777 	 * locks to the server will re-establish aur current local locking state
15778 	 * with the v4 server.
15779 	 * If we get an error, send SIGLOST to the application for that lock.
15780 	 */
15781 
15782 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15783 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15784 		    "nfs4_reinstitute_local_lock_state: need to issue "
15785 		    "flock: [%"PRIx64" - %"PRIx64"] : %s",
15786 		    llp->ll_flock.l_start,
15787 		    llp->ll_flock.l_start + llp->ll_flock.l_len,
15788 		    llp->ll_flock.l_type == F_RDLCK ? "READ" :
15789 		    llp->ll_flock.l_type == F_WRLCK ? "WRITE" : "INVALID"));
15790 		/*
15791 		 * No need to relock what we already have
15792 		 */
15793 		if (llp->ll_flock.l_type == lost_flp->l_type)
15794 			continue;
15795 
15796 		push_reinstate(vp, cmd, &llp->ll_flock, cr, lop);
15797 	}
15798 
15799 	/*
15800 	 * Now keeping the start of the lost lock as our reference parse the
15801 	 * newly created ri_llp locklist to find the ranges that we have locked
15802 	 * with the v4 server but not in the current local locking. We need
15803 	 * to unlock these ranges.
15804 	 * These ranges can also be reffered to as those ranges, where the lost
15805 	 * lock does not overlap with the locks in the ri_llp but are locked
15806 	 * since the server replied to the lost lock.
15807 	 */
15808 	cur_start = lost_flp->l_start;
15809 	lost_flp_end = lock_to_end(lost_flp);
15810 
15811 	ul_fl.l_type = F_UNLCK;
15812 	ul_fl.l_whence = 0;	/* aka SEEK_SET */
15813 	ul_fl.l_sysid = lost_flp->l_sysid;
15814 	ul_fl.l_pid = lost_flp->l_pid;
15815 
15816 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15817 		llp_ll_flock_end = lock_to_end(&llp->ll_flock);
15818 
15819 		if (llp->ll_flock.l_start <= cur_start) {
15820 			cur_start = start_check(llp_ll_flock_end);
15821 			continue;
15822 		}
15823 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15824 		    "nfs4_reinstitute_local_lock_state: "
15825 		    "UNLOCK [%"PRIx64" - %"PRIx64"]",
15826 		    cur_start, llp->ll_flock.l_start));
15827 
15828 		ul_fl.l_start = cur_start;
15829 		ul_fl.l_len = end_to_len(cur_start,
15830 		    (llp->ll_flock.l_start - 1));
15831 
15832 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
15833 		cur_start = start_check(llp_ll_flock_end);
15834 	}
15835 
15836 	/*
15837 	 * In the case where the lost lock ends after all intersecting locks,
15838 	 * unlock the last part of the lost lock range.
15839 	 */
15840 	if (cur_start != start_check(lost_flp_end)) {
15841 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15842 		    "nfs4_reinstitute_local_lock_state: UNLOCK end of the "
15843 		    "lost lock region [%"PRIx64" - %"PRIx64"]",
15844 		    cur_start, lost_flp->l_start + lost_flp->l_len));
15845 
15846 		ul_fl.l_start = cur_start;
15847 		/*
15848 		 * Is it an to-EOF lock? if so unlock till the end
15849 		 */
15850 		if (lost_flp->l_len == 0)
15851 			ul_fl.l_len = 0;
15852 		else
15853 			ul_fl.l_len = start_check(lost_flp_end) - cur_start;
15854 
15855 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
15856 	}
15857 
15858 	if (locks != NULL)
15859 		flk_free_locklist(locks);
15860 
15861 	/* Free up our newly created locklist */
15862 	for (llp = ri_llp; llp != NULL; ) {
15863 		tmp_llp = llp->ll_next;
15864 		kmem_free(llp, sizeof (locklist_t));
15865 		llp = tmp_llp;
15866 	}
15867 
15868 	/*
15869 	 * Now return back to the original calling nfs4frlock()
15870 	 * and let us naturally drop our seqid syncs.
15871 	 */
15872 }
15873 
15874 /*
15875  * Create a lost state record for the given lock reinstantiation request
15876  * and push it onto the lost state queue.
15877  */
15878 static void
15879 push_reinstate(vnode_t *vp, int cmd, flock64_t *flk, cred_t *cr,
15880     nfs4_lock_owner_t *lop)
15881 {
15882 	nfs4_lost_rqst_t req;
15883 	nfs_lock_type4 locktype;
15884 	nfs4_error_t e = { EINTR, NFS4_OK, RPC_SUCCESS };
15885 
15886 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
15887 
15888 	locktype = flk_to_locktype(cmd, flk->l_type);
15889 	nfs4frlock_save_lost_rqst(NFS4_LCK_CTYPE_REINSTATE, EINTR, locktype,
15890 	    NULL, NULL, lop, flk, &req, cr, vp);
15891 	(void) nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
15892 	    (req.lr_op == OP_LOCK || req.lr_op == OP_LOCKU) ?
15893 	    &req : NULL, flk->l_type == F_UNLCK ? OP_LOCKU : OP_LOCK,
15894 	    NULL);
15895 }
15896