xref: /titanic_50/usr/src/uts/common/fs/nfs/nfs4_vnops.c (revision c869993e79c1eafbec61a56bf6cea848fe754c71)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 /*
27  *	Copyright 1983,1984,1985,1986,1987,1988,1989 AT&T.
28  *	All Rights Reserved
29  */
30 
31 #pragma ident	"%Z%%M%	%I%	%E% SMI"
32 
33 #include <sys/param.h>
34 #include <sys/types.h>
35 #include <sys/systm.h>
36 #include <sys/cred.h>
37 #include <sys/time.h>
38 #include <sys/vnode.h>
39 #include <sys/vfs.h>
40 #include <sys/vfs_opreg.h>
41 #include <sys/file.h>
42 #include <sys/filio.h>
43 #include <sys/uio.h>
44 #include <sys/buf.h>
45 #include <sys/mman.h>
46 #include <sys/pathname.h>
47 #include <sys/dirent.h>
48 #include <sys/debug.h>
49 #include <sys/vmsystm.h>
50 #include <sys/fcntl.h>
51 #include <sys/flock.h>
52 #include <sys/swap.h>
53 #include <sys/errno.h>
54 #include <sys/strsubr.h>
55 #include <sys/sysmacros.h>
56 #include <sys/kmem.h>
57 #include <sys/cmn_err.h>
58 #include <sys/pathconf.h>
59 #include <sys/utsname.h>
60 #include <sys/dnlc.h>
61 #include <sys/acl.h>
62 #include <sys/systeminfo.h>
63 #include <sys/policy.h>
64 #include <sys/sdt.h>
65 #include <sys/list.h>
66 #include <sys/stat.h>
67 
68 #include <rpc/types.h>
69 #include <rpc/auth.h>
70 #include <rpc/clnt.h>
71 
72 #include <nfs/nfs.h>
73 #include <nfs/nfs_clnt.h>
74 #include <nfs/nfs_acl.h>
75 #include <nfs/lm.h>
76 #include <nfs/nfs4.h>
77 #include <nfs/nfs4_kprot.h>
78 #include <nfs/rnode4.h>
79 #include <nfs/nfs4_clnt.h>
80 
81 #include <vm/hat.h>
82 #include <vm/as.h>
83 #include <vm/page.h>
84 #include <vm/pvn.h>
85 #include <vm/seg.h>
86 #include <vm/seg_map.h>
87 #include <vm/seg_kpm.h>
88 #include <vm/seg_vn.h>
89 
90 #include <fs/fs_subr.h>
91 
92 #include <sys/ddi.h>
93 #include <sys/int_fmtio.h>
94 
95 typedef struct {
96 	nfs4_ga_res_t	*di_garp;
97 	cred_t		*di_cred;
98 	hrtime_t	di_time_call;
99 } dirattr_info_t;
100 
101 typedef enum nfs4_acl_op {
102 	NFS4_ACL_GET,
103 	NFS4_ACL_SET
104 } nfs4_acl_op_t;
105 
106 static 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 		e.error = EIO;
5813 		goto exit;
5814 	}
5815 	garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
5816 
5817 	/*
5818 	 * The RESTOREFH may have failed
5819 	 */
5820 	if (res.array[5].nfs_resop4_u.oprestorefh.status != NFS4_OK) {
5821 		sfh4_rele(&sfhp);
5822 		e.error = EIO;
5823 		goto exit;
5824 	}
5825 
5826 	if (res.array[6].nfs_resop4_u.opnverify.status != NFS4ERR_SAME) {
5827 		/*
5828 		 * First make sure the NVERIFY failed as we expected,
5829 		 * if it didn't then be conservative and error out
5830 		 * as we can't trust the directory.
5831 		 */
5832 		if (res.array[6].nfs_resop4_u.opnverify.status != NFS4_OK) {
5833 			sfh4_rele(&sfhp);
5834 			e.error = EIO;
5835 			goto exit;
5836 		}
5837 
5838 		/*
5839 		 * We know the NVERIFY "failed" so the directory has changed,
5840 		 * so we must:
5841 		 *	purge the caches (access and indirectly dnlc if needed)
5842 		 */
5843 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5844 
5845 		if (res.array[7].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5846 			sfh4_rele(&sfhp);
5847 			goto exit;
5848 		}
5849 		nfs4_attr_cache(dvp,
5850 		    &res.array[7].nfs_resop4_u.opgetattr.ga_res,
5851 		    t, cr, FALSE, NULL);
5852 
5853 		if (res.array[8].nfs_resop4_u.opaccess.status != NFS4_OK) {
5854 			nfs4_purge_stale_fh(e.error, dvp, cr);
5855 			sfh4_rele(&sfhp);
5856 			e.error = geterrno4(res.status);
5857 			goto exit;
5858 		}
5859 
5860 		/*
5861 		 * Now we know the directory is valid,
5862 		 * cache new directory access
5863 		 */
5864 		nfs4_access_cache(drp,
5865 		    args.array[8].nfs_argop4_u.opaccess.access,
5866 		    res.array[8].nfs_resop4_u.opaccess.access, cr);
5867 
5868 		/*
5869 		 * recheck VEXEC access
5870 		 */
5871 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5872 		if (cacc != NFS4_ACCESS_ALLOWED) {
5873 			/*
5874 			 * Directory permissions might have been revoked
5875 			 */
5876 			if (cacc == NFS4_ACCESS_DENIED) {
5877 				sfh4_rele(&sfhp);
5878 				e.error = EACCES;
5879 				goto exit;
5880 			}
5881 
5882 			/*
5883 			 * Somehow we must not have asked for enough
5884 			 * so try a singleton ACCESS should never happen
5885 			 */
5886 			e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5887 			if (e.error) {
5888 				sfh4_rele(&sfhp);
5889 				goto exit;
5890 			}
5891 		}
5892 
5893 		e.error = geterrno4(res.status);
5894 	} else {
5895 		hrtime_t now;
5896 		hrtime_t delta = 0;
5897 
5898 		e.error = 0;
5899 
5900 		/*
5901 		 * Because the NVERIFY "succeeded" we know that the
5902 		 * directory attributes are still valid
5903 		 * so update r_time_attr_inval
5904 		 */
5905 		now = gethrtime();
5906 		mutex_enter(&drp->r_statelock);
5907 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
5908 			delta = now - drp->r_time_attr_saved;
5909 			if (delta < mi->mi_acdirmin)
5910 				delta = mi->mi_acdirmin;
5911 			else if (delta > mi->mi_acdirmax)
5912 				delta = mi->mi_acdirmax;
5913 		}
5914 		drp->r_time_attr_inval = now + delta;
5915 		mutex_exit(&drp->r_statelock);
5916 
5917 		/*
5918 		 * Even though we have a valid directory attr cache,
5919 		 * we may not have access.
5920 		 * This should almost always hit the cache.
5921 		 */
5922 		e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5923 		if (e.error) {
5924 			sfh4_rele(&sfhp);
5925 			goto exit;
5926 		}
5927 	}
5928 
5929 	/*
5930 	 * Now we have successfully completed the lookup, if the
5931 	 * directory has changed we now have the valid attributes.
5932 	 * We also know we have directory access.
5933 	 * Create the new rnode and insert it in the dnlc.
5934 	 */
5935 	if (isdotdot) {
5936 		e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
5937 		if (e.error) {
5938 			sfh4_rele(&sfhp);
5939 			goto exit;
5940 		}
5941 		/*
5942 		 * XXX if nfs4_make_dotdot uses an existing rnode
5943 		 * XXX it doesn't update the attributes.
5944 		 * XXX for now just save them again to save an OTW
5945 		 */
5946 		nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
5947 	} else {
5948 		nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
5949 		    dvp, fn_get(VTOSV(dvp)->sv_name, nm));
5950 	}
5951 	sfh4_rele(&sfhp);
5952 
5953 	nrp = VTOR4(nvp);
5954 	mutex_enter(&nrp->r_statev4_lock);
5955 	if (!nrp->created_v4) {
5956 		mutex_exit(&nrp->r_statev4_lock);
5957 		dnlc_update(dvp, nm, nvp);
5958 	} else
5959 		mutex_exit(&nrp->r_statev4_lock);
5960 
5961 	*vpp = nvp;
5962 
5963 exit:
5964 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5965 	kmem_free(argop, argoplist_size);
5966 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5967 	return (e.error);
5968 }
5969 
5970 #ifdef DEBUG
5971 void
5972 nfs4lookup_dump_compound(char *where, nfs_argop4 *argbase, int argcnt)
5973 {
5974 	uint_t i, len;
5975 	zoneid_t zoneid = getzoneid();
5976 	char *s;
5977 
5978 	zcmn_err(zoneid, CE_NOTE, "%s: dumping cmpd", where);
5979 	for (i = 0; i < argcnt; i++) {
5980 		nfs_argop4 *op = &argbase[i];
5981 		switch (op->argop) {
5982 		case OP_CPUTFH:
5983 		case OP_PUTFH:
5984 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putfh", i);
5985 			break;
5986 		case OP_PUTROOTFH:
5987 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putrootfh", i);
5988 			break;
5989 		case OP_CLOOKUP:
5990 			s = op->nfs_argop4_u.opclookup.cname;
5991 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
5992 			break;
5993 		case OP_LOOKUP:
5994 			s = utf8_to_str(&op->nfs_argop4_u.oplookup.objname,
5995 			    &len, NULL);
5996 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
5997 			kmem_free(s, len);
5998 			break;
5999 		case OP_LOOKUPP:
6000 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookupp ..", i);
6001 			break;
6002 		case OP_GETFH:
6003 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getfh", i);
6004 			break;
6005 		case OP_GETATTR:
6006 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getattr", i);
6007 			break;
6008 		case OP_OPENATTR:
6009 			zcmn_err(zoneid, CE_NOTE, "\t op %d, openattr", i);
6010 			break;
6011 		default:
6012 			zcmn_err(zoneid, CE_NOTE, "\t op %d, opcode %d", i,
6013 			    op->argop);
6014 			break;
6015 		}
6016 	}
6017 }
6018 #endif
6019 
6020 /*
6021  * nfs4lookup_setup - constructs a multi-lookup compound request.
6022  *
6023  * Given the path "nm1/nm2/.../nmn", the following compound requests
6024  * may be created:
6025  *
6026  * Note: Getfh is not be needed because filehandle attr is mandatory, but it
6027  * is faster, for now.
6028  *
6029  * l4_getattrs indicates the type of compound requested.
6030  *
6031  * LKP4_NO_ATTRIBUTE - no attributes (used by secinfo):
6032  *
6033  *	compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ...  Lookup {nmn} }
6034  *
6035  *   total number of ops is n + 1.
6036  *
6037  * LKP4_LAST_NAMED_ATTR - multi-component path for a named
6038  *      attribute: create lookups plus one OPENATTR/GETFH/GETATTR
6039  *      before the last component, and only get attributes
6040  *      for the last component.  Note that the second-to-last
6041  *	pathname component is XATTR_RPATH, which does NOT go
6042  *	over-the-wire as a lookup.
6043  *
6044  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Lookup {nmn-2};
6045  *		Openattr; Getfh; Getattr; Lookup {nmn}; Getfh; Getattr }
6046  *
6047  *   and total number of ops is n + 5.
6048  *
6049  * LKP4_LAST_ATTRDIR - multi-component path for the hidden named
6050  *      attribute directory: create lookups plus an OPENATTR
6051  *	replacing the last lookup.  Note that the last pathname
6052  *	component is XATTR_RPATH, which does NOT go over-the-wire
6053  *	as a lookup.
6054  *
6055  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Getfh; Getattr;
6056  *		Openattr; Getfh; Getattr }
6057  *
6058  *   and total number of ops is n + 5.
6059  *
6060  * LKP4_ALL_ATTRIBUTES - create lookups and get attributes for intermediate
6061  *	nodes too.
6062  *
6063  *	compound { Put*fh; Lookup {nm1}; Getfh; Getattr;
6064  *		Lookup {nm2}; ...  Lookup {nmn}; Getfh; Getattr }
6065  *
6066  *   and total number of ops is 3*n + 1.
6067  *
6068  * All cases: returns the index in the arg array of the final LOOKUP op, or
6069  * -1 if no LOOKUPs were used.
6070  */
6071 int
6072 nfs4lookup_setup(char *nm, lookup4_param_t *lookupargp, int needgetfh)
6073 {
6074 	enum lkp4_attr_setup l4_getattrs = lookupargp->l4_getattrs;
6075 	nfs_argop4 *argbase, *argop;
6076 	int arglen, argcnt;
6077 	int n = 1;	/* number of components */
6078 	int nga = 1;	/* number of Getattr's in request */
6079 	char c = '\0', *s, *p;
6080 	int lookup_idx = -1;
6081 	int argoplist_size;
6082 
6083 	/* set lookuparg response result to 0 */
6084 	lookupargp->resp->status = NFS4_OK;
6085 
6086 	/* skip leading "/" or "." e.g. ".//./" if there is */
6087 	for (; ; nm++) {
6088 		if (*nm != '/' && *nm != '.')
6089 			break;
6090 
6091 		/* ".." is counted as 1 component */
6092 		if (*nm == '.' && *(nm + 1) == '.')
6093 			break;
6094 	}
6095 
6096 	/*
6097 	 * Find n = number of components - nm must be null terminated
6098 	 * Skip "." components.
6099 	 */
6100 	if (*nm != '\0')
6101 		for (n = 1, s = nm; *s != '\0'; s++) {
6102 			if ((*s == '/') && (*(s + 1) != '/') &&
6103 			    (*(s + 1) != '\0') &&
6104 			    !(*(s + 1) == '.' && (*(s + 2) == '/' ||
6105 			    *(s + 2) == '\0')))
6106 				n++;
6107 		}
6108 	else
6109 		n = 0;
6110 
6111 	/*
6112 	 * nga is number of components that need Getfh+Getattr
6113 	 */
6114 	switch (l4_getattrs) {
6115 	case LKP4_NO_ATTRIBUTES:
6116 		nga = 0;
6117 		break;
6118 	case LKP4_ALL_ATTRIBUTES:
6119 		nga = n;
6120 		/*
6121 		 * Always have at least 1 getfh, getattr pair
6122 		 */
6123 		if (nga == 0)
6124 			nga++;
6125 		break;
6126 	case LKP4_LAST_ATTRDIR:
6127 	case LKP4_LAST_NAMED_ATTR:
6128 		nga = n+1;
6129 		break;
6130 	}
6131 
6132 	/*
6133 	 * If change to use the filehandle attr instead of getfh
6134 	 * the following line can be deleted.
6135 	 */
6136 	nga *= 2;
6137 
6138 	/*
6139 	 * calculate number of ops in request as
6140 	 * header + trailer + lookups + getattrs
6141 	 */
6142 	arglen = lookupargp->header_len + lookupargp->trailer_len + n + nga;
6143 
6144 	argoplist_size = arglen * sizeof (nfs_argop4);
6145 	argop = argbase = kmem_alloc(argoplist_size, KM_SLEEP);
6146 	lookupargp->argsp->array = argop;
6147 
6148 	argcnt = lookupargp->header_len;
6149 	argop += argcnt;
6150 
6151 	/*
6152 	 * loop and create a lookup op and possibly getattr/getfh for
6153 	 * each component. Skip "." components.
6154 	 */
6155 	for (s = nm; *s != '\0'; s = p) {
6156 		/*
6157 		 * Set up a pathname struct for each component if needed
6158 		 */
6159 		while (*s == '/')
6160 			s++;
6161 		if (*s == '\0')
6162 			break;
6163 
6164 		for (p = s; (*p != '/') && (*p != '\0'); p++)
6165 			;
6166 		c = *p;
6167 		*p = '\0';
6168 
6169 		if (s[0] == '.' && s[1] == '\0') {
6170 			*p = c;
6171 			continue;
6172 		}
6173 		if (l4_getattrs == LKP4_LAST_ATTRDIR &&
6174 		    strcmp(s, XATTR_RPATH) == 0) {
6175 			/* getfh XXX may not be needed in future */
6176 			argop->argop = OP_GETFH;
6177 			argop++;
6178 			argcnt++;
6179 
6180 			/* getattr */
6181 			argop->argop = OP_GETATTR;
6182 			argop->nfs_argop4_u.opgetattr.attr_request =
6183 			    lookupargp->ga_bits;
6184 			argop->nfs_argop4_u.opgetattr.mi =
6185 			    lookupargp->mi;
6186 			argop++;
6187 			argcnt++;
6188 
6189 			/* openattr */
6190 			argop->argop = OP_OPENATTR;
6191 		} else if (l4_getattrs == LKP4_LAST_NAMED_ATTR &&
6192 		    strcmp(s, XATTR_RPATH) == 0) {
6193 			/* openattr */
6194 			argop->argop = OP_OPENATTR;
6195 			argop++;
6196 			argcnt++;
6197 
6198 			/* getfh XXX may not be needed in future */
6199 			argop->argop = OP_GETFH;
6200 			argop++;
6201 			argcnt++;
6202 
6203 			/* getattr */
6204 			argop->argop = OP_GETATTR;
6205 			argop->nfs_argop4_u.opgetattr.attr_request =
6206 			    lookupargp->ga_bits;
6207 			argop->nfs_argop4_u.opgetattr.mi =
6208 			    lookupargp->mi;
6209 			argop++;
6210 			argcnt++;
6211 			*p = c;
6212 			continue;
6213 		} else if (s[0] == '.' && s[1] == '.' && s[2] == '\0') {
6214 			/* lookupp */
6215 			argop->argop = OP_LOOKUPP;
6216 		} else {
6217 			/* lookup */
6218 			argop->argop = OP_LOOKUP;
6219 			(void) str_to_utf8(s,
6220 			    &argop->nfs_argop4_u.oplookup.objname);
6221 		}
6222 		lookup_idx = argcnt;
6223 		argop++;
6224 		argcnt++;
6225 
6226 		*p = c;
6227 
6228 		if (l4_getattrs == LKP4_ALL_ATTRIBUTES) {
6229 			/* getfh XXX may not be needed in future */
6230 			argop->argop = OP_GETFH;
6231 			argop++;
6232 			argcnt++;
6233 
6234 			/* getattr */
6235 			argop->argop = OP_GETATTR;
6236 			argop->nfs_argop4_u.opgetattr.attr_request =
6237 			    lookupargp->ga_bits;
6238 			argop->nfs_argop4_u.opgetattr.mi =
6239 			    lookupargp->mi;
6240 			argop++;
6241 			argcnt++;
6242 		}
6243 	}
6244 
6245 	if ((l4_getattrs != LKP4_NO_ATTRIBUTES) &&
6246 	    ((l4_getattrs != LKP4_ALL_ATTRIBUTES) || (lookup_idx < 0))) {
6247 		if (needgetfh) {
6248 			/* stick in a post-lookup getfh */
6249 			argop->argop = OP_GETFH;
6250 			argcnt++;
6251 			argop++;
6252 		}
6253 		/* post-lookup getattr */
6254 		argop->argop = OP_GETATTR;
6255 		argop->nfs_argop4_u.opgetattr.attr_request =
6256 		    lookupargp->ga_bits;
6257 		argop->nfs_argop4_u.opgetattr.mi = lookupargp->mi;
6258 		argcnt++;
6259 	}
6260 	argcnt += lookupargp->trailer_len;	/* actual op count */
6261 	lookupargp->argsp->array_len = argcnt;
6262 	lookupargp->arglen = arglen;
6263 
6264 #ifdef DEBUG
6265 	if (nfs4_client_lookup_debug)
6266 		nfs4lookup_dump_compound("nfs4lookup_setup", argbase, argcnt);
6267 #endif
6268 
6269 	return (lookup_idx);
6270 }
6271 
6272 static int
6273 nfs4openattr(vnode_t *dvp, vnode_t **avp, int cflag, cred_t *cr)
6274 {
6275 	COMPOUND4args_clnt	args;
6276 	COMPOUND4res_clnt	res;
6277 	GETFH4res	*gf_res = NULL;
6278 	nfs_argop4	argop[4];
6279 	nfs_resop4	*resop = NULL;
6280 	nfs4_sharedfh_t *sfhp;
6281 	hrtime_t t;
6282 	nfs4_error_t	e;
6283 
6284 	rnode4_t	*drp;
6285 	int		doqueue = 1;
6286 	vnode_t		*vp;
6287 	int		needrecov = 0;
6288 	nfs4_recov_state_t recov_state;
6289 
6290 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
6291 
6292 	*avp = NULL;
6293 	recov_state.rs_flags = 0;
6294 	recov_state.rs_num_retry_despite_err = 0;
6295 
6296 recov_retry:
6297 	/* COMPOUND: putfh, openattr, getfh, getattr */
6298 	args.array_len = 4;
6299 	args.array = argop;
6300 	args.ctag = TAG_OPENATTR;
6301 
6302 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
6303 	if (e.error)
6304 		return (e.error);
6305 
6306 	drp = VTOR4(dvp);
6307 
6308 	/* putfh */
6309 	argop[0].argop = OP_CPUTFH;
6310 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6311 
6312 	/* openattr */
6313 	argop[1].argop = OP_OPENATTR;
6314 	argop[1].nfs_argop4_u.opopenattr.createdir = (cflag ? TRUE : FALSE);
6315 
6316 	/* getfh */
6317 	argop[2].argop = OP_GETFH;
6318 
6319 	/* getattr */
6320 	argop[3].argop = OP_GETATTR;
6321 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6322 	argop[3].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
6323 
6324 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
6325 	    "nfs4openattr: %s call, drp %s", needrecov ? "recov" : "first",
6326 	    rnode4info(drp)));
6327 
6328 	t = gethrtime();
6329 
6330 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
6331 
6332 	needrecov = nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp);
6333 	if (needrecov) {
6334 		bool_t abort;
6335 
6336 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
6337 		    "nfs4openattr: initiating recovery\n"));
6338 
6339 		abort = nfs4_start_recovery(&e,
6340 		    VTOMI4(dvp), dvp, NULL, NULL, NULL,
6341 		    OP_OPENATTR, NULL);
6342 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6343 		if (!e.error) {
6344 			e.error = geterrno4(res.status);
6345 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6346 		}
6347 		if (abort == FALSE)
6348 			goto recov_retry;
6349 		return (e.error);
6350 	}
6351 
6352 	if (e.error) {
6353 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6354 		return (e.error);
6355 	}
6356 
6357 	if (res.status) {
6358 		/*
6359 		 * If OTW errro is NOTSUPP, then it should be
6360 		 * translated to EINVAL.  All Solaris file system
6361 		 * implementations return EINVAL to the syscall layer
6362 		 * when the attrdir cannot be created due to an
6363 		 * implementation restriction or noxattr mount option.
6364 		 */
6365 		if (res.status == NFS4ERR_NOTSUPP) {
6366 			mutex_enter(&drp->r_statelock);
6367 			if (drp->r_xattr_dir)
6368 				VN_RELE(drp->r_xattr_dir);
6369 			VN_HOLD(NFS4_XATTR_DIR_NOTSUPP);
6370 			drp->r_xattr_dir = NFS4_XATTR_DIR_NOTSUPP;
6371 			mutex_exit(&drp->r_statelock);
6372 
6373 			e.error = EINVAL;
6374 		} else {
6375 			e.error = geterrno4(res.status);
6376 		}
6377 
6378 		if (e.error) {
6379 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6380 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
6381 			    needrecov);
6382 			return (e.error);
6383 		}
6384 	}
6385 
6386 	resop = &res.array[0];  /* putfh res */
6387 	ASSERT(resop->nfs_resop4_u.opgetfh.status == NFS4_OK);
6388 
6389 	resop = &res.array[1];  /* openattr res */
6390 	ASSERT(resop->nfs_resop4_u.opopenattr.status == NFS4_OK);
6391 
6392 	resop = &res.array[2];  /* getfh res */
6393 	gf_res = &resop->nfs_resop4_u.opgetfh;
6394 	if (gf_res->object.nfs_fh4_len == 0) {
6395 		*avp = NULL;
6396 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6397 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6398 		return (ENOENT);
6399 	}
6400 
6401 	sfhp = sfh4_get(&gf_res->object, VTOMI4(dvp));
6402 	vp = makenfs4node(sfhp, &res.array[3].nfs_resop4_u.opgetattr.ga_res,
6403 	    dvp->v_vfsp, t, cr, dvp,
6404 	    fn_get(VTOSV(dvp)->sv_name, XATTR_RPATH));
6405 	sfh4_rele(&sfhp);
6406 
6407 	if (e.error)
6408 		PURGE_ATTRCACHE4(vp);
6409 
6410 	mutex_enter(&vp->v_lock);
6411 	vp->v_flag |= V_XATTRDIR;
6412 	mutex_exit(&vp->v_lock);
6413 
6414 	*avp = vp;
6415 
6416 	mutex_enter(&drp->r_statelock);
6417 	if (drp->r_xattr_dir)
6418 		VN_RELE(drp->r_xattr_dir);
6419 	VN_HOLD(vp);
6420 	drp->r_xattr_dir = vp;
6421 
6422 	/*
6423 	 * Invalidate pathconf4 cache because r_xattr_dir is no longer
6424 	 * NULL.  xattrs could be created at any time, and we have no
6425 	 * way to update pc4_xattr_exists in the base object if/when
6426 	 * it happens.
6427 	 */
6428 	drp->r_pathconf.pc4_xattr_valid = 0;
6429 
6430 	mutex_exit(&drp->r_statelock);
6431 
6432 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6433 
6434 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6435 
6436 	return (0);
6437 }
6438 
6439 /* ARGSUSED */
6440 static int
6441 nfs4_create(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
6442 	int mode, vnode_t **vpp, cred_t *cr, int flags, caller_context_t *ct,
6443 	vsecattr_t *vsecp)
6444 {
6445 	int error;
6446 	vnode_t *vp = NULL;
6447 	rnode4_t *rp;
6448 	struct vattr vattr;
6449 	rnode4_t *drp;
6450 	vnode_t *tempvp;
6451 	enum createmode4 createmode;
6452 	bool_t must_trunc = FALSE;
6453 	int	truncating = 0;
6454 
6455 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
6456 		return (EPERM);
6457 	if (exclusive == EXCL && (dvp->v_flag & V_XATTRDIR)) {
6458 		return (EINVAL);
6459 	}
6460 
6461 	/* . and .. have special meaning in the protocol, reject them. */
6462 
6463 	if (nm[0] == '.' && (nm[1] == '\0' || (nm[1] == '.' && nm[2] == '\0')))
6464 		return (EISDIR);
6465 
6466 	drp = VTOR4(dvp);
6467 
6468 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
6469 		return (EINTR);
6470 
6471 top:
6472 	/*
6473 	 * We make a copy of the attributes because the caller does not
6474 	 * expect us to change what va points to.
6475 	 */
6476 	vattr = *va;
6477 
6478 	/*
6479 	 * If the pathname is "", then dvp is the root vnode of
6480 	 * a remote file mounted over a local directory.
6481 	 * All that needs to be done is access
6482 	 * checking and truncation.  Note that we avoid doing
6483 	 * open w/ create because the parent directory might
6484 	 * be in pseudo-fs and the open would fail.
6485 	 */
6486 	if (*nm == '\0') {
6487 		error = 0;
6488 		VN_HOLD(dvp);
6489 		vp = dvp;
6490 		must_trunc = TRUE;
6491 	} else {
6492 		/*
6493 		 * We need to go over the wire, just to be sure whether the
6494 		 * file exists or not.  Using the DNLC can be dangerous in
6495 		 * this case when making a decision regarding existence.
6496 		 */
6497 		error = nfs4lookup(dvp, nm, &vp, cr, 1);
6498 	}
6499 
6500 	if (exclusive)
6501 		createmode = EXCLUSIVE4;
6502 	else
6503 		createmode = GUARDED4;
6504 
6505 	/*
6506 	 * error would be set if the file does not exist on the
6507 	 * server, so lets go create it.
6508 	 */
6509 	if (error) {
6510 		goto create_otw;
6511 	}
6512 
6513 	/*
6514 	 * File does exist on the server
6515 	 */
6516 	if (exclusive == EXCL)
6517 		error = EEXIST;
6518 	else if (vp->v_type == VDIR && (mode & VWRITE))
6519 		error = EISDIR;
6520 	else {
6521 		/*
6522 		 * If vnode is a device, create special vnode.
6523 		 */
6524 		if (ISVDEV(vp->v_type)) {
6525 			tempvp = vp;
6526 			vp = specvp(vp, vp->v_rdev, vp->v_type, cr);
6527 			VN_RELE(tempvp);
6528 		}
6529 		if (!(error = VOP_ACCESS(vp, mode, 0, cr, ct))) {
6530 			if ((vattr.va_mask & AT_SIZE) &&
6531 			    vp->v_type == VREG) {
6532 				rp = VTOR4(vp);
6533 				/*
6534 				 * Check here for large file handled
6535 				 * by LF-unaware process (as
6536 				 * ufs_create() does)
6537 				 */
6538 				if (!(flags & FOFFMAX)) {
6539 					mutex_enter(&rp->r_statelock);
6540 					if (rp->r_size > MAXOFF32_T)
6541 						error = EOVERFLOW;
6542 					mutex_exit(&rp->r_statelock);
6543 				}
6544 
6545 				/* if error is set then we need to return */
6546 				if (error) {
6547 					nfs_rw_exit(&drp->r_rwlock);
6548 					VN_RELE(vp);
6549 					return (error);
6550 				}
6551 
6552 				if (must_trunc) {
6553 					vattr.va_mask = AT_SIZE;
6554 					error = nfs4setattr(vp, &vattr, 0, cr,
6555 					    NULL);
6556 				} else {
6557 				/*
6558 				 * we know we have a regular file that already
6559 				 * exists and we may end up truncating the file
6560 				 * as a result of the open_otw, so flush out
6561 				 * any dirty pages for this file first.
6562 				 */
6563 					if (nfs4_has_pages(vp) &&
6564 					    ((rp->r_flags & R4DIRTY) ||
6565 					    rp->r_count > 0 ||
6566 					    rp->r_mapcnt > 0)) {
6567 						error = nfs4_putpage(vp,
6568 						    (offset_t)0, 0, 0, cr, ct);
6569 						if (error && (error == ENOSPC ||
6570 						    error == EDQUOT)) {
6571 							mutex_enter(
6572 							    &rp->r_statelock);
6573 							if (!rp->r_error)
6574 								rp->r_error =
6575 								    error;
6576 							mutex_exit(
6577 							    &rp->r_statelock);
6578 						}
6579 					}
6580 					vattr.va_mask = (AT_SIZE |
6581 					    AT_TYPE | AT_MODE);
6582 					vattr.va_type = VREG;
6583 					createmode = UNCHECKED4;
6584 					truncating = 1;
6585 					goto create_otw;
6586 				}
6587 			}
6588 		}
6589 	}
6590 	nfs_rw_exit(&drp->r_rwlock);
6591 	if (error) {
6592 		VN_RELE(vp);
6593 	} else {
6594 		vnode_t *tvp;
6595 		rnode4_t *trp;
6596 		/*
6597 		 * existing file got truncated, notify.
6598 		 */
6599 		tvp = vp;
6600 		if (vp->v_type == VREG) {
6601 			trp = VTOR4(vp);
6602 			if (IS_SHADOW(vp, trp))
6603 				tvp = RTOV4(trp);
6604 		}
6605 		vnevent_create(tvp, ct);
6606 		*vpp = vp;
6607 	}
6608 	return (error);
6609 
6610 create_otw:
6611 	dnlc_remove(dvp, nm);
6612 
6613 	ASSERT(vattr.va_mask & AT_TYPE);
6614 
6615 	/*
6616 	 * If not a regular file let nfs4mknod() handle it.
6617 	 */
6618 	if (vattr.va_type != VREG) {
6619 		error = nfs4mknod(dvp, nm, &vattr, exclusive, mode, vpp, cr);
6620 		nfs_rw_exit(&drp->r_rwlock);
6621 		return (error);
6622 	}
6623 
6624 	/*
6625 	 * It _is_ a regular file.
6626 	 */
6627 	ASSERT(vattr.va_mask & AT_MODE);
6628 	if (MANDMODE(vattr.va_mode)) {
6629 		nfs_rw_exit(&drp->r_rwlock);
6630 		return (EACCES);
6631 	}
6632 
6633 	/*
6634 	 * If this happens to be a mknod of a regular file, then flags will
6635 	 * have neither FREAD or FWRITE.  However, we must set at least one
6636 	 * for the call to nfs4open_otw.  If it's open(O_CREAT) driving
6637 	 * nfs4_create, then either FREAD, FWRITE, or FRDWR has already been
6638 	 * set (based on openmode specified by app).
6639 	 */
6640 	if ((flags & (FREAD|FWRITE)) == 0)
6641 		flags |= (FREAD|FWRITE);
6642 
6643 	error = nfs4open_otw(dvp, nm, &vattr, vpp, cr, 1, flags, createmode, 0);
6644 
6645 	if (vp != NULL) {
6646 		/* if create was successful, throw away the file's pages */
6647 		if (!error && (vattr.va_mask & AT_SIZE))
6648 			nfs4_invalidate_pages(vp, (vattr.va_size & PAGEMASK),
6649 			    cr);
6650 		/* release the lookup hold */
6651 		VN_RELE(vp);
6652 		vp = NULL;
6653 	}
6654 
6655 	/*
6656 	 * validate that we opened a regular file. This handles a misbehaving
6657 	 * server that returns an incorrect FH.
6658 	 */
6659 	if ((error == 0) && *vpp && (*vpp)->v_type != VREG) {
6660 		error = EISDIR;
6661 		VN_RELE(*vpp);
6662 	}
6663 
6664 	/*
6665 	 * If this is not an exclusive create, then the CREATE
6666 	 * request will be made with the GUARDED mode set.  This
6667 	 * means that the server will return EEXIST if the file
6668 	 * exists.  The file could exist because of a retransmitted
6669 	 * request.  In this case, we recover by starting over and
6670 	 * checking to see whether the file exists.  This second
6671 	 * time through it should and a CREATE request will not be
6672 	 * sent.
6673 	 *
6674 	 * This handles the problem of a dangling CREATE request
6675 	 * which contains attributes which indicate that the file
6676 	 * should be truncated.  This retransmitted request could
6677 	 * possibly truncate valid data in the file if not caught
6678 	 * by the duplicate request mechanism on the server or if
6679 	 * not caught by other means.  The scenario is:
6680 	 *
6681 	 * Client transmits CREATE request with size = 0
6682 	 * Client times out, retransmits request.
6683 	 * Response to the first request arrives from the server
6684 	 *  and the client proceeds on.
6685 	 * Client writes data to the file.
6686 	 * The server now processes retransmitted CREATE request
6687 	 *  and truncates file.
6688 	 *
6689 	 * The use of the GUARDED CREATE request prevents this from
6690 	 * happening because the retransmitted CREATE would fail
6691 	 * with EEXIST and would not truncate the file.
6692 	 */
6693 	if (error == EEXIST && exclusive == NONEXCL) {
6694 #ifdef DEBUG
6695 		nfs4_create_misses++;
6696 #endif
6697 		goto top;
6698 	}
6699 	nfs_rw_exit(&drp->r_rwlock);
6700 	if (truncating && !error && *vpp) {
6701 		vnode_t *tvp;
6702 		rnode4_t *trp;
6703 		/*
6704 		 * existing file got truncated, notify.
6705 		 */
6706 		tvp = *vpp;
6707 		trp = VTOR4(tvp);
6708 		if (IS_SHADOW(tvp, trp))
6709 			tvp = RTOV4(trp);
6710 		vnevent_create(tvp, ct);
6711 	}
6712 	return (error);
6713 }
6714 
6715 /*
6716  * Create compound (for mkdir, mknod, symlink):
6717  * { Putfh <dfh>; Create; Getfh; Getattr }
6718  * It's okay if setattr failed to set gid - this is not considered
6719  * an error, but purge attrs in that case.
6720  */
6721 static int
6722 call_nfs4_create_req(vnode_t *dvp, char *nm, void *data, struct vattr *va,
6723     vnode_t **vpp, cred_t *cr, nfs_ftype4 type)
6724 {
6725 	int need_end_op = FALSE;
6726 	COMPOUND4args_clnt args;
6727 	COMPOUND4res_clnt res, *resp = NULL;
6728 	nfs_argop4 *argop;
6729 	nfs_resop4 *resop;
6730 	int doqueue;
6731 	mntinfo4_t *mi;
6732 	rnode4_t *drp = VTOR4(dvp);
6733 	change_info4 *cinfo;
6734 	GETFH4res *gf_res;
6735 	struct vattr vattr;
6736 	vnode_t *vp;
6737 	fattr4 *crattr;
6738 	bool_t needrecov = FALSE;
6739 	nfs4_recov_state_t recov_state;
6740 	nfs4_sharedfh_t *sfhp = NULL;
6741 	hrtime_t t;
6742 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
6743 	int numops, argoplist_size, setgid_flag, idx_create, idx_fattr;
6744 	dirattr_info_t dinfo, *dinfop;
6745 	servinfo4_t *svp;
6746 	bitmap4 supp_attrs;
6747 
6748 	ASSERT(type == NF4DIR || type == NF4LNK || type == NF4BLK ||
6749 	    type == NF4CHR || type == NF4SOCK || type == NF4FIFO);
6750 
6751 	mi = VTOMI4(dvp);
6752 
6753 	/*
6754 	 * Make sure we properly deal with setting the right gid
6755 	 * on a new directory to reflect the parent's setgid bit
6756 	 */
6757 	setgid_flag = 0;
6758 	if (type == NF4DIR) {
6759 		struct vattr dva;
6760 
6761 		va->va_mode &= ~VSGID;
6762 		dva.va_mask = AT_MODE | AT_GID;
6763 		if (VOP_GETATTR(dvp, &dva, 0, cr, NULL) == 0) {
6764 
6765 			/*
6766 			 * If the parent's directory has the setgid bit set
6767 			 * _and_ the client was able to get a valid mapping
6768 			 * for the parent dir's owner_group, we want to
6769 			 * append NVERIFY(owner_group == dva.va_gid) and
6770 			 * SETTATTR to the CREATE compound.
6771 			 */
6772 			if (mi->mi_flags & MI4_GRPID || dva.va_mode & VSGID) {
6773 				setgid_flag = 1;
6774 				va->va_mode |= VSGID;
6775 				if (dva.va_gid != GID_NOBODY) {
6776 					va->va_mask |= AT_GID;
6777 					va->va_gid = dva.va_gid;
6778 				}
6779 			}
6780 		}
6781 	}
6782 
6783 	/*
6784 	 * Create ops:
6785 	 *	0:putfh(dir) 1:savefh(dir) 2:create 3:getfh(new) 4:getattr(new)
6786 	 *	5:restorefh(dir) 6:getattr(dir)
6787 	 *
6788 	 * if (setgid)
6789 	 *	0:putfh(dir) 1:create 2:getfh(new) 3:getattr(new)
6790 	 *	4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
6791 	 *	8:nverify 9:setattr
6792 	 */
6793 	if (setgid_flag) {
6794 		numops = 10;
6795 		idx_create = 1;
6796 		idx_fattr = 3;
6797 	} else {
6798 		numops = 7;
6799 		idx_create = 2;
6800 		idx_fattr = 4;
6801 	}
6802 
6803 	ASSERT(nfs_zone() == mi->mi_zone);
6804 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp))) {
6805 		return (EINTR);
6806 	}
6807 	recov_state.rs_flags = 0;
6808 	recov_state.rs_num_retry_despite_err = 0;
6809 
6810 	argoplist_size = numops * sizeof (nfs_argop4);
6811 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
6812 
6813 recov_retry:
6814 	if (type == NF4LNK)
6815 		args.ctag = TAG_SYMLINK;
6816 	else if (type == NF4DIR)
6817 		args.ctag = TAG_MKDIR;
6818 	else
6819 		args.ctag = TAG_MKNOD;
6820 
6821 	args.array_len = numops;
6822 	args.array = argop;
6823 
6824 	if (e.error = nfs4_start_op(mi, dvp, NULL, &recov_state)) {
6825 		nfs_rw_exit(&drp->r_rwlock);
6826 		kmem_free(argop, argoplist_size);
6827 		return (e.error);
6828 	}
6829 	need_end_op = TRUE;
6830 
6831 
6832 	/* 0: putfh directory */
6833 	argop[0].argop = OP_CPUTFH;
6834 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6835 
6836 	/* 1/2: Create object */
6837 	argop[idx_create].argop = OP_CCREATE;
6838 	argop[idx_create].nfs_argop4_u.opccreate.cname = nm;
6839 	argop[idx_create].nfs_argop4_u.opccreate.type = type;
6840 	if (type == NF4LNK) {
6841 		/*
6842 		 * symlink, treat name as data
6843 		 */
6844 		ASSERT(data != NULL);
6845 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.clinkdata =
6846 		    (char *)data;
6847 	}
6848 	if (type == NF4BLK || type == NF4CHR) {
6849 		ASSERT(data != NULL);
6850 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.devdata =
6851 		    *((specdata4 *)data);
6852 	}
6853 
6854 	crattr = &argop[idx_create].nfs_argop4_u.opccreate.createattrs;
6855 
6856 	svp = drp->r_server;
6857 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
6858 	supp_attrs = svp->sv_supp_attrs;
6859 	nfs_rw_exit(&svp->sv_lock);
6860 
6861 	if (vattr_to_fattr4(va, NULL, crattr, 0, OP_CREATE, supp_attrs)) {
6862 		nfs_rw_exit(&drp->r_rwlock);
6863 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
6864 		e.error = EINVAL;
6865 		kmem_free(argop, argoplist_size);
6866 		return (e.error);
6867 	}
6868 
6869 	/* 2/3: getfh fh of created object */
6870 	ASSERT(idx_create + 1 == idx_fattr - 1);
6871 	argop[idx_create + 1].argop = OP_GETFH;
6872 
6873 	/* 3/4: getattr of new object */
6874 	argop[idx_fattr].argop = OP_GETATTR;
6875 	argop[idx_fattr].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6876 	argop[idx_fattr].nfs_argop4_u.opgetattr.mi = mi;
6877 
6878 	if (setgid_flag) {
6879 		vattr_t	_v;
6880 
6881 		argop[4].argop = OP_SAVEFH;
6882 
6883 		argop[5].argop = OP_CPUTFH;
6884 		argop[5].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6885 
6886 		argop[6].argop = OP_GETATTR;
6887 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6888 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
6889 
6890 		argop[7].argop = OP_RESTOREFH;
6891 
6892 		/*
6893 		 * nverify
6894 		 *
6895 		 * XXX - Revisit the last argument to nfs4_end_op()
6896 		 *	 once 5020486 is fixed.
6897 		 */
6898 		_v.va_mask = AT_GID;
6899 		_v.va_gid = va->va_gid;
6900 		if (e.error = nfs4args_verify(&argop[8], &_v, OP_NVERIFY,
6901 		    supp_attrs)) {
6902 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
6903 			nfs_rw_exit(&drp->r_rwlock);
6904 			nfs4_fattr4_free(crattr);
6905 			kmem_free(argop, argoplist_size);
6906 			return (e.error);
6907 		}
6908 
6909 		/*
6910 		 * setattr
6911 		 *
6912 		 * We _know_ we're not messing with AT_SIZE or AT_XTIME,
6913 		 * so no need for stateid or flags. Also we specify NULL
6914 		 * rp since we're only interested in setting owner_group
6915 		 * attributes.
6916 		 */
6917 		nfs4args_setattr(&argop[9], &_v, NULL, 0, NULL, cr, supp_attrs,
6918 		    &e.error, 0);
6919 
6920 		if (e.error) {
6921 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
6922 			nfs_rw_exit(&drp->r_rwlock);
6923 			nfs4_fattr4_free(crattr);
6924 			nfs4args_verify_free(&argop[8]);
6925 			kmem_free(argop, argoplist_size);
6926 			return (e.error);
6927 		}
6928 	} else {
6929 		argop[1].argop = OP_SAVEFH;
6930 
6931 		argop[5].argop = OP_RESTOREFH;
6932 
6933 		argop[6].argop = OP_GETATTR;
6934 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6935 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
6936 	}
6937 
6938 	dnlc_remove(dvp, nm);
6939 
6940 	doqueue = 1;
6941 	t = gethrtime();
6942 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
6943 
6944 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
6945 	if (e.error) {
6946 		PURGE_ATTRCACHE4(dvp);
6947 		if (!needrecov)
6948 			goto out;
6949 	}
6950 
6951 	if (needrecov) {
6952 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
6953 		    OP_CREATE, NULL) == FALSE) {
6954 			nfs4_end_op(mi, dvp, NULL, &recov_state,
6955 			    needrecov);
6956 			need_end_op = FALSE;
6957 			nfs4_fattr4_free(crattr);
6958 			if (setgid_flag) {
6959 				nfs4args_verify_free(&argop[8]);
6960 				nfs4args_setattr_free(&argop[9]);
6961 			}
6962 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6963 			goto recov_retry;
6964 		}
6965 	}
6966 
6967 	resp = &res;
6968 
6969 	if (res.status != NFS4_OK && res.array_len <= idx_fattr + 1) {
6970 
6971 		if (res.status == NFS4ERR_BADOWNER)
6972 			nfs4_log_badowner(mi, OP_CREATE);
6973 
6974 		e.error = geterrno4(res.status);
6975 
6976 		/*
6977 		 * This check is left over from when create was implemented
6978 		 * using a setattr op (instead of createattrs).  If the
6979 		 * putfh/create/getfh failed, the error was returned.  If
6980 		 * setattr/getattr failed, we keep going.
6981 		 *
6982 		 * It might be better to get rid of the GETFH also, and just
6983 		 * do PUTFH/CREATE/GETATTR since the FH attr is mandatory.
6984 		 * Then if any of the operations failed, we could return the
6985 		 * error now, and remove much of the error code below.
6986 		 */
6987 		if (res.array_len <= idx_fattr) {
6988 			/*
6989 			 * Either Putfh, Create or Getfh failed.
6990 			 */
6991 			PURGE_ATTRCACHE4(dvp);
6992 			/*
6993 			 * nfs4_purge_stale_fh() may generate otw calls through
6994 			 * nfs4_invalidate_pages. Hence the need to call
6995 			 * nfs4_end_op() here to avoid nfs4_start_op() deadlock.
6996 			 */
6997 			nfs4_end_op(mi, dvp, NULL, &recov_state,
6998 			    needrecov);
6999 			need_end_op = FALSE;
7000 			nfs4_purge_stale_fh(e.error, dvp, cr);
7001 			goto out;
7002 		}
7003 	}
7004 
7005 	resop = &res.array[idx_create];	/* create res */
7006 	cinfo = &resop->nfs_resop4_u.opcreate.cinfo;
7007 
7008 	resop = &res.array[idx_create + 1]; /* getfh res */
7009 	gf_res = &resop->nfs_resop4_u.opgetfh;
7010 
7011 	sfhp = sfh4_get(&gf_res->object, mi);
7012 	if (e.error) {
7013 		*vpp = vp = makenfs4node(sfhp, NULL, dvp->v_vfsp, t, cr, dvp,
7014 		    fn_get(VTOSV(dvp)->sv_name, nm));
7015 		if (vp->v_type == VNON) {
7016 			vattr.va_mask = AT_TYPE;
7017 			/*
7018 			 * Need to call nfs4_end_op before nfs4getattr to avoid
7019 			 * potential nfs4_start_op deadlock. See RFE 4777612.
7020 			 */
7021 			nfs4_end_op(mi, dvp, NULL, &recov_state,
7022 			    needrecov);
7023 			need_end_op = FALSE;
7024 			e.error = nfs4getattr(vp, &vattr, cr);
7025 			if (e.error) {
7026 				VN_RELE(vp);
7027 				*vpp = NULL;
7028 				goto out;
7029 			}
7030 			vp->v_type = vattr.va_type;
7031 		}
7032 		e.error = 0;
7033 	} else {
7034 		*vpp = vp = makenfs4node(sfhp,
7035 		    &res.array[idx_fattr].nfs_resop4_u.opgetattr.ga_res,
7036 		    dvp->v_vfsp, t, cr,
7037 		    dvp, fn_get(VTOSV(dvp)->sv_name, nm));
7038 	}
7039 
7040 	/*
7041 	 * If compound succeeded, then update dir attrs
7042 	 */
7043 	if (res.status == NFS4_OK) {
7044 		dinfo.di_garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
7045 		dinfo.di_cred = cr;
7046 		dinfo.di_time_call = t;
7047 		dinfop = &dinfo;
7048 	} else
7049 		dinfop = NULL;
7050 
7051 	/* Update directory cache attribute, readdir and dnlc caches */
7052 	nfs4_update_dircaches(cinfo, dvp, vp, nm, dinfop);
7053 
7054 out:
7055 	if (sfhp != NULL)
7056 		sfh4_rele(&sfhp);
7057 	nfs_rw_exit(&drp->r_rwlock);
7058 	nfs4_fattr4_free(crattr);
7059 	if (setgid_flag) {
7060 		nfs4args_verify_free(&argop[8]);
7061 		nfs4args_setattr_free(&argop[9]);
7062 	}
7063 	if (resp)
7064 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7065 	if (need_end_op)
7066 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
7067 
7068 	kmem_free(argop, argoplist_size);
7069 	return (e.error);
7070 }
7071 
7072 /* ARGSUSED */
7073 static int
7074 nfs4mknod(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
7075     int mode, vnode_t **vpp, cred_t *cr)
7076 {
7077 	int error;
7078 	vnode_t *vp;
7079 	nfs_ftype4 type;
7080 	specdata4 spec, *specp = NULL;
7081 
7082 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
7083 
7084 	switch (va->va_type) {
7085 	case VCHR:
7086 	case VBLK:
7087 		type = (va->va_type == VCHR) ? NF4CHR : NF4BLK;
7088 		spec.specdata1 = getmajor(va->va_rdev);
7089 		spec.specdata2 = getminor(va->va_rdev);
7090 		specp = &spec;
7091 		break;
7092 
7093 	case VFIFO:
7094 		type = NF4FIFO;
7095 		break;
7096 	case VSOCK:
7097 		type = NF4SOCK;
7098 		break;
7099 
7100 	default:
7101 		return (EINVAL);
7102 	}
7103 
7104 	error = call_nfs4_create_req(dvp, nm, specp, va, &vp, cr, type);
7105 	if (error) {
7106 		return (error);
7107 	}
7108 
7109 	/*
7110 	 * This might not be needed any more; special case to deal
7111 	 * with problematic v2/v3 servers.  Since create was unable
7112 	 * to set group correctly, not sure what hope setattr has.
7113 	 */
7114 	if (va->va_gid != VTOR4(vp)->r_attr.va_gid) {
7115 		va->va_mask = AT_GID;
7116 		(void) nfs4setattr(vp, va, 0, cr, NULL);
7117 	}
7118 
7119 	/*
7120 	 * If vnode is a device create special vnode
7121 	 */
7122 	if (ISVDEV(vp->v_type)) {
7123 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
7124 		VN_RELE(vp);
7125 	} else {
7126 		*vpp = vp;
7127 	}
7128 	return (error);
7129 }
7130 
7131 /*
7132  * Remove requires that the current fh be the target directory.
7133  * After the operation, the current fh is unchanged.
7134  * The compound op structure is:
7135  *      PUTFH(targetdir), REMOVE
7136  *
7137  * Weirdness: if the vnode to be removed is open
7138  * we rename it instead of removing it and nfs_inactive
7139  * will remove the new name.
7140  */
7141 /* ARGSUSED */
7142 static int
7143 nfs4_remove(vnode_t *dvp, char *nm, cred_t *cr, caller_context_t *ct, int flags)
7144 {
7145 	COMPOUND4args_clnt args;
7146 	COMPOUND4res_clnt res, *resp = NULL;
7147 	REMOVE4res *rm_res;
7148 	nfs_argop4 argop[3];
7149 	nfs_resop4 *resop;
7150 	vnode_t *vp;
7151 	char *tmpname;
7152 	int doqueue;
7153 	mntinfo4_t *mi;
7154 	rnode4_t *rp;
7155 	rnode4_t *drp;
7156 	int needrecov = 0;
7157 	nfs4_recov_state_t recov_state;
7158 	int isopen;
7159 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7160 	dirattr_info_t dinfo;
7161 
7162 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
7163 		return (EPERM);
7164 	drp = VTOR4(dvp);
7165 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
7166 		return (EINTR);
7167 
7168 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
7169 	if (e.error) {
7170 		nfs_rw_exit(&drp->r_rwlock);
7171 		return (e.error);
7172 	}
7173 
7174 	if (vp->v_type == VDIR) {
7175 		VN_RELE(vp);
7176 		nfs_rw_exit(&drp->r_rwlock);
7177 		return (EISDIR);
7178 	}
7179 
7180 	/*
7181 	 * First just remove the entry from the name cache, as it
7182 	 * is most likely the only entry for this vp.
7183 	 */
7184 	dnlc_remove(dvp, nm);
7185 
7186 	rp = VTOR4(vp);
7187 
7188 	/*
7189 	 * For regular file types, check to see if the file is open by looking
7190 	 * at the open streams.
7191 	 * For all other types, check the reference count on the vnode.  Since
7192 	 * they are not opened OTW they never have an open stream.
7193 	 *
7194 	 * If the file is open, rename it to .nfsXXXX.
7195 	 */
7196 	if (vp->v_type != VREG) {
7197 		/*
7198 		 * If the file has a v_count > 1 then there may be more than one
7199 		 * entry in the name cache due multiple links or an open file,
7200 		 * but we don't have the real reference count so flush all
7201 		 * possible entries.
7202 		 */
7203 		if (vp->v_count > 1)
7204 			dnlc_purge_vp(vp);
7205 
7206 		/*
7207 		 * Now we have the real reference count.
7208 		 */
7209 		isopen = vp->v_count > 1;
7210 	} else {
7211 		mutex_enter(&rp->r_os_lock);
7212 		isopen = list_head(&rp->r_open_streams) != NULL;
7213 		mutex_exit(&rp->r_os_lock);
7214 	}
7215 
7216 	mutex_enter(&rp->r_statelock);
7217 	if (isopen &&
7218 	    (rp->r_unldvp == NULL || strcmp(nm, rp->r_unlname) == 0)) {
7219 		mutex_exit(&rp->r_statelock);
7220 		tmpname = newname();
7221 		e.error = nfs4rename(dvp, nm, dvp, tmpname, cr, ct);
7222 		if (e.error)
7223 			kmem_free(tmpname, MAXNAMELEN);
7224 		else {
7225 			mutex_enter(&rp->r_statelock);
7226 			if (rp->r_unldvp == NULL) {
7227 				VN_HOLD(dvp);
7228 				rp->r_unldvp = dvp;
7229 				if (rp->r_unlcred != NULL)
7230 					crfree(rp->r_unlcred);
7231 				crhold(cr);
7232 				rp->r_unlcred = cr;
7233 				rp->r_unlname = tmpname;
7234 			} else {
7235 				kmem_free(rp->r_unlname, MAXNAMELEN);
7236 				rp->r_unlname = tmpname;
7237 			}
7238 			mutex_exit(&rp->r_statelock);
7239 		}
7240 		VN_RELE(vp);
7241 		nfs_rw_exit(&drp->r_rwlock);
7242 		return (e.error);
7243 	}
7244 	/*
7245 	 * Actually remove the file/dir
7246 	 */
7247 	mutex_exit(&rp->r_statelock);
7248 
7249 	/*
7250 	 * We need to flush any dirty pages which happen to
7251 	 * be hanging around before removing the file.
7252 	 * This shouldn't happen very often since in NFSv4
7253 	 * we should be close to open consistent.
7254 	 */
7255 	if (nfs4_has_pages(vp) &&
7256 	    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
7257 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr, ct);
7258 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
7259 			mutex_enter(&rp->r_statelock);
7260 			if (!rp->r_error)
7261 				rp->r_error = e.error;
7262 			mutex_exit(&rp->r_statelock);
7263 		}
7264 	}
7265 
7266 	mi = VTOMI4(dvp);
7267 
7268 	(void) nfs4delegreturn(rp, NFS4_DR_REOPEN);
7269 	recov_state.rs_flags = 0;
7270 	recov_state.rs_num_retry_despite_err = 0;
7271 
7272 recov_retry:
7273 	/*
7274 	 * Remove ops: putfh dir; remove
7275 	 */
7276 	args.ctag = TAG_REMOVE;
7277 	args.array_len = 3;
7278 	args.array = argop;
7279 
7280 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
7281 	if (e.error) {
7282 		nfs_rw_exit(&drp->r_rwlock);
7283 		VN_RELE(vp);
7284 		return (e.error);
7285 	}
7286 
7287 	/* putfh directory */
7288 	argop[0].argop = OP_CPUTFH;
7289 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
7290 
7291 	/* remove */
7292 	argop[1].argop = OP_CREMOVE;
7293 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
7294 
7295 	/* getattr dir */
7296 	argop[2].argop = OP_GETATTR;
7297 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7298 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
7299 
7300 	doqueue = 1;
7301 	dinfo.di_time_call = gethrtime();
7302 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
7303 
7304 	PURGE_ATTRCACHE4(vp);
7305 
7306 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
7307 	if (e.error)
7308 		PURGE_ATTRCACHE4(dvp);
7309 
7310 	if (needrecov) {
7311 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp,
7312 		    NULL, NULL, NULL, OP_REMOVE, NULL) == FALSE) {
7313 			if (!e.error)
7314 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7315 				    (caddr_t)&res);
7316 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
7317 			    needrecov);
7318 			goto recov_retry;
7319 		}
7320 	}
7321 
7322 	/*
7323 	 * Matching nfs4_end_op() for start_op() above.
7324 	 * There is a path in the code below which calls
7325 	 * nfs4_purge_stale_fh(), which may generate otw calls through
7326 	 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
7327 	 * here to avoid nfs4_start_op() deadlock.
7328 	 */
7329 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
7330 
7331 	if (!e.error) {
7332 		resp = &res;
7333 
7334 		if (res.status) {
7335 			e.error = geterrno4(res.status);
7336 			PURGE_ATTRCACHE4(dvp);
7337 			nfs4_purge_stale_fh(e.error, dvp, cr);
7338 		} else {
7339 			resop = &res.array[1];	/* remove res */
7340 			rm_res = &resop->nfs_resop4_u.opremove;
7341 
7342 			dinfo.di_garp =
7343 			    &res.array[2].nfs_resop4_u.opgetattr.ga_res;
7344 			dinfo.di_cred = cr;
7345 
7346 			/* Update directory attr, readdir and dnlc caches */
7347 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
7348 			    &dinfo);
7349 		}
7350 	}
7351 	nfs_rw_exit(&drp->r_rwlock);
7352 	if (resp)
7353 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7354 
7355 	if (e.error == 0) {
7356 		vnode_t *tvp;
7357 		rnode4_t *trp;
7358 		trp = VTOR4(vp);
7359 		tvp = vp;
7360 		if (IS_SHADOW(vp, trp))
7361 			tvp = RTOV4(trp);
7362 		vnevent_remove(tvp, dvp, nm, ct);
7363 	}
7364 	VN_RELE(vp);
7365 	return (e.error);
7366 }
7367 
7368 /*
7369  * Link requires that the current fh be the target directory and the
7370  * saved fh be the source fh. After the operation, the current fh is unchanged.
7371  * Thus the compound op structure is:
7372  *	PUTFH(file), SAVEFH, PUTFH(targetdir), LINK, RESTOREFH,
7373  *	GETATTR(file)
7374  */
7375 /* ARGSUSED */
7376 static int
7377 nfs4_link(vnode_t *tdvp, vnode_t *svp, char *tnm, cred_t *cr,
7378     caller_context_t *ct, int flags)
7379 {
7380 	COMPOUND4args_clnt args;
7381 	COMPOUND4res_clnt res, *resp = NULL;
7382 	LINK4res *ln_res;
7383 	int argoplist_size  = 7 * sizeof (nfs_argop4);
7384 	nfs_argop4 *argop;
7385 	nfs_resop4 *resop;
7386 	vnode_t *realvp, *nvp;
7387 	int doqueue;
7388 	mntinfo4_t *mi;
7389 	rnode4_t *tdrp;
7390 	bool_t needrecov = FALSE;
7391 	nfs4_recov_state_t recov_state;
7392 	hrtime_t t;
7393 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7394 	dirattr_info_t dinfo;
7395 
7396 	ASSERT(*tnm != '\0');
7397 	ASSERT(tdvp->v_type == VDIR);
7398 	ASSERT(nfs4_consistent_type(tdvp));
7399 	ASSERT(nfs4_consistent_type(svp));
7400 
7401 	if (nfs_zone() != VTOMI4(tdvp)->mi_zone)
7402 		return (EPERM);
7403 	if (VOP_REALVP(svp, &realvp, ct) == 0) {
7404 		svp = realvp;
7405 		ASSERT(nfs4_consistent_type(svp));
7406 	}
7407 
7408 	tdrp = VTOR4(tdvp);
7409 	mi = VTOMI4(svp);
7410 
7411 	if (!(mi->mi_flags & MI4_LINK)) {
7412 		return (EOPNOTSUPP);
7413 	}
7414 	recov_state.rs_flags = 0;
7415 	recov_state.rs_num_retry_despite_err = 0;
7416 
7417 	if (nfs_rw_enter_sig(&tdrp->r_rwlock, RW_WRITER, INTR4(tdvp)))
7418 		return (EINTR);
7419 
7420 recov_retry:
7421 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
7422 
7423 	args.ctag = TAG_LINK;
7424 
7425 	/*
7426 	 * Link ops: putfh fl; savefh; putfh tdir; link; getattr(dir);
7427 	 * restorefh; getattr(fl)
7428 	 */
7429 	args.array_len = 7;
7430 	args.array = argop;
7431 
7432 	e.error = nfs4_start_op(VTOMI4(svp), svp, tdvp, &recov_state);
7433 	if (e.error) {
7434 		kmem_free(argop, argoplist_size);
7435 		nfs_rw_exit(&tdrp->r_rwlock);
7436 		return (e.error);
7437 	}
7438 
7439 	/* 0. putfh file */
7440 	argop[0].argop = OP_CPUTFH;
7441 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(svp)->r_fh;
7442 
7443 	/* 1. save current fh to free up the space for the dir */
7444 	argop[1].argop = OP_SAVEFH;
7445 
7446 	/* 2. putfh targetdir */
7447 	argop[2].argop = OP_CPUTFH;
7448 	argop[2].nfs_argop4_u.opcputfh.sfh = tdrp->r_fh;
7449 
7450 	/* 3. link: current_fh is targetdir, saved_fh is source */
7451 	argop[3].argop = OP_CLINK;
7452 	argop[3].nfs_argop4_u.opclink.cnewname = tnm;
7453 
7454 	/* 4. Get attributes of dir */
7455 	argop[4].argop = OP_GETATTR;
7456 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7457 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
7458 
7459 	/* 5. If link was successful, restore current vp to file */
7460 	argop[5].argop = OP_RESTOREFH;
7461 
7462 	/* 6. Get attributes of linked object */
7463 	argop[6].argop = OP_GETATTR;
7464 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7465 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
7466 
7467 	dnlc_remove(tdvp, tnm);
7468 
7469 	doqueue = 1;
7470 	t = gethrtime();
7471 
7472 	rfs4call(VTOMI4(svp), &args, &res, cr, &doqueue, 0, &e);
7473 
7474 	needrecov = nfs4_needs_recovery(&e, FALSE, svp->v_vfsp);
7475 	if (e.error != 0 && !needrecov) {
7476 		PURGE_ATTRCACHE4(tdvp);
7477 		PURGE_ATTRCACHE4(svp);
7478 		nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7479 		goto out;
7480 	}
7481 
7482 	if (needrecov) {
7483 		bool_t abort;
7484 
7485 		abort = nfs4_start_recovery(&e, VTOMI4(svp), svp, tdvp,
7486 		    NULL, NULL, OP_LINK, NULL);
7487 		if (abort == FALSE) {
7488 			nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state,
7489 			    needrecov);
7490 			kmem_free(argop, argoplist_size);
7491 			if (!e.error)
7492 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7493 				    (caddr_t)&res);
7494 			goto recov_retry;
7495 		} else {
7496 			if (e.error != 0) {
7497 				PURGE_ATTRCACHE4(tdvp);
7498 				PURGE_ATTRCACHE4(svp);
7499 				nfs4_end_op(VTOMI4(svp), svp, tdvp,
7500 				    &recov_state, needrecov);
7501 				goto out;
7502 			}
7503 			/* fall through for res.status case */
7504 		}
7505 	}
7506 
7507 	nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7508 
7509 	resp = &res;
7510 	if (res.status) {
7511 		/* If link succeeded, then don't return error */
7512 		e.error = geterrno4(res.status);
7513 		if (res.array_len <= 4) {
7514 			/*
7515 			 * Either Putfh, Savefh, Putfh dir, or Link failed
7516 			 */
7517 			PURGE_ATTRCACHE4(svp);
7518 			PURGE_ATTRCACHE4(tdvp);
7519 			if (e.error == EOPNOTSUPP) {
7520 				mutex_enter(&mi->mi_lock);
7521 				mi->mi_flags &= ~MI4_LINK;
7522 				mutex_exit(&mi->mi_lock);
7523 			}
7524 			/* Remap EISDIR to EPERM for non-root user for SVVS */
7525 			/* XXX-LP */
7526 			if (e.error == EISDIR && crgetuid(cr) != 0)
7527 				e.error = EPERM;
7528 			goto out;
7529 		}
7530 	}
7531 
7532 	/* either no error or one of the postop getattr failed */
7533 
7534 	/*
7535 	 * XXX - if LINK succeeded, but no attrs were returned for link
7536 	 * file, purge its cache.
7537 	 *
7538 	 * XXX Perform a simplified version of wcc checking. Instead of
7539 	 * have another getattr to get pre-op, just purge cache if
7540 	 * any of the ops prior to and including the getattr failed.
7541 	 * If the getattr succeeded then update the attrcache accordingly.
7542 	 */
7543 
7544 	/*
7545 	 * update cache with link file postattrs.
7546 	 * Note: at this point resop points to link res.
7547 	 */
7548 	resop = &res.array[3];	/* link res */
7549 	ln_res = &resop->nfs_resop4_u.oplink;
7550 	if (res.status == NFS4_OK)
7551 		e.error = nfs4_update_attrcache(res.status,
7552 		    &res.array[6].nfs_resop4_u.opgetattr.ga_res,
7553 		    t, svp, cr);
7554 
7555 	/*
7556 	 * Call makenfs4node to create the new shadow vp for tnm.
7557 	 * We pass NULL attrs because we just cached attrs for
7558 	 * the src object.  All we're trying to accomplish is to
7559 	 * to create the new shadow vnode.
7560 	 */
7561 	nvp = makenfs4node(VTOR4(svp)->r_fh, NULL, tdvp->v_vfsp, t, cr,
7562 	    tdvp, fn_get(VTOSV(tdvp)->sv_name, tnm));
7563 
7564 	/* Update target cache attribute, readdir and dnlc caches */
7565 	dinfo.di_garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
7566 	dinfo.di_time_call = t;
7567 	dinfo.di_cred = cr;
7568 
7569 	nfs4_update_dircaches(&ln_res->cinfo, tdvp, nvp, tnm, &dinfo);
7570 	ASSERT(nfs4_consistent_type(tdvp));
7571 	ASSERT(nfs4_consistent_type(svp));
7572 	ASSERT(nfs4_consistent_type(nvp));
7573 	VN_RELE(nvp);
7574 
7575 	if (!e.error) {
7576 		vnode_t *tvp;
7577 		rnode4_t *trp;
7578 		/*
7579 		 * Notify the source file of this link operation.
7580 		 */
7581 		trp = VTOR4(svp);
7582 		tvp = svp;
7583 		if (IS_SHADOW(svp, trp))
7584 			tvp = RTOV4(trp);
7585 		vnevent_link(tvp, ct);
7586 	}
7587 out:
7588 	kmem_free(argop, argoplist_size);
7589 	if (resp)
7590 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7591 
7592 	nfs_rw_exit(&tdrp->r_rwlock);
7593 
7594 	return (e.error);
7595 }
7596 
7597 /* ARGSUSED */
7598 static int
7599 nfs4_rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr,
7600     caller_context_t *ct, int flags)
7601 {
7602 	vnode_t *realvp;
7603 
7604 	if (nfs_zone() != VTOMI4(odvp)->mi_zone)
7605 		return (EPERM);
7606 	if (VOP_REALVP(ndvp, &realvp, ct) == 0)
7607 		ndvp = realvp;
7608 
7609 	return (nfs4rename(odvp, onm, ndvp, nnm, cr, ct));
7610 }
7611 
7612 /*
7613  * nfs4rename does the real work of renaming in NFS Version 4.
7614  *
7615  * A file handle is considered volatile for renaming purposes if either
7616  * of the volatile bits are turned on. However, the compound may differ
7617  * based on the likelihood of the filehandle to change during rename.
7618  */
7619 static int
7620 nfs4rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr,
7621     caller_context_t *ct)
7622 {
7623 	int error;
7624 	mntinfo4_t *mi;
7625 	vnode_t *nvp = NULL;
7626 	vnode_t *ovp = NULL;
7627 	char *tmpname = NULL;
7628 	rnode4_t *rp;
7629 	rnode4_t *odrp;
7630 	rnode4_t *ndrp;
7631 	int did_link = 0;
7632 	int do_link = 1;
7633 	nfsstat4 stat = NFS4_OK;
7634 
7635 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
7636 	ASSERT(nfs4_consistent_type(odvp));
7637 	ASSERT(nfs4_consistent_type(ndvp));
7638 
7639 	if (onm[0] == '.' && (onm[1] == '\0' ||
7640 	    (onm[1] == '.' && onm[2] == '\0')))
7641 		return (EINVAL);
7642 
7643 	if (nnm[0] == '.' && (nnm[1] == '\0' ||
7644 	    (nnm[1] == '.' && nnm[2] == '\0')))
7645 		return (EINVAL);
7646 
7647 	odrp = VTOR4(odvp);
7648 	ndrp = VTOR4(ndvp);
7649 	if ((intptr_t)odrp < (intptr_t)ndrp) {
7650 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp)))
7651 			return (EINTR);
7652 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp))) {
7653 			nfs_rw_exit(&odrp->r_rwlock);
7654 			return (EINTR);
7655 		}
7656 	} else {
7657 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp)))
7658 			return (EINTR);
7659 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp))) {
7660 			nfs_rw_exit(&ndrp->r_rwlock);
7661 			return (EINTR);
7662 		}
7663 	}
7664 
7665 	/*
7666 	 * Lookup the target file.  If it exists, it needs to be
7667 	 * checked to see whether it is a mount point and whether
7668 	 * it is active (open).
7669 	 */
7670 	error = nfs4lookup(ndvp, nnm, &nvp, cr, 0);
7671 	if (!error) {
7672 		int	isactive;
7673 
7674 		ASSERT(nfs4_consistent_type(nvp));
7675 		/*
7676 		 * If this file has been mounted on, then just
7677 		 * return busy because renaming to it would remove
7678 		 * the mounted file system from the name space.
7679 		 */
7680 		if (vn_ismntpt(nvp)) {
7681 			VN_RELE(nvp);
7682 			nfs_rw_exit(&odrp->r_rwlock);
7683 			nfs_rw_exit(&ndrp->r_rwlock);
7684 			return (EBUSY);
7685 		}
7686 
7687 		/*
7688 		 * First just remove the entry from the name cache, as it
7689 		 * is most likely the only entry for this vp.
7690 		 */
7691 		dnlc_remove(ndvp, nnm);
7692 
7693 		rp = VTOR4(nvp);
7694 
7695 		if (nvp->v_type != VREG) {
7696 			/*
7697 			 * Purge the name cache of all references to this vnode
7698 			 * so that we can check the reference count to infer
7699 			 * whether it is active or not.
7700 			 */
7701 			if (nvp->v_count > 1)
7702 				dnlc_purge_vp(nvp);
7703 
7704 			isactive = nvp->v_count > 1;
7705 		} else {
7706 			mutex_enter(&rp->r_os_lock);
7707 			isactive = list_head(&rp->r_open_streams) != NULL;
7708 			mutex_exit(&rp->r_os_lock);
7709 		}
7710 
7711 		/*
7712 		 * If the vnode is active and is not a directory,
7713 		 * arrange to rename it to a
7714 		 * temporary file so that it will continue to be
7715 		 * accessible.  This implements the "unlink-open-file"
7716 		 * semantics for the target of a rename operation.
7717 		 * Before doing this though, make sure that the
7718 		 * source and target files are not already the same.
7719 		 */
7720 		if (isactive && nvp->v_type != VDIR) {
7721 			/*
7722 			 * Lookup the source name.
7723 			 */
7724 			error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7725 
7726 			/*
7727 			 * The source name *should* already exist.
7728 			 */
7729 			if (error) {
7730 				VN_RELE(nvp);
7731 				nfs_rw_exit(&odrp->r_rwlock);
7732 				nfs_rw_exit(&ndrp->r_rwlock);
7733 				return (error);
7734 			}
7735 
7736 			ASSERT(nfs4_consistent_type(ovp));
7737 
7738 			/*
7739 			 * Compare the two vnodes.  If they are the same,
7740 			 * just release all held vnodes and return success.
7741 			 */
7742 			if (VN_CMP(ovp, nvp)) {
7743 				VN_RELE(ovp);
7744 				VN_RELE(nvp);
7745 				nfs_rw_exit(&odrp->r_rwlock);
7746 				nfs_rw_exit(&ndrp->r_rwlock);
7747 				return (0);
7748 			}
7749 
7750 			/*
7751 			 * Can't mix and match directories and non-
7752 			 * directories in rename operations.  We already
7753 			 * know that the target is not a directory.  If
7754 			 * the source is a directory, return an error.
7755 			 */
7756 			if (ovp->v_type == VDIR) {
7757 				VN_RELE(ovp);
7758 				VN_RELE(nvp);
7759 				nfs_rw_exit(&odrp->r_rwlock);
7760 				nfs_rw_exit(&ndrp->r_rwlock);
7761 				return (ENOTDIR);
7762 			}
7763 link_call:
7764 			/*
7765 			 * The target file exists, is not the same as
7766 			 * the source file, and is active.  We first
7767 			 * try to Link it to a temporary filename to
7768 			 * avoid having the server removing the file
7769 			 * completely (which could cause data loss to
7770 			 * the user's POV in the event the Rename fails
7771 			 * -- see bug 1165874).
7772 			 */
7773 			/*
7774 			 * The do_link and did_link booleans are
7775 			 * introduced in the event we get NFS4ERR_FILE_OPEN
7776 			 * returned for the Rename.  Some servers can
7777 			 * not Rename over an Open file, so they return
7778 			 * this error.  The client needs to Remove the
7779 			 * newly created Link and do two Renames, just
7780 			 * as if the server didn't support LINK.
7781 			 */
7782 			tmpname = newname();
7783 			error = 0;
7784 
7785 			if (do_link) {
7786 				error = nfs4_link(ndvp, nvp, tmpname, cr,
7787 				    NULL, 0);
7788 			}
7789 			if (error == EOPNOTSUPP || !do_link) {
7790 				error = nfs4_rename(ndvp, nnm, ndvp, tmpname,
7791 				    cr, NULL, 0);
7792 				did_link = 0;
7793 			} else {
7794 				did_link = 1;
7795 			}
7796 			if (error) {
7797 				kmem_free(tmpname, MAXNAMELEN);
7798 				VN_RELE(ovp);
7799 				VN_RELE(nvp);
7800 				nfs_rw_exit(&odrp->r_rwlock);
7801 				nfs_rw_exit(&ndrp->r_rwlock);
7802 				return (error);
7803 			}
7804 
7805 			mutex_enter(&rp->r_statelock);
7806 			if (rp->r_unldvp == NULL) {
7807 				VN_HOLD(ndvp);
7808 				rp->r_unldvp = ndvp;
7809 				if (rp->r_unlcred != NULL)
7810 					crfree(rp->r_unlcred);
7811 				crhold(cr);
7812 				rp->r_unlcred = cr;
7813 				rp->r_unlname = tmpname;
7814 			} else {
7815 				if (rp->r_unlname)
7816 					kmem_free(rp->r_unlname, MAXNAMELEN);
7817 				rp->r_unlname = tmpname;
7818 			}
7819 			mutex_exit(&rp->r_statelock);
7820 		}
7821 
7822 		(void) nfs4delegreturn(VTOR4(nvp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7823 
7824 		ASSERT(nfs4_consistent_type(nvp));
7825 	}
7826 
7827 	if (ovp == NULL) {
7828 		/*
7829 		 * When renaming directories to be a subdirectory of a
7830 		 * different parent, the dnlc entry for ".." will no
7831 		 * longer be valid, so it must be removed.
7832 		 *
7833 		 * We do a lookup here to determine whether we are renaming
7834 		 * a directory and we need to check if we are renaming
7835 		 * an unlinked file.  This might have already been done
7836 		 * in previous code, so we check ovp == NULL to avoid
7837 		 * doing it twice.
7838 		 */
7839 		error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7840 		/*
7841 		 * The source name *should* already exist.
7842 		 */
7843 		if (error) {
7844 			nfs_rw_exit(&odrp->r_rwlock);
7845 			nfs_rw_exit(&ndrp->r_rwlock);
7846 			if (nvp) {
7847 				VN_RELE(nvp);
7848 			}
7849 			return (error);
7850 		}
7851 		ASSERT(ovp != NULL);
7852 		ASSERT(nfs4_consistent_type(ovp));
7853 	}
7854 
7855 	/*
7856 	 * Is the object being renamed a dir, and if so, is
7857 	 * it being renamed to a child of itself?  The underlying
7858 	 * fs should ultimately return EINVAL for this case;
7859 	 * however, buggy beta non-Solaris NFSv4 servers at
7860 	 * interop testing events have allowed this behavior,
7861 	 * and it caused our client to panic due to a recursive
7862 	 * mutex_enter in fn_move.
7863 	 *
7864 	 * The tedious locking in fn_move could be changed to
7865 	 * deal with this case, and the client could avoid the
7866 	 * panic; however, the client would just confuse itself
7867 	 * later and misbehave.  A better way to handle the broken
7868 	 * server is to detect this condition and return EINVAL
7869 	 * without ever sending the the bogus rename to the server.
7870 	 * We know the rename is invalid -- just fail it now.
7871 	 */
7872 	if (ovp->v_type == VDIR && VN_CMP(ndvp, ovp)) {
7873 		VN_RELE(ovp);
7874 		nfs_rw_exit(&odrp->r_rwlock);
7875 		nfs_rw_exit(&ndrp->r_rwlock);
7876 		if (nvp) {
7877 			VN_RELE(nvp);
7878 		}
7879 		return (EINVAL);
7880 	}
7881 
7882 	(void) nfs4delegreturn(VTOR4(ovp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7883 
7884 	/*
7885 	 * If FH4_VOL_RENAME or FH4_VOLATILE_ANY bits are set, it is
7886 	 * possible for the filehandle to change due to the rename.
7887 	 * If neither of these bits is set, but FH4_VOL_MIGRATION is set,
7888 	 * the fh will not change because of the rename, but we still need
7889 	 * to update its rnode entry with the new name for
7890 	 * an eventual fh change due to migration. The FH4_NOEXPIRE_ON_OPEN
7891 	 * has no effect on these for now, but for future improvements,
7892 	 * we might want to use it too to simplify handling of files
7893 	 * that are open with that flag on. (XXX)
7894 	 */
7895 	mi = VTOMI4(odvp);
7896 	if (NFS4_VOLATILE_FH(mi))
7897 		error = nfs4rename_volatile_fh(odvp, onm, ovp, ndvp, nnm, cr,
7898 		    &stat);
7899 	else
7900 		error = nfs4rename_persistent_fh(odvp, onm, ovp, ndvp, nnm, cr,
7901 		    &stat);
7902 
7903 	ASSERT(nfs4_consistent_type(odvp));
7904 	ASSERT(nfs4_consistent_type(ndvp));
7905 	ASSERT(nfs4_consistent_type(ovp));
7906 
7907 	if (stat == NFS4ERR_FILE_OPEN && did_link) {
7908 		do_link = 0;
7909 		/*
7910 		 * Before the 'link_call' code, we did a nfs4_lookup
7911 		 * that puts a VN_HOLD on nvp.  After the nfs4_link
7912 		 * call we call VN_RELE to match that hold.  We need
7913 		 * to place an additional VN_HOLD here since we will
7914 		 * be hitting that VN_RELE again.
7915 		 */
7916 		VN_HOLD(nvp);
7917 
7918 		(void) nfs4_remove(ndvp, tmpname, cr, NULL, 0);
7919 
7920 		/* Undo the unlinked file naming stuff we just did */
7921 		mutex_enter(&rp->r_statelock);
7922 		if (rp->r_unldvp) {
7923 			VN_RELE(ndvp);
7924 			rp->r_unldvp = NULL;
7925 			if (rp->r_unlcred != NULL)
7926 				crfree(rp->r_unlcred);
7927 			rp->r_unlcred = NULL;
7928 			/* rp->r_unlanme points to tmpname */
7929 			if (rp->r_unlname)
7930 				kmem_free(rp->r_unlname, MAXNAMELEN);
7931 			rp->r_unlname = NULL;
7932 		}
7933 		mutex_exit(&rp->r_statelock);
7934 
7935 		if (nvp) {
7936 			VN_RELE(nvp);
7937 		}
7938 		goto link_call;
7939 	}
7940 
7941 	if (error) {
7942 		VN_RELE(ovp);
7943 		nfs_rw_exit(&odrp->r_rwlock);
7944 		nfs_rw_exit(&ndrp->r_rwlock);
7945 		if (nvp) {
7946 			VN_RELE(nvp);
7947 		}
7948 		return (error);
7949 	}
7950 
7951 	/*
7952 	 * when renaming directories to be a subdirectory of a
7953 	 * different parent, the dnlc entry for ".." will no
7954 	 * longer be valid, so it must be removed
7955 	 */
7956 	rp = VTOR4(ovp);
7957 	if (ndvp != odvp) {
7958 		if (ovp->v_type == VDIR) {
7959 			dnlc_remove(ovp, "..");
7960 			if (rp->r_dir != NULL)
7961 				nfs4_purge_rddir_cache(ovp);
7962 		}
7963 	}
7964 
7965 	/*
7966 	 * If we are renaming the unlinked file, update the
7967 	 * r_unldvp and r_unlname as needed.
7968 	 */
7969 	mutex_enter(&rp->r_statelock);
7970 	if (rp->r_unldvp != NULL) {
7971 		if (strcmp(rp->r_unlname, onm) == 0) {
7972 			(void) strncpy(rp->r_unlname, nnm, MAXNAMELEN);
7973 			rp->r_unlname[MAXNAMELEN - 1] = '\0';
7974 			if (ndvp != rp->r_unldvp) {
7975 				VN_RELE(rp->r_unldvp);
7976 				rp->r_unldvp = ndvp;
7977 				VN_HOLD(ndvp);
7978 			}
7979 		}
7980 	}
7981 	mutex_exit(&rp->r_statelock);
7982 
7983 	/*
7984 	 * Notify the rename vnevents to source vnode, and to the target
7985 	 * vnode if it already existed.
7986 	 */
7987 	if (error == 0) {
7988 		vnode_t *tvp;
7989 		rnode4_t *trp;
7990 		/*
7991 		 * Notify the vnode. Each links is represented by
7992 		 * a different vnode, in nfsv4.
7993 		 */
7994 		if (nvp) {
7995 			trp = VTOR4(nvp);
7996 			tvp = nvp;
7997 			if (IS_SHADOW(nvp, trp))
7998 				tvp = RTOV4(trp);
7999 			vnevent_rename_dest(tvp, ndvp, nnm, ct);
8000 		}
8001 
8002 		/*
8003 		 * if the source and destination directory are not the
8004 		 * same notify the destination directory.
8005 		 */
8006 		if (VTOR4(odvp) != VTOR4(ndvp)) {
8007 			trp = VTOR4(ndvp);
8008 			tvp = ndvp;
8009 			if (IS_SHADOW(ndvp, trp))
8010 				tvp = RTOV4(trp);
8011 			vnevent_rename_dest_dir(tvp, ct);
8012 		}
8013 
8014 		trp = VTOR4(ovp);
8015 		tvp = ovp;
8016 		if (IS_SHADOW(ovp, trp))
8017 			tvp = RTOV4(trp);
8018 		vnevent_rename_src(tvp, odvp, onm, ct);
8019 	}
8020 
8021 	if (nvp) {
8022 		VN_RELE(nvp);
8023 	}
8024 	VN_RELE(ovp);
8025 
8026 	nfs_rw_exit(&odrp->r_rwlock);
8027 	nfs_rw_exit(&ndrp->r_rwlock);
8028 
8029 	return (error);
8030 }
8031 
8032 /*
8033  * nfs4rename_persistent does the otw portion of renaming in NFS Version 4,
8034  * when it is known that the filehandle is persistent through rename.
8035  *
8036  * Rename requires that the current fh be the target directory and the
8037  * saved fh be the source directory. After the operation, the current fh
8038  * is unchanged.
8039  * The compound op structure for persistent fh rename is:
8040  *      PUTFH(sourcdir), SAVEFH, PUTFH(targetdir), RENAME
8041  * Rather than bother with the directory postop args, we'll simply
8042  * update that a change occurred in the cache, so no post-op getattrs.
8043  */
8044 static int
8045 nfs4rename_persistent_fh(vnode_t *odvp, char *onm, vnode_t *renvp,
8046     vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
8047 {
8048 	COMPOUND4args_clnt args;
8049 	COMPOUND4res_clnt res, *resp = NULL;
8050 	nfs_argop4 *argop;
8051 	nfs_resop4 *resop;
8052 	int doqueue, argoplist_size;
8053 	mntinfo4_t *mi;
8054 	rnode4_t *odrp = VTOR4(odvp);
8055 	rnode4_t *ndrp = VTOR4(ndvp);
8056 	RENAME4res *rn_res;
8057 	bool_t needrecov;
8058 	nfs4_recov_state_t recov_state;
8059 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8060 	dirattr_info_t dinfo, *dinfop;
8061 
8062 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
8063 
8064 	recov_state.rs_flags = 0;
8065 	recov_state.rs_num_retry_despite_err = 0;
8066 
8067 	/*
8068 	 * Rename ops: putfh sdir; savefh; putfh tdir; rename; getattr tdir
8069 	 *
8070 	 * If source/target are different dirs, then append putfh(src); getattr
8071 	 */
8072 	args.array_len = (odvp == ndvp) ? 5 : 7;
8073 	argoplist_size = args.array_len * sizeof (nfs_argop4);
8074 	args.array = argop = kmem_alloc(argoplist_size, KM_SLEEP);
8075 
8076 recov_retry:
8077 	*statp = NFS4_OK;
8078 
8079 	/* No need to Lookup the file, persistent fh */
8080 	args.ctag = TAG_RENAME;
8081 
8082 	mi = VTOMI4(odvp);
8083 	e.error = nfs4_start_op(mi, odvp, ndvp, &recov_state);
8084 	if (e.error) {
8085 		kmem_free(argop, argoplist_size);
8086 		return (e.error);
8087 	}
8088 
8089 	/* 0: putfh source directory */
8090 	argop[0].argop = OP_CPUTFH;
8091 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8092 
8093 	/* 1: Save source fh to free up current for target */
8094 	argop[1].argop = OP_SAVEFH;
8095 
8096 	/* 2: putfh targetdir */
8097 	argop[2].argop = OP_CPUTFH;
8098 	argop[2].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8099 
8100 	/* 3: current_fh is targetdir, saved_fh is sourcedir */
8101 	argop[3].argop = OP_CRENAME;
8102 	argop[3].nfs_argop4_u.opcrename.coldname = onm;
8103 	argop[3].nfs_argop4_u.opcrename.cnewname = nnm;
8104 
8105 	/* 4: getattr (targetdir) */
8106 	argop[4].argop = OP_GETATTR;
8107 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8108 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
8109 
8110 	if (ndvp != odvp) {
8111 
8112 		/* 5: putfh (sourcedir) */
8113 		argop[5].argop = OP_CPUTFH;
8114 		argop[5].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8115 
8116 		/* 6: getattr (sourcedir) */
8117 		argop[6].argop = OP_GETATTR;
8118 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8119 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
8120 	}
8121 
8122 	dnlc_remove(odvp, onm);
8123 	dnlc_remove(ndvp, nnm);
8124 
8125 	doqueue = 1;
8126 	dinfo.di_time_call = gethrtime();
8127 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8128 
8129 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8130 	if (e.error) {
8131 		PURGE_ATTRCACHE4(odvp);
8132 		PURGE_ATTRCACHE4(ndvp);
8133 	} else {
8134 		*statp = res.status;
8135 	}
8136 
8137 	if (needrecov) {
8138 		if (nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8139 		    OP_RENAME, NULL) == FALSE) {
8140 			nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
8141 			if (!e.error)
8142 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8143 				    (caddr_t)&res);
8144 			goto recov_retry;
8145 		}
8146 	}
8147 
8148 	if (!e.error) {
8149 		resp = &res;
8150 		/*
8151 		 * as long as OP_RENAME
8152 		 */
8153 		if (res.status != NFS4_OK && res.array_len <= 4) {
8154 			e.error = geterrno4(res.status);
8155 			PURGE_ATTRCACHE4(odvp);
8156 			PURGE_ATTRCACHE4(ndvp);
8157 			/*
8158 			 * System V defines rename to return EEXIST, not
8159 			 * ENOTEMPTY if the target directory is not empty.
8160 			 * Over the wire, the error is NFSERR_ENOTEMPTY
8161 			 * which geterrno4 maps to ENOTEMPTY.
8162 			 */
8163 			if (e.error == ENOTEMPTY)
8164 				e.error = EEXIST;
8165 		} else {
8166 
8167 			resop = &res.array[3];	/* rename res */
8168 			rn_res = &resop->nfs_resop4_u.oprename;
8169 
8170 			if (res.status == NFS4_OK) {
8171 				/*
8172 				 * Update target attribute, readdir and dnlc
8173 				 * caches.
8174 				 */
8175 				dinfo.di_garp =
8176 				    &res.array[4].nfs_resop4_u.opgetattr.ga_res;
8177 				dinfo.di_cred = cr;
8178 				dinfop = &dinfo;
8179 			} else
8180 				dinfop = NULL;
8181 
8182 			nfs4_update_dircaches(&rn_res->target_cinfo,
8183 			    ndvp, NULL, NULL, dinfop);
8184 
8185 			/*
8186 			 * Update source attribute, readdir and dnlc caches
8187 			 *
8188 			 */
8189 			if (ndvp != odvp) {
8190 				if (dinfop)
8191 					dinfo.di_garp =
8192 					    &(res.array[6].nfs_resop4_u.
8193 					    opgetattr.ga_res);
8194 
8195 				nfs4_update_dircaches(&rn_res->source_cinfo,
8196 				    odvp, NULL, NULL, dinfop);
8197 			}
8198 
8199 			fn_move(VTOSV(renvp)->sv_name, VTOSV(ndvp)->sv_name,
8200 			    nnm);
8201 		}
8202 	}
8203 
8204 	if (resp)
8205 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8206 	nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
8207 	kmem_free(argop, argoplist_size);
8208 
8209 	return (e.error);
8210 }
8211 
8212 /*
8213  * nfs4rename_volatile_fh does the otw part of renaming in NFS Version 4, when
8214  * it is possible for the filehandle to change due to the rename.
8215  *
8216  * The compound req in this case includes a post-rename lookup and getattr
8217  * to ensure that we have the correct fh and attributes for the object.
8218  *
8219  * Rename requires that the current fh be the target directory and the
8220  * saved fh be the source directory. After the operation, the current fh
8221  * is unchanged.
8222  *
8223  * We need the new filehandle (hence a LOOKUP and GETFH) so that we can
8224  * update the filehandle for the renamed object.  We also get the old
8225  * filehandle for historical reasons; this should be taken out sometime.
8226  * This results in a rather cumbersome compound...
8227  *
8228  *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8229  *    PUTFH(targetdir), RENAME, LOOKUP(trgt), GETFH(new), GETATTR
8230  *
8231  */
8232 static int
8233 nfs4rename_volatile_fh(vnode_t *odvp, char *onm, vnode_t *ovp,
8234     vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
8235 {
8236 	COMPOUND4args_clnt args;
8237 	COMPOUND4res_clnt res, *resp = NULL;
8238 	int argoplist_size;
8239 	nfs_argop4 *argop;
8240 	nfs_resop4 *resop;
8241 	int doqueue;
8242 	mntinfo4_t *mi;
8243 	rnode4_t *odrp = VTOR4(odvp);	/* old directory */
8244 	rnode4_t *ndrp = VTOR4(ndvp);	/* new directory */
8245 	rnode4_t *orp = VTOR4(ovp);	/* object being renamed */
8246 	RENAME4res *rn_res;
8247 	GETFH4res *ngf_res;
8248 	bool_t needrecov;
8249 	nfs4_recov_state_t recov_state;
8250 	hrtime_t t;
8251 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8252 	dirattr_info_t dinfo, *dinfop = &dinfo;
8253 
8254 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
8255 
8256 	recov_state.rs_flags = 0;
8257 	recov_state.rs_num_retry_despite_err = 0;
8258 
8259 recov_retry:
8260 	*statp = NFS4_OK;
8261 
8262 	/*
8263 	 * There is a window between the RPC and updating the path and
8264 	 * filehandle stored in the rnode.  Lock out the FHEXPIRED recovery
8265 	 * code, so that it doesn't try to use the old path during that
8266 	 * window.
8267 	 */
8268 	mutex_enter(&orp->r_statelock);
8269 	while (orp->r_flags & R4RECEXPFH) {
8270 		klwp_t *lwp = ttolwp(curthread);
8271 
8272 		if (lwp != NULL)
8273 			lwp->lwp_nostop++;
8274 		if (cv_wait_sig(&orp->r_cv, &orp->r_statelock) == 0) {
8275 			mutex_exit(&orp->r_statelock);
8276 			if (lwp != NULL)
8277 				lwp->lwp_nostop--;
8278 			return (EINTR);
8279 		}
8280 		if (lwp != NULL)
8281 			lwp->lwp_nostop--;
8282 	}
8283 	orp->r_flags |= R4RECEXPFH;
8284 	mutex_exit(&orp->r_statelock);
8285 
8286 	mi = VTOMI4(odvp);
8287 
8288 	args.ctag = TAG_RENAME_VFH;
8289 	args.array_len = (odvp == ndvp) ? 10 : 12;
8290 	argoplist_size  = args.array_len * sizeof (nfs_argop4);
8291 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
8292 
8293 	/*
8294 	 * Rename ops:
8295 	 *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8296 	 *    PUTFH(targetdir), RENAME, GETATTR(targetdir)
8297 	 *    LOOKUP(trgt), GETFH(new), GETATTR,
8298 	 *
8299 	 *    if (odvp != ndvp)
8300 	 *	add putfh(sourcedir), getattr(sourcedir) }
8301 	 */
8302 	args.array = argop;
8303 
8304 	e.error = nfs4_start_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8305 	    &recov_state, NULL);
8306 	if (e.error) {
8307 		kmem_free(argop, argoplist_size);
8308 		mutex_enter(&orp->r_statelock);
8309 		orp->r_flags &= ~R4RECEXPFH;
8310 		cv_broadcast(&orp->r_cv);
8311 		mutex_exit(&orp->r_statelock);
8312 		return (e.error);
8313 	}
8314 
8315 	/* 0: putfh source directory */
8316 	argop[0].argop = OP_CPUTFH;
8317 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8318 
8319 	/* 1: Save source fh to free up current for target */
8320 	argop[1].argop = OP_SAVEFH;
8321 
8322 	/* 2: Lookup pre-rename fh of renamed object */
8323 	argop[2].argop = OP_CLOOKUP;
8324 	argop[2].nfs_argop4_u.opclookup.cname = onm;
8325 
8326 	/* 3: getfh fh of renamed object (before rename) */
8327 	argop[3].argop = OP_GETFH;
8328 
8329 	/* 4: putfh targetdir */
8330 	argop[4].argop = OP_CPUTFH;
8331 	argop[4].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8332 
8333 	/* 5: current_fh is targetdir, saved_fh is sourcedir */
8334 	argop[5].argop = OP_CRENAME;
8335 	argop[5].nfs_argop4_u.opcrename.coldname = onm;
8336 	argop[5].nfs_argop4_u.opcrename.cnewname = nnm;
8337 
8338 	/* 6: getattr of target dir (post op attrs) */
8339 	argop[6].argop = OP_GETATTR;
8340 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8341 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
8342 
8343 	/* 7: Lookup post-rename fh of renamed object */
8344 	argop[7].argop = OP_CLOOKUP;
8345 	argop[7].nfs_argop4_u.opclookup.cname = nnm;
8346 
8347 	/* 8: getfh fh of renamed object (after rename) */
8348 	argop[8].argop = OP_GETFH;
8349 
8350 	/* 9: getattr of renamed object */
8351 	argop[9].argop = OP_GETATTR;
8352 	argop[9].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8353 	argop[9].nfs_argop4_u.opgetattr.mi = mi;
8354 
8355 	/*
8356 	 * If source/target dirs are different, then get new post-op
8357 	 * attrs for source dir also.
8358 	 */
8359 	if (ndvp != odvp) {
8360 		/* 10: putfh (sourcedir) */
8361 		argop[10].argop = OP_CPUTFH;
8362 		argop[10].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8363 
8364 		/* 11: getattr (sourcedir) */
8365 		argop[11].argop = OP_GETATTR;
8366 		argop[11].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8367 		argop[11].nfs_argop4_u.opgetattr.mi = mi;
8368 	}
8369 
8370 	dnlc_remove(odvp, onm);
8371 	dnlc_remove(ndvp, nnm);
8372 
8373 	doqueue = 1;
8374 	t = gethrtime();
8375 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8376 
8377 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8378 	if (e.error) {
8379 		PURGE_ATTRCACHE4(odvp);
8380 		PURGE_ATTRCACHE4(ndvp);
8381 		if (!needrecov) {
8382 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8383 			    &recov_state, needrecov);
8384 			goto out;
8385 		}
8386 	} else {
8387 		*statp = res.status;
8388 	}
8389 
8390 	if (needrecov) {
8391 		bool_t abort;
8392 
8393 		abort = nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8394 		    OP_RENAME, NULL);
8395 		if (abort == FALSE) {
8396 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8397 			    &recov_state, needrecov);
8398 			kmem_free(argop, argoplist_size);
8399 			if (!e.error)
8400 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8401 				    (caddr_t)&res);
8402 			mutex_enter(&orp->r_statelock);
8403 			orp->r_flags &= ~R4RECEXPFH;
8404 			cv_broadcast(&orp->r_cv);
8405 			mutex_exit(&orp->r_statelock);
8406 			goto recov_retry;
8407 		} else {
8408 			if (e.error != 0) {
8409 				nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8410 				    &recov_state, needrecov);
8411 				goto out;
8412 			}
8413 			/* fall through for res.status case */
8414 		}
8415 	}
8416 
8417 	resp = &res;
8418 	/*
8419 	 * If OP_RENAME (or any prev op) failed, then return an error.
8420 	 * OP_RENAME is index 5, so if array len <= 6 we return an error.
8421 	 */
8422 	if ((res.status != NFS4_OK) && (res.array_len <= 6)) {
8423 		/*
8424 		 * Error in an op other than last Getattr
8425 		 */
8426 		e.error = geterrno4(res.status);
8427 		PURGE_ATTRCACHE4(odvp);
8428 		PURGE_ATTRCACHE4(ndvp);
8429 		/*
8430 		 * System V defines rename to return EEXIST, not
8431 		 * ENOTEMPTY if the target directory is not empty.
8432 		 * Over the wire, the error is NFSERR_ENOTEMPTY
8433 		 * which geterrno4 maps to ENOTEMPTY.
8434 		 */
8435 		if (e.error == ENOTEMPTY)
8436 			e.error = EEXIST;
8437 		nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state,
8438 		    needrecov);
8439 		goto out;
8440 	}
8441 
8442 	/* rename results */
8443 	rn_res = &res.array[5].nfs_resop4_u.oprename;
8444 
8445 	if (res.status == NFS4_OK) {
8446 		/* Update target attribute, readdir and dnlc caches */
8447 		dinfo.di_garp =
8448 		    &res.array[6].nfs_resop4_u.opgetattr.ga_res;
8449 		dinfo.di_cred = cr;
8450 		dinfo.di_time_call = t;
8451 	} else
8452 		dinfop = NULL;
8453 
8454 	/* Update source cache attribute, readdir and dnlc caches */
8455 	nfs4_update_dircaches(&rn_res->target_cinfo, ndvp, NULL, NULL, dinfop);
8456 
8457 	/* Update source cache attribute, readdir and dnlc caches */
8458 	if (ndvp != odvp) {
8459 
8460 		/*
8461 		 * If dinfop is non-NULL, then compound succeded, so
8462 		 * set di_garp to attrs for source dir.  dinfop is only
8463 		 * set to NULL when compound fails.
8464 		 */
8465 		if (dinfop)
8466 			dinfo.di_garp =
8467 			    &res.array[11].nfs_resop4_u.opgetattr.ga_res;
8468 		nfs4_update_dircaches(&rn_res->source_cinfo, odvp, NULL, NULL,
8469 		    dinfop);
8470 	}
8471 
8472 	/*
8473 	 * Update the rnode with the new component name and args,
8474 	 * and if the file handle changed, also update it with the new fh.
8475 	 * This is only necessary if the target object has an rnode
8476 	 * entry and there is no need to create one for it.
8477 	 */
8478 	resop = &res.array[8];	/* getfh new res */
8479 	ngf_res = &resop->nfs_resop4_u.opgetfh;
8480 
8481 	/*
8482 	 * Update the path and filehandle for the renamed object.
8483 	 */
8484 	nfs4rename_update(ovp, ndvp, &ngf_res->object, nnm);
8485 
8486 	nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state, needrecov);
8487 
8488 	if (res.status == NFS4_OK) {
8489 		resop++;	/* getattr res */
8490 		e.error = nfs4_update_attrcache(res.status,
8491 		    &resop->nfs_resop4_u.opgetattr.ga_res,
8492 		    t, ovp, cr);
8493 	}
8494 
8495 out:
8496 	kmem_free(argop, argoplist_size);
8497 	if (resp)
8498 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8499 	mutex_enter(&orp->r_statelock);
8500 	orp->r_flags &= ~R4RECEXPFH;
8501 	cv_broadcast(&orp->r_cv);
8502 	mutex_exit(&orp->r_statelock);
8503 
8504 	return (e.error);
8505 }
8506 
8507 /* ARGSUSED */
8508 static int
8509 nfs4_mkdir(vnode_t *dvp, char *nm, struct vattr *va, vnode_t **vpp, cred_t *cr,
8510     caller_context_t *ct, int flags, vsecattr_t *vsecp)
8511 {
8512 	int error;
8513 	vnode_t *vp;
8514 
8515 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8516 		return (EPERM);
8517 	/*
8518 	 * As ".." has special meaning and rather than send a mkdir
8519 	 * over the wire to just let the server freak out, we just
8520 	 * short circuit it here and return EEXIST
8521 	 */
8522 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8523 		return (EEXIST);
8524 
8525 	/*
8526 	 * Decision to get the right gid and setgid bit of the
8527 	 * new directory is now made in call_nfs4_create_req.
8528 	 */
8529 	va->va_mask |= AT_MODE;
8530 	error = call_nfs4_create_req(dvp, nm, NULL, va, &vp, cr, NF4DIR);
8531 	if (error)
8532 		return (error);
8533 
8534 	*vpp = vp;
8535 	return (0);
8536 }
8537 
8538 
8539 /*
8540  * rmdir is using the same remove v4 op as does remove.
8541  * Remove requires that the current fh be the target directory.
8542  * After the operation, the current fh is unchanged.
8543  * The compound op structure is:
8544  *      PUTFH(targetdir), REMOVE
8545  */
8546 /*ARGSUSED4*/
8547 static int
8548 nfs4_rmdir(vnode_t *dvp, char *nm, vnode_t *cdir, cred_t *cr,
8549     caller_context_t *ct, int flags)
8550 {
8551 	int need_end_op = FALSE;
8552 	COMPOUND4args_clnt args;
8553 	COMPOUND4res_clnt res, *resp = NULL;
8554 	REMOVE4res *rm_res;
8555 	nfs_argop4 argop[3];
8556 	nfs_resop4 *resop;
8557 	vnode_t *vp;
8558 	int doqueue;
8559 	mntinfo4_t *mi;
8560 	rnode4_t *drp;
8561 	bool_t needrecov = FALSE;
8562 	nfs4_recov_state_t recov_state;
8563 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8564 	dirattr_info_t dinfo, *dinfop;
8565 
8566 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8567 		return (EPERM);
8568 	/*
8569 	 * As ".." has special meaning and rather than send a rmdir
8570 	 * over the wire to just let the server freak out, we just
8571 	 * short circuit it here and return EEXIST
8572 	 */
8573 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8574 		return (EEXIST);
8575 
8576 	drp = VTOR4(dvp);
8577 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
8578 		return (EINTR);
8579 
8580 	/*
8581 	 * Attempt to prevent a rmdir(".") from succeeding.
8582 	 */
8583 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
8584 	if (e.error) {
8585 		nfs_rw_exit(&drp->r_rwlock);
8586 		return (e.error);
8587 	}
8588 	if (vp == cdir) {
8589 		VN_RELE(vp);
8590 		nfs_rw_exit(&drp->r_rwlock);
8591 		return (EINVAL);
8592 	}
8593 
8594 	/*
8595 	 * Since nfsv4 remove op works on both files and directories,
8596 	 * check that the removed object is indeed a directory.
8597 	 */
8598 	if (vp->v_type != VDIR) {
8599 		VN_RELE(vp);
8600 		nfs_rw_exit(&drp->r_rwlock);
8601 		return (ENOTDIR);
8602 	}
8603 
8604 	/*
8605 	 * First just remove the entry from the name cache, as it
8606 	 * is most likely an entry for this vp.
8607 	 */
8608 	dnlc_remove(dvp, nm);
8609 
8610 	/*
8611 	 * If there vnode reference count is greater than one, then
8612 	 * there may be additional references in the DNLC which will
8613 	 * need to be purged.  First, trying removing the entry for
8614 	 * the parent directory and see if that removes the additional
8615 	 * reference(s).  If that doesn't do it, then use dnlc_purge_vp
8616 	 * to completely remove any references to the directory which
8617 	 * might still exist in the DNLC.
8618 	 */
8619 	if (vp->v_count > 1) {
8620 		dnlc_remove(vp, "..");
8621 		if (vp->v_count > 1)
8622 			dnlc_purge_vp(vp);
8623 	}
8624 
8625 	mi = VTOMI4(dvp);
8626 	recov_state.rs_flags = 0;
8627 	recov_state.rs_num_retry_despite_err = 0;
8628 
8629 recov_retry:
8630 	args.ctag = TAG_RMDIR;
8631 
8632 	/*
8633 	 * Rmdir ops: putfh dir; remove
8634 	 */
8635 	args.array_len = 3;
8636 	args.array = argop;
8637 
8638 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
8639 	if (e.error) {
8640 		nfs_rw_exit(&drp->r_rwlock);
8641 		return (e.error);
8642 	}
8643 	need_end_op = TRUE;
8644 
8645 	/* putfh directory */
8646 	argop[0].argop = OP_CPUTFH;
8647 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
8648 
8649 	/* remove */
8650 	argop[1].argop = OP_CREMOVE;
8651 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
8652 
8653 	/* getattr (postop attrs for dir that contained removed dir) */
8654 	argop[2].argop = OP_GETATTR;
8655 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8656 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
8657 
8658 	dinfo.di_time_call = gethrtime();
8659 	doqueue = 1;
8660 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8661 
8662 	PURGE_ATTRCACHE4(vp);
8663 
8664 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8665 	if (e.error) {
8666 		PURGE_ATTRCACHE4(dvp);
8667 	}
8668 
8669 	if (needrecov) {
8670 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp, NULL, NULL,
8671 		    NULL, OP_REMOVE, NULL) == FALSE) {
8672 			if (!e.error)
8673 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8674 				    (caddr_t)&res);
8675 
8676 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
8677 			    needrecov);
8678 			need_end_op = FALSE;
8679 			goto recov_retry;
8680 		}
8681 	}
8682 
8683 	if (!e.error) {
8684 		resp = &res;
8685 
8686 		/*
8687 		 * Only return error if first 2 ops (OP_REMOVE or earlier)
8688 		 * failed.
8689 		 */
8690 		if (res.status != NFS4_OK && res.array_len <= 2) {
8691 			e.error = geterrno4(res.status);
8692 			PURGE_ATTRCACHE4(dvp);
8693 			nfs4_end_op(VTOMI4(dvp), dvp, NULL,
8694 			    &recov_state, needrecov);
8695 			need_end_op = FALSE;
8696 			nfs4_purge_stale_fh(e.error, dvp, cr);
8697 			/*
8698 			 * System V defines rmdir to return EEXIST, not
8699 			 * ENOTEMPTY if the directory is not empty.  Over
8700 			 * the wire, the error is NFSERR_ENOTEMPTY which
8701 			 * geterrno4 maps to ENOTEMPTY.
8702 			 */
8703 			if (e.error == ENOTEMPTY)
8704 				e.error = EEXIST;
8705 		} else {
8706 			resop = &res.array[1];	/* remove res */
8707 			rm_res = &resop->nfs_resop4_u.opremove;
8708 
8709 			if (res.status == NFS4_OK) {
8710 				resop = &res.array[2];	/* dir attrs */
8711 				dinfo.di_garp =
8712 				    &resop->nfs_resop4_u.opgetattr.ga_res;
8713 				dinfo.di_cred = cr;
8714 				dinfop = &dinfo;
8715 			} else
8716 				dinfop = NULL;
8717 
8718 			/* Update dir attribute, readdir and dnlc caches */
8719 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
8720 			    dinfop);
8721 
8722 			/* destroy rddir cache for dir that was removed */
8723 			if (VTOR4(vp)->r_dir != NULL)
8724 				nfs4_purge_rddir_cache(vp);
8725 		}
8726 	}
8727 
8728 	if (need_end_op)
8729 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
8730 
8731 	nfs_rw_exit(&drp->r_rwlock);
8732 
8733 	if (resp)
8734 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8735 
8736 	if (e.error == 0) {
8737 		vnode_t *tvp;
8738 		rnode4_t *trp;
8739 		trp = VTOR4(vp);
8740 		tvp = vp;
8741 		if (IS_SHADOW(vp, trp))
8742 			tvp = RTOV4(trp);
8743 		vnevent_rmdir(tvp, dvp, nm, ct);
8744 	}
8745 
8746 	VN_RELE(vp);
8747 
8748 	return (e.error);
8749 }
8750 
8751 /* ARGSUSED */
8752 static int
8753 nfs4_symlink(vnode_t *dvp, char *lnm, struct vattr *tva, char *tnm, cred_t *cr,
8754     caller_context_t *ct, int flags)
8755 {
8756 	int error;
8757 	vnode_t *vp;
8758 	rnode4_t *rp;
8759 	char *contents;
8760 	mntinfo4_t *mi = VTOMI4(dvp);
8761 
8762 	if (nfs_zone() != mi->mi_zone)
8763 		return (EPERM);
8764 	if (!(mi->mi_flags & MI4_SYMLINK))
8765 		return (EOPNOTSUPP);
8766 
8767 	error = call_nfs4_create_req(dvp, lnm, tnm, tva, &vp, cr, NF4LNK);
8768 	if (error)
8769 		return (error);
8770 
8771 	ASSERT(nfs4_consistent_type(vp));
8772 	rp = VTOR4(vp);
8773 	if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
8774 
8775 		contents = kmem_alloc(MAXPATHLEN, KM_SLEEP);
8776 
8777 		if (contents != NULL) {
8778 			mutex_enter(&rp->r_statelock);
8779 			if (rp->r_symlink.contents == NULL) {
8780 				rp->r_symlink.len = strlen(tnm);
8781 				bcopy(tnm, contents, rp->r_symlink.len);
8782 				rp->r_symlink.contents = contents;
8783 				rp->r_symlink.size = MAXPATHLEN;
8784 				mutex_exit(&rp->r_statelock);
8785 			} else {
8786 				mutex_exit(&rp->r_statelock);
8787 				kmem_free((void *)contents, MAXPATHLEN);
8788 			}
8789 		}
8790 	}
8791 	VN_RELE(vp);
8792 
8793 	return (error);
8794 }
8795 
8796 
8797 /*
8798  * Read directory entries.
8799  * There are some weird things to look out for here.  The uio_loffset
8800  * field is either 0 or it is the offset returned from a previous
8801  * readdir.  It is an opaque value used by the server to find the
8802  * correct directory block to read. The count field is the number
8803  * of blocks to read on the server.  This is advisory only, the server
8804  * may return only one block's worth of entries.  Entries may be compressed
8805  * on the server.
8806  */
8807 /* ARGSUSED */
8808 static int
8809 nfs4_readdir(vnode_t *vp, struct uio *uiop, cred_t *cr, int *eofp,
8810 	caller_context_t *ct, int flags)
8811 {
8812 	int error;
8813 	uint_t count;
8814 	rnode4_t *rp;
8815 	rddir4_cache *rdc;
8816 	rddir4_cache *rrdc;
8817 
8818 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
8819 		return (EIO);
8820 	rp = VTOR4(vp);
8821 
8822 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
8823 
8824 	/*
8825 	 * Make sure that the directory cache is valid.
8826 	 */
8827 	if (rp->r_dir != NULL) {
8828 		if (nfs_disable_rddir_cache != 0) {
8829 			/*
8830 			 * Setting nfs_disable_rddir_cache in /etc/system
8831 			 * allows interoperability with servers that do not
8832 			 * properly update the attributes of directories.
8833 			 * Any cached information gets purged before an
8834 			 * access is made to it.
8835 			 */
8836 			nfs4_purge_rddir_cache(vp);
8837 		}
8838 
8839 		error = nfs4_validate_caches(vp, cr);
8840 		if (error)
8841 			return (error);
8842 	}
8843 
8844 	count = MIN(uiop->uio_iov->iov_len, MAXBSIZE);
8845 
8846 	/*
8847 	 * Short circuit last readdir which always returns 0 bytes.
8848 	 * This can be done after the directory has been read through
8849 	 * completely at least once.  This will set r_direof which
8850 	 * can be used to find the value of the last cookie.
8851 	 */
8852 	mutex_enter(&rp->r_statelock);
8853 	if (rp->r_direof != NULL &&
8854 	    uiop->uio_loffset == rp->r_direof->nfs4_ncookie) {
8855 		mutex_exit(&rp->r_statelock);
8856 #ifdef DEBUG
8857 		nfs4_readdir_cache_shorts++;
8858 #endif
8859 		if (eofp)
8860 			*eofp = 1;
8861 		return (0);
8862 	}
8863 
8864 	/*
8865 	 * Look for a cache entry.  Cache entries are identified
8866 	 * by the NFS cookie value and the byte count requested.
8867 	 */
8868 	rdc = rddir4_cache_lookup(rp, uiop->uio_loffset, count);
8869 
8870 	/*
8871 	 * If rdc is NULL then the lookup resulted in an unrecoverable error.
8872 	 */
8873 	if (rdc == NULL) {
8874 		mutex_exit(&rp->r_statelock);
8875 		return (EINTR);
8876 	}
8877 
8878 	/*
8879 	 * Check to see if we need to fill this entry in.
8880 	 */
8881 	if (rdc->flags & RDDIRREQ) {
8882 		rdc->flags &= ~RDDIRREQ;
8883 		rdc->flags |= RDDIR;
8884 		mutex_exit(&rp->r_statelock);
8885 
8886 		/*
8887 		 * Do the readdir.
8888 		 */
8889 		nfs4readdir(vp, rdc, cr);
8890 
8891 		/*
8892 		 * Reacquire the lock, so that we can continue
8893 		 */
8894 		mutex_enter(&rp->r_statelock);
8895 		/*
8896 		 * The entry is now complete
8897 		 */
8898 		rdc->flags &= ~RDDIR;
8899 	}
8900 
8901 	ASSERT(!(rdc->flags & RDDIR));
8902 
8903 	/*
8904 	 * If an error occurred while attempting
8905 	 * to fill the cache entry, mark the entry invalid and
8906 	 * just return the error.
8907 	 */
8908 	if (rdc->error) {
8909 		error = rdc->error;
8910 		rdc->flags |= RDDIRREQ;
8911 		rddir4_cache_rele(rp, rdc);
8912 		mutex_exit(&rp->r_statelock);
8913 		return (error);
8914 	}
8915 
8916 	/*
8917 	 * The cache entry is complete and good,
8918 	 * copyout the dirent structs to the calling
8919 	 * thread.
8920 	 */
8921 	error = uiomove(rdc->entries, rdc->actlen, UIO_READ, uiop);
8922 
8923 	/*
8924 	 * If no error occurred during the copyout,
8925 	 * update the offset in the uio struct to
8926 	 * contain the value of the next NFS 4 cookie
8927 	 * and set the eof value appropriately.
8928 	 */
8929 	if (!error) {
8930 		uiop->uio_loffset = rdc->nfs4_ncookie;
8931 		if (eofp)
8932 			*eofp = rdc->eof;
8933 	}
8934 
8935 	/*
8936 	 * Decide whether to do readahead.  Don't if we
8937 	 * have already read to the end of directory.
8938 	 */
8939 	if (rdc->eof) {
8940 		/*
8941 		 * Make the entry the direof only if it is cached
8942 		 */
8943 		if (rdc->flags & RDDIRCACHED)
8944 			rp->r_direof = rdc;
8945 		rddir4_cache_rele(rp, rdc);
8946 		mutex_exit(&rp->r_statelock);
8947 		return (error);
8948 	}
8949 
8950 	/* Determine if a readdir readahead should be done */
8951 	if (!(rp->r_flags & R4LOOKUP)) {
8952 		rddir4_cache_rele(rp, rdc);
8953 		mutex_exit(&rp->r_statelock);
8954 		return (error);
8955 	}
8956 
8957 	/*
8958 	 * Now look for a readahead entry.
8959 	 *
8960 	 * Check to see whether we found an entry for the readahead.
8961 	 * If so, we don't need to do anything further, so free the new
8962 	 * entry if one was allocated.  Otherwise, allocate a new entry, add
8963 	 * it to the cache, and then initiate an asynchronous readdir
8964 	 * operation to fill it.
8965 	 */
8966 	rrdc = rddir4_cache_lookup(rp, rdc->nfs4_ncookie, count);
8967 
8968 	/*
8969 	 * A readdir cache entry could not be obtained for the readahead.  In
8970 	 * this case we skip the readahead and return.
8971 	 */
8972 	if (rrdc == NULL) {
8973 		rddir4_cache_rele(rp, rdc);
8974 		mutex_exit(&rp->r_statelock);
8975 		return (error);
8976 	}
8977 
8978 	/*
8979 	 * Check to see if we need to fill this entry in.
8980 	 */
8981 	if (rrdc->flags & RDDIRREQ) {
8982 		rrdc->flags &= ~RDDIRREQ;
8983 		rrdc->flags |= RDDIR;
8984 		rddir4_cache_rele(rp, rdc);
8985 		mutex_exit(&rp->r_statelock);
8986 #ifdef DEBUG
8987 		nfs4_readdir_readahead++;
8988 #endif
8989 		/*
8990 		 * Do the readdir.
8991 		 */
8992 		nfs4_async_readdir(vp, rrdc, cr, do_nfs4readdir);
8993 		return (error);
8994 	}
8995 
8996 	rddir4_cache_rele(rp, rrdc);
8997 	rddir4_cache_rele(rp, rdc);
8998 	mutex_exit(&rp->r_statelock);
8999 	return (error);
9000 }
9001 
9002 static int
9003 do_nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
9004 {
9005 	int error;
9006 	rnode4_t *rp;
9007 
9008 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
9009 
9010 	rp = VTOR4(vp);
9011 
9012 	/*
9013 	 * Obtain the readdir results for the caller.
9014 	 */
9015 	nfs4readdir(vp, rdc, cr);
9016 
9017 	mutex_enter(&rp->r_statelock);
9018 	/*
9019 	 * The entry is now complete
9020 	 */
9021 	rdc->flags &= ~RDDIR;
9022 
9023 	error = rdc->error;
9024 	if (error)
9025 		rdc->flags |= RDDIRREQ;
9026 	rddir4_cache_rele(rp, rdc);
9027 	mutex_exit(&rp->r_statelock);
9028 
9029 	return (error);
9030 }
9031 
9032 /*
9033  * Read directory entries.
9034  * There are some weird things to look out for here.  The uio_loffset
9035  * field is either 0 or it is the offset returned from a previous
9036  * readdir.  It is an opaque value used by the server to find the
9037  * correct directory block to read. The count field is the number
9038  * of blocks to read on the server.  This is advisory only, the server
9039  * may return only one block's worth of entries.  Entries may be compressed
9040  * on the server.
9041  *
9042  * Generates the following compound request:
9043  * 1. If readdir offset is zero and no dnlc entry for parent exists,
9044  *    must include a Lookupp as well. In this case, send:
9045  *    { Putfh <fh>; Readdir; Lookupp; Getfh; Getattr }
9046  * 2. Otherwise just do: { Putfh <fh>; Readdir }
9047  *
9048  * Get complete attributes and filehandles for entries if this is the
9049  * first read of the directory. Otherwise, just get fileid's.
9050  */
9051 static void
9052 nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
9053 {
9054 	COMPOUND4args_clnt args;
9055 	COMPOUND4res_clnt res;
9056 	READDIR4args *rargs;
9057 	READDIR4res_clnt *rd_res;
9058 	bitmap4 rd_bitsval;
9059 	nfs_argop4 argop[5];
9060 	nfs_resop4 *resop;
9061 	rnode4_t *rp = VTOR4(vp);
9062 	mntinfo4_t *mi = VTOMI4(vp);
9063 	int doqueue;
9064 	u_longlong_t nodeid, pnodeid;	/* id's of dir and its parents */
9065 	vnode_t *dvp;
9066 	nfs_cookie4 cookie = (nfs_cookie4)rdc->nfs4_cookie;
9067 	int num_ops, res_opcnt;
9068 	bool_t needrecov = FALSE;
9069 	nfs4_recov_state_t recov_state;
9070 	hrtime_t t;
9071 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
9072 
9073 	ASSERT(nfs_zone() == mi->mi_zone);
9074 	ASSERT(rdc->flags & RDDIR);
9075 	ASSERT(rdc->entries == NULL);
9076 
9077 	/*
9078 	 * If rp were a stub, it should have triggered and caused
9079 	 * a mount for us to get this far.
9080 	 */
9081 	ASSERT(!RP_ISSTUB(rp));
9082 
9083 	num_ops = 2;
9084 	if (cookie == (nfs_cookie4)0 || cookie == (nfs_cookie4)1) {
9085 		/*
9086 		 * Since nfsv4 readdir may not return entries for "." and "..",
9087 		 * the client must recreate them:
9088 		 * To find the correct nodeid, do the following:
9089 		 * For current node, get nodeid from dnlc.
9090 		 * - if current node is rootvp, set pnodeid to nodeid.
9091 		 * - else if parent is in the dnlc, get its nodeid from there.
9092 		 * - else add LOOKUPP+GETATTR to compound.
9093 		 */
9094 		nodeid = rp->r_attr.va_nodeid;
9095 		if (vp->v_flag & VROOT) {
9096 			pnodeid = nodeid;	/* root of mount point */
9097 		} else {
9098 			dvp = dnlc_lookup(vp, "..");
9099 			if (dvp != NULL && dvp != DNLC_NO_VNODE) {
9100 				/* parent in dnlc cache - no need for otw */
9101 				pnodeid = VTOR4(dvp)->r_attr.va_nodeid;
9102 			} else {
9103 				/*
9104 				 * parent not in dnlc cache,
9105 				 * do lookupp to get its id
9106 				 */
9107 				num_ops = 5;
9108 				pnodeid = 0; /* set later by getattr parent */
9109 			}
9110 			if (dvp)
9111 				VN_RELE(dvp);
9112 		}
9113 	}
9114 	recov_state.rs_flags = 0;
9115 	recov_state.rs_num_retry_despite_err = 0;
9116 
9117 	/* Save the original mount point security flavor */
9118 	(void) save_mnt_secinfo(mi->mi_curr_serv);
9119 
9120 recov_retry:
9121 	args.ctag = TAG_READDIR;
9122 
9123 	args.array = argop;
9124 	args.array_len = num_ops;
9125 
9126 	if (e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9127 	    &recov_state, NULL)) {
9128 		/*
9129 		 * If readdir a node that is a stub for a crossed mount point,
9130 		 * keep the original secinfo flavor for the current file
9131 		 * system, not the crossed one.
9132 		 */
9133 		(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9134 		rdc->error = e.error;
9135 		return;
9136 	}
9137 
9138 	/*
9139 	 * Determine which attrs to request for dirents.  This code
9140 	 * must be protected by nfs4_start/end_fop because of r_server
9141 	 * (which will change during failover recovery).
9142 	 *
9143 	 */
9144 	if (rp->r_flags & (R4LOOKUP | R4READDIRWATTR)) {
9145 		/*
9146 		 * Get all vattr attrs plus filehandle and rdattr_error
9147 		 */
9148 		rd_bitsval = NFS4_VATTR_MASK |
9149 		    FATTR4_RDATTR_ERROR_MASK |
9150 		    FATTR4_FILEHANDLE_MASK;
9151 
9152 		if (rp->r_flags & R4READDIRWATTR) {
9153 			mutex_enter(&rp->r_statelock);
9154 			rp->r_flags &= ~R4READDIRWATTR;
9155 			mutex_exit(&rp->r_statelock);
9156 		}
9157 	} else {
9158 		servinfo4_t *svp = rp->r_server;
9159 
9160 		/*
9161 		 * Already read directory. Use readdir with
9162 		 * no attrs (except for mounted_on_fileid) for updates.
9163 		 */
9164 		rd_bitsval = FATTR4_RDATTR_ERROR_MASK;
9165 
9166 		/*
9167 		 * request mounted on fileid if supported, else request
9168 		 * fileid.  maybe we should verify that fileid is supported
9169 		 * and request something else if not.
9170 		 */
9171 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
9172 		if (svp->sv_supp_attrs & FATTR4_MOUNTED_ON_FILEID_MASK)
9173 			rd_bitsval |= FATTR4_MOUNTED_ON_FILEID_MASK;
9174 		nfs_rw_exit(&svp->sv_lock);
9175 	}
9176 
9177 	/* putfh directory fh */
9178 	argop[0].argop = OP_CPUTFH;
9179 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
9180 
9181 	argop[1].argop = OP_READDIR;
9182 	rargs = &argop[1].nfs_argop4_u.opreaddir;
9183 	/*
9184 	 * 1 and 2 are reserved for client "." and ".." entry offset.
9185 	 * cookie 0 should be used over-the-wire to start reading at
9186 	 * the beginning of the directory excluding "." and "..".
9187 	 */
9188 	if (rdc->nfs4_cookie == 0 ||
9189 	    rdc->nfs4_cookie == 1 ||
9190 	    rdc->nfs4_cookie == 2) {
9191 		rargs->cookie = (nfs_cookie4)0;
9192 		rargs->cookieverf = 0;
9193 	} else {
9194 		rargs->cookie = (nfs_cookie4)rdc->nfs4_cookie;
9195 		mutex_enter(&rp->r_statelock);
9196 		rargs->cookieverf = rp->r_cookieverf4;
9197 		mutex_exit(&rp->r_statelock);
9198 	}
9199 	rargs->dircount = MIN(rdc->buflen, mi->mi_tsize);
9200 	rargs->maxcount = mi->mi_tsize;
9201 	rargs->attr_request = rd_bitsval;
9202 	rargs->rdc = rdc;
9203 	rargs->dvp = vp;
9204 	rargs->mi = mi;
9205 	rargs->cr = cr;
9206 
9207 
9208 	/*
9209 	 * If count < than the minimum required, we return no entries
9210 	 * and fail with EINVAL
9211 	 */
9212 	if (rargs->dircount < (DIRENT64_RECLEN(1) + DIRENT64_RECLEN(2))) {
9213 		rdc->error = EINVAL;
9214 		goto out;
9215 	}
9216 
9217 	if (args.array_len == 5) {
9218 		/*
9219 		 * Add lookupp and getattr for parent nodeid.
9220 		 */
9221 		argop[2].argop = OP_LOOKUPP;
9222 
9223 		argop[3].argop = OP_GETFH;
9224 
9225 		/* getattr parent */
9226 		argop[4].argop = OP_GETATTR;
9227 		argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
9228 		argop[4].nfs_argop4_u.opgetattr.mi = mi;
9229 	}
9230 
9231 	doqueue = 1;
9232 
9233 	if (mi->mi_io_kstats) {
9234 		mutex_enter(&mi->mi_lock);
9235 		kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
9236 		mutex_exit(&mi->mi_lock);
9237 	}
9238 
9239 	/* capture the time of this call */
9240 	rargs->t = t = gethrtime();
9241 
9242 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
9243 
9244 	if (mi->mi_io_kstats) {
9245 		mutex_enter(&mi->mi_lock);
9246 		kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
9247 		mutex_exit(&mi->mi_lock);
9248 	}
9249 
9250 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
9251 
9252 	/*
9253 	 * If RPC error occurred and it isn't an error that
9254 	 * triggers recovery, then go ahead and fail now.
9255 	 */
9256 	if (e.error != 0 && !needrecov) {
9257 		rdc->error = e.error;
9258 		goto out;
9259 	}
9260 
9261 	if (needrecov) {
9262 		bool_t abort;
9263 
9264 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
9265 		    "nfs4readdir: initiating recovery.\n"));
9266 
9267 		abort = nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
9268 		    NULL, OP_READDIR, NULL);
9269 		if (abort == FALSE) {
9270 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9271 			    &recov_state, needrecov);
9272 			if (!e.error)
9273 				(void) xdr_free(xdr_COMPOUND4res_clnt,
9274 				    (caddr_t)&res);
9275 			if (rdc->entries != NULL) {
9276 				kmem_free(rdc->entries, rdc->entlen);
9277 				rdc->entries = NULL;
9278 			}
9279 			goto recov_retry;
9280 		}
9281 
9282 		if (e.error != 0) {
9283 			rdc->error = e.error;
9284 			goto out;
9285 		}
9286 
9287 		/* fall through for res.status case */
9288 	}
9289 
9290 	res_opcnt = res.array_len;
9291 
9292 	/*
9293 	 * If compound failed first 2 ops (PUTFH+READDIR), then return
9294 	 * failure here.  Subsequent ops are for filling out dot-dot
9295 	 * dirent, and if they fail, we still want to give the caller
9296 	 * the dirents returned by (the successful) READDIR op, so we need
9297 	 * to silently ignore failure for subsequent ops (LOOKUPP+GETATTR).
9298 	 *
9299 	 * One example where PUTFH+READDIR ops would succeed but
9300 	 * LOOKUPP+GETATTR would fail would be a dir that has r perm
9301 	 * but lacks x.  In this case, a POSIX server's VOP_READDIR
9302 	 * would succeed; however, VOP_LOOKUP(..) would fail since no
9303 	 * x perm.  We need to come up with a non-vendor-specific way
9304 	 * for a POSIX server to return d_ino from dotdot's dirent if
9305 	 * client only requests mounted_on_fileid, and just say the
9306 	 * LOOKUPP succeeded and fill out the GETATTR.  However, if
9307 	 * client requested any mandatory attrs, server would be required
9308 	 * to fail the GETATTR op because it can't call VOP_LOOKUP+VOP_GETATTR
9309 	 * for dotdot.
9310 	 */
9311 
9312 	if (res.status) {
9313 		if (res_opcnt <= 2) {
9314 			e.error = geterrno4(res.status);
9315 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9316 			    &recov_state, needrecov);
9317 			nfs4_purge_stale_fh(e.error, vp, cr);
9318 			rdc->error = e.error;
9319 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9320 			if (rdc->entries != NULL) {
9321 				kmem_free(rdc->entries, rdc->entlen);
9322 				rdc->entries = NULL;
9323 			}
9324 			/*
9325 			 * If readdir a node that is a stub for a
9326 			 * crossed mount point, keep the original
9327 			 * secinfo flavor for the current file system,
9328 			 * not the crossed one.
9329 			 */
9330 			(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9331 			return;
9332 		}
9333 	}
9334 
9335 	resop = &res.array[1];	/* readdir res */
9336 	rd_res = &resop->nfs_resop4_u.opreaddirclnt;
9337 
9338 	mutex_enter(&rp->r_statelock);
9339 	rp->r_cookieverf4 = rd_res->cookieverf;
9340 	mutex_exit(&rp->r_statelock);
9341 
9342 	/*
9343 	 * For "." and ".." entries
9344 	 * e.g.
9345 	 *	seek(cookie=0) -> "." entry with d_off = 1
9346 	 *	seek(cookie=1) -> ".." entry with d_off = 2
9347 	 */
9348 	if (cookie == (nfs_cookie4) 0) {
9349 		if (rd_res->dotp)
9350 			rd_res->dotp->d_ino = nodeid;
9351 		if (rd_res->dotdotp)
9352 			rd_res->dotdotp->d_ino = pnodeid;
9353 	}
9354 	if (cookie == (nfs_cookie4) 1) {
9355 		if (rd_res->dotdotp)
9356 			rd_res->dotdotp->d_ino = pnodeid;
9357 	}
9358 
9359 
9360 	/* LOOKUPP+GETATTR attemped */
9361 	if (args.array_len == 5 && rd_res->dotdotp) {
9362 		if (res.status == NFS4_OK && res_opcnt == 5) {
9363 			nfs_fh4 *fhp;
9364 			nfs4_sharedfh_t *sfhp;
9365 			vnode_t *pvp;
9366 			nfs4_ga_res_t *garp;
9367 
9368 			resop++;	/* lookupp */
9369 			resop++;	/* getfh   */
9370 			fhp = &resop->nfs_resop4_u.opgetfh.object;
9371 
9372 			resop++;	/* getattr of parent */
9373 
9374 			/*
9375 			 * First, take care of finishing the
9376 			 * readdir results.
9377 			 */
9378 			garp = &resop->nfs_resop4_u.opgetattr.ga_res;
9379 			/*
9380 			 * The d_ino of .. must be the inode number
9381 			 * of the mounted filesystem.
9382 			 */
9383 			if (garp->n4g_va.va_mask & AT_NODEID)
9384 				rd_res->dotdotp->d_ino =
9385 				    garp->n4g_va.va_nodeid;
9386 
9387 
9388 			/*
9389 			 * Next, create the ".." dnlc entry
9390 			 */
9391 			sfhp = sfh4_get(fhp, mi);
9392 			if (!nfs4_make_dotdot(sfhp, t, vp, cr, &pvp, 0)) {
9393 				dnlc_update(vp, "..", pvp);
9394 				VN_RELE(pvp);
9395 			}
9396 			sfh4_rele(&sfhp);
9397 		}
9398 	}
9399 
9400 	if (mi->mi_io_kstats) {
9401 		mutex_enter(&mi->mi_lock);
9402 		KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
9403 		KSTAT_IO_PTR(mi->mi_io_kstats)->nread += rdc->actlen;
9404 		mutex_exit(&mi->mi_lock);
9405 	}
9406 
9407 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9408 
9409 out:
9410 	/*
9411 	 * If readdir a node that is a stub for a crossed mount point,
9412 	 * keep the original secinfo flavor for the current file system,
9413 	 * not the crossed one.
9414 	 */
9415 	(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9416 
9417 	nfs4_end_fop(mi, vp, NULL, OH_READDIR, &recov_state, needrecov);
9418 }
9419 
9420 
9421 static int
9422 nfs4_bio(struct buf *bp, stable_how4 *stab_comm, cred_t *cr, bool_t readahead)
9423 {
9424 	rnode4_t *rp = VTOR4(bp->b_vp);
9425 	int count;
9426 	int error;
9427 	cred_t *cred_otw = NULL;
9428 	offset_t offset;
9429 	nfs4_open_stream_t *osp = NULL;
9430 	bool_t first_time = TRUE;	/* first time getting otw cred */
9431 	bool_t last_time = FALSE;	/* last time getting otw cred */
9432 
9433 	ASSERT(nfs_zone() == VTOMI4(bp->b_vp)->mi_zone);
9434 
9435 	DTRACE_IO1(start, struct buf *, bp);
9436 	offset = ldbtob(bp->b_lblkno);
9437 
9438 	if (bp->b_flags & B_READ) {
9439 	read_again:
9440 		/*
9441 		 * Releases the osp, if it is provided.
9442 		 * Puts a hold on the cred_otw and the new osp (if found).
9443 		 */
9444 		cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9445 		    &first_time, &last_time);
9446 		error = bp->b_error = nfs4read(bp->b_vp, bp->b_un.b_addr,
9447 		    offset, bp->b_bcount, &bp->b_resid, cred_otw,
9448 		    readahead, NULL);
9449 		crfree(cred_otw);
9450 		if (!error) {
9451 			if (bp->b_resid) {
9452 				/*
9453 				 * Didn't get it all because we hit EOF,
9454 				 * zero all the memory beyond the EOF.
9455 				 */
9456 				/* bzero(rdaddr + */
9457 				bzero(bp->b_un.b_addr +
9458 				    bp->b_bcount - bp->b_resid, bp->b_resid);
9459 			}
9460 			mutex_enter(&rp->r_statelock);
9461 			if (bp->b_resid == bp->b_bcount &&
9462 			    offset >= rp->r_size) {
9463 				/*
9464 				 * We didn't read anything at all as we are
9465 				 * past EOF.  Return an error indicator back
9466 				 * but don't destroy the pages (yet).
9467 				 */
9468 				error = NFS_EOF;
9469 			}
9470 			mutex_exit(&rp->r_statelock);
9471 		} else if (error == EACCES && last_time == FALSE) {
9472 				goto read_again;
9473 		}
9474 	} else {
9475 		if (!(rp->r_flags & R4STALE)) {
9476 write_again:
9477 			/*
9478 			 * Releases the osp, if it is provided.
9479 			 * Puts a hold on the cred_otw and the new
9480 			 * osp (if found).
9481 			 */
9482 			cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9483 			    &first_time, &last_time);
9484 			mutex_enter(&rp->r_statelock);
9485 			count = MIN(bp->b_bcount, rp->r_size - offset);
9486 			mutex_exit(&rp->r_statelock);
9487 			if (count < 0)
9488 				cmn_err(CE_PANIC, "nfs4_bio: write count < 0");
9489 #ifdef DEBUG
9490 			if (count == 0) {
9491 				zoneid_t zoneid = getzoneid();
9492 
9493 				zcmn_err(zoneid, CE_WARN,
9494 				    "nfs4_bio: zero length write at %lld",
9495 				    offset);
9496 				zcmn_err(zoneid, CE_CONT, "flags=0x%x, "
9497 				    "b_bcount=%ld, file size=%lld",
9498 				    rp->r_flags, (long)bp->b_bcount,
9499 				    rp->r_size);
9500 				sfh4_printfhandle(VTOR4(bp->b_vp)->r_fh);
9501 				if (nfs4_bio_do_stop)
9502 					debug_enter("nfs4_bio");
9503 			}
9504 #endif
9505 			error = nfs4write(bp->b_vp, bp->b_un.b_addr, offset,
9506 			    count, cred_otw, stab_comm);
9507 			if (error == EACCES && last_time == FALSE) {
9508 				crfree(cred_otw);
9509 				goto write_again;
9510 			}
9511 			bp->b_error = error;
9512 			if (error && error != EINTR &&
9513 			    !(bp->b_vp->v_vfsp->vfs_flag & VFS_UNMOUNTED)) {
9514 				/*
9515 				 * Don't print EDQUOT errors on the console.
9516 				 * Don't print asynchronous EACCES errors.
9517 				 * Don't print EFBIG errors.
9518 				 * Print all other write errors.
9519 				 */
9520 				if (error != EDQUOT && error != EFBIG &&
9521 				    (error != EACCES ||
9522 				    !(bp->b_flags & B_ASYNC)))
9523 					nfs4_write_error(bp->b_vp,
9524 					    error, cred_otw);
9525 				/*
9526 				 * Update r_error and r_flags as appropriate.
9527 				 * If the error was ESTALE, then mark the
9528 				 * rnode as not being writeable and save
9529 				 * the error status.  Otherwise, save any
9530 				 * errors which occur from asynchronous
9531 				 * page invalidations.  Any errors occurring
9532 				 * from other operations should be saved
9533 				 * by the caller.
9534 				 */
9535 				mutex_enter(&rp->r_statelock);
9536 				if (error == ESTALE) {
9537 					rp->r_flags |= R4STALE;
9538 					if (!rp->r_error)
9539 						rp->r_error = error;
9540 				} else if (!rp->r_error &&
9541 				    (bp->b_flags &
9542 				    (B_INVAL|B_FORCE|B_ASYNC)) ==
9543 				    (B_INVAL|B_FORCE|B_ASYNC)) {
9544 					rp->r_error = error;
9545 				}
9546 				mutex_exit(&rp->r_statelock);
9547 			}
9548 			crfree(cred_otw);
9549 		} else
9550 			error = rp->r_error;
9551 	}
9552 
9553 	if (error != 0 && error != NFS_EOF)
9554 		bp->b_flags |= B_ERROR;
9555 
9556 	if (osp)
9557 		open_stream_rele(osp, rp);
9558 
9559 	DTRACE_IO1(done, struct buf *, bp);
9560 
9561 	return (error);
9562 }
9563 
9564 /* ARGSUSED */
9565 int
9566 nfs4_fid(vnode_t *vp, fid_t *fidp, caller_context_t *ct)
9567 {
9568 	return (EREMOTE);
9569 }
9570 
9571 /* ARGSUSED2 */
9572 int
9573 nfs4_rwlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9574 {
9575 	rnode4_t *rp = VTOR4(vp);
9576 
9577 	if (!write_lock) {
9578 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9579 		return (V_WRITELOCK_FALSE);
9580 	}
9581 
9582 	if ((rp->r_flags & R4DIRECTIO) ||
9583 	    (VTOMI4(vp)->mi_flags & MI4_DIRECTIO)) {
9584 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9585 		if (rp->r_mapcnt == 0 && !nfs4_has_pages(vp))
9586 			return (V_WRITELOCK_FALSE);
9587 		nfs_rw_exit(&rp->r_rwlock);
9588 	}
9589 
9590 	(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, FALSE);
9591 	return (V_WRITELOCK_TRUE);
9592 }
9593 
9594 /* ARGSUSED */
9595 void
9596 nfs4_rwunlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9597 {
9598 	rnode4_t *rp = VTOR4(vp);
9599 
9600 	nfs_rw_exit(&rp->r_rwlock);
9601 }
9602 
9603 /* ARGSUSED */
9604 static int
9605 nfs4_seek(vnode_t *vp, offset_t ooff, offset_t *noffp, caller_context_t *ct)
9606 {
9607 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9608 		return (EIO);
9609 
9610 	/*
9611 	 * Because we stuff the readdir cookie into the offset field
9612 	 * someone may attempt to do an lseek with the cookie which
9613 	 * we want to succeed.
9614 	 */
9615 	if (vp->v_type == VDIR)
9616 		return (0);
9617 	if (*noffp < 0)
9618 		return (EINVAL);
9619 	return (0);
9620 }
9621 
9622 
9623 /*
9624  * Return all the pages from [off..off+len) in file
9625  */
9626 /* ARGSUSED */
9627 static int
9628 nfs4_getpage(vnode_t *vp, offset_t off, size_t len, uint_t *protp,
9629     page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9630 	enum seg_rw rw, cred_t *cr, caller_context_t *ct)
9631 {
9632 	rnode4_t *rp;
9633 	int error;
9634 	mntinfo4_t *mi;
9635 
9636 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9637 		return (EIO);
9638 	rp = VTOR4(vp);
9639 	if (IS_SHADOW(vp, rp))
9640 		vp = RTOV4(rp);
9641 
9642 	if (vp->v_flag & VNOMAP)
9643 		return (ENOSYS);
9644 
9645 	if (protp != NULL)
9646 		*protp = PROT_ALL;
9647 
9648 	/*
9649 	 * Now validate that the caches are up to date.
9650 	 */
9651 	if (error = nfs4_validate_caches(vp, cr))
9652 		return (error);
9653 
9654 	mi = VTOMI4(vp);
9655 retry:
9656 	mutex_enter(&rp->r_statelock);
9657 
9658 	/*
9659 	 * Don't create dirty pages faster than they
9660 	 * can be cleaned so that the system doesn't
9661 	 * get imbalanced.  If the async queue is
9662 	 * maxed out, then wait for it to drain before
9663 	 * creating more dirty pages.  Also, wait for
9664 	 * any threads doing pagewalks in the vop_getattr
9665 	 * entry points so that they don't block for
9666 	 * long periods.
9667 	 */
9668 	if (rw == S_CREATE) {
9669 		while ((mi->mi_max_threads != 0 &&
9670 		    rp->r_awcount > 2 * mi->mi_max_threads) ||
9671 		    rp->r_gcount > 0)
9672 			cv_wait(&rp->r_cv, &rp->r_statelock);
9673 	}
9674 
9675 	/*
9676 	 * If we are getting called as a side effect of an nfs_write()
9677 	 * operation the local file size might not be extended yet.
9678 	 * In this case we want to be able to return pages of zeroes.
9679 	 */
9680 	if (off + len > rp->r_size + PAGEOFFSET && seg != segkmap) {
9681 		NFS4_DEBUG(nfs4_pageio_debug,
9682 		    (CE_NOTE, "getpage beyond EOF: off=%lld, "
9683 		    "len=%llu, size=%llu, attrsize =%llu", off,
9684 		    (u_longlong_t)len, rp->r_size, rp->r_attr.va_size));
9685 		mutex_exit(&rp->r_statelock);
9686 		return (EFAULT);		/* beyond EOF */
9687 	}
9688 
9689 	mutex_exit(&rp->r_statelock);
9690 
9691 	if (len <= PAGESIZE) {
9692 		error = nfs4_getapage(vp, off, len, protp, pl, plsz,
9693 		    seg, addr, rw, cr);
9694 		NFS4_DEBUG(nfs4_pageio_debug && error,
9695 		    (CE_NOTE, "getpage error %d; off=%lld, "
9696 		    "len=%lld", error, off, (u_longlong_t)len));
9697 	} else {
9698 		error = pvn_getpages(nfs4_getapage, vp, off, len, protp,
9699 		    pl, plsz, seg, addr, rw, cr);
9700 		NFS4_DEBUG(nfs4_pageio_debug && error,
9701 		    (CE_NOTE, "getpages error %d; off=%lld, "
9702 		    "len=%lld", error, off, (u_longlong_t)len));
9703 	}
9704 
9705 	switch (error) {
9706 	case NFS_EOF:
9707 		nfs4_purge_caches(vp, NFS4_NOPURGE_DNLC, cr, FALSE);
9708 		goto retry;
9709 	case ESTALE:
9710 		nfs4_purge_stale_fh(error, vp, cr);
9711 	}
9712 
9713 	return (error);
9714 }
9715 
9716 /*
9717  * Called from pvn_getpages or nfs4_getpage to get a particular page.
9718  */
9719 /* ARGSUSED */
9720 static int
9721 nfs4_getapage(vnode_t *vp, u_offset_t off, size_t len, uint_t *protp,
9722     page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9723     enum seg_rw rw, cred_t *cr)
9724 {
9725 	rnode4_t *rp;
9726 	uint_t bsize;
9727 	struct buf *bp;
9728 	page_t *pp;
9729 	u_offset_t lbn;
9730 	u_offset_t io_off;
9731 	u_offset_t blkoff;
9732 	u_offset_t rablkoff;
9733 	size_t io_len;
9734 	uint_t blksize;
9735 	int error;
9736 	int readahead;
9737 	int readahead_issued = 0;
9738 	int ra_window; /* readahead window */
9739 	page_t *pagefound;
9740 	page_t *savepp;
9741 
9742 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9743 		return (EIO);
9744 
9745 	rp = VTOR4(vp);
9746 	ASSERT(!IS_SHADOW(vp, rp));
9747 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
9748 
9749 reread:
9750 	bp = NULL;
9751 	pp = NULL;
9752 	pagefound = NULL;
9753 
9754 	if (pl != NULL)
9755 		pl[0] = NULL;
9756 
9757 	error = 0;
9758 	lbn = off / bsize;
9759 	blkoff = lbn * bsize;
9760 
9761 	/*
9762 	 * Queueing up the readahead before doing the synchronous read
9763 	 * results in a significant increase in read throughput because
9764 	 * of the increased parallelism between the async threads and
9765 	 * the process context.
9766 	 */
9767 	if ((off & ((vp->v_vfsp->vfs_bsize) - 1)) == 0 &&
9768 	    rw != S_CREATE &&
9769 	    !(vp->v_flag & VNOCACHE)) {
9770 		mutex_enter(&rp->r_statelock);
9771 
9772 		/*
9773 		 * Calculate the number of readaheads to do.
9774 		 * a) No readaheads at offset = 0.
9775 		 * b) Do maximum(nfs4_nra) readaheads when the readahead
9776 		 *    window is closed.
9777 		 * c) Do readaheads between 1 to (nfs4_nra - 1) depending
9778 		 *    upon how far the readahead window is open or close.
9779 		 * d) No readaheads if rp->r_nextr is not within the scope
9780 		 *    of the readahead window (random i/o).
9781 		 */
9782 
9783 		if (off == 0)
9784 			readahead = 0;
9785 		else if (blkoff == rp->r_nextr)
9786 			readahead = nfs4_nra;
9787 		else if (rp->r_nextr > blkoff &&
9788 		    ((ra_window = (rp->r_nextr - blkoff) / bsize)
9789 		    <= (nfs4_nra - 1)))
9790 			readahead = nfs4_nra - ra_window;
9791 		else
9792 			readahead = 0;
9793 
9794 		rablkoff = rp->r_nextr;
9795 		while (readahead > 0 && rablkoff + bsize < rp->r_size) {
9796 			mutex_exit(&rp->r_statelock);
9797 			if (nfs4_async_readahead(vp, rablkoff + bsize,
9798 			    addr + (rablkoff + bsize - off),
9799 			    seg, cr, nfs4_readahead) < 0) {
9800 				mutex_enter(&rp->r_statelock);
9801 				break;
9802 			}
9803 			readahead--;
9804 			rablkoff += bsize;
9805 			/*
9806 			 * Indicate that we did a readahead so
9807 			 * readahead offset is not updated
9808 			 * by the synchronous read below.
9809 			 */
9810 			readahead_issued = 1;
9811 			mutex_enter(&rp->r_statelock);
9812 			/*
9813 			 * set readahead offset to
9814 			 * offset of last async readahead
9815 			 * request.
9816 			 */
9817 			rp->r_nextr = rablkoff;
9818 		}
9819 		mutex_exit(&rp->r_statelock);
9820 	}
9821 
9822 again:
9823 	if ((pagefound = page_exists(vp, off)) == NULL) {
9824 		if (pl == NULL) {
9825 			(void) nfs4_async_readahead(vp, blkoff, addr, seg, cr,
9826 			    nfs4_readahead);
9827 		} else if (rw == S_CREATE) {
9828 			/*
9829 			 * Block for this page is not allocated, or the offset
9830 			 * is beyond the current allocation size, or we're
9831 			 * allocating a swap slot and the page was not found,
9832 			 * so allocate it and return a zero page.
9833 			 */
9834 			if ((pp = page_create_va(vp, off,
9835 			    PAGESIZE, PG_WAIT, seg, addr)) == NULL)
9836 				cmn_err(CE_PANIC, "nfs4_getapage: page_create");
9837 			io_len = PAGESIZE;
9838 			mutex_enter(&rp->r_statelock);
9839 			rp->r_nextr = off + PAGESIZE;
9840 			mutex_exit(&rp->r_statelock);
9841 		} else {
9842 			/*
9843 			 * Need to go to server to get a block
9844 			 */
9845 			mutex_enter(&rp->r_statelock);
9846 			if (blkoff < rp->r_size &&
9847 			    blkoff + bsize > rp->r_size) {
9848 				/*
9849 				 * If less than a block left in
9850 				 * file read less than a block.
9851 				 */
9852 				if (rp->r_size <= off) {
9853 					/*
9854 					 * Trying to access beyond EOF,
9855 					 * set up to get at least one page.
9856 					 */
9857 					blksize = off + PAGESIZE - blkoff;
9858 				} else
9859 					blksize = rp->r_size - blkoff;
9860 			} else if ((off == 0) ||
9861 			    (off != rp->r_nextr && !readahead_issued)) {
9862 				blksize = PAGESIZE;
9863 				blkoff = off; /* block = page here */
9864 			} else
9865 				blksize = bsize;
9866 			mutex_exit(&rp->r_statelock);
9867 
9868 			pp = pvn_read_kluster(vp, off, seg, addr, &io_off,
9869 			    &io_len, blkoff, blksize, 0);
9870 
9871 			/*
9872 			 * Some other thread has entered the page,
9873 			 * so just use it.
9874 			 */
9875 			if (pp == NULL)
9876 				goto again;
9877 
9878 			/*
9879 			 * Now round the request size up to page boundaries.
9880 			 * This ensures that the entire page will be
9881 			 * initialized to zeroes if EOF is encountered.
9882 			 */
9883 			io_len = ptob(btopr(io_len));
9884 
9885 			bp = pageio_setup(pp, io_len, vp, B_READ);
9886 			ASSERT(bp != NULL);
9887 
9888 			/*
9889 			 * pageio_setup should have set b_addr to 0.  This
9890 			 * is correct since we want to do I/O on a page
9891 			 * boundary.  bp_mapin will use this addr to calculate
9892 			 * an offset, and then set b_addr to the kernel virtual
9893 			 * address it allocated for us.
9894 			 */
9895 			ASSERT(bp->b_un.b_addr == 0);
9896 
9897 			bp->b_edev = 0;
9898 			bp->b_dev = 0;
9899 			bp->b_lblkno = lbtodb(io_off);
9900 			bp->b_file = vp;
9901 			bp->b_offset = (offset_t)off;
9902 			bp_mapin(bp);
9903 
9904 			/*
9905 			 * If doing a write beyond what we believe is EOF,
9906 			 * don't bother trying to read the pages from the
9907 			 * server, we'll just zero the pages here.  We
9908 			 * don't check that the rw flag is S_WRITE here
9909 			 * because some implementations may attempt a
9910 			 * read access to the buffer before copying data.
9911 			 */
9912 			mutex_enter(&rp->r_statelock);
9913 			if (io_off >= rp->r_size && seg == segkmap) {
9914 				mutex_exit(&rp->r_statelock);
9915 				bzero(bp->b_un.b_addr, io_len);
9916 			} else {
9917 				mutex_exit(&rp->r_statelock);
9918 				error = nfs4_bio(bp, NULL, cr, FALSE);
9919 			}
9920 
9921 			/*
9922 			 * Unmap the buffer before freeing it.
9923 			 */
9924 			bp_mapout(bp);
9925 			pageio_done(bp);
9926 
9927 			savepp = pp;
9928 			do {
9929 				pp->p_fsdata = C_NOCOMMIT;
9930 			} while ((pp = pp->p_next) != savepp);
9931 
9932 			if (error == NFS_EOF) {
9933 				/*
9934 				 * If doing a write system call just return
9935 				 * zeroed pages, else user tried to get pages
9936 				 * beyond EOF, return error.  We don't check
9937 				 * that the rw flag is S_WRITE here because
9938 				 * some implementations may attempt a read
9939 				 * access to the buffer before copying data.
9940 				 */
9941 				if (seg == segkmap)
9942 					error = 0;
9943 				else
9944 					error = EFAULT;
9945 			}
9946 
9947 			if (!readahead_issued && !error) {
9948 				mutex_enter(&rp->r_statelock);
9949 				rp->r_nextr = io_off + io_len;
9950 				mutex_exit(&rp->r_statelock);
9951 			}
9952 		}
9953 	}
9954 
9955 out:
9956 	if (pl == NULL)
9957 		return (error);
9958 
9959 	if (error) {
9960 		if (pp != NULL)
9961 			pvn_read_done(pp, B_ERROR);
9962 		return (error);
9963 	}
9964 
9965 	if (pagefound) {
9966 		se_t se = (rw == S_CREATE ? SE_EXCL : SE_SHARED);
9967 
9968 		/*
9969 		 * Page exists in the cache, acquire the appropriate lock.
9970 		 * If this fails, start all over again.
9971 		 */
9972 		if ((pp = page_lookup(vp, off, se)) == NULL) {
9973 #ifdef DEBUG
9974 			nfs4_lostpage++;
9975 #endif
9976 			goto reread;
9977 		}
9978 		pl[0] = pp;
9979 		pl[1] = NULL;
9980 		return (0);
9981 	}
9982 
9983 	if (pp != NULL)
9984 		pvn_plist_init(pp, pl, plsz, off, io_len, rw);
9985 
9986 	return (error);
9987 }
9988 
9989 static void
9990 nfs4_readahead(vnode_t *vp, u_offset_t blkoff, caddr_t addr, struct seg *seg,
9991     cred_t *cr)
9992 {
9993 	int error;
9994 	page_t *pp;
9995 	u_offset_t io_off;
9996 	size_t io_len;
9997 	struct buf *bp;
9998 	uint_t bsize, blksize;
9999 	rnode4_t *rp = VTOR4(vp);
10000 	page_t *savepp;
10001 
10002 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10003 
10004 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
10005 
10006 	mutex_enter(&rp->r_statelock);
10007 	if (blkoff < rp->r_size && blkoff + bsize > rp->r_size) {
10008 		/*
10009 		 * If less than a block left in file read less
10010 		 * than a block.
10011 		 */
10012 		blksize = rp->r_size - blkoff;
10013 	} else
10014 		blksize = bsize;
10015 	mutex_exit(&rp->r_statelock);
10016 
10017 	pp = pvn_read_kluster(vp, blkoff, segkmap, addr,
10018 	    &io_off, &io_len, blkoff, blksize, 1);
10019 	/*
10020 	 * The isra flag passed to the kluster function is 1, we may have
10021 	 * gotten a return value of NULL for a variety of reasons (# of free
10022 	 * pages < minfree, someone entered the page on the vnode etc). In all
10023 	 * cases, we want to punt on the readahead.
10024 	 */
10025 	if (pp == NULL)
10026 		return;
10027 
10028 	/*
10029 	 * Now round the request size up to page boundaries.
10030 	 * This ensures that the entire page will be
10031 	 * initialized to zeroes if EOF is encountered.
10032 	 */
10033 	io_len = ptob(btopr(io_len));
10034 
10035 	bp = pageio_setup(pp, io_len, vp, B_READ);
10036 	ASSERT(bp != NULL);
10037 
10038 	/*
10039 	 * pageio_setup should have set b_addr to 0.  This is correct since
10040 	 * we want to do I/O on a page boundary. bp_mapin() will use this addr
10041 	 * to calculate an offset, and then set b_addr to the kernel virtual
10042 	 * address it allocated for us.
10043 	 */
10044 	ASSERT(bp->b_un.b_addr == 0);
10045 
10046 	bp->b_edev = 0;
10047 	bp->b_dev = 0;
10048 	bp->b_lblkno = lbtodb(io_off);
10049 	bp->b_file = vp;
10050 	bp->b_offset = (offset_t)blkoff;
10051 	bp_mapin(bp);
10052 
10053 	/*
10054 	 * If doing a write beyond what we believe is EOF, don't bother trying
10055 	 * to read the pages from the server, we'll just zero the pages here.
10056 	 * We don't check that the rw flag is S_WRITE here because some
10057 	 * implementations may attempt a read access to the buffer before
10058 	 * copying data.
10059 	 */
10060 	mutex_enter(&rp->r_statelock);
10061 	if (io_off >= rp->r_size && seg == segkmap) {
10062 		mutex_exit(&rp->r_statelock);
10063 		bzero(bp->b_un.b_addr, io_len);
10064 		error = 0;
10065 	} else {
10066 		mutex_exit(&rp->r_statelock);
10067 		error = nfs4_bio(bp, NULL, cr, TRUE);
10068 		if (error == NFS_EOF)
10069 			error = 0;
10070 	}
10071 
10072 	/*
10073 	 * Unmap the buffer before freeing it.
10074 	 */
10075 	bp_mapout(bp);
10076 	pageio_done(bp);
10077 
10078 	savepp = pp;
10079 	do {
10080 		pp->p_fsdata = C_NOCOMMIT;
10081 	} while ((pp = pp->p_next) != savepp);
10082 
10083 	pvn_read_done(pp, error ? B_READ | B_ERROR : B_READ);
10084 
10085 	/*
10086 	 * In case of error set readahead offset
10087 	 * to the lowest offset.
10088 	 * pvn_read_done() calls VN_DISPOSE to destroy the pages
10089 	 */
10090 	if (error && rp->r_nextr > io_off) {
10091 		mutex_enter(&rp->r_statelock);
10092 		if (rp->r_nextr > io_off)
10093 			rp->r_nextr = io_off;
10094 		mutex_exit(&rp->r_statelock);
10095 	}
10096 }
10097 
10098 /*
10099  * Flags are composed of {B_INVAL, B_FREE, B_DONTNEED, B_FORCE}
10100  * If len == 0, do from off to EOF.
10101  *
10102  * The normal cases should be len == 0 && off == 0 (entire vp list) or
10103  * len == MAXBSIZE (from segmap_release actions), and len == PAGESIZE
10104  * (from pageout).
10105  */
10106 /* ARGSUSED */
10107 static int
10108 nfs4_putpage(vnode_t *vp, offset_t off, size_t len, int flags, cred_t *cr,
10109 	caller_context_t *ct)
10110 {
10111 	int error;
10112 	rnode4_t *rp;
10113 
10114 	ASSERT(cr != NULL);
10115 
10116 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
10117 		return (EIO);
10118 
10119 	rp = VTOR4(vp);
10120 	if (IS_SHADOW(vp, rp))
10121 		vp = RTOV4(rp);
10122 
10123 	/*
10124 	 * XXX - Why should this check be made here?
10125 	 */
10126 	if (vp->v_flag & VNOMAP)
10127 		return (ENOSYS);
10128 
10129 	if (len == 0 && !(flags & B_INVAL) &&
10130 	    (vp->v_vfsp->vfs_flag & VFS_RDONLY))
10131 		return (0);
10132 
10133 	mutex_enter(&rp->r_statelock);
10134 	rp->r_count++;
10135 	mutex_exit(&rp->r_statelock);
10136 	error = nfs4_putpages(vp, off, len, flags, cr);
10137 	mutex_enter(&rp->r_statelock);
10138 	rp->r_count--;
10139 	cv_broadcast(&rp->r_cv);
10140 	mutex_exit(&rp->r_statelock);
10141 
10142 	return (error);
10143 }
10144 
10145 /*
10146  * Write out a single page, possibly klustering adjacent dirty pages.
10147  */
10148 int
10149 nfs4_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp, size_t *lenp,
10150     int flags, cred_t *cr)
10151 {
10152 	u_offset_t io_off;
10153 	u_offset_t lbn_off;
10154 	u_offset_t lbn;
10155 	size_t io_len;
10156 	uint_t bsize;
10157 	int error;
10158 	rnode4_t *rp;
10159 
10160 	ASSERT(!(vp->v_vfsp->vfs_flag & VFS_RDONLY));
10161 	ASSERT(pp != NULL);
10162 	ASSERT(cr != NULL);
10163 	ASSERT((flags & B_ASYNC) || nfs_zone() == VTOMI4(vp)->mi_zone);
10164 
10165 	rp = VTOR4(vp);
10166 	ASSERT(rp->r_count > 0);
10167 	ASSERT(!IS_SHADOW(vp, rp));
10168 
10169 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
10170 	lbn = pp->p_offset / bsize;
10171 	lbn_off = lbn * bsize;
10172 
10173 	/*
10174 	 * Find a kluster that fits in one block, or in
10175 	 * one page if pages are bigger than blocks.  If
10176 	 * there is less file space allocated than a whole
10177 	 * page, we'll shorten the i/o request below.
10178 	 */
10179 	pp = pvn_write_kluster(vp, pp, &io_off, &io_len, lbn_off,
10180 	    roundup(bsize, PAGESIZE), flags);
10181 
10182 	/*
10183 	 * pvn_write_kluster shouldn't have returned a page with offset
10184 	 * behind the original page we were given.  Verify that.
10185 	 */
10186 	ASSERT((pp->p_offset / bsize) >= lbn);
10187 
10188 	/*
10189 	 * Now pp will have the list of kept dirty pages marked for
10190 	 * write back.  It will also handle invalidation and freeing
10191 	 * of pages that are not dirty.  Check for page length rounding
10192 	 * problems.
10193 	 */
10194 	if (io_off + io_len > lbn_off + bsize) {
10195 		ASSERT((io_off + io_len) - (lbn_off + bsize) < PAGESIZE);
10196 		io_len = lbn_off + bsize - io_off;
10197 	}
10198 	/*
10199 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10200 	 * consistent value of r_size. R4MODINPROGRESS is set in writerp4().
10201 	 * When R4MODINPROGRESS is set it indicates that a uiomove() is in
10202 	 * progress and the r_size has not been made consistent with the
10203 	 * new size of the file. When the uiomove() completes the r_size is
10204 	 * updated and the R4MODINPROGRESS flag is cleared.
10205 	 *
10206 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10207 	 * consistent value of r_size. Without this handshaking, it is
10208 	 * possible that nfs4_bio() picks  up the old value of r_size
10209 	 * before the uiomove() in writerp4() completes. This will result
10210 	 * in the write through nfs4_bio() being dropped.
10211 	 *
10212 	 * More precisely, there is a window between the time the uiomove()
10213 	 * completes and the time the r_size is updated. If a VOP_PUTPAGE()
10214 	 * operation intervenes in this window, the page will be picked up,
10215 	 * because it is dirty (it will be unlocked, unless it was
10216 	 * pagecreate'd). When the page is picked up as dirty, the dirty
10217 	 * bit is reset (pvn_getdirty()). In nfs4write(), r_size is
10218 	 * checked. This will still be the old size. Therefore the page will
10219 	 * not be written out. When segmap_release() calls VOP_PUTPAGE(),
10220 	 * the page will be found to be clean and the write will be dropped.
10221 	 */
10222 	if (rp->r_flags & R4MODINPROGRESS) {
10223 		mutex_enter(&rp->r_statelock);
10224 		if ((rp->r_flags & R4MODINPROGRESS) &&
10225 		    rp->r_modaddr + MAXBSIZE > io_off &&
10226 		    rp->r_modaddr < io_off + io_len) {
10227 			page_t *plist;
10228 			/*
10229 			 * A write is in progress for this region of the file.
10230 			 * If we did not detect R4MODINPROGRESS here then this
10231 			 * path through nfs_putapage() would eventually go to
10232 			 * nfs4_bio() and may not write out all of the data
10233 			 * in the pages. We end up losing data. So we decide
10234 			 * to set the modified bit on each page in the page
10235 			 * list and mark the rnode with R4DIRTY. This write
10236 			 * will be restarted at some later time.
10237 			 */
10238 			plist = pp;
10239 			while (plist != NULL) {
10240 				pp = plist;
10241 				page_sub(&plist, pp);
10242 				hat_setmod(pp);
10243 				page_io_unlock(pp);
10244 				page_unlock(pp);
10245 			}
10246 			rp->r_flags |= R4DIRTY;
10247 			mutex_exit(&rp->r_statelock);
10248 			if (offp)
10249 				*offp = io_off;
10250 			if (lenp)
10251 				*lenp = io_len;
10252 			return (0);
10253 		}
10254 		mutex_exit(&rp->r_statelock);
10255 	}
10256 
10257 	if (flags & B_ASYNC) {
10258 		error = nfs4_async_putapage(vp, pp, io_off, io_len, flags, cr,
10259 		    nfs4_sync_putapage);
10260 	} else
10261 		error = nfs4_sync_putapage(vp, pp, io_off, io_len, flags, cr);
10262 
10263 	if (offp)
10264 		*offp = io_off;
10265 	if (lenp)
10266 		*lenp = io_len;
10267 	return (error);
10268 }
10269 
10270 static int
10271 nfs4_sync_putapage(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
10272     int flags, cred_t *cr)
10273 {
10274 	int error;
10275 	rnode4_t *rp;
10276 
10277 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10278 
10279 	flags |= B_WRITE;
10280 
10281 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
10282 
10283 	rp = VTOR4(vp);
10284 
10285 	if ((error == ENOSPC || error == EDQUOT || error == EFBIG ||
10286 	    error == EACCES) &&
10287 	    (flags & (B_INVAL|B_FORCE)) != (B_INVAL|B_FORCE)) {
10288 		if (!(rp->r_flags & R4OUTOFSPACE)) {
10289 			mutex_enter(&rp->r_statelock);
10290 			rp->r_flags |= R4OUTOFSPACE;
10291 			mutex_exit(&rp->r_statelock);
10292 		}
10293 		flags |= B_ERROR;
10294 		pvn_write_done(pp, flags);
10295 		/*
10296 		 * If this was not an async thread, then try again to
10297 		 * write out the pages, but this time, also destroy
10298 		 * them whether or not the write is successful.  This
10299 		 * will prevent memory from filling up with these
10300 		 * pages and destroying them is the only alternative
10301 		 * if they can't be written out.
10302 		 *
10303 		 * Don't do this if this is an async thread because
10304 		 * when the pages are unlocked in pvn_write_done,
10305 		 * some other thread could have come along, locked
10306 		 * them, and queued for an async thread.  It would be
10307 		 * possible for all of the async threads to be tied
10308 		 * up waiting to lock the pages again and they would
10309 		 * all already be locked and waiting for an async
10310 		 * thread to handle them.  Deadlock.
10311 		 */
10312 		if (!(flags & B_ASYNC)) {
10313 			error = nfs4_putpage(vp, io_off, io_len,
10314 			    B_INVAL | B_FORCE, cr, NULL);
10315 		}
10316 	} else {
10317 		if (error)
10318 			flags |= B_ERROR;
10319 		else if (rp->r_flags & R4OUTOFSPACE) {
10320 			mutex_enter(&rp->r_statelock);
10321 			rp->r_flags &= ~R4OUTOFSPACE;
10322 			mutex_exit(&rp->r_statelock);
10323 		}
10324 		pvn_write_done(pp, flags);
10325 		if (freemem < desfree)
10326 			(void) nfs4_commit_vp(vp, (u_offset_t)0, 0, cr,
10327 			    NFS4_WRITE_NOWAIT);
10328 	}
10329 
10330 	return (error);
10331 }
10332 
10333 #ifdef DEBUG
10334 int nfs4_force_open_before_mmap = 0;
10335 #endif
10336 
10337 /* ARGSUSED */
10338 static int
10339 nfs4_map(vnode_t *vp, offset_t off, struct as *as, caddr_t *addrp,
10340     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
10341     caller_context_t *ct)
10342 {
10343 	struct segvn_crargs vn_a;
10344 	int error = 0;
10345 	rnode4_t *rp = VTOR4(vp);
10346 	mntinfo4_t *mi = VTOMI4(vp);
10347 
10348 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10349 		return (EIO);
10350 
10351 	if (vp->v_flag & VNOMAP)
10352 		return (ENOSYS);
10353 
10354 	if (off < 0 || (off + len) < 0)
10355 		return (ENXIO);
10356 
10357 	if (vp->v_type != VREG)
10358 		return (ENODEV);
10359 
10360 	/*
10361 	 * If the file is delegated to the client don't do anything.
10362 	 * If the file is not delegated, then validate the data cache.
10363 	 */
10364 	mutex_enter(&rp->r_statev4_lock);
10365 	if (rp->r_deleg_type == OPEN_DELEGATE_NONE) {
10366 		mutex_exit(&rp->r_statev4_lock);
10367 		error = nfs4_validate_caches(vp, cr);
10368 		if (error)
10369 			return (error);
10370 	} else {
10371 		mutex_exit(&rp->r_statev4_lock);
10372 	}
10373 
10374 	/*
10375 	 * Check to see if the vnode is currently marked as not cachable.
10376 	 * This means portions of the file are locked (through VOP_FRLOCK).
10377 	 * In this case the map request must be refused.  We use
10378 	 * rp->r_lkserlock to avoid a race with concurrent lock requests.
10379 	 */
10380 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_READER, INTR4(vp)))
10381 		return (EINTR);
10382 
10383 	if (vp->v_flag & VNOCACHE) {
10384 		error = EAGAIN;
10385 		goto done;
10386 	}
10387 
10388 	/*
10389 	 * Don't allow concurrent locks and mapping if mandatory locking is
10390 	 * enabled.
10391 	 */
10392 	if (flk_has_remote_locks(vp)) {
10393 		struct vattr va;
10394 		va.va_mask = AT_MODE;
10395 		error = nfs4getattr(vp, &va, cr);
10396 		if (error != 0)
10397 			goto done;
10398 		if (MANDLOCK(vp, va.va_mode)) {
10399 			error = EAGAIN;
10400 			goto done;
10401 		}
10402 	}
10403 
10404 	/*
10405 	 * It is possible that the rnode has a lost lock request that we
10406 	 * are still trying to recover, and that the request conflicts with
10407 	 * this map request.
10408 	 *
10409 	 * An alternative approach would be for nfs4_safemap() to consider
10410 	 * queued lock requests when deciding whether to set or clear
10411 	 * VNOCACHE.  This would require the frlock code path to call
10412 	 * nfs4_safemap() after enqueing a lost request.
10413 	 */
10414 	if (nfs4_map_lost_lock_conflict(vp)) {
10415 		error = EAGAIN;
10416 		goto done;
10417 	}
10418 
10419 	as_rangelock(as);
10420 	if (!(flags & MAP_FIXED)) {
10421 		map_addr(addrp, len, off, 1, flags);
10422 		if (*addrp == NULL) {
10423 			as_rangeunlock(as);
10424 			error = ENOMEM;
10425 			goto done;
10426 		}
10427 	} else {
10428 		/*
10429 		 * User specified address - blow away any previous mappings
10430 		 */
10431 		(void) as_unmap(as, *addrp, len);
10432 	}
10433 
10434 	if (vp->v_type == VREG) {
10435 		/*
10436 		 * We need to retrieve the open stream
10437 		 */
10438 		nfs4_open_stream_t	*osp = NULL;
10439 		nfs4_open_owner_t	*oop = NULL;
10440 
10441 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10442 		if (oop != NULL) {
10443 			/* returns with 'os_sync_lock' held */
10444 			osp = find_open_stream(oop, rp);
10445 			open_owner_rele(oop);
10446 		}
10447 		if (osp == NULL) {
10448 #ifdef DEBUG
10449 			if (nfs4_force_open_before_mmap) {
10450 				error = EIO;
10451 				goto done;
10452 			}
10453 #endif
10454 			/* returns with 'os_sync_lock' held */
10455 			error = open_and_get_osp(vp, cr, &osp);
10456 			if (osp == NULL) {
10457 				NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10458 				    "nfs4_map: we tried to OPEN the file "
10459 				    "but again no osp, so fail with EIO"));
10460 				goto done;
10461 			}
10462 		}
10463 
10464 		if (osp->os_failed_reopen) {
10465 			mutex_exit(&osp->os_sync_lock);
10466 			open_stream_rele(osp, rp);
10467 			NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
10468 			    "nfs4_map: os_failed_reopen set on "
10469 			    "osp %p, cr %p, rp %s", (void *)osp,
10470 			    (void *)cr, rnode4info(rp)));
10471 			error = EIO;
10472 			goto done;
10473 		}
10474 		mutex_exit(&osp->os_sync_lock);
10475 		open_stream_rele(osp, rp);
10476 	}
10477 
10478 	vn_a.vp = vp;
10479 	vn_a.offset = off;
10480 	vn_a.type = (flags & MAP_TYPE);
10481 	vn_a.prot = (uchar_t)prot;
10482 	vn_a.maxprot = (uchar_t)maxprot;
10483 	vn_a.flags = (flags & ~MAP_TYPE);
10484 	vn_a.cred = cr;
10485 	vn_a.amp = NULL;
10486 	vn_a.szc = 0;
10487 	vn_a.lgrp_mem_policy_flags = 0;
10488 
10489 	error = as_map(as, *addrp, len, segvn_create, &vn_a);
10490 	as_rangeunlock(as);
10491 
10492 done:
10493 	nfs_rw_exit(&rp->r_lkserlock);
10494 	return (error);
10495 }
10496 
10497 /*
10498  * We're most likely dealing with a kernel module that likes to READ
10499  * and mmap without OPENing the file (ie: lookup/read/mmap), so lets
10500  * officially OPEN the file to create the necessary client state
10501  * for bookkeeping of os_mmap_read/write counts.
10502  *
10503  * Since VOP_MAP only passes in a pointer to the vnode rather than
10504  * a double pointer, we can't handle the case where nfs4open_otw()
10505  * returns a different vnode than the one passed into VOP_MAP (since
10506  * VOP_DELMAP will not see the vnode nfs4open_otw used).  In this case,
10507  * we return NULL and let nfs4_map() fail.  Note: the only case where
10508  * this should happen is if the file got removed and replaced with the
10509  * same name on the server (in addition to the fact that we're trying
10510  * to VOP_MAP withouth VOP_OPENing the file in the first place).
10511  */
10512 static int
10513 open_and_get_osp(vnode_t *map_vp, cred_t *cr, nfs4_open_stream_t **ospp)
10514 {
10515 	rnode4_t		*rp, *drp;
10516 	vnode_t			*dvp, *open_vp;
10517 	char			file_name[MAXNAMELEN];
10518 	int			just_created;
10519 	nfs4_open_stream_t	*osp;
10520 	nfs4_open_owner_t	*oop;
10521 	int			error;
10522 
10523 	*ospp = NULL;
10524 	open_vp = map_vp;
10525 
10526 	rp = VTOR4(open_vp);
10527 	if ((error = vtodv(open_vp, &dvp, cr, TRUE)) != 0)
10528 		return (error);
10529 	drp = VTOR4(dvp);
10530 
10531 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp))) {
10532 		VN_RELE(dvp);
10533 		return (EINTR);
10534 	}
10535 
10536 	if ((error = vtoname(open_vp, file_name, MAXNAMELEN)) != 0) {
10537 		nfs_rw_exit(&drp->r_rwlock);
10538 		VN_RELE(dvp);
10539 		return (error);
10540 	}
10541 
10542 	mutex_enter(&rp->r_statev4_lock);
10543 	if (rp->created_v4) {
10544 		rp->created_v4 = 0;
10545 		mutex_exit(&rp->r_statev4_lock);
10546 
10547 		dnlc_update(dvp, file_name, open_vp);
10548 		/* This is needed so we don't bump the open ref count */
10549 		just_created = 1;
10550 	} else {
10551 		mutex_exit(&rp->r_statev4_lock);
10552 		just_created = 0;
10553 	}
10554 
10555 	VN_HOLD(map_vp);
10556 
10557 	error = nfs4open_otw(dvp, file_name, NULL, &open_vp, cr, 0, FREAD, 0,
10558 	    just_created);
10559 	if (error) {
10560 		nfs_rw_exit(&drp->r_rwlock);
10561 		VN_RELE(dvp);
10562 		VN_RELE(map_vp);
10563 		return (error);
10564 	}
10565 
10566 	nfs_rw_exit(&drp->r_rwlock);
10567 	VN_RELE(dvp);
10568 
10569 	/*
10570 	 * If nfs4open_otw() returned a different vnode then "undo"
10571 	 * the open and return failure to the caller.
10572 	 */
10573 	if (!VN_CMP(open_vp, map_vp)) {
10574 		nfs4_error_t e;
10575 
10576 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10577 		    "open returned a different vnode"));
10578 		/*
10579 		 * If there's an error, ignore it,
10580 		 * and let VOP_INACTIVE handle it.
10581 		 */
10582 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10583 		    CLOSE_NORM, 0, 0, 0);
10584 		VN_RELE(map_vp);
10585 		return (EIO);
10586 	}
10587 
10588 	VN_RELE(map_vp);
10589 
10590 	oop = find_open_owner(cr, NFS4_PERM_CREATED, VTOMI4(open_vp));
10591 	if (!oop) {
10592 		nfs4_error_t e;
10593 
10594 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10595 		    "no open owner"));
10596 		/*
10597 		 * If there's an error, ignore it,
10598 		 * and let VOP_INACTIVE handle it.
10599 		 */
10600 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10601 		    CLOSE_NORM, 0, 0, 0);
10602 		return (EIO);
10603 	}
10604 	osp = find_open_stream(oop, rp);
10605 	open_owner_rele(oop);
10606 	*ospp = osp;
10607 	return (0);
10608 }
10609 
10610 /*
10611  * Please be aware that when this function is called, the address space write
10612  * a_lock is held.  Do not put over the wire calls in this function.
10613  */
10614 /* ARGSUSED */
10615 static int
10616 nfs4_addmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
10617     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
10618     caller_context_t *ct)
10619 {
10620 	rnode4_t		*rp;
10621 	int			error = 0;
10622 	mntinfo4_t		*mi;
10623 
10624 	mi = VTOMI4(vp);
10625 	rp = VTOR4(vp);
10626 
10627 	if (nfs_zone() != mi->mi_zone)
10628 		return (EIO);
10629 	if (vp->v_flag & VNOMAP)
10630 		return (ENOSYS);
10631 
10632 	/*
10633 	 * Need to hold rwlock while incrementing the mapcnt so that
10634 	 * mmap'ing can be serialized with writes so that the caching
10635 	 * can be handled correctly.
10636 	 *
10637 	 * Don't need to update the open stream first, since this
10638 	 * mmap can't add any additional share access that isn't
10639 	 * already contained in the open stream (for the case where we
10640 	 * open/mmap/only update rp->r_mapcnt/server reboots/reopen doesn't
10641 	 * take into account os_mmap_read[write] counts).
10642 	 */
10643 	if (nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, INTR(vp)))
10644 		return (EINTR);
10645 	atomic_add_long((ulong_t *)&rp->r_mapcnt, btopr(len));
10646 	nfs_rw_exit(&rp->r_rwlock);
10647 
10648 	if (vp->v_type == VREG) {
10649 		/*
10650 		 * We need to retrieve the open stream and update the counts.
10651 		 * If there is no open stream here, something is wrong.
10652 		 */
10653 		nfs4_open_stream_t	*osp = NULL;
10654 		nfs4_open_owner_t	*oop = NULL;
10655 
10656 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10657 		if (oop != NULL) {
10658 			/* returns with 'os_sync_lock' held */
10659 			osp = find_open_stream(oop, rp);
10660 			open_owner_rele(oop);
10661 		}
10662 		if (osp == NULL) {
10663 			NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10664 			    "nfs4_addmap: we should have an osp"
10665 			    "but we don't, so fail with EIO"));
10666 			error = EIO;
10667 			goto out;
10668 		}
10669 
10670 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "nfs4_addmap: osp %p,"
10671 		    " pages %ld, prot 0x%x", (void *)osp, btopr(len), prot));
10672 
10673 		/*
10674 		 * Update the map count in the open stream.
10675 		 * This is necessary in the case where we
10676 		 * open/mmap/close/, then the server reboots, and we
10677 		 * attempt to reopen.  If the mmap doesn't add share
10678 		 * access then we send an invalid reopen with
10679 		 * access = NONE.
10680 		 *
10681 		 * We need to specifically check each PROT_* so a mmap
10682 		 * call of (PROT_WRITE | PROT_EXEC) will ensure us both
10683 		 * read and write access.  A simple comparison of prot
10684 		 * to ~PROT_WRITE to determine read access is insufficient
10685 		 * since prot can be |= with PROT_USER, etc.
10686 		 */
10687 
10688 		/*
10689 		 * Unless we're MAP_SHARED, no sense in adding os_mmap_write
10690 		 */
10691 		if ((flags & MAP_SHARED) && (maxprot & PROT_WRITE))
10692 			osp->os_mmap_write += btopr(len);
10693 		if (maxprot & PROT_READ)
10694 			osp->os_mmap_read += btopr(len);
10695 		if (maxprot & PROT_EXEC)
10696 			osp->os_mmap_read += btopr(len);
10697 		/*
10698 		 * Ensure that os_mmap_read gets incremented, even if
10699 		 * maxprot were to look like PROT_NONE.
10700 		 */
10701 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
10702 		    !(maxprot & PROT_EXEC))
10703 			osp->os_mmap_read += btopr(len);
10704 		osp->os_mapcnt += btopr(len);
10705 		mutex_exit(&osp->os_sync_lock);
10706 		open_stream_rele(osp, rp);
10707 	}
10708 
10709 out:
10710 	/*
10711 	 * If we got an error, then undo our
10712 	 * incrementing of 'r_mapcnt'.
10713 	 */
10714 
10715 	if (error) {
10716 		atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(len));
10717 		ASSERT(rp->r_mapcnt >= 0);
10718 	}
10719 	return (error);
10720 }
10721 
10722 /* ARGSUSED */
10723 static int
10724 nfs4_cmp(vnode_t *vp1, vnode_t *vp2, caller_context_t *ct)
10725 {
10726 
10727 	return (VTOR4(vp1) == VTOR4(vp2));
10728 }
10729 
10730 /* ARGSUSED */
10731 static int
10732 nfs4_frlock(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
10733     offset_t offset, struct flk_callback *flk_cbp, cred_t *cr,
10734     caller_context_t *ct)
10735 {
10736 	int rc;
10737 	u_offset_t start, end;
10738 	rnode4_t *rp;
10739 	int error = 0, intr = INTR4(vp);
10740 	nfs4_error_t e;
10741 
10742 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10743 		return (EIO);
10744 
10745 	/* check for valid cmd parameter */
10746 	if (cmd != F_GETLK && cmd != F_SETLK && cmd != F_SETLKW)
10747 		return (EINVAL);
10748 
10749 	/* Verify l_type. */
10750 	switch (bfp->l_type) {
10751 	case F_RDLCK:
10752 		if (cmd != F_GETLK && !(flag & FREAD))
10753 			return (EBADF);
10754 		break;
10755 	case F_WRLCK:
10756 		if (cmd != F_GETLK && !(flag & FWRITE))
10757 			return (EBADF);
10758 		break;
10759 	case F_UNLCK:
10760 		intr = 0;
10761 		break;
10762 
10763 	default:
10764 		return (EINVAL);
10765 	}
10766 
10767 	/* check the validity of the lock range */
10768 	if (rc = flk_convert_lock_data(vp, bfp, &start, &end, offset))
10769 		return (rc);
10770 	if (rc = flk_check_lock_data(start, end, MAXEND))
10771 		return (rc);
10772 
10773 	/*
10774 	 * If the filesystem is mounted using local locking, pass the
10775 	 * request off to the local locking code.
10776 	 */
10777 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK || vp->v_type != VREG) {
10778 		if (cmd == F_SETLK || cmd == F_SETLKW) {
10779 			/*
10780 			 * For complete safety, we should be holding
10781 			 * r_lkserlock.  However, we can't call
10782 			 * nfs4_safelock and then fs_frlock while
10783 			 * holding r_lkserlock, so just invoke
10784 			 * nfs4_safelock and expect that this will
10785 			 * catch enough of the cases.
10786 			 */
10787 			if (!nfs4_safelock(vp, bfp, cr))
10788 				return (EAGAIN);
10789 		}
10790 		return (fs_frlock(vp, cmd, bfp, flag, offset, flk_cbp, cr, ct));
10791 	}
10792 
10793 	rp = VTOR4(vp);
10794 
10795 	/*
10796 	 * Check whether the given lock request can proceed, given the
10797 	 * current file mappings.
10798 	 */
10799 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_WRITER, intr))
10800 		return (EINTR);
10801 	if (cmd == F_SETLK || cmd == F_SETLKW) {
10802 		if (!nfs4_safelock(vp, bfp, cr)) {
10803 			rc = EAGAIN;
10804 			goto done;
10805 		}
10806 	}
10807 
10808 	/*
10809 	 * Flush the cache after waiting for async I/O to finish.  For new
10810 	 * locks, this is so that the process gets the latest bits from the
10811 	 * server.  For unlocks, this is so that other clients see the
10812 	 * latest bits once the file has been unlocked.  If currently dirty
10813 	 * pages can't be flushed, then don't allow a lock to be set.  But
10814 	 * allow unlocks to succeed, to avoid having orphan locks on the
10815 	 * server.
10816 	 */
10817 	if (cmd != F_GETLK) {
10818 		mutex_enter(&rp->r_statelock);
10819 		while (rp->r_count > 0) {
10820 			if (intr) {
10821 				klwp_t *lwp = ttolwp(curthread);
10822 
10823 				if (lwp != NULL)
10824 					lwp->lwp_nostop++;
10825 				if (cv_wait_sig(&rp->r_cv,
10826 				    &rp->r_statelock) == 0) {
10827 					if (lwp != NULL)
10828 						lwp->lwp_nostop--;
10829 					rc = EINTR;
10830 					break;
10831 				}
10832 				if (lwp != NULL)
10833 					lwp->lwp_nostop--;
10834 				} else
10835 					cv_wait(&rp->r_cv, &rp->r_statelock);
10836 		}
10837 		mutex_exit(&rp->r_statelock);
10838 		if (rc != 0)
10839 			goto done;
10840 		error = nfs4_putpage(vp, (offset_t)0, 0, B_INVAL, cr, ct);
10841 		if (error) {
10842 			if (error == ENOSPC || error == EDQUOT) {
10843 				mutex_enter(&rp->r_statelock);
10844 				if (!rp->r_error)
10845 					rp->r_error = error;
10846 				mutex_exit(&rp->r_statelock);
10847 			}
10848 			if (bfp->l_type != F_UNLCK) {
10849 				rc = ENOLCK;
10850 				goto done;
10851 			}
10852 		}
10853 	}
10854 
10855 	/*
10856 	 * Call the lock manager to do the real work of contacting
10857 	 * the server and obtaining the lock.
10858 	 */
10859 	nfs4frlock(NFS4_LCK_CTYPE_NORM, vp, cmd, bfp, flag, offset,
10860 	    cr, &e, NULL, NULL);
10861 	rc = e.error;
10862 
10863 	if (rc == 0)
10864 		nfs4_lockcompletion(vp, cmd);
10865 
10866 done:
10867 	nfs_rw_exit(&rp->r_lkserlock);
10868 
10869 	return (rc);
10870 }
10871 
10872 /*
10873  * Free storage space associated with the specified vnode.  The portion
10874  * to be freed is specified by bfp->l_start and bfp->l_len (already
10875  * normalized to a "whence" of 0).
10876  *
10877  * This is an experimental facility whose continued existence is not
10878  * guaranteed.  Currently, we only support the special case
10879  * of l_len == 0, meaning free to end of file.
10880  */
10881 /* ARGSUSED */
10882 static int
10883 nfs4_space(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
10884     offset_t offset, cred_t *cr, caller_context_t *ct)
10885 {
10886 	int error;
10887 
10888 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10889 		return (EIO);
10890 	ASSERT(vp->v_type == VREG);
10891 	if (cmd != F_FREESP)
10892 		return (EINVAL);
10893 
10894 	error = convoff(vp, bfp, 0, offset);
10895 	if (!error) {
10896 		ASSERT(bfp->l_start >= 0);
10897 		if (bfp->l_len == 0) {
10898 			struct vattr va;
10899 
10900 			va.va_mask = AT_SIZE;
10901 			va.va_size = bfp->l_start;
10902 			error = nfs4setattr(vp, &va, 0, cr, NULL);
10903 		} else
10904 			error = EINVAL;
10905 	}
10906 
10907 	return (error);
10908 }
10909 
10910 /* ARGSUSED */
10911 int
10912 nfs4_realvp(vnode_t *vp, vnode_t **vpp, caller_context_t *ct)
10913 {
10914 	rnode4_t *rp;
10915 	rp = VTOR4(vp);
10916 
10917 	if (vp->v_type == VREG && IS_SHADOW(vp, rp)) {
10918 		vp = RTOV4(rp);
10919 	}
10920 	*vpp = vp;
10921 	return (0);
10922 }
10923 
10924 /*
10925  * Setup and add an address space callback to do the work of the delmap call.
10926  * The callback will (and must be) deleted in the actual callback function.
10927  *
10928  * This is done in order to take care of the problem that we have with holding
10929  * the address space's a_lock for a long period of time (e.g. if the NFS server
10930  * is down).  Callbacks will be executed in the address space code while the
10931  * a_lock is not held.  Holding the address space's a_lock causes things such
10932  * as ps and fork to hang because they are trying to acquire this lock as well.
10933  */
10934 /* ARGSUSED */
10935 static int
10936 nfs4_delmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
10937     size_t len, uint_t prot, uint_t maxprot, uint_t flags, cred_t *cr,
10938     caller_context_t *ct)
10939 {
10940 	int			caller_found;
10941 	int			error;
10942 	rnode4_t		*rp;
10943 	nfs4_delmap_args_t	*dmapp;
10944 	nfs4_delmapcall_t	*delmap_call;
10945 
10946 	if (vp->v_flag & VNOMAP)
10947 		return (ENOSYS);
10948 
10949 	/*
10950 	 * A process may not change zones if it has NFS pages mmap'ed
10951 	 * in, so we can't legitimately get here from the wrong zone.
10952 	 */
10953 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10954 
10955 	rp = VTOR4(vp);
10956 
10957 	/*
10958 	 * The way that the address space of this process deletes its mapping
10959 	 * of this file is via the following call chains:
10960 	 * - as_free()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
10961 	 * - as_unmap()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
10962 	 *
10963 	 * With the use of address space callbacks we are allowed to drop the
10964 	 * address space lock, a_lock, while executing the NFS operations that
10965 	 * need to go over the wire.  Returning EAGAIN to the caller of this
10966 	 * function is what drives the execution of the callback that we add
10967 	 * below.  The callback will be executed by the address space code
10968 	 * after dropping the a_lock.  When the callback is finished, since
10969 	 * we dropped the a_lock, it must be re-acquired and segvn_unmap()
10970 	 * is called again on the same segment to finish the rest of the work
10971 	 * that needs to happen during unmapping.
10972 	 *
10973 	 * This action of calling back into the segment driver causes
10974 	 * nfs4_delmap() to get called again, but since the callback was
10975 	 * already executed at this point, it already did the work and there
10976 	 * is nothing left for us to do.
10977 	 *
10978 	 * To Summarize:
10979 	 * - The first time nfs4_delmap is called by the current thread is when
10980 	 * we add the caller associated with this delmap to the delmap caller
10981 	 * list, add the callback, and return EAGAIN.
10982 	 * - The second time in this call chain when nfs4_delmap is called we
10983 	 * will find this caller in the delmap caller list and realize there
10984 	 * is no more work to do thus removing this caller from the list and
10985 	 * returning the error that was set in the callback execution.
10986 	 */
10987 	caller_found = nfs4_find_and_delete_delmapcall(rp, &error);
10988 	if (caller_found) {
10989 		/*
10990 		 * 'error' is from the actual delmap operations.  To avoid
10991 		 * hangs, we need to handle the return of EAGAIN differently
10992 		 * since this is what drives the callback execution.
10993 		 * In this case, we don't want to return EAGAIN and do the
10994 		 * callback execution because there are none to execute.
10995 		 */
10996 		if (error == EAGAIN)
10997 			return (0);
10998 		else
10999 			return (error);
11000 	}
11001 
11002 	/* current caller was not in the list */
11003 	delmap_call = nfs4_init_delmapcall();
11004 
11005 	mutex_enter(&rp->r_statelock);
11006 	list_insert_tail(&rp->r_indelmap, delmap_call);
11007 	mutex_exit(&rp->r_statelock);
11008 
11009 	dmapp = kmem_alloc(sizeof (nfs4_delmap_args_t), KM_SLEEP);
11010 
11011 	dmapp->vp = vp;
11012 	dmapp->off = off;
11013 	dmapp->addr = addr;
11014 	dmapp->len = len;
11015 	dmapp->prot = prot;
11016 	dmapp->maxprot = maxprot;
11017 	dmapp->flags = flags;
11018 	dmapp->cr = cr;
11019 	dmapp->caller = delmap_call;
11020 
11021 	error = as_add_callback(as, nfs4_delmap_callback, dmapp,
11022 	    AS_UNMAP_EVENT, addr, len, KM_SLEEP);
11023 
11024 	return (error ? error : EAGAIN);
11025 }
11026 
11027 static nfs4_delmapcall_t *
11028 nfs4_init_delmapcall()
11029 {
11030 	nfs4_delmapcall_t	*delmap_call;
11031 
11032 	delmap_call = kmem_alloc(sizeof (nfs4_delmapcall_t), KM_SLEEP);
11033 	delmap_call->call_id = curthread;
11034 	delmap_call->error = 0;
11035 
11036 	return (delmap_call);
11037 }
11038 
11039 static void
11040 nfs4_free_delmapcall(nfs4_delmapcall_t *delmap_call)
11041 {
11042 	kmem_free(delmap_call, sizeof (nfs4_delmapcall_t));
11043 }
11044 
11045 /*
11046  * Searches for the current delmap caller (based on curthread) in the list of
11047  * callers.  If it is found, we remove it and free the delmap caller.
11048  * Returns:
11049  *      0 if the caller wasn't found
11050  *      1 if the caller was found, removed and freed.  *errp will be set
11051  *	to what the result of the delmap was.
11052  */
11053 static int
11054 nfs4_find_and_delete_delmapcall(rnode4_t *rp, int *errp)
11055 {
11056 	nfs4_delmapcall_t	*delmap_call;
11057 
11058 	/*
11059 	 * If the list doesn't exist yet, we create it and return
11060 	 * that the caller wasn't found.  No list = no callers.
11061 	 */
11062 	mutex_enter(&rp->r_statelock);
11063 	if (!(rp->r_flags & R4DELMAPLIST)) {
11064 		/* The list does not exist */
11065 		list_create(&rp->r_indelmap, sizeof (nfs4_delmapcall_t),
11066 		    offsetof(nfs4_delmapcall_t, call_node));
11067 		rp->r_flags |= R4DELMAPLIST;
11068 		mutex_exit(&rp->r_statelock);
11069 		return (0);
11070 	} else {
11071 		/* The list exists so search it */
11072 		for (delmap_call = list_head(&rp->r_indelmap);
11073 		    delmap_call != NULL;
11074 		    delmap_call = list_next(&rp->r_indelmap, delmap_call)) {
11075 			if (delmap_call->call_id == curthread) {
11076 				/* current caller is in the list */
11077 				*errp = delmap_call->error;
11078 				list_remove(&rp->r_indelmap, delmap_call);
11079 				mutex_exit(&rp->r_statelock);
11080 				nfs4_free_delmapcall(delmap_call);
11081 				return (1);
11082 			}
11083 		}
11084 	}
11085 	mutex_exit(&rp->r_statelock);
11086 	return (0);
11087 }
11088 
11089 /*
11090  * Remove some pages from an mmap'd vnode.  Just update the
11091  * count of pages.  If doing close-to-open, then flush and
11092  * commit all of the pages associated with this file.
11093  * Otherwise, start an asynchronous page flush to write out
11094  * any dirty pages.  This will also associate a credential
11095  * with the rnode which can be used to write the pages.
11096  */
11097 /* ARGSUSED */
11098 static void
11099 nfs4_delmap_callback(struct as *as, void *arg, uint_t event)
11100 {
11101 	nfs4_error_t		e = { 0, NFS4_OK, RPC_SUCCESS };
11102 	rnode4_t		*rp;
11103 	mntinfo4_t		*mi;
11104 	nfs4_delmap_args_t	*dmapp = (nfs4_delmap_args_t *)arg;
11105 
11106 	rp = VTOR4(dmapp->vp);
11107 	mi = VTOMI4(dmapp->vp);
11108 
11109 	atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(dmapp->len));
11110 	ASSERT(rp->r_mapcnt >= 0);
11111 
11112 	/*
11113 	 * Initiate a page flush and potential commit if there are
11114 	 * pages, the file system was not mounted readonly, the segment
11115 	 * was mapped shared, and the pages themselves were writeable.
11116 	 */
11117 	if (nfs4_has_pages(dmapp->vp) &&
11118 	    !(dmapp->vp->v_vfsp->vfs_flag & VFS_RDONLY) &&
11119 	    dmapp->flags == MAP_SHARED && (dmapp->maxprot & PROT_WRITE)) {
11120 		mutex_enter(&rp->r_statelock);
11121 		rp->r_flags |= R4DIRTY;
11122 		mutex_exit(&rp->r_statelock);
11123 		e.error = nfs4_putpage_commit(dmapp->vp, dmapp->off,
11124 		    dmapp->len, dmapp->cr);
11125 		if (!e.error) {
11126 			mutex_enter(&rp->r_statelock);
11127 			e.error = rp->r_error;
11128 			rp->r_error = 0;
11129 			mutex_exit(&rp->r_statelock);
11130 		}
11131 	} else
11132 		e.error = 0;
11133 
11134 	if ((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO))
11135 		(void) nfs4_putpage(dmapp->vp, dmapp->off, dmapp->len,
11136 		    B_INVAL, dmapp->cr, NULL);
11137 
11138 	if (e.error) {
11139 		e.stat = puterrno4(e.error);
11140 		nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
11141 		    OP_COMMIT, FALSE, NULL, 0, dmapp->vp);
11142 		dmapp->caller->error = e.error;
11143 	}
11144 
11145 	/* Check to see if we need to close the file */
11146 
11147 	if (dmapp->vp->v_type == VREG) {
11148 		nfs4close_one(dmapp->vp, NULL, dmapp->cr, 0, NULL, &e,
11149 		    CLOSE_DELMAP, dmapp->len, dmapp->maxprot, dmapp->flags);
11150 
11151 		if (e.error != 0 || e.stat != NFS4_OK) {
11152 			/*
11153 			 * Since it is possible that e.error == 0 and
11154 			 * e.stat != NFS4_OK (and vice versa),
11155 			 * we do the proper checking in order to get both
11156 			 * e.error and e.stat reporting the correct info.
11157 			 */
11158 			if (e.stat == NFS4_OK)
11159 				e.stat = puterrno4(e.error);
11160 			if (e.error == 0)
11161 				e.error = geterrno4(e.stat);
11162 
11163 			nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
11164 			    OP_CLOSE, FALSE, NULL, 0, dmapp->vp);
11165 			dmapp->caller->error = e.error;
11166 		}
11167 	}
11168 
11169 	(void) as_delete_callback(as, arg);
11170 	kmem_free(dmapp, sizeof (nfs4_delmap_args_t));
11171 }
11172 
11173 
11174 static uint_t
11175 fattr4_maxfilesize_to_bits(uint64_t ll)
11176 {
11177 	uint_t l = 1;
11178 
11179 	if (ll == 0) {
11180 		return (0);
11181 	}
11182 
11183 	if (ll & 0xffffffff00000000) {
11184 		l += 32; ll >>= 32;
11185 	}
11186 	if (ll & 0xffff0000) {
11187 		l += 16; ll >>= 16;
11188 	}
11189 	if (ll & 0xff00) {
11190 		l += 8; ll >>= 8;
11191 	}
11192 	if (ll & 0xf0) {
11193 		l += 4; ll >>= 4;
11194 	}
11195 	if (ll & 0xc) {
11196 		l += 2; ll >>= 2;
11197 	}
11198 	if (ll & 0x2) {
11199 		l += 1;
11200 	}
11201 	return (l);
11202 }
11203 
11204 /* ARGSUSED */
11205 int
11206 nfs4_pathconf(vnode_t *vp, int cmd, ulong_t *valp, cred_t *cr,
11207 	caller_context_t *ct)
11208 {
11209 	int error;
11210 	hrtime_t t;
11211 	rnode4_t *rp;
11212 	nfs4_ga_res_t gar;
11213 	nfs4_ga_ext_res_t ger;
11214 
11215 	gar.n4g_ext_res = &ger;
11216 
11217 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
11218 		return (EIO);
11219 	if (cmd == _PC_PATH_MAX || cmd == _PC_SYMLINK_MAX) {
11220 		*valp = MAXPATHLEN;
11221 		return (0);
11222 	}
11223 	if (cmd == _PC_ACL_ENABLED) {
11224 		*valp = _ACL_ACE_ENABLED;
11225 		return (0);
11226 	}
11227 
11228 	rp = VTOR4(vp);
11229 	if (cmd == _PC_XATTR_EXISTS) {
11230 		/*
11231 		 * Eventually should attempt small client readdir before
11232 		 * going otw with GETATTR(FATTR4_NAMED_ATTR).  For now
11233 		 * just drive the OTW getattr.  This is required because
11234 		 * _PC_XATTR_EXISTS can only return true if attributes
11235 		 * exist -- simply checking for existence of the attrdir
11236 		 * is not sufficient.
11237 		 *
11238 		 * pc4_xattr_valid can be only be trusted when r_xattr_dir
11239 		 * is NULL.  Once the xadir vp exists, we can create xattrs,
11240 		 * and we don't have any way to update the "base" object's
11241 		 * pc4_xattr_exists from the xattr or xadir.  Maybe FEM
11242 		 * could help out.
11243 		 */
11244 		if (ATTRCACHE4_VALID(vp) && rp->r_pathconf.pc4_xattr_valid &&
11245 		    rp->r_xattr_dir == NULL) {
11246 			*valp = rp->r_pathconf.pc4_xattr_exists;
11247 			return (0);
11248 		}
11249 	} else {  /* OLD CODE */
11250 		if (ATTRCACHE4_VALID(vp)) {
11251 			mutex_enter(&rp->r_statelock);
11252 			if (rp->r_pathconf.pc4_cache_valid) {
11253 				error = 0;
11254 				switch (cmd) {
11255 				case _PC_FILESIZEBITS:
11256 					*valp =
11257 					    rp->r_pathconf.pc4_filesizebits;
11258 					break;
11259 				case _PC_LINK_MAX:
11260 					*valp =
11261 					    rp->r_pathconf.pc4_link_max;
11262 					break;
11263 				case _PC_NAME_MAX:
11264 					*valp =
11265 					    rp->r_pathconf.pc4_name_max;
11266 					break;
11267 				case _PC_CHOWN_RESTRICTED:
11268 					*valp =
11269 					    rp->r_pathconf.pc4_chown_restricted;
11270 					break;
11271 				case _PC_NO_TRUNC:
11272 					*valp =
11273 					    rp->r_pathconf.pc4_no_trunc;
11274 					break;
11275 				default:
11276 					error = EINVAL;
11277 					break;
11278 				}
11279 				mutex_exit(&rp->r_statelock);
11280 #ifdef DEBUG
11281 				nfs4_pathconf_cache_hits++;
11282 #endif
11283 				return (error);
11284 			}
11285 			mutex_exit(&rp->r_statelock);
11286 		}
11287 	}
11288 #ifdef DEBUG
11289 	nfs4_pathconf_cache_misses++;
11290 #endif
11291 
11292 	t = gethrtime();
11293 
11294 	error = nfs4_attr_otw(vp, TAG_PATHCONF, &gar, NFS4_PATHCONF_MASK, cr);
11295 
11296 	if (error) {
11297 		mutex_enter(&rp->r_statelock);
11298 		rp->r_pathconf.pc4_cache_valid = FALSE;
11299 		rp->r_pathconf.pc4_xattr_valid = FALSE;
11300 		mutex_exit(&rp->r_statelock);
11301 		return (error);
11302 	}
11303 
11304 	/* interpret the max filesize */
11305 	gar.n4g_ext_res->n4g_pc4.pc4_filesizebits =
11306 	    fattr4_maxfilesize_to_bits(gar.n4g_ext_res->n4g_maxfilesize);
11307 
11308 	/* Store the attributes we just received */
11309 	nfs4_attr_cache(vp, &gar, t, cr, TRUE, NULL);
11310 
11311 	switch (cmd) {
11312 	case _PC_FILESIZEBITS:
11313 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_filesizebits;
11314 		break;
11315 	case _PC_LINK_MAX:
11316 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_link_max;
11317 		break;
11318 	case _PC_NAME_MAX:
11319 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_name_max;
11320 		break;
11321 	case _PC_CHOWN_RESTRICTED:
11322 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_chown_restricted;
11323 		break;
11324 	case _PC_NO_TRUNC:
11325 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_no_trunc;
11326 		break;
11327 	case _PC_XATTR_EXISTS:
11328 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_xattr_exists;
11329 		break;
11330 	default:
11331 		return (EINVAL);
11332 	}
11333 
11334 	return (0);
11335 }
11336 
11337 /*
11338  * Called by async thread to do synchronous pageio. Do the i/o, wait
11339  * for it to complete, and cleanup the page list when done.
11340  */
11341 static int
11342 nfs4_sync_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11343     int flags, cred_t *cr)
11344 {
11345 	int error;
11346 
11347 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11348 
11349 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11350 	if (flags & B_READ)
11351 		pvn_read_done(pp, (error ? B_ERROR : 0) | flags);
11352 	else
11353 		pvn_write_done(pp, (error ? B_ERROR : 0) | flags);
11354 	return (error);
11355 }
11356 
11357 /* ARGSUSED */
11358 static int
11359 nfs4_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11360 	int flags, cred_t *cr, caller_context_t *ct)
11361 {
11362 	int error;
11363 	rnode4_t *rp;
11364 
11365 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
11366 		return (EIO);
11367 
11368 	if (pp == NULL)
11369 		return (EINVAL);
11370 
11371 	rp = VTOR4(vp);
11372 	mutex_enter(&rp->r_statelock);
11373 	rp->r_count++;
11374 	mutex_exit(&rp->r_statelock);
11375 
11376 	if (flags & B_ASYNC) {
11377 		error = nfs4_async_pageio(vp, pp, io_off, io_len, flags, cr,
11378 		    nfs4_sync_pageio);
11379 	} else
11380 		error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11381 	mutex_enter(&rp->r_statelock);
11382 	rp->r_count--;
11383 	cv_broadcast(&rp->r_cv);
11384 	mutex_exit(&rp->r_statelock);
11385 	return (error);
11386 }
11387 
11388 /* ARGSUSED */
11389 static void
11390 nfs4_dispose(vnode_t *vp, page_t *pp, int fl, int dn, cred_t *cr,
11391 	caller_context_t *ct)
11392 {
11393 	int error;
11394 	rnode4_t *rp;
11395 	page_t *plist;
11396 	page_t *pptr;
11397 	offset3 offset;
11398 	count3 len;
11399 	k_sigset_t smask;
11400 
11401 	/*
11402 	 * We should get called with fl equal to either B_FREE or
11403 	 * B_INVAL.  Any other value is illegal.
11404 	 *
11405 	 * The page that we are either supposed to free or destroy
11406 	 * should be exclusive locked and its io lock should not
11407 	 * be held.
11408 	 */
11409 	ASSERT(fl == B_FREE || fl == B_INVAL);
11410 	ASSERT((PAGE_EXCL(pp) && !page_iolock_assert(pp)) || panicstr);
11411 
11412 	rp = VTOR4(vp);
11413 
11414 	/*
11415 	 * If the page doesn't need to be committed or we shouldn't
11416 	 * even bother attempting to commit it, then just make sure
11417 	 * that the p_fsdata byte is clear and then either free or
11418 	 * destroy the page as appropriate.
11419 	 */
11420 	if (pp->p_fsdata == C_NOCOMMIT || (rp->r_flags & R4STALE)) {
11421 		pp->p_fsdata = C_NOCOMMIT;
11422 		if (fl == B_FREE)
11423 			page_free(pp, dn);
11424 		else
11425 			page_destroy(pp, dn);
11426 		return;
11427 	}
11428 
11429 	/*
11430 	 * If there is a page invalidation operation going on, then
11431 	 * if this is one of the pages being destroyed, then just
11432 	 * clear the p_fsdata byte and then either free or destroy
11433 	 * the page as appropriate.
11434 	 */
11435 	mutex_enter(&rp->r_statelock);
11436 	if ((rp->r_flags & R4TRUNCATE) && pp->p_offset >= rp->r_truncaddr) {
11437 		mutex_exit(&rp->r_statelock);
11438 		pp->p_fsdata = C_NOCOMMIT;
11439 		if (fl == B_FREE)
11440 			page_free(pp, dn);
11441 		else
11442 			page_destroy(pp, dn);
11443 		return;
11444 	}
11445 
11446 	/*
11447 	 * If we are freeing this page and someone else is already
11448 	 * waiting to do a commit, then just unlock the page and
11449 	 * return.  That other thread will take care of commiting
11450 	 * this page.  The page can be freed sometime after the
11451 	 * commit has finished.  Otherwise, if the page is marked
11452 	 * as delay commit, then we may be getting called from
11453 	 * pvn_write_done, one page at a time.   This could result
11454 	 * in one commit per page, so we end up doing lots of small
11455 	 * commits instead of fewer larger commits.  This is bad,
11456 	 * we want do as few commits as possible.
11457 	 */
11458 	if (fl == B_FREE) {
11459 		if (rp->r_flags & R4COMMITWAIT) {
11460 			page_unlock(pp);
11461 			mutex_exit(&rp->r_statelock);
11462 			return;
11463 		}
11464 		if (pp->p_fsdata == C_DELAYCOMMIT) {
11465 			pp->p_fsdata = C_COMMIT;
11466 			page_unlock(pp);
11467 			mutex_exit(&rp->r_statelock);
11468 			return;
11469 		}
11470 	}
11471 
11472 	/*
11473 	 * Check to see if there is a signal which would prevent an
11474 	 * attempt to commit the pages from being successful.  If so,
11475 	 * then don't bother with all of the work to gather pages and
11476 	 * generate the unsuccessful RPC.  Just return from here and
11477 	 * let the page be committed at some later time.
11478 	 */
11479 	sigintr(&smask, VTOMI4(vp)->mi_flags & MI4_INT);
11480 	if (ttolwp(curthread) != NULL && ISSIG(curthread, JUSTLOOKING)) {
11481 		sigunintr(&smask);
11482 		page_unlock(pp);
11483 		mutex_exit(&rp->r_statelock);
11484 		return;
11485 	}
11486 	sigunintr(&smask);
11487 
11488 	/*
11489 	 * We are starting to need to commit pages, so let's try
11490 	 * to commit as many as possible at once to reduce the
11491 	 * overhead.
11492 	 *
11493 	 * Set the `commit inprogress' state bit.  We must
11494 	 * first wait until any current one finishes.  Then
11495 	 * we initialize the c_pages list with this page.
11496 	 */
11497 	while (rp->r_flags & R4COMMIT) {
11498 		rp->r_flags |= R4COMMITWAIT;
11499 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
11500 		rp->r_flags &= ~R4COMMITWAIT;
11501 	}
11502 	rp->r_flags |= R4COMMIT;
11503 	mutex_exit(&rp->r_statelock);
11504 	ASSERT(rp->r_commit.c_pages == NULL);
11505 	rp->r_commit.c_pages = pp;
11506 	rp->r_commit.c_commbase = (offset3)pp->p_offset;
11507 	rp->r_commit.c_commlen = PAGESIZE;
11508 
11509 	/*
11510 	 * Gather together all other pages which can be committed.
11511 	 * They will all be chained off r_commit.c_pages.
11512 	 */
11513 	nfs4_get_commit(vp);
11514 
11515 	/*
11516 	 * Clear the `commit inprogress' status and disconnect
11517 	 * the list of pages to be committed from the rnode.
11518 	 * At this same time, we also save the starting offset
11519 	 * and length of data to be committed on the server.
11520 	 */
11521 	plist = rp->r_commit.c_pages;
11522 	rp->r_commit.c_pages = NULL;
11523 	offset = rp->r_commit.c_commbase;
11524 	len = rp->r_commit.c_commlen;
11525 	mutex_enter(&rp->r_statelock);
11526 	rp->r_flags &= ~R4COMMIT;
11527 	cv_broadcast(&rp->r_commit.c_cv);
11528 	mutex_exit(&rp->r_statelock);
11529 
11530 	if (curproc == proc_pageout || curproc == proc_fsflush ||
11531 	    nfs_zone() != VTOMI4(vp)->mi_zone) {
11532 		nfs4_async_commit(vp, plist, offset, len,
11533 		    cr, do_nfs4_async_commit);
11534 		return;
11535 	}
11536 
11537 	/*
11538 	 * Actually generate the COMMIT op over the wire operation.
11539 	 */
11540 	error = nfs4_commit(vp, (offset4)offset, (count4)len, cr);
11541 
11542 	/*
11543 	 * If we got an error during the commit, just unlock all
11544 	 * of the pages.  The pages will get retransmitted to the
11545 	 * server during a putpage operation.
11546 	 */
11547 	if (error) {
11548 		while (plist != NULL) {
11549 			pptr = plist;
11550 			page_sub(&plist, pptr);
11551 			page_unlock(pptr);
11552 		}
11553 		return;
11554 	}
11555 
11556 	/*
11557 	 * We've tried as hard as we can to commit the data to stable
11558 	 * storage on the server.  We just unlock the rest of the pages
11559 	 * and clear the commit required state.  They will be put
11560 	 * onto the tail of the cachelist if they are nolonger
11561 	 * mapped.
11562 	 */
11563 	while (plist != pp) {
11564 		pptr = plist;
11565 		page_sub(&plist, pptr);
11566 		pptr->p_fsdata = C_NOCOMMIT;
11567 		page_unlock(pptr);
11568 	}
11569 
11570 	/*
11571 	 * It is possible that nfs4_commit didn't return error but
11572 	 * some other thread has modified the page we are going
11573 	 * to free/destroy.
11574 	 *    In this case we need to rewrite the page. Do an explicit check
11575 	 * before attempting to free/destroy the page. If modified, needs to
11576 	 * be rewritten so unlock the page and return.
11577 	 */
11578 	if (hat_ismod(pp)) {
11579 		pp->p_fsdata = C_NOCOMMIT;
11580 		page_unlock(pp);
11581 		return;
11582 	}
11583 
11584 	/*
11585 	 * Now, as appropriate, either free or destroy the page
11586 	 * that we were called with.
11587 	 */
11588 	pp->p_fsdata = C_NOCOMMIT;
11589 	if (fl == B_FREE)
11590 		page_free(pp, dn);
11591 	else
11592 		page_destroy(pp, dn);
11593 }
11594 
11595 /*
11596  * Commit requires that the current fh be the file written to.
11597  * The compound op structure is:
11598  *      PUTFH(file), COMMIT
11599  */
11600 static int
11601 nfs4_commit(vnode_t *vp, offset4 offset, count4 count, cred_t *cr)
11602 {
11603 	COMPOUND4args_clnt args;
11604 	COMPOUND4res_clnt res;
11605 	COMMIT4res *cm_res;
11606 	nfs_argop4 argop[2];
11607 	nfs_resop4 *resop;
11608 	int doqueue;
11609 	mntinfo4_t *mi;
11610 	rnode4_t *rp;
11611 	cred_t *cred_otw = NULL;
11612 	bool_t needrecov = FALSE;
11613 	nfs4_recov_state_t recov_state;
11614 	nfs4_open_stream_t *osp = NULL;
11615 	bool_t first_time = TRUE;	/* first time getting OTW cred */
11616 	bool_t last_time = FALSE;	/* last time getting OTW cred */
11617 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
11618 
11619 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11620 
11621 	rp = VTOR4(vp);
11622 
11623 	mi = VTOMI4(vp);
11624 	recov_state.rs_flags = 0;
11625 	recov_state.rs_num_retry_despite_err = 0;
11626 get_commit_cred:
11627 	/*
11628 	 * Releases the osp, if a valid open stream is provided.
11629 	 * Puts a hold on the cred_otw and the new osp (if found).
11630 	 */
11631 	cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
11632 	    &first_time, &last_time);
11633 	args.ctag = TAG_COMMIT;
11634 recov_retry:
11635 	/*
11636 	 * Commit ops: putfh file; commit
11637 	 */
11638 	args.array_len = 2;
11639 	args.array = argop;
11640 
11641 	e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11642 	    &recov_state, NULL);
11643 	if (e.error) {
11644 		crfree(cred_otw);
11645 		if (osp != NULL)
11646 			open_stream_rele(osp, rp);
11647 		return (e.error);
11648 	}
11649 
11650 	/* putfh directory */
11651 	argop[0].argop = OP_CPUTFH;
11652 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
11653 
11654 	/* commit */
11655 	argop[1].argop = OP_COMMIT;
11656 	argop[1].nfs_argop4_u.opcommit.offset = offset;
11657 	argop[1].nfs_argop4_u.opcommit.count = count;
11658 
11659 	doqueue = 1;
11660 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, &e);
11661 
11662 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
11663 	if (!needrecov && e.error) {
11664 		nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state,
11665 		    needrecov);
11666 		crfree(cred_otw);
11667 		if (e.error == EACCES && last_time == FALSE)
11668 			goto get_commit_cred;
11669 		if (osp != NULL)
11670 			open_stream_rele(osp, rp);
11671 		return (e.error);
11672 	}
11673 
11674 	if (needrecov) {
11675 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
11676 		    NULL, OP_COMMIT, NULL) == FALSE) {
11677 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11678 			    &recov_state, needrecov);
11679 			if (!e.error)
11680 				(void) xdr_free(xdr_COMPOUND4res_clnt,
11681 				    (caddr_t)&res);
11682 			goto recov_retry;
11683 		}
11684 		if (e.error) {
11685 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11686 			    &recov_state, needrecov);
11687 			crfree(cred_otw);
11688 			if (osp != NULL)
11689 				open_stream_rele(osp, rp);
11690 			return (e.error);
11691 		}
11692 		/* fall through for res.status case */
11693 	}
11694 
11695 	if (res.status) {
11696 		e.error = geterrno4(res.status);
11697 		if (e.error == EACCES && last_time == FALSE) {
11698 			crfree(cred_otw);
11699 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11700 			    &recov_state, needrecov);
11701 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11702 			goto get_commit_cred;
11703 		}
11704 		/*
11705 		 * Can't do a nfs4_purge_stale_fh here because this
11706 		 * can cause a deadlock.  nfs4_commit can
11707 		 * be called from nfs4_dispose which can be called
11708 		 * indirectly via pvn_vplist_dirty.  nfs4_purge_stale_fh
11709 		 * can call back to pvn_vplist_dirty.
11710 		 */
11711 		if (e.error == ESTALE) {
11712 			mutex_enter(&rp->r_statelock);
11713 			rp->r_flags |= R4STALE;
11714 			if (!rp->r_error)
11715 				rp->r_error = e.error;
11716 			mutex_exit(&rp->r_statelock);
11717 			PURGE_ATTRCACHE4(vp);
11718 		} else {
11719 			mutex_enter(&rp->r_statelock);
11720 			if (!rp->r_error)
11721 				rp->r_error = e.error;
11722 			mutex_exit(&rp->r_statelock);
11723 		}
11724 	} else {
11725 		ASSERT(rp->r_flags & R4HAVEVERF);
11726 		resop = &res.array[1];	/* commit res */
11727 		cm_res = &resop->nfs_resop4_u.opcommit;
11728 		mutex_enter(&rp->r_statelock);
11729 		if (cm_res->writeverf == rp->r_writeverf) {
11730 			mutex_exit(&rp->r_statelock);
11731 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11732 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11733 			    &recov_state, needrecov);
11734 			crfree(cred_otw);
11735 			if (osp != NULL)
11736 				open_stream_rele(osp, rp);
11737 			return (0);
11738 		}
11739 		nfs4_set_mod(vp);
11740 		rp->r_writeverf = cm_res->writeverf;
11741 		mutex_exit(&rp->r_statelock);
11742 		e.error = NFS_VERF_MISMATCH;
11743 	}
11744 
11745 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
11746 	nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state, needrecov);
11747 	crfree(cred_otw);
11748 	if (osp != NULL)
11749 		open_stream_rele(osp, rp);
11750 
11751 	return (e.error);
11752 }
11753 
11754 static void
11755 nfs4_set_mod(vnode_t *vp)
11756 {
11757 	page_t *pp;
11758 	kmutex_t *vphm;
11759 	rnode4_t *rp;
11760 
11761 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11762 
11763 	/* make sure we're looking at the master vnode, not a shadow */
11764 
11765 	rp = VTOR4(vp);
11766 	if (IS_SHADOW(vp, rp))
11767 		vp = RTOV4(rp);
11768 
11769 	vphm = page_vnode_mutex(vp);
11770 	mutex_enter(vphm);
11771 	/*
11772 	 * If there are no pages associated with this vnode, then
11773 	 * just return.
11774 	 */
11775 	if ((pp = vp->v_pages) == NULL) {
11776 		mutex_exit(vphm);
11777 		return;
11778 	}
11779 
11780 	do {
11781 		if (pp->p_fsdata != C_NOCOMMIT) {
11782 			hat_setmod(pp);
11783 			pp->p_fsdata = C_NOCOMMIT;
11784 		}
11785 	} while ((pp = pp->p_vpnext) != vp->v_pages);
11786 	mutex_exit(vphm);
11787 }
11788 
11789 /*
11790  * This function is used to gather a page list of the pages which
11791  * can be committed on the server.
11792  *
11793  * The calling thread must have set R4COMMIT.  This bit is used to
11794  * serialize access to the commit structure in the rnode.  As long
11795  * as the thread has set R4COMMIT, then it can manipulate the commit
11796  * structure without requiring any other locks.
11797  *
11798  * When this function is called from nfs4_dispose() the page passed
11799  * into nfs4_dispose() will be SE_EXCL locked, and so this function
11800  * will skip it. This is not a problem since we initially add the
11801  * page to the r_commit page list.
11802  *
11803  */
11804 static void
11805 nfs4_get_commit(vnode_t *vp)
11806 {
11807 	rnode4_t *rp;
11808 	page_t *pp;
11809 	kmutex_t *vphm;
11810 
11811 	rp = VTOR4(vp);
11812 
11813 	ASSERT(rp->r_flags & R4COMMIT);
11814 
11815 	/* make sure we're looking at the master vnode, not a shadow */
11816 
11817 	if (IS_SHADOW(vp, rp))
11818 		vp = RTOV4(rp);
11819 
11820 	vphm = page_vnode_mutex(vp);
11821 	mutex_enter(vphm);
11822 
11823 	/*
11824 	 * If there are no pages associated with this vnode, then
11825 	 * just return.
11826 	 */
11827 	if ((pp = vp->v_pages) == NULL) {
11828 		mutex_exit(vphm);
11829 		return;
11830 	}
11831 
11832 	/*
11833 	 * Step through all of the pages associated with this vnode
11834 	 * looking for pages which need to be committed.
11835 	 */
11836 	do {
11837 		/*
11838 		 * First short-cut everything (without the page_lock)
11839 		 * and see if this page does not need to be committed
11840 		 * or is modified if so then we'll just skip it.
11841 		 */
11842 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp))
11843 			continue;
11844 
11845 		/*
11846 		 * Attempt to lock the page.  If we can't, then
11847 		 * someone else is messing with it or we have been
11848 		 * called from nfs4_dispose and this is the page that
11849 		 * nfs4_dispose was called with.. anyway just skip it.
11850 		 */
11851 		if (!page_trylock(pp, SE_EXCL))
11852 			continue;
11853 
11854 		/*
11855 		 * Lets check again now that we have the page lock.
11856 		 */
11857 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
11858 			page_unlock(pp);
11859 			continue;
11860 		}
11861 
11862 		/* this had better not be a free page */
11863 		ASSERT(PP_ISFREE(pp) == 0);
11864 
11865 		/*
11866 		 * The page needs to be committed and we locked it.
11867 		 * Update the base and length parameters and add it
11868 		 * to r_pages.
11869 		 */
11870 		if (rp->r_commit.c_pages == NULL) {
11871 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11872 			rp->r_commit.c_commlen = PAGESIZE;
11873 		} else if (pp->p_offset < rp->r_commit.c_commbase) {
11874 			rp->r_commit.c_commlen = rp->r_commit.c_commbase -
11875 			    (offset3)pp->p_offset + rp->r_commit.c_commlen;
11876 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11877 		} else if ((rp->r_commit.c_commbase + rp->r_commit.c_commlen)
11878 		    <= pp->p_offset) {
11879 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
11880 			    rp->r_commit.c_commbase + PAGESIZE;
11881 		}
11882 		page_add(&rp->r_commit.c_pages, pp);
11883 	} while ((pp = pp->p_vpnext) != vp->v_pages);
11884 
11885 	mutex_exit(vphm);
11886 }
11887 
11888 /*
11889  * This routine is used to gather together a page list of the pages
11890  * which are to be committed on the server.  This routine must not
11891  * be called if the calling thread holds any locked pages.
11892  *
11893  * The calling thread must have set R4COMMIT.  This bit is used to
11894  * serialize access to the commit structure in the rnode.  As long
11895  * as the thread has set R4COMMIT, then it can manipulate the commit
11896  * structure without requiring any other locks.
11897  */
11898 static void
11899 nfs4_get_commit_range(vnode_t *vp, u_offset_t soff, size_t len)
11900 {
11901 
11902 	rnode4_t *rp;
11903 	page_t *pp;
11904 	u_offset_t end;
11905 	u_offset_t off;
11906 	ASSERT(len != 0);
11907 	rp = VTOR4(vp);
11908 	ASSERT(rp->r_flags & R4COMMIT);
11909 
11910 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11911 
11912 	/* make sure we're looking at the master vnode, not a shadow */
11913 
11914 	if (IS_SHADOW(vp, rp))
11915 		vp = RTOV4(rp);
11916 
11917 	/*
11918 	 * If there are no pages associated with this vnode, then
11919 	 * just return.
11920 	 */
11921 	if ((pp = vp->v_pages) == NULL)
11922 		return;
11923 	/*
11924 	 * Calculate the ending offset.
11925 	 */
11926 	end = soff + len;
11927 	for (off = soff; off < end; off += PAGESIZE) {
11928 		/*
11929 		 * Lookup each page by vp, offset.
11930 		 */
11931 		if ((pp = page_lookup_nowait(vp, off, SE_EXCL)) == NULL)
11932 			continue;
11933 		/*
11934 		 * If this page does not need to be committed or is
11935 		 * modified, then just skip it.
11936 		 */
11937 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
11938 			page_unlock(pp);
11939 			continue;
11940 		}
11941 
11942 		ASSERT(PP_ISFREE(pp) == 0);
11943 		/*
11944 		 * The page needs to be committed and we locked it.
11945 		 * Update the base and length parameters and add it
11946 		 * to r_pages.
11947 		 */
11948 		if (rp->r_commit.c_pages == NULL) {
11949 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
11950 			rp->r_commit.c_commlen = PAGESIZE;
11951 		} else {
11952 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
11953 			    rp->r_commit.c_commbase + PAGESIZE;
11954 		}
11955 		page_add(&rp->r_commit.c_pages, pp);
11956 	}
11957 }
11958 
11959 /*
11960  * Called from nfs4_close(), nfs4_fsync() and nfs4_delmap().
11961  * Flushes and commits data to the server.
11962  */
11963 static int
11964 nfs4_putpage_commit(vnode_t *vp, offset_t poff, size_t plen, cred_t *cr)
11965 {
11966 	int error;
11967 	verifier4 write_verf;
11968 	rnode4_t *rp = VTOR4(vp);
11969 
11970 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11971 
11972 	/*
11973 	 * Flush the data portion of the file and then commit any
11974 	 * portions which need to be committed.  This may need to
11975 	 * be done twice if the server has changed state since
11976 	 * data was last written.  The data will need to be
11977 	 * rewritten to the server and then a new commit done.
11978 	 *
11979 	 * In fact, this may need to be done several times if the
11980 	 * server is having problems and crashing while we are
11981 	 * attempting to do this.
11982 	 */
11983 
11984 top:
11985 	/*
11986 	 * Do a flush based on the poff and plen arguments.  This
11987 	 * will synchronously write out any modified pages in the
11988 	 * range specified by (poff, plen). This starts all of the
11989 	 * i/o operations which will be waited for in the next
11990 	 * call to nfs4_putpage
11991 	 */
11992 
11993 	mutex_enter(&rp->r_statelock);
11994 	write_verf = rp->r_writeverf;
11995 	mutex_exit(&rp->r_statelock);
11996 
11997 	error = nfs4_putpage(vp, poff, plen, B_ASYNC, cr, NULL);
11998 	if (error == EAGAIN)
11999 		error = 0;
12000 
12001 	/*
12002 	 * Do a flush based on the poff and plen arguments.  This
12003 	 * will synchronously write out any modified pages in the
12004 	 * range specified by (poff, plen) and wait until all of
12005 	 * the asynchronous i/o's in that range are done as well.
12006 	 */
12007 	if (!error)
12008 		error = nfs4_putpage(vp, poff, plen, 0, cr, NULL);
12009 
12010 	if (error)
12011 		return (error);
12012 
12013 	mutex_enter(&rp->r_statelock);
12014 	if (rp->r_writeverf != write_verf) {
12015 		mutex_exit(&rp->r_statelock);
12016 		goto top;
12017 	}
12018 	mutex_exit(&rp->r_statelock);
12019 
12020 	/*
12021 	 * Now commit any pages which might need to be committed.
12022 	 * If the error, NFS_VERF_MISMATCH, is returned, then
12023 	 * start over with the flush operation.
12024 	 */
12025 	error = nfs4_commit_vp(vp, poff, plen, cr, NFS4_WRITE_WAIT);
12026 
12027 	if (error == NFS_VERF_MISMATCH)
12028 		goto top;
12029 
12030 	return (error);
12031 }
12032 
12033 /*
12034  * nfs4_commit_vp()  will wait for other pending commits and
12035  * will either commit the whole file or a range, plen dictates
12036  * if we commit whole file. a value of zero indicates the whole
12037  * file. Called from nfs4_putpage_commit() or nfs4_sync_putapage()
12038  */
12039 static int
12040 nfs4_commit_vp(vnode_t *vp, u_offset_t poff, size_t plen,
12041     cred_t *cr, int wait_on_writes)
12042 {
12043 	rnode4_t *rp;
12044 	page_t *plist;
12045 	offset3 offset;
12046 	count3 len;
12047 
12048 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12049 
12050 	rp = VTOR4(vp);
12051 
12052 	/*
12053 	 *  before we gather commitable pages make
12054 	 *  sure there are no outstanding async writes
12055 	 */
12056 	if (rp->r_count && wait_on_writes == NFS4_WRITE_WAIT) {
12057 		mutex_enter(&rp->r_statelock);
12058 		while (rp->r_count > 0) {
12059 			cv_wait(&rp->r_cv, &rp->r_statelock);
12060 		}
12061 		mutex_exit(&rp->r_statelock);
12062 	}
12063 
12064 	/*
12065 	 * Set the `commit inprogress' state bit.  We must
12066 	 * first wait until any current one finishes.
12067 	 */
12068 	mutex_enter(&rp->r_statelock);
12069 	while (rp->r_flags & R4COMMIT) {
12070 		rp->r_flags |= R4COMMITWAIT;
12071 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
12072 		rp->r_flags &= ~R4COMMITWAIT;
12073 	}
12074 	rp->r_flags |= R4COMMIT;
12075 	mutex_exit(&rp->r_statelock);
12076 
12077 	/*
12078 	 * Gather all of the pages which need to be
12079 	 * committed.
12080 	 */
12081 	if (plen == 0)
12082 		nfs4_get_commit(vp);
12083 	else
12084 		nfs4_get_commit_range(vp, poff, plen);
12085 
12086 	/*
12087 	 * Clear the `commit inprogress' bit and disconnect the
12088 	 * page list which was gathered by nfs4_get_commit.
12089 	 */
12090 	plist = rp->r_commit.c_pages;
12091 	rp->r_commit.c_pages = NULL;
12092 	offset = rp->r_commit.c_commbase;
12093 	len = rp->r_commit.c_commlen;
12094 	mutex_enter(&rp->r_statelock);
12095 	rp->r_flags &= ~R4COMMIT;
12096 	cv_broadcast(&rp->r_commit.c_cv);
12097 	mutex_exit(&rp->r_statelock);
12098 
12099 	/*
12100 	 * If any pages need to be committed, commit them and
12101 	 * then unlock them so that they can be freed some
12102 	 * time later.
12103 	 */
12104 	if (plist == NULL)
12105 		return (0);
12106 
12107 	/*
12108 	 * No error occurred during the flush portion
12109 	 * of this operation, so now attempt to commit
12110 	 * the data to stable storage on the server.
12111 	 *
12112 	 * This will unlock all of the pages on the list.
12113 	 */
12114 	return (nfs4_sync_commit(vp, plist, offset, len, cr));
12115 }
12116 
12117 static int
12118 nfs4_sync_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
12119     cred_t *cr)
12120 {
12121 	int error;
12122 	page_t *pp;
12123 
12124 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12125 
12126 	error = nfs4_commit(vp, (offset4)offset, (count3)count, cr);
12127 
12128 	/*
12129 	 * If we got an error, then just unlock all of the pages
12130 	 * on the list.
12131 	 */
12132 	if (error) {
12133 		while (plist != NULL) {
12134 			pp = plist;
12135 			page_sub(&plist, pp);
12136 			page_unlock(pp);
12137 		}
12138 		return (error);
12139 	}
12140 	/*
12141 	 * We've tried as hard as we can to commit the data to stable
12142 	 * storage on the server.  We just unlock the pages and clear
12143 	 * the commit required state.  They will get freed later.
12144 	 */
12145 	while (plist != NULL) {
12146 		pp = plist;
12147 		page_sub(&plist, pp);
12148 		pp->p_fsdata = C_NOCOMMIT;
12149 		page_unlock(pp);
12150 	}
12151 
12152 	return (error);
12153 }
12154 
12155 static void
12156 do_nfs4_async_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
12157     cred_t *cr)
12158 {
12159 
12160 	(void) nfs4_sync_commit(vp, plist, offset, count, cr);
12161 }
12162 
12163 /*ARGSUSED*/
12164 static int
12165 nfs4_setsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr,
12166 	caller_context_t *ct)
12167 {
12168 	int		error = 0;
12169 	mntinfo4_t	*mi;
12170 	vattr_t		va;
12171 	vsecattr_t	nfsace4_vsap;
12172 
12173 	mi = VTOMI4(vp);
12174 	if (nfs_zone() != mi->mi_zone)
12175 		return (EIO);
12176 	if (mi->mi_flags & MI4_ACL) {
12177 		/* if we have a delegation, return it */
12178 		if (VTOR4(vp)->r_deleg_type != OPEN_DELEGATE_NONE)
12179 			(void) nfs4delegreturn(VTOR4(vp),
12180 			    NFS4_DR_REOPEN|NFS4_DR_PUSH);
12181 
12182 		error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask,
12183 		    NFS4_ACL_SET);
12184 		if (error) /* EINVAL */
12185 			return (error);
12186 
12187 		if (vsecattr->vsa_mask & (VSA_ACL | VSA_DFACL)) {
12188 			/*
12189 			 * These are aclent_t type entries.
12190 			 */
12191 			error = vs_aent_to_ace4(vsecattr, &nfsace4_vsap,
12192 			    vp->v_type == VDIR, FALSE);
12193 			if (error)
12194 				return (error);
12195 		} else {
12196 			/*
12197 			 * These are ace_t type entries.
12198 			 */
12199 			error = vs_acet_to_ace4(vsecattr, &nfsace4_vsap,
12200 			    FALSE);
12201 			if (error)
12202 				return (error);
12203 		}
12204 		bzero(&va, sizeof (va));
12205 		error = nfs4setattr(vp, &va, flag, cr, &nfsace4_vsap);
12206 		vs_ace4_destroy(&nfsace4_vsap);
12207 		return (error);
12208 	}
12209 	return (ENOSYS);
12210 }
12211 
12212 /* ARGSUSED */
12213 int
12214 nfs4_getsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr,
12215 	caller_context_t *ct)
12216 {
12217 	int		error;
12218 	mntinfo4_t	*mi;
12219 	nfs4_ga_res_t	gar;
12220 	rnode4_t	*rp = VTOR4(vp);
12221 
12222 	mi = VTOMI4(vp);
12223 	if (nfs_zone() != mi->mi_zone)
12224 		return (EIO);
12225 
12226 	bzero(&gar, sizeof (gar));
12227 	gar.n4g_vsa.vsa_mask = vsecattr->vsa_mask;
12228 
12229 	/*
12230 	 * vsecattr->vsa_mask holds the original acl request mask.
12231 	 * This is needed when determining what to return.
12232 	 * (See: nfs4_create_getsecattr_return())
12233 	 */
12234 	error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask, NFS4_ACL_GET);
12235 	if (error) /* EINVAL */
12236 		return (error);
12237 
12238 	if (mi->mi_flags & MI4_ACL) {
12239 		/*
12240 		 * Check if the data is cached and the cache is valid.  If it
12241 		 * is we don't go over the wire.
12242 		 */
12243 		if (rp->r_secattr != NULL && ATTRCACHE4_VALID(vp)) {
12244 			mutex_enter(&rp->r_statelock);
12245 			if (rp->r_secattr != NULL) {
12246 				error = nfs4_create_getsecattr_return(
12247 				    rp->r_secattr, vsecattr, rp->r_attr.va_uid,
12248 				    rp->r_attr.va_gid,
12249 				    vp->v_type == VDIR);
12250 				if (!error) { /* error == 0 - Success! */
12251 					mutex_exit(&rp->r_statelock);
12252 					return (error);
12253 				}
12254 			}
12255 			mutex_exit(&rp->r_statelock);
12256 		}
12257 
12258 		/*
12259 		 * The getattr otw call will always get both the acl, in
12260 		 * the form of a list of nfsace4's, and the number of acl
12261 		 * entries; independent of the value of gar.n4g_vsa.vsa_mask.
12262 		 */
12263 		gar.n4g_va.va_mask = AT_ALL;
12264 		error =  nfs4_getattr_otw(vp, &gar, cr, 1);
12265 		if (error) {
12266 			vs_ace4_destroy(&gar.n4g_vsa);
12267 			if (error == ENOTSUP || error == EOPNOTSUPP)
12268 				error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12269 			return (error);
12270 		}
12271 
12272 		if (!(gar.n4g_resbmap & FATTR4_ACL_MASK)) {
12273 			/*
12274 			 * No error was returned, but according to the response
12275 			 * bitmap, neither was an acl.
12276 			 */
12277 			vs_ace4_destroy(&gar.n4g_vsa);
12278 			error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12279 			return (error);
12280 		}
12281 
12282 		/*
12283 		 * Update the cache with the ACL.
12284 		 */
12285 		nfs4_acl_fill_cache(rp, &gar.n4g_vsa);
12286 
12287 		error = nfs4_create_getsecattr_return(&gar.n4g_vsa,
12288 		    vsecattr, gar.n4g_va.va_uid, gar.n4g_va.va_gid,
12289 		    vp->v_type == VDIR);
12290 		vs_ace4_destroy(&gar.n4g_vsa);
12291 		if ((error) && (vsecattr->vsa_mask &
12292 		    (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) &&
12293 		    (error != EACCES)) {
12294 			error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12295 		}
12296 		return (error);
12297 	}
12298 	error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12299 	return (error);
12300 }
12301 
12302 /*
12303  * The function returns:
12304  * 	- 0 (zero) if the passed in "acl_mask" is a valid request.
12305  * 	- EINVAL if the passed in "acl_mask" is an invalid request.
12306  *
12307  * In the case of getting an acl (op == NFS4_ACL_GET) the mask is invalid if:
12308  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12309  *
12310  * In the case of setting an acl (op == NFS4_ACL_SET) the mask is invalid if:
12311  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12312  * - We have a count field set without the corresponding acl field set. (e.g. -
12313  * VSA_ACECNT is set, but VSA_ACE is not)
12314  */
12315 static int
12316 nfs4_is_acl_mask_valid(uint_t acl_mask, nfs4_acl_op_t op)
12317 {
12318 	/* Shortcut the masks that are always valid. */
12319 	if (acl_mask == (VSA_ACE | VSA_ACECNT))
12320 		return (0);
12321 	if (acl_mask == (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT))
12322 		return (0);
12323 
12324 	if (acl_mask & (VSA_ACE | VSA_ACECNT)) {
12325 		/*
12326 		 * We can't have any VSA_ACL type stuff in the mask now.
12327 		 */
12328 		if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12329 		    VSA_DFACLCNT))
12330 			return (EINVAL);
12331 
12332 		if (op == NFS4_ACL_SET) {
12333 			if ((acl_mask & VSA_ACECNT) && !(acl_mask & VSA_ACE))
12334 				return (EINVAL);
12335 		}
12336 	}
12337 
12338 	if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) {
12339 		/*
12340 		 * We can't have any VSA_ACE type stuff in the mask now.
12341 		 */
12342 		if (acl_mask & (VSA_ACE | VSA_ACECNT))
12343 			return (EINVAL);
12344 
12345 		if (op == NFS4_ACL_SET) {
12346 			if ((acl_mask & VSA_ACLCNT) && !(acl_mask & VSA_ACL))
12347 				return (EINVAL);
12348 
12349 			if ((acl_mask & VSA_DFACLCNT) &&
12350 			    !(acl_mask & VSA_DFACL))
12351 				return (EINVAL);
12352 		}
12353 	}
12354 	return (0);
12355 }
12356 
12357 /*
12358  * The theory behind creating the correct getsecattr return is simply this:
12359  * "Don't return anything that the caller is not expecting to have to free."
12360  */
12361 static int
12362 nfs4_create_getsecattr_return(vsecattr_t *filled_vsap, vsecattr_t *vsap,
12363     uid_t uid, gid_t gid, int isdir)
12364 {
12365 	int error = 0;
12366 	/* Save the mask since the translators modify it. */
12367 	uint_t	orig_mask = vsap->vsa_mask;
12368 
12369 	if (orig_mask & (VSA_ACE | VSA_ACECNT)) {
12370 		error = vs_ace4_to_acet(filled_vsap, vsap, uid, gid,
12371 		    FALSE, ((orig_mask & VSA_ACE) ? FALSE : TRUE));
12372 
12373 		if (error)
12374 			return (error);
12375 
12376 		/*
12377 		 * If the caller only asked for the ace count (VSA_ACECNT)
12378 		 * don't give them the full acl (VSA_ACE), free it.
12379 		 */
12380 		if (!orig_mask & VSA_ACE) {
12381 			if (vsap->vsa_aclentp != NULL) {
12382 				kmem_free(vsap->vsa_aclentp,
12383 				    vsap->vsa_aclcnt * sizeof (ace_t));
12384 				vsap->vsa_aclentp = NULL;
12385 			}
12386 		}
12387 		vsap->vsa_mask = orig_mask;
12388 
12389 	} else if (orig_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12390 	    VSA_DFACLCNT)) {
12391 		error = vs_ace4_to_aent(filled_vsap, vsap, uid, gid,
12392 		    isdir, FALSE,
12393 		    ((orig_mask & (VSA_ACL | VSA_DFACL)) ? FALSE : TRUE));
12394 
12395 		if (error)
12396 			return (error);
12397 
12398 		/*
12399 		 * If the caller only asked for the acl count (VSA_ACLCNT)
12400 		 * and/or the default acl count (VSA_DFACLCNT) don't give them
12401 		 * the acl (VSA_ACL) or default acl (VSA_DFACL), free it.
12402 		 */
12403 		if (!orig_mask & VSA_ACL) {
12404 			if (vsap->vsa_aclentp != NULL) {
12405 				kmem_free(vsap->vsa_aclentp,
12406 				    vsap->vsa_aclcnt * sizeof (aclent_t));
12407 				vsap->vsa_aclentp = NULL;
12408 			}
12409 		}
12410 
12411 		if (!orig_mask & VSA_DFACL) {
12412 			if (vsap->vsa_dfaclentp != NULL) {
12413 				kmem_free(vsap->vsa_dfaclentp,
12414 				    vsap->vsa_dfaclcnt * sizeof (aclent_t));
12415 				vsap->vsa_dfaclentp = NULL;
12416 			}
12417 		}
12418 		vsap->vsa_mask = orig_mask;
12419 	}
12420 	return (0);
12421 }
12422 
12423 /* ARGSUSED */
12424 int
12425 nfs4_shrlock(vnode_t *vp, int cmd, struct shrlock *shr, int flag, cred_t *cr,
12426     caller_context_t *ct)
12427 {
12428 	int error;
12429 
12430 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
12431 		return (EIO);
12432 	/*
12433 	 * check for valid cmd parameter
12434 	 */
12435 	if (cmd != F_SHARE && cmd != F_UNSHARE && cmd != F_HASREMOTELOCKS)
12436 		return (EINVAL);
12437 
12438 	/*
12439 	 * Check access permissions
12440 	 */
12441 	if ((cmd & F_SHARE) &&
12442 	    (((shr->s_access & F_RDACC) && (flag & FREAD) == 0) ||
12443 	    (shr->s_access == F_WRACC && (flag & FWRITE) == 0)))
12444 		return (EBADF);
12445 
12446 	/*
12447 	 * If the filesystem is mounted using local locking, pass the
12448 	 * request off to the local share code.
12449 	 */
12450 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK)
12451 		return (fs_shrlock(vp, cmd, shr, flag, cr, ct));
12452 
12453 	switch (cmd) {
12454 	case F_SHARE:
12455 	case F_UNSHARE:
12456 		/*
12457 		 * This will be properly implemented later,
12458 		 * see RFE: 4823948 .
12459 		 */
12460 		error = EAGAIN;
12461 		break;
12462 
12463 	case F_HASREMOTELOCKS:
12464 		/*
12465 		 * NFS client can't store remote locks itself
12466 		 */
12467 		shr->s_access = 0;
12468 		error = 0;
12469 		break;
12470 
12471 	default:
12472 		error = EINVAL;
12473 		break;
12474 	}
12475 
12476 	return (error);
12477 }
12478 
12479 /*
12480  * Common code called by directory ops to update the attrcache
12481  */
12482 static int
12483 nfs4_update_attrcache(nfsstat4 status, nfs4_ga_res_t *garp,
12484     hrtime_t t, vnode_t *vp, cred_t *cr)
12485 {
12486 	int error = 0;
12487 
12488 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12489 
12490 	if (status != NFS4_OK) {
12491 		/* getattr not done or failed */
12492 		PURGE_ATTRCACHE4(vp);
12493 		return (error);
12494 	}
12495 
12496 	if (garp) {
12497 		nfs4_attr_cache(vp, garp, t, cr, FALSE, NULL);
12498 	} else {
12499 		PURGE_ATTRCACHE4(vp);
12500 	}
12501 	return (error);
12502 }
12503 
12504 /*
12505  * Update directory caches for directory modification ops (link, rename, etc.)
12506  * When dinfo is NULL, manage dircaches in the old way.
12507  */
12508 static void
12509 nfs4_update_dircaches(change_info4 *cinfo, vnode_t *dvp, vnode_t *vp, char *nm,
12510     dirattr_info_t *dinfo)
12511 {
12512 	rnode4_t	*drp = VTOR4(dvp);
12513 
12514 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
12515 
12516 	/* Purge rddir cache for dir since it changed */
12517 	if (drp->r_dir != NULL)
12518 		nfs4_purge_rddir_cache(dvp);
12519 
12520 	/*
12521 	 * If caller provided dinfo, then use it to manage dir caches.
12522 	 */
12523 	if (dinfo != NULL) {
12524 		if (vp != NULL) {
12525 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12526 			if (!VTOR4(vp)->created_v4) {
12527 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12528 				dnlc_update(dvp, nm, vp);
12529 			} else {
12530 				/*
12531 				 * XXX don't update if the created_v4 flag is
12532 				 * set
12533 				 */
12534 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12535 				NFS4_DEBUG(nfs4_client_state_debug,
12536 				    (CE_NOTE, "nfs4_update_dircaches: "
12537 				    "don't update dnlc: created_v4 flag"));
12538 			}
12539 		}
12540 
12541 		nfs4_attr_cache(dvp, dinfo->di_garp, dinfo->di_time_call,
12542 		    dinfo->di_cred, FALSE, cinfo);
12543 
12544 		return;
12545 	}
12546 
12547 	/*
12548 	 * Caller didn't provide dinfo, then check change_info4 to update DNLC.
12549 	 * Since caller modified dir but didn't receive post-dirmod-op dir
12550 	 * attrs, the dir's attrs must be purged.
12551 	 *
12552 	 * XXX this check and dnlc update/purge should really be atomic,
12553 	 * XXX but can't use rnode statelock because it'll deadlock in
12554 	 * XXX dnlc_purge_vp, however, the risk is minimal even if a race
12555 	 * XXX does occur.
12556 	 *
12557 	 * XXX We also may want to check that atomic is true in the
12558 	 * XXX change_info struct. If it is not, the change_info may
12559 	 * XXX reflect changes by more than one clients which means that
12560 	 * XXX our cache may not be valid.
12561 	 */
12562 	PURGE_ATTRCACHE4(dvp);
12563 	if (drp->r_change == cinfo->before) {
12564 		/* no changes took place in the directory prior to our link */
12565 		if (vp != NULL) {
12566 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12567 			if (!VTOR4(vp)->created_v4) {
12568 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12569 				dnlc_update(dvp, nm, vp);
12570 			} else {
12571 				/*
12572 				 * XXX dont' update if the created_v4 flag
12573 				 * is set
12574 				 */
12575 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12576 				NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
12577 				    "nfs4_update_dircaches: don't"
12578 				    " update dnlc: created_v4 flag"));
12579 			}
12580 		}
12581 	} else {
12582 		/* Another client modified directory - purge its dnlc cache */
12583 		dnlc_purge_vp(dvp);
12584 	}
12585 }
12586 
12587 /*
12588  * The OPEN_CONFIRM operation confirms the sequence number used in OPENing a
12589  * file.
12590  *
12591  * The 'reopening_file' boolean should be set to TRUE if we are reopening this
12592  * file (ie: client recovery) and otherwise set to FALSE.
12593  *
12594  * 'nfs4_start/end_op' should have been called by the proper (ie: not recovery
12595  * initiated) calling functions.
12596  *
12597  * 'resend' is set to TRUE if this is a OPEN_CONFIRM issued as a result
12598  * of resending a 'lost' open request.
12599  *
12600  * 'num_bseqid_retryp' makes sure we don't loop forever on a broken
12601  * server that hands out BAD_SEQID on open confirm.
12602  *
12603  * Errors are returned via the nfs4_error_t parameter.
12604  */
12605 void
12606 nfs4open_confirm(vnode_t *vp, seqid4 *seqid, stateid4 *stateid, cred_t *cr,
12607     bool_t reopening_file, bool_t *retry_open, nfs4_open_owner_t *oop,
12608     bool_t resend, nfs4_error_t *ep, int *num_bseqid_retryp)
12609 {
12610 	COMPOUND4args_clnt args;
12611 	COMPOUND4res_clnt res;
12612 	nfs_argop4 argop[2];
12613 	nfs_resop4 *resop;
12614 	int doqueue = 1;
12615 	mntinfo4_t *mi;
12616 	OPEN_CONFIRM4args *open_confirm_args;
12617 	int needrecov;
12618 
12619 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12620 #if DEBUG
12621 	mutex_enter(&oop->oo_lock);
12622 	ASSERT(oop->oo_seqid_inuse);
12623 	mutex_exit(&oop->oo_lock);
12624 #endif
12625 
12626 recov_retry_confirm:
12627 	nfs4_error_zinit(ep);
12628 	*retry_open = FALSE;
12629 
12630 	if (resend)
12631 		args.ctag = TAG_OPEN_CONFIRM_LOST;
12632 	else
12633 		args.ctag = TAG_OPEN_CONFIRM;
12634 
12635 	args.array_len = 2;
12636 	args.array = argop;
12637 
12638 	/* putfh target fh */
12639 	argop[0].argop = OP_CPUTFH;
12640 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
12641 
12642 	argop[1].argop = OP_OPEN_CONFIRM;
12643 	open_confirm_args = &argop[1].nfs_argop4_u.opopen_confirm;
12644 
12645 	(*seqid) += 1;
12646 	open_confirm_args->seqid = *seqid;
12647 	open_confirm_args->open_stateid = *stateid;
12648 
12649 	mi = VTOMI4(vp);
12650 
12651 	rfs4call(mi, &args, &res, cr, &doqueue, 0, ep);
12652 
12653 	if (!ep->error && nfs4_need_to_bump_seqid(&res)) {
12654 		nfs4_set_open_seqid((*seqid), oop, args.ctag);
12655 	}
12656 
12657 	needrecov = nfs4_needs_recovery(ep, FALSE, mi->mi_vfsp);
12658 	if (!needrecov && ep->error)
12659 		return;
12660 
12661 	if (needrecov) {
12662 		bool_t abort = FALSE;
12663 
12664 		if (reopening_file == FALSE) {
12665 			nfs4_bseqid_entry_t *bsep = NULL;
12666 
12667 			if (!ep->error && res.status == NFS4ERR_BAD_SEQID)
12668 				bsep = nfs4_create_bseqid_entry(oop, NULL,
12669 				    vp, 0, args.ctag,
12670 				    open_confirm_args->seqid);
12671 
12672 			abort = nfs4_start_recovery(ep, VTOMI4(vp), vp,
12673 			    NULL, NULL, NULL, OP_OPEN_CONFIRM, bsep);
12674 			if (bsep) {
12675 				kmem_free(bsep, sizeof (*bsep));
12676 				if (num_bseqid_retryp &&
12677 				    --(*num_bseqid_retryp) == 0)
12678 					abort = TRUE;
12679 			}
12680 		}
12681 		if ((ep->error == ETIMEDOUT ||
12682 		    res.status == NFS4ERR_RESOURCE) &&
12683 		    abort == FALSE && resend == FALSE) {
12684 			if (!ep->error)
12685 				(void) xdr_free(xdr_COMPOUND4res_clnt,
12686 				    (caddr_t)&res);
12687 
12688 			delay(SEC_TO_TICK(confirm_retry_sec));
12689 			goto recov_retry_confirm;
12690 		}
12691 		/* State may have changed so retry the entire OPEN op */
12692 		if (abort == FALSE)
12693 			*retry_open = TRUE;
12694 		else
12695 			*retry_open = FALSE;
12696 		if (!ep->error)
12697 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12698 		return;
12699 	}
12700 
12701 	if (res.status) {
12702 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12703 		return;
12704 	}
12705 
12706 	resop = &res.array[1];  /* open confirm res */
12707 	bcopy(&resop->nfs_resop4_u.opopen_confirm.open_stateid,
12708 	    stateid, sizeof (*stateid));
12709 
12710 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12711 }
12712 
12713 /*
12714  * Return the credentials associated with a client state object.  The
12715  * caller is responsible for freeing the credentials.
12716  */
12717 
12718 static cred_t *
12719 state_to_cred(nfs4_open_stream_t *osp)
12720 {
12721 	cred_t *cr;
12722 
12723 	/*
12724 	 * It's ok to not lock the open stream and open owner to get
12725 	 * the oo_cred since this is only written once (upon creation)
12726 	 * and will not change.
12727 	 */
12728 	cr = osp->os_open_owner->oo_cred;
12729 	crhold(cr);
12730 
12731 	return (cr);
12732 }
12733 
12734 /*
12735  * nfs4_find_sysid
12736  *
12737  * Find the sysid for the knetconfig associated with the given mi.
12738  */
12739 static struct lm_sysid *
12740 nfs4_find_sysid(mntinfo4_t *mi)
12741 {
12742 	ASSERT(nfs_zone() == mi->mi_zone);
12743 
12744 	/*
12745 	 * Switch from RDMA knconf to original mount knconf
12746 	 */
12747 	return (lm_get_sysid(ORIG_KNCONF(mi), &mi->mi_curr_serv->sv_addr,
12748 	    mi->mi_curr_serv->sv_hostname, NULL));
12749 }
12750 
12751 #ifdef DEBUG
12752 /*
12753  * Return a string version of the call type for easy reading.
12754  */
12755 static char *
12756 nfs4frlock_get_call_type(nfs4_lock_call_type_t ctype)
12757 {
12758 	switch (ctype) {
12759 	case NFS4_LCK_CTYPE_NORM:
12760 		return ("NORMAL");
12761 	case NFS4_LCK_CTYPE_RECLAIM:
12762 		return ("RECLAIM");
12763 	case NFS4_LCK_CTYPE_RESEND:
12764 		return ("RESEND");
12765 	case NFS4_LCK_CTYPE_REINSTATE:
12766 		return ("REINSTATE");
12767 	default:
12768 		cmn_err(CE_PANIC, "nfs4frlock_get_call_type: got illegal "
12769 		    "type %d", ctype);
12770 		return ("");
12771 	}
12772 }
12773 #endif
12774 
12775 /*
12776  * Map the frlock cmd and lock type to the NFSv4 over-the-wire lock type
12777  * Unlock requests don't have an over-the-wire locktype, so we just return
12778  * something non-threatening.
12779  */
12780 
12781 static nfs_lock_type4
12782 flk_to_locktype(int cmd, int l_type)
12783 {
12784 	ASSERT(l_type == F_RDLCK || l_type == F_WRLCK || l_type == F_UNLCK);
12785 
12786 	switch (l_type) {
12787 	case F_UNLCK:
12788 		return (READ_LT);
12789 	case F_RDLCK:
12790 		if (cmd == F_SETLK)
12791 			return (READ_LT);
12792 		else
12793 			return (READW_LT);
12794 	case F_WRLCK:
12795 		if (cmd == F_SETLK)
12796 			return (WRITE_LT);
12797 		else
12798 			return (WRITEW_LT);
12799 	}
12800 	panic("flk_to_locktype");
12801 	/*NOTREACHED*/
12802 }
12803 
12804 /*
12805  * Do some preliminary checks for nfs4frlock.
12806  */
12807 static int
12808 nfs4frlock_validate_args(int cmd, flock64_t *flk, int flag, vnode_t *vp,
12809     u_offset_t offset)
12810 {
12811 	int error = 0;
12812 
12813 	/*
12814 	 * If we are setting a lock, check that the file is opened
12815 	 * with the correct mode.
12816 	 */
12817 	if (cmd == F_SETLK || cmd == F_SETLKW) {
12818 		if ((flk->l_type == F_RDLCK && (flag & FREAD) == 0) ||
12819 		    (flk->l_type == F_WRLCK && (flag & FWRITE) == 0)) {
12820 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12821 			    "nfs4frlock_validate_args: file was opened with "
12822 			    "incorrect mode"));
12823 			return (EBADF);
12824 		}
12825 	}
12826 
12827 	/* Convert the offset. It may need to be restored before returning. */
12828 	if (error = convoff(vp, flk, 0, offset)) {
12829 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12830 		    "nfs4frlock_validate_args: convoff  =>  error= %d\n",
12831 		    error));
12832 		return (error);
12833 	}
12834 
12835 	return (error);
12836 }
12837 
12838 /*
12839  * Set the flock64's lm_sysid for nfs4frlock.
12840  */
12841 static int
12842 nfs4frlock_get_sysid(struct lm_sysid **lspp, vnode_t *vp, flock64_t *flk)
12843 {
12844 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12845 
12846 	/* Find the lm_sysid */
12847 	*lspp = nfs4_find_sysid(VTOMI4(vp));
12848 
12849 	if (*lspp == NULL) {
12850 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
12851 		    "nfs4frlock_get_sysid: no sysid, return ENOLCK"));
12852 		return (ENOLCK);
12853 	}
12854 
12855 	flk->l_sysid = lm_sysidt(*lspp);
12856 
12857 	return (0);
12858 }
12859 
12860 /*
12861  * Do the remaining preliminary setup for nfs4frlock.
12862  */
12863 static void
12864 nfs4frlock_pre_setup(clock_t *tick_delayp, nfs4_recov_state_t *recov_statep,
12865     flock64_t *flk, short *whencep, vnode_t *vp, cred_t *search_cr,
12866     cred_t **cred_otw)
12867 {
12868 	/*
12869 	 * set tick_delay to the base delay time.
12870 	 * (NFS4_BASE_WAIT_TIME is in secs)
12871 	 */
12872 
12873 	*tick_delayp = drv_usectohz(NFS4_BASE_WAIT_TIME * 1000 * 1000);
12874 
12875 	/*
12876 	 * If lock is relative to EOF, we need the newest length of the
12877 	 * file. Therefore invalidate the ATTR_CACHE.
12878 	 */
12879 
12880 	*whencep = flk->l_whence;
12881 
12882 	if (*whencep == 2)		/* SEEK_END */
12883 		PURGE_ATTRCACHE4(vp);
12884 
12885 	recov_statep->rs_flags = 0;
12886 	recov_statep->rs_num_retry_despite_err = 0;
12887 	*cred_otw = nfs4_get_otw_cred(search_cr, VTOMI4(vp), NULL);
12888 }
12889 
12890 /*
12891  * Initialize and allocate the data structures necessary for
12892  * the nfs4frlock call.
12893  * Allocates argsp's op array, frees up the saved_rqstpp if there is one.
12894  */
12895 static void
12896 nfs4frlock_call_init(COMPOUND4args_clnt *argsp, COMPOUND4args_clnt **argspp,
12897     nfs_argop4 **argopp, nfs4_op_hint_t *op_hintp, flock64_t *flk, int cmd,
12898     bool_t *retry, bool_t *did_start_fop, COMPOUND4res_clnt **respp,
12899     bool_t *skip_get_err, nfs4_lost_rqst_t *lost_rqstp)
12900 {
12901 	int		argoplist_size;
12902 	int		num_ops = 2;
12903 
12904 	*retry = FALSE;
12905 	*did_start_fop = FALSE;
12906 	*skip_get_err = FALSE;
12907 	lost_rqstp->lr_op = 0;
12908 	argoplist_size  = num_ops * sizeof (nfs_argop4);
12909 	/* fill array with zero */
12910 	*argopp = kmem_zalloc(argoplist_size, KM_SLEEP);
12911 
12912 	*argspp = argsp;
12913 	*respp = NULL;
12914 
12915 	argsp->array_len = num_ops;
12916 	argsp->array = *argopp;
12917 
12918 	/* initialize in case of error; will get real value down below */
12919 	argsp->ctag = TAG_NONE;
12920 
12921 	if ((cmd == F_SETLK || cmd == F_SETLKW) && flk->l_type == F_UNLCK)
12922 		*op_hintp = OH_LOCKU;
12923 	else
12924 		*op_hintp = OH_OTHER;
12925 }
12926 
12927 /*
12928  * Call the nfs4_start_fop() for nfs4frlock, if necessary.  Assign
12929  * the proper nfs4_server_t for this instance of nfs4frlock.
12930  * Returns 0 (success) or an errno value.
12931  */
12932 static int
12933 nfs4frlock_start_call(nfs4_lock_call_type_t ctype, vnode_t *vp,
12934     nfs4_op_hint_t op_hint, nfs4_recov_state_t *recov_statep,
12935     bool_t *did_start_fop, bool_t *startrecovp)
12936 {
12937 	int error = 0;
12938 	rnode4_t *rp;
12939 
12940 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12941 
12942 	if (ctype == NFS4_LCK_CTYPE_NORM) {
12943 		error = nfs4_start_fop(VTOMI4(vp), vp, NULL, op_hint,
12944 		    recov_statep, startrecovp);
12945 		if (error)
12946 			return (error);
12947 		*did_start_fop = TRUE;
12948 	} else {
12949 		*did_start_fop = FALSE;
12950 		*startrecovp = FALSE;
12951 	}
12952 
12953 	if (!error) {
12954 		rp = VTOR4(vp);
12955 
12956 		/* If the file failed recovery, just quit. */
12957 		mutex_enter(&rp->r_statelock);
12958 		if (rp->r_flags & R4RECOVERR) {
12959 			error = EIO;
12960 		}
12961 		mutex_exit(&rp->r_statelock);
12962 	}
12963 
12964 	return (error);
12965 }
12966 
12967 /*
12968  * Setup the LOCK4/LOCKU4 arguments for resending a lost lock request.  A
12969  * resend nfs4frlock call is initiated by the recovery framework.
12970  * Acquires the lop and oop seqid synchronization.
12971  */
12972 static void
12973 nfs4frlock_setup_resend_lock_args(nfs4_lost_rqst_t *resend_rqstp,
12974     COMPOUND4args_clnt *argsp, nfs_argop4 *argop, nfs4_lock_owner_t **lopp,
12975     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
12976     LOCK4args **lock_argsp, LOCKU4args **locku_argsp)
12977 {
12978 	mntinfo4_t *mi = VTOMI4(resend_rqstp->lr_vp);
12979 	int error;
12980 
12981 	NFS4_DEBUG((nfs4_lost_rqst_debug || nfs4_client_lock_debug),
12982 	    (CE_NOTE,
12983 	    "nfs4frlock_setup_resend_lock_args: have lost lock to resend"));
12984 	ASSERT(resend_rqstp != NULL);
12985 	ASSERT(resend_rqstp->lr_op == OP_LOCK ||
12986 	    resend_rqstp->lr_op == OP_LOCKU);
12987 
12988 	*oopp = resend_rqstp->lr_oop;
12989 	if (resend_rqstp->lr_oop) {
12990 		open_owner_hold(resend_rqstp->lr_oop);
12991 		error = nfs4_start_open_seqid_sync(resend_rqstp->lr_oop, mi);
12992 		ASSERT(error == 0);	/* recov thread always succeeds */
12993 	}
12994 
12995 	/* Must resend this lost lock/locku request. */
12996 	ASSERT(resend_rqstp->lr_lop != NULL);
12997 	*lopp = resend_rqstp->lr_lop;
12998 	lock_owner_hold(resend_rqstp->lr_lop);
12999 	error = nfs4_start_lock_seqid_sync(resend_rqstp->lr_lop, mi);
13000 	ASSERT(error == 0);	/* recov thread always succeeds */
13001 
13002 	*ospp = resend_rqstp->lr_osp;
13003 	if (*ospp)
13004 		open_stream_hold(resend_rqstp->lr_osp);
13005 
13006 	if (resend_rqstp->lr_op == OP_LOCK) {
13007 		LOCK4args *lock_args;
13008 
13009 		argop->argop = OP_LOCK;
13010 		*lock_argsp = lock_args = &argop->nfs_argop4_u.oplock;
13011 		lock_args->locktype = resend_rqstp->lr_locktype;
13012 		lock_args->reclaim =
13013 		    (resend_rqstp->lr_ctype == NFS4_LCK_CTYPE_RECLAIM);
13014 		lock_args->offset = resend_rqstp->lr_flk->l_start;
13015 		lock_args->length = resend_rqstp->lr_flk->l_len;
13016 		if (lock_args->length == 0)
13017 			lock_args->length = ~lock_args->length;
13018 		nfs4_setup_lock_args(*lopp, *oopp, *ospp,
13019 		    mi2clientid(mi), &lock_args->locker);
13020 
13021 		switch (resend_rqstp->lr_ctype) {
13022 		case NFS4_LCK_CTYPE_RESEND:
13023 			argsp->ctag = TAG_LOCK_RESEND;
13024 			break;
13025 		case NFS4_LCK_CTYPE_REINSTATE:
13026 			argsp->ctag = TAG_LOCK_REINSTATE;
13027 			break;
13028 		case NFS4_LCK_CTYPE_RECLAIM:
13029 			argsp->ctag = TAG_LOCK_RECLAIM;
13030 			break;
13031 		default:
13032 			argsp->ctag = TAG_LOCK_UNKNOWN;
13033 			break;
13034 		}
13035 	} else {
13036 		LOCKU4args *locku_args;
13037 		nfs4_lock_owner_t *lop = resend_rqstp->lr_lop;
13038 
13039 		argop->argop = OP_LOCKU;
13040 		*locku_argsp = locku_args = &argop->nfs_argop4_u.oplocku;
13041 		locku_args->locktype = READ_LT;
13042 		locku_args->seqid = lop->lock_seqid + 1;
13043 		mutex_enter(&lop->lo_lock);
13044 		locku_args->lock_stateid = lop->lock_stateid;
13045 		mutex_exit(&lop->lo_lock);
13046 		locku_args->offset = resend_rqstp->lr_flk->l_start;
13047 		locku_args->length = resend_rqstp->lr_flk->l_len;
13048 		if (locku_args->length == 0)
13049 			locku_args->length = ~locku_args->length;
13050 
13051 		switch (resend_rqstp->lr_ctype) {
13052 		case NFS4_LCK_CTYPE_RESEND:
13053 			argsp->ctag = TAG_LOCKU_RESEND;
13054 			break;
13055 		case NFS4_LCK_CTYPE_REINSTATE:
13056 			argsp->ctag = TAG_LOCKU_REINSTATE;
13057 			break;
13058 		default:
13059 			argsp->ctag = TAG_LOCK_UNKNOWN;
13060 			break;
13061 		}
13062 	}
13063 }
13064 
13065 /*
13066  * Setup the LOCKT4 arguments.
13067  */
13068 static void
13069 nfs4frlock_setup_lockt_args(nfs4_lock_call_type_t ctype, nfs_argop4 *argop,
13070     LOCKT4args **lockt_argsp, COMPOUND4args_clnt *argsp, flock64_t *flk,
13071     rnode4_t *rp)
13072 {
13073 	LOCKT4args *lockt_args;
13074 
13075 	ASSERT(nfs_zone() == VTOMI4(RTOV4(rp))->mi_zone);
13076 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13077 	argop->argop = OP_LOCKT;
13078 	argsp->ctag = TAG_LOCKT;
13079 	lockt_args = &argop->nfs_argop4_u.oplockt;
13080 
13081 	/*
13082 	 * The locktype will be READ_LT unless it's
13083 	 * a write lock. We do this because the Solaris
13084 	 * system call allows the combination of
13085 	 * F_UNLCK and F_GETLK* and so in that case the
13086 	 * unlock is mapped to a read.
13087 	 */
13088 	if (flk->l_type == F_WRLCK)
13089 		lockt_args->locktype = WRITE_LT;
13090 	else
13091 		lockt_args->locktype = READ_LT;
13092 
13093 	lockt_args->owner.clientid = mi2clientid(VTOMI4(RTOV4(rp)));
13094 	/* set the lock owner4 args */
13095 	nfs4_setlockowner_args(&lockt_args->owner, rp,
13096 	    ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pidp->pid_id :
13097 	    flk->l_pid);
13098 	lockt_args->offset = flk->l_start;
13099 	lockt_args->length = flk->l_len;
13100 	if (flk->l_len == 0)
13101 		lockt_args->length = ~lockt_args->length;
13102 
13103 	*lockt_argsp = lockt_args;
13104 }
13105 
13106 /*
13107  * If the client is holding a delegation, and the open stream to be used
13108  * with this lock request is a delegation open stream, then re-open the stream.
13109  * Sets the nfs4_error_t to all zeros unless the open stream has already
13110  * failed a reopen or we couldn't find the open stream.  NFS4ERR_DELAY
13111  * means the caller should retry (like a recovery retry).
13112  */
13113 static void
13114 nfs4frlock_check_deleg(vnode_t *vp, nfs4_error_t *ep, cred_t *cr, int lt)
13115 {
13116 	open_delegation_type4	dt;
13117 	bool_t			reopen_needed, force;
13118 	nfs4_open_stream_t	*osp;
13119 	open_claim_type4 	oclaim;
13120 	rnode4_t		*rp = VTOR4(vp);
13121 	mntinfo4_t		*mi = VTOMI4(vp);
13122 
13123 	ASSERT(nfs_zone() == mi->mi_zone);
13124 
13125 	nfs4_error_zinit(ep);
13126 
13127 	mutex_enter(&rp->r_statev4_lock);
13128 	dt = rp->r_deleg_type;
13129 	mutex_exit(&rp->r_statev4_lock);
13130 
13131 	if (dt != OPEN_DELEGATE_NONE) {
13132 		nfs4_open_owner_t	*oop;
13133 
13134 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
13135 		if (!oop) {
13136 			ep->stat = NFS4ERR_IO;
13137 			return;
13138 		}
13139 		/* returns with 'os_sync_lock' held */
13140 		osp = find_open_stream(oop, rp);
13141 		if (!osp) {
13142 			open_owner_rele(oop);
13143 			ep->stat = NFS4ERR_IO;
13144 			return;
13145 		}
13146 
13147 		if (osp->os_failed_reopen) {
13148 			NFS4_DEBUG((nfs4_open_stream_debug ||
13149 			    nfs4_client_lock_debug), (CE_NOTE,
13150 			    "nfs4frlock_check_deleg: os_failed_reopen set "
13151 			    "for osp %p, cr %p, rp %s", (void *)osp,
13152 			    (void *)cr, rnode4info(rp)));
13153 			mutex_exit(&osp->os_sync_lock);
13154 			open_stream_rele(osp, rp);
13155 			open_owner_rele(oop);
13156 			ep->stat = NFS4ERR_IO;
13157 			return;
13158 		}
13159 
13160 		/*
13161 		 * Determine whether a reopen is needed.  If this
13162 		 * is a delegation open stream, then send the open
13163 		 * to the server to give visibility to the open owner.
13164 		 * Even if it isn't a delegation open stream, we need
13165 		 * to check if the previous open CLAIM_DELEGATE_CUR
13166 		 * was sufficient.
13167 		 */
13168 
13169 		reopen_needed = osp->os_delegation ||
13170 		    ((lt == F_RDLCK &&
13171 		    !(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_READ)) ||
13172 		    (lt == F_WRLCK &&
13173 		    !(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_WRITE)));
13174 
13175 		mutex_exit(&osp->os_sync_lock);
13176 		open_owner_rele(oop);
13177 
13178 		if (reopen_needed) {
13179 			/*
13180 			 * Always use CLAIM_PREVIOUS after server reboot.
13181 			 * The server will reject CLAIM_DELEGATE_CUR if
13182 			 * it is used during the grace period.
13183 			 */
13184 			mutex_enter(&mi->mi_lock);
13185 			if (mi->mi_recovflags & MI4R_SRV_REBOOT) {
13186 				oclaim = CLAIM_PREVIOUS;
13187 				force = TRUE;
13188 			} else {
13189 				oclaim = CLAIM_DELEGATE_CUR;
13190 				force = FALSE;
13191 			}
13192 			mutex_exit(&mi->mi_lock);
13193 
13194 			nfs4_reopen(vp, osp, ep, oclaim, force, FALSE);
13195 			if (ep->error == EAGAIN) {
13196 				nfs4_error_zinit(ep);
13197 				ep->stat = NFS4ERR_DELAY;
13198 			}
13199 		}
13200 		open_stream_rele(osp, rp);
13201 		osp = NULL;
13202 	}
13203 }
13204 
13205 /*
13206  * Setup the LOCKU4 arguments.
13207  * Returns errors via the nfs4_error_t.
13208  * NFS4_OK		no problems.  *go_otwp is TRUE if call should go
13209  *			over-the-wire.  The caller must release the
13210  *			reference on *lopp.
13211  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13212  * (other)		unrecoverable error.
13213  */
13214 static void
13215 nfs4frlock_setup_locku_args(nfs4_lock_call_type_t ctype, nfs_argop4 *argop,
13216     LOCKU4args **locku_argsp, flock64_t *flk,
13217     nfs4_lock_owner_t **lopp, nfs4_error_t *ep, COMPOUND4args_clnt *argsp,
13218     vnode_t *vp, int flag, u_offset_t offset, cred_t *cr,
13219     bool_t *skip_get_err, bool_t *go_otwp)
13220 {
13221 	nfs4_lock_owner_t	*lop = NULL;
13222 	LOCKU4args		*locku_args;
13223 	pid_t			pid;
13224 	bool_t			is_spec = FALSE;
13225 	rnode4_t		*rp = VTOR4(vp);
13226 
13227 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13228 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13229 
13230 	nfs4frlock_check_deleg(vp, ep, cr, F_UNLCK);
13231 	if (ep->error || ep->stat)
13232 		return;
13233 
13234 	argop->argop = OP_LOCKU;
13235 	if (ctype == NFS4_LCK_CTYPE_REINSTATE)
13236 		argsp->ctag = TAG_LOCKU_REINSTATE;
13237 	else
13238 		argsp->ctag = TAG_LOCKU;
13239 	locku_args = &argop->nfs_argop4_u.oplocku;
13240 	*locku_argsp = locku_args;
13241 
13242 	/*
13243 	 * XXX what should locku_args->locktype be?
13244 	 * setting to ALWAYS be READ_LT so at least
13245 	 * it is a valid locktype.
13246 	 */
13247 
13248 	locku_args->locktype = READ_LT;
13249 
13250 	pid = ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pidp->pid_id :
13251 	    flk->l_pid;
13252 
13253 	/*
13254 	 * Get the lock owner stateid.  If no lock owner
13255 	 * exists, return success.
13256 	 */
13257 	lop = find_lock_owner(rp, pid, LOWN_ANY);
13258 	*lopp = lop;
13259 	if (lop && CLNT_ISSPECIAL(&lop->lock_stateid))
13260 		is_spec = TRUE;
13261 	if (!lop || is_spec) {
13262 		/*
13263 		 * No lock owner so no locks to unlock.
13264 		 * Return success.  If there was a failed
13265 		 * reclaim earlier, the lock might still be
13266 		 * registered with the local locking code,
13267 		 * so notify it of the unlock.
13268 		 *
13269 		 * If the lockowner is using a special stateid,
13270 		 * then the original lock request (that created
13271 		 * this lockowner) was never successful, so we
13272 		 * have no lock to undo OTW.
13273 		 */
13274 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13275 		    "nfs4frlock_setup_locku_args: LOCKU: no lock owner "
13276 		    "(%ld) so return success", (long)pid));
13277 
13278 		if (ctype == NFS4_LCK_CTYPE_NORM)
13279 			flk->l_pid = curproc->p_pid;
13280 		nfs4_register_lock_locally(vp, flk, flag, offset);
13281 		/*
13282 		 * Release our hold and NULL out so final_cleanup
13283 		 * doesn't try to end a lock seqid sync we
13284 		 * never started.
13285 		 */
13286 		if (is_spec) {
13287 			lock_owner_rele(lop);
13288 			*lopp = NULL;
13289 		}
13290 		*skip_get_err = TRUE;
13291 		*go_otwp = FALSE;
13292 		return;
13293 	}
13294 
13295 	ep->error = nfs4_start_lock_seqid_sync(lop, VTOMI4(vp));
13296 	if (ep->error == EAGAIN) {
13297 		lock_owner_rele(lop);
13298 		*lopp = NULL;
13299 		return;
13300 	}
13301 
13302 	mutex_enter(&lop->lo_lock);
13303 	locku_args->lock_stateid = lop->lock_stateid;
13304 	mutex_exit(&lop->lo_lock);
13305 	locku_args->seqid = lop->lock_seqid + 1;
13306 
13307 	/* leave the ref count on lop, rele after RPC call */
13308 
13309 	locku_args->offset = flk->l_start;
13310 	locku_args->length = flk->l_len;
13311 	if (flk->l_len == 0)
13312 		locku_args->length = ~locku_args->length;
13313 
13314 	*go_otwp = TRUE;
13315 }
13316 
13317 /*
13318  * Setup the LOCK4 arguments.
13319  *
13320  * Returns errors via the nfs4_error_t.
13321  * NFS4_OK		no problems
13322  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13323  * (other)		unrecoverable error
13324  */
13325 static void
13326 nfs4frlock_setup_lock_args(nfs4_lock_call_type_t ctype, LOCK4args **lock_argsp,
13327     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13328     nfs4_lock_owner_t **lopp, nfs_argop4 *argop, COMPOUND4args_clnt *argsp,
13329     flock64_t *flk, int cmd, vnode_t *vp, cred_t *cr, nfs4_error_t *ep)
13330 {
13331 	LOCK4args		*lock_args;
13332 	nfs4_open_owner_t	*oop = NULL;
13333 	nfs4_open_stream_t	*osp = NULL;
13334 	nfs4_lock_owner_t	*lop = NULL;
13335 	pid_t			pid;
13336 	rnode4_t		*rp = VTOR4(vp);
13337 
13338 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13339 
13340 	nfs4frlock_check_deleg(vp, ep, cr, flk->l_type);
13341 	if (ep->error || ep->stat != NFS4_OK)
13342 		return;
13343 
13344 	argop->argop = OP_LOCK;
13345 	if (ctype == NFS4_LCK_CTYPE_NORM)
13346 		argsp->ctag = TAG_LOCK;
13347 	else if (ctype == NFS4_LCK_CTYPE_RECLAIM)
13348 		argsp->ctag = TAG_RELOCK;
13349 	else
13350 		argsp->ctag = TAG_LOCK_REINSTATE;
13351 	lock_args = &argop->nfs_argop4_u.oplock;
13352 	lock_args->locktype = flk_to_locktype(cmd, flk->l_type);
13353 	lock_args->reclaim = ctype == NFS4_LCK_CTYPE_RECLAIM ? 1 : 0;
13354 	/*
13355 	 * Get the lock owner.  If no lock owner exists,
13356 	 * create a 'temporary' one and grab the open seqid
13357 	 * synchronization (which puts a hold on the open
13358 	 * owner and open stream).
13359 	 * This also grabs the lock seqid synchronization.
13360 	 */
13361 	pid = ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pid : flk->l_pid;
13362 	ep->stat =
13363 	    nfs4_find_or_create_lock_owner(pid, rp, cr, &oop, &osp, &lop);
13364 
13365 	if (ep->stat != NFS4_OK)
13366 		goto out;
13367 
13368 	nfs4_setup_lock_args(lop, oop, osp, mi2clientid(VTOMI4(vp)),
13369 	    &lock_args->locker);
13370 
13371 	lock_args->offset = flk->l_start;
13372 	lock_args->length = flk->l_len;
13373 	if (flk->l_len == 0)
13374 		lock_args->length = ~lock_args->length;
13375 	*lock_argsp = lock_args;
13376 out:
13377 	*oopp = oop;
13378 	*ospp = osp;
13379 	*lopp = lop;
13380 }
13381 
13382 /*
13383  * After we get the reply from the server, record the proper information
13384  * for possible resend lock requests.
13385  *
13386  * Allocates memory for the saved_rqstp if we have a lost lock to save.
13387  */
13388 static void
13389 nfs4frlock_save_lost_rqst(nfs4_lock_call_type_t ctype, int error,
13390     nfs_lock_type4 locktype, nfs4_open_owner_t *oop,
13391     nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop, flock64_t *flk,
13392     nfs4_lost_rqst_t *lost_rqstp, cred_t *cr, vnode_t *vp)
13393 {
13394 	bool_t unlock = (flk->l_type == F_UNLCK);
13395 
13396 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13397 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM ||
13398 	    ctype == NFS4_LCK_CTYPE_REINSTATE);
13399 
13400 	if (error != 0 && !unlock) {
13401 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13402 		    nfs4_client_lock_debug), (CE_NOTE,
13403 		    "nfs4frlock_save_lost_rqst: set lo_pending_rqsts to 1 "
13404 		    " for lop %p", (void *)lop));
13405 		ASSERT(lop != NULL);
13406 		mutex_enter(&lop->lo_lock);
13407 		lop->lo_pending_rqsts = 1;
13408 		mutex_exit(&lop->lo_lock);
13409 	}
13410 
13411 	lost_rqstp->lr_putfirst = FALSE;
13412 	lost_rqstp->lr_op = 0;
13413 
13414 	/*
13415 	 * For lock/locku requests, we treat EINTR as ETIMEDOUT for
13416 	 * recovery purposes so that the lock request that was sent
13417 	 * can be saved and re-issued later.  Ditto for EIO from a forced
13418 	 * unmount.  This is done to have the client's local locking state
13419 	 * match the v4 server's state; that is, the request was
13420 	 * potentially received and accepted by the server but the client
13421 	 * thinks it was not.
13422 	 */
13423 	if (error == ETIMEDOUT || error == EINTR ||
13424 	    NFS4_FRC_UNMT_ERR(error, vp->v_vfsp)) {
13425 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13426 		    nfs4_client_lock_debug), (CE_NOTE,
13427 		    "nfs4frlock_save_lost_rqst: got a lost %s lock for "
13428 		    "lop %p oop %p osp %p", unlock ? "LOCKU" : "LOCK",
13429 		    (void *)lop, (void *)oop, (void *)osp));
13430 		if (unlock)
13431 			lost_rqstp->lr_op = OP_LOCKU;
13432 		else {
13433 			lost_rqstp->lr_op = OP_LOCK;
13434 			lost_rqstp->lr_locktype = locktype;
13435 		}
13436 		/*
13437 		 * Objects are held and rele'd via the recovery code.
13438 		 * See nfs4_save_lost_rqst.
13439 		 */
13440 		lost_rqstp->lr_vp = vp;
13441 		lost_rqstp->lr_dvp = NULL;
13442 		lost_rqstp->lr_oop = oop;
13443 		lost_rqstp->lr_osp = osp;
13444 		lost_rqstp->lr_lop = lop;
13445 		lost_rqstp->lr_cr = cr;
13446 		switch (ctype) {
13447 		case NFS4_LCK_CTYPE_NORM:
13448 			flk->l_pid = ttoproc(curthread)->p_pid;
13449 			lost_rqstp->lr_ctype = NFS4_LCK_CTYPE_RESEND;
13450 			break;
13451 		case NFS4_LCK_CTYPE_REINSTATE:
13452 			lost_rqstp->lr_putfirst = TRUE;
13453 			lost_rqstp->lr_ctype = ctype;
13454 			break;
13455 		default:
13456 			break;
13457 		}
13458 		lost_rqstp->lr_flk = flk;
13459 	}
13460 }
13461 
13462 /*
13463  * Update lop's seqid.  Also update the seqid stored in a resend request,
13464  * if any.  (Some recovery errors increment the seqid, and we may have to
13465  * send the resend request again.)
13466  */
13467 
13468 static void
13469 nfs4frlock_bump_seqid(LOCK4args *lock_args, LOCKU4args *locku_args,
13470     nfs4_open_owner_t *oop, nfs4_lock_owner_t *lop, nfs4_tag_type_t tag_type)
13471 {
13472 	if (lock_args) {
13473 		if (lock_args->locker.new_lock_owner == TRUE)
13474 			nfs4_get_and_set_next_open_seqid(oop, tag_type);
13475 		else {
13476 			ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13477 			nfs4_set_lock_seqid(lop->lock_seqid + 1, lop);
13478 		}
13479 	} else if (locku_args) {
13480 		ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13481 		nfs4_set_lock_seqid(lop->lock_seqid +1, lop);
13482 	}
13483 }
13484 
13485 /*
13486  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13487  * COMPOUND4 args/res for calls that need to retry.
13488  * Switches the *cred_otwp to base_cr.
13489  */
13490 static void
13491 nfs4frlock_check_access(vnode_t *vp, nfs4_op_hint_t op_hint,
13492     nfs4_recov_state_t *recov_statep, int needrecov, bool_t *did_start_fop,
13493     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp, int error,
13494     nfs4_lock_owner_t **lopp, nfs4_open_owner_t **oopp,
13495     nfs4_open_stream_t **ospp, cred_t *base_cr, cred_t **cred_otwp)
13496 {
13497 	nfs4_open_owner_t	*oop = *oopp;
13498 	nfs4_open_stream_t	*osp = *ospp;
13499 	nfs4_lock_owner_t	*lop = *lopp;
13500 	nfs_argop4		*argop = (*argspp)->array;
13501 
13502 	if (*did_start_fop) {
13503 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13504 		    needrecov);
13505 		*did_start_fop = FALSE;
13506 	}
13507 	ASSERT((*argspp)->array_len == 2);
13508 	if (argop[1].argop == OP_LOCK)
13509 		nfs4args_lock_free(&argop[1]);
13510 	else if (argop[1].argop == OP_LOCKT)
13511 		nfs4args_lockt_free(&argop[1]);
13512 	kmem_free(argop, 2 * sizeof (nfs_argop4));
13513 	if (!error)
13514 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13515 	*argspp = NULL;
13516 	*respp = NULL;
13517 
13518 	if (lop) {
13519 		nfs4_end_lock_seqid_sync(lop);
13520 		lock_owner_rele(lop);
13521 		*lopp = NULL;
13522 	}
13523 
13524 	/* need to free up the reference on osp for lock args */
13525 	if (osp != NULL) {
13526 		open_stream_rele(osp, VTOR4(vp));
13527 		*ospp = NULL;
13528 	}
13529 
13530 	/* need to free up the reference on oop for lock args */
13531 	if (oop != NULL) {
13532 		nfs4_end_open_seqid_sync(oop);
13533 		open_owner_rele(oop);
13534 		*oopp = NULL;
13535 	}
13536 
13537 	crfree(*cred_otwp);
13538 	*cred_otwp = base_cr;
13539 	crhold(*cred_otwp);
13540 }
13541 
13542 /*
13543  * Function to process the client's recovery for nfs4frlock.
13544  * Returns TRUE if we should retry the lock request; FALSE otherwise.
13545  *
13546  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13547  * COMPOUND4 args/res for calls that need to retry.
13548  *
13549  * Note: the rp's r_lkserlock is *not* dropped during this path.
13550  */
13551 static bool_t
13552 nfs4frlock_recovery(int needrecov, nfs4_error_t *ep,
13553     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13554     LOCK4args *lock_args, LOCKU4args *locku_args,
13555     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13556     nfs4_lock_owner_t **lopp, rnode4_t *rp, vnode_t *vp,
13557     nfs4_recov_state_t *recov_statep, nfs4_op_hint_t op_hint,
13558     bool_t *did_start_fop, nfs4_lost_rqst_t *lost_rqstp, flock64_t *flk)
13559 {
13560 	nfs4_open_owner_t	*oop = *oopp;
13561 	nfs4_open_stream_t	*osp = *ospp;
13562 	nfs4_lock_owner_t	*lop = *lopp;
13563 
13564 	bool_t abort, retry;
13565 
13566 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13567 	ASSERT((*argspp) != NULL);
13568 	ASSERT((*respp) != NULL);
13569 	if (lock_args || locku_args)
13570 		ASSERT(lop != NULL);
13571 
13572 	NFS4_DEBUG((nfs4_client_lock_debug || nfs4_client_recov_debug),
13573 	    (CE_NOTE, "nfs4frlock_recovery: initiating recovery\n"));
13574 
13575 	retry = TRUE;
13576 	abort = FALSE;
13577 	if (needrecov) {
13578 		nfs4_bseqid_entry_t *bsep = NULL;
13579 		nfs_opnum4 op;
13580 
13581 		op = lock_args ? OP_LOCK : locku_args ? OP_LOCKU : OP_LOCKT;
13582 
13583 		if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID) {
13584 			seqid4 seqid;
13585 
13586 			if (lock_args) {
13587 				if (lock_args->locker.new_lock_owner == TRUE)
13588 					seqid = lock_args->locker.locker4_u.
13589 					    open_owner.open_seqid;
13590 				else
13591 					seqid = lock_args->locker.locker4_u.
13592 					    lock_owner.lock_seqid;
13593 			} else if (locku_args) {
13594 				seqid = locku_args->seqid;
13595 			} else {
13596 				seqid = 0;
13597 			}
13598 
13599 			bsep = nfs4_create_bseqid_entry(oop, lop, vp,
13600 			    flk->l_pid, (*argspp)->ctag, seqid);
13601 		}
13602 
13603 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL, NULL,
13604 		    (lost_rqstp && (lost_rqstp->lr_op == OP_LOCK ||
13605 		    lost_rqstp->lr_op == OP_LOCKU)) ? lost_rqstp :
13606 		    NULL, op, bsep);
13607 
13608 		if (bsep)
13609 			kmem_free(bsep, sizeof (*bsep));
13610 	}
13611 
13612 	/*
13613 	 * Return that we do not want to retry the request for 3 cases:
13614 	 * 1. If we received EINTR or are bailing out because of a forced
13615 	 *    unmount, we came into this code path just for the sake of
13616 	 *    initiating recovery, we now need to return the error.
13617 	 * 2. If we have aborted recovery.
13618 	 * 3. We received NFS4ERR_BAD_SEQID.
13619 	 */
13620 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp) ||
13621 	    abort == TRUE || (ep->error == 0 && ep->stat == NFS4ERR_BAD_SEQID))
13622 		retry = FALSE;
13623 
13624 	if (*did_start_fop == TRUE) {
13625 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13626 		    needrecov);
13627 		*did_start_fop = FALSE;
13628 	}
13629 
13630 	if (retry == TRUE) {
13631 		nfs_argop4	*argop;
13632 
13633 		argop = (*argspp)->array;
13634 		ASSERT((*argspp)->array_len == 2);
13635 
13636 		if (argop[1].argop == OP_LOCK)
13637 			nfs4args_lock_free(&argop[1]);
13638 		else if (argop[1].argop == OP_LOCKT)
13639 			nfs4args_lockt_free(&argop[1]);
13640 		kmem_free(argop, 2 * sizeof (nfs_argop4));
13641 		if (!ep->error)
13642 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13643 		*respp = NULL;
13644 		*argspp = NULL;
13645 	}
13646 
13647 	if (lop != NULL) {
13648 		nfs4_end_lock_seqid_sync(lop);
13649 		lock_owner_rele(lop);
13650 	}
13651 
13652 	*lopp = NULL;
13653 
13654 	/* need to free up the reference on osp for lock args */
13655 	if (osp != NULL) {
13656 		open_stream_rele(osp, rp);
13657 		*ospp = NULL;
13658 	}
13659 
13660 	/* need to free up the reference on oop for lock args */
13661 	if (oop != NULL) {
13662 		nfs4_end_open_seqid_sync(oop);
13663 		open_owner_rele(oop);
13664 		*oopp = NULL;
13665 	}
13666 
13667 	return (retry);
13668 }
13669 
13670 /*
13671  * Handles the successful reply from the server for nfs4frlock.
13672  */
13673 static void
13674 nfs4frlock_results_ok(nfs4_lock_call_type_t ctype, int cmd, flock64_t *flk,
13675     vnode_t *vp, int flag, u_offset_t offset,
13676     nfs4_lost_rqst_t *resend_rqstp)
13677 {
13678 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13679 	if ((cmd == F_SETLK || cmd == F_SETLKW) &&
13680 	    (flk->l_type == F_RDLCK || flk->l_type == F_WRLCK)) {
13681 		if (ctype == NFS4_LCK_CTYPE_NORM) {
13682 			flk->l_pid = ttoproc(curthread)->p_pid;
13683 			/*
13684 			 * We do not register lost locks locally in
13685 			 * the 'resend' case since the user/application
13686 			 * doesn't think we have the lock.
13687 			 */
13688 			ASSERT(!resend_rqstp);
13689 			nfs4_register_lock_locally(vp, flk, flag, offset);
13690 		}
13691 	}
13692 }
13693 
13694 /*
13695  * Handle the DENIED reply from the server for nfs4frlock.
13696  * Returns TRUE if we should retry the request; FALSE otherwise.
13697  *
13698  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13699  * COMPOUND4 args/res for calls that need to retry.  Can also
13700  * drop and regrab the r_lkserlock.
13701  */
13702 static bool_t
13703 nfs4frlock_results_denied(nfs4_lock_call_type_t ctype, LOCK4args *lock_args,
13704     LOCKT4args *lockt_args, nfs4_open_owner_t **oopp,
13705     nfs4_open_stream_t **ospp, nfs4_lock_owner_t **lopp, int cmd,
13706     vnode_t *vp, flock64_t *flk, nfs4_op_hint_t op_hint,
13707     nfs4_recov_state_t *recov_statep, int needrecov,
13708     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13709     clock_t *tick_delayp, short *whencep, int *errorp,
13710     nfs_resop4 *resop, cred_t *cr, bool_t *did_start_fop,
13711     bool_t *skip_get_err)
13712 {
13713 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13714 
13715 	if (lock_args) {
13716 		nfs4_open_owner_t	*oop = *oopp;
13717 		nfs4_open_stream_t	*osp = *ospp;
13718 		nfs4_lock_owner_t	*lop = *lopp;
13719 		int			intr;
13720 
13721 		/*
13722 		 * Blocking lock needs to sleep and retry from the request.
13723 		 *
13724 		 * Do not block and wait for 'resend' or 'reinstate'
13725 		 * lock requests, just return the error.
13726 		 *
13727 		 * Note: reclaim requests have cmd == F_SETLK, not F_SETLKW.
13728 		 */
13729 		if (cmd == F_SETLKW) {
13730 			rnode4_t *rp = VTOR4(vp);
13731 			nfs_argop4 *argop = (*argspp)->array;
13732 
13733 			ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13734 
13735 			nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
13736 			    recov_statep, needrecov);
13737 			*did_start_fop = FALSE;
13738 			ASSERT((*argspp)->array_len == 2);
13739 			if (argop[1].argop == OP_LOCK)
13740 				nfs4args_lock_free(&argop[1]);
13741 			else if (argop[1].argop == OP_LOCKT)
13742 				nfs4args_lockt_free(&argop[1]);
13743 			kmem_free(argop, 2 * sizeof (nfs_argop4));
13744 			if (*respp)
13745 				(void) xdr_free(xdr_COMPOUND4res_clnt,
13746 				    (caddr_t)*respp);
13747 			*argspp = NULL;
13748 			*respp = NULL;
13749 			nfs4_end_lock_seqid_sync(lop);
13750 			lock_owner_rele(lop);
13751 			*lopp = NULL;
13752 			if (osp != NULL) {
13753 				open_stream_rele(osp, rp);
13754 				*ospp = NULL;
13755 			}
13756 			if (oop != NULL) {
13757 				nfs4_end_open_seqid_sync(oop);
13758 				open_owner_rele(oop);
13759 				*oopp = NULL;
13760 			}
13761 
13762 			nfs_rw_exit(&rp->r_lkserlock);
13763 
13764 			intr = nfs4_block_and_wait(tick_delayp, rp);
13765 
13766 			if (intr) {
13767 				(void) nfs_rw_enter_sig(&rp->r_lkserlock,
13768 				    RW_WRITER, FALSE);
13769 				*errorp = EINTR;
13770 				return (FALSE);
13771 			}
13772 
13773 			(void) nfs_rw_enter_sig(&rp->r_lkserlock,
13774 			    RW_WRITER, FALSE);
13775 
13776 			/*
13777 			 * Make sure we are still safe to lock with
13778 			 * regards to mmapping.
13779 			 */
13780 			if (!nfs4_safelock(vp, flk, cr)) {
13781 				*errorp = EAGAIN;
13782 				return (FALSE);
13783 			}
13784 
13785 			return (TRUE);
13786 		}
13787 		if (ctype == NFS4_LCK_CTYPE_NORM)
13788 			*errorp = EAGAIN;
13789 		*skip_get_err = TRUE;
13790 		flk->l_whence = 0;
13791 		*whencep = 0;
13792 		return (FALSE);
13793 	} else if (lockt_args) {
13794 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13795 		    "nfs4frlock_results_denied: OP_LOCKT DENIED"));
13796 
13797 		denied_to_flk(&resop->nfs_resop4_u.oplockt.denied,
13798 		    flk, lockt_args);
13799 
13800 		/* according to NLM code */
13801 		*errorp = 0;
13802 		*whencep = 0;
13803 		*skip_get_err = TRUE;
13804 		return (FALSE);
13805 	}
13806 	return (FALSE);
13807 }
13808 
13809 /*
13810  * Handles all NFS4 errors besides NFS4_OK and NFS4ERR_DENIED for nfs4frlock.
13811  */
13812 static void
13813 nfs4frlock_results_default(COMPOUND4res_clnt *resp, int *errorp)
13814 {
13815 	switch (resp->status) {
13816 	case NFS4ERR_ACCESS:
13817 	case NFS4ERR_ADMIN_REVOKED:
13818 	case NFS4ERR_BADHANDLE:
13819 	case NFS4ERR_BAD_RANGE:
13820 	case NFS4ERR_BAD_SEQID:
13821 	case NFS4ERR_BAD_STATEID:
13822 	case NFS4ERR_BADXDR:
13823 	case NFS4ERR_DEADLOCK:
13824 	case NFS4ERR_DELAY:
13825 	case NFS4ERR_EXPIRED:
13826 	case NFS4ERR_FHEXPIRED:
13827 	case NFS4ERR_GRACE:
13828 	case NFS4ERR_INVAL:
13829 	case NFS4ERR_ISDIR:
13830 	case NFS4ERR_LEASE_MOVED:
13831 	case NFS4ERR_LOCK_NOTSUPP:
13832 	case NFS4ERR_LOCK_RANGE:
13833 	case NFS4ERR_MOVED:
13834 	case NFS4ERR_NOFILEHANDLE:
13835 	case NFS4ERR_NO_GRACE:
13836 	case NFS4ERR_OLD_STATEID:
13837 	case NFS4ERR_OPENMODE:
13838 	case NFS4ERR_RECLAIM_BAD:
13839 	case NFS4ERR_RECLAIM_CONFLICT:
13840 	case NFS4ERR_RESOURCE:
13841 	case NFS4ERR_SERVERFAULT:
13842 	case NFS4ERR_STALE:
13843 	case NFS4ERR_STALE_CLIENTID:
13844 	case NFS4ERR_STALE_STATEID:
13845 		return;
13846 	default:
13847 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13848 		    "nfs4frlock_results_default: got unrecognizable "
13849 		    "res.status %d", resp->status));
13850 		*errorp = NFS4ERR_INVAL;
13851 	}
13852 }
13853 
13854 /*
13855  * The lock request was successful, so update the client's state.
13856  */
13857 static void
13858 nfs4frlock_update_state(LOCK4args *lock_args, LOCKU4args *locku_args,
13859     LOCKT4args *lockt_args, nfs_resop4 *resop, nfs4_lock_owner_t *lop,
13860     vnode_t *vp, flock64_t *flk, cred_t *cr,
13861     nfs4_lost_rqst_t *resend_rqstp)
13862 {
13863 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13864 
13865 	if (lock_args) {
13866 		LOCK4res *lock_res;
13867 
13868 		lock_res = &resop->nfs_resop4_u.oplock;
13869 		/* update the stateid with server's response */
13870 
13871 		if (lock_args->locker.new_lock_owner == TRUE) {
13872 			mutex_enter(&lop->lo_lock);
13873 			lop->lo_just_created = NFS4_PERM_CREATED;
13874 			mutex_exit(&lop->lo_lock);
13875 		}
13876 
13877 		nfs4_set_lock_stateid(lop, lock_res->LOCK4res_u.lock_stateid);
13878 
13879 		/*
13880 		 * If the lock was the result of a resending a lost
13881 		 * request, we've synched up the stateid and seqid
13882 		 * with the server, but now the server might be out of sync
13883 		 * with what the application thinks it has for locks.
13884 		 * Clean that up here.  It's unclear whether we should do
13885 		 * this even if the filesystem has been forcibly unmounted.
13886 		 * For most servers, it's probably wasted effort, but
13887 		 * RFC3530 lets servers require that unlocks exactly match
13888 		 * the locks that are held.
13889 		 */
13890 		if (resend_rqstp != NULL &&
13891 		    resend_rqstp->lr_ctype != NFS4_LCK_CTYPE_REINSTATE) {
13892 			nfs4_reinstitute_local_lock_state(vp, flk, cr, lop);
13893 		} else {
13894 			flk->l_whence = 0;
13895 		}
13896 	} else if (locku_args) {
13897 		LOCKU4res *locku_res;
13898 
13899 		locku_res = &resop->nfs_resop4_u.oplocku;
13900 
13901 		/* Update the stateid with the server's response */
13902 		nfs4_set_lock_stateid(lop, locku_res->lock_stateid);
13903 	} else if (lockt_args) {
13904 		/* Switch the lock type to express success, see fcntl */
13905 		flk->l_type = F_UNLCK;
13906 		flk->l_whence = 0;
13907 	}
13908 }
13909 
13910 /*
13911  * Do final cleanup before exiting nfs4frlock.
13912  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13913  * COMPOUND4 args/res for calls that haven't already.
13914  */
13915 static void
13916 nfs4frlock_final_cleanup(nfs4_lock_call_type_t ctype, COMPOUND4args_clnt *argsp,
13917     COMPOUND4res_clnt *resp, vnode_t *vp, nfs4_op_hint_t op_hint,
13918     nfs4_recov_state_t *recov_statep, int needrecov, nfs4_open_owner_t *oop,
13919     nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop, flock64_t *flk,
13920     short whence, u_offset_t offset, struct lm_sysid *ls,
13921     int *errorp, LOCK4args *lock_args, LOCKU4args *locku_args,
13922     bool_t did_start_fop, bool_t skip_get_err,
13923     cred_t *cred_otw, cred_t *cred)
13924 {
13925 	mntinfo4_t	*mi = VTOMI4(vp);
13926 	rnode4_t	*rp = VTOR4(vp);
13927 	int		error = *errorp;
13928 	nfs_argop4	*argop;
13929 
13930 	ASSERT(nfs_zone() == mi->mi_zone);
13931 	/*
13932 	 * The client recovery code wants the raw status information,
13933 	 * so don't map the NFS status code to an errno value for
13934 	 * non-normal call types.
13935 	 */
13936 	if (ctype == NFS4_LCK_CTYPE_NORM) {
13937 		if (*errorp == 0 && resp != NULL && skip_get_err == FALSE)
13938 			*errorp = geterrno4(resp->status);
13939 		if (did_start_fop == TRUE)
13940 			nfs4_end_fop(mi, vp, NULL, op_hint, recov_statep,
13941 			    needrecov);
13942 
13943 		/*
13944 		 * We've established a new lock on the server, so invalidate
13945 		 * the pages associated with the vnode to get the most up to
13946 		 * date pages from the server after acquiring the lock. We
13947 		 * want to be sure that the read operation gets the newest data.
13948 		 * N.B.
13949 		 * We used to do this in nfs4frlock_results_ok but that doesn't
13950 		 * work since VOP_PUTPAGE can call nfs4_commit which calls
13951 		 * nfs4_start_fop. We flush the pages below after calling
13952 		 * nfs4_end_fop above
13953 		 */
13954 		if (!error && resp && resp->status == NFS4_OK) {
13955 			int error;
13956 
13957 			error = VOP_PUTPAGE(vp, (u_offset_t)0,
13958 			    0, B_INVAL, cred, NULL);
13959 
13960 			if (error && (error == ENOSPC || error == EDQUOT)) {
13961 				rnode4_t *rp = VTOR4(vp);
13962 
13963 				mutex_enter(&rp->r_statelock);
13964 				if (!rp->r_error)
13965 					rp->r_error = error;
13966 				mutex_exit(&rp->r_statelock);
13967 			}
13968 		}
13969 	}
13970 	if (argsp) {
13971 		ASSERT(argsp->array_len == 2);
13972 		argop = argsp->array;
13973 		if (argop[1].argop == OP_LOCK)
13974 			nfs4args_lock_free(&argop[1]);
13975 		else if (argop[1].argop == OP_LOCKT)
13976 			nfs4args_lockt_free(&argop[1]);
13977 		kmem_free(argop, 2 * sizeof (nfs_argop4));
13978 		if (resp)
13979 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
13980 	}
13981 
13982 	/* free the reference on the lock owner */
13983 	if (lop != NULL) {
13984 		nfs4_end_lock_seqid_sync(lop);
13985 		lock_owner_rele(lop);
13986 	}
13987 
13988 	/* need to free up the reference on osp for lock args */
13989 	if (osp != NULL)
13990 		open_stream_rele(osp, rp);
13991 
13992 	/* need to free up the reference on oop for lock args */
13993 	if (oop != NULL) {
13994 		nfs4_end_open_seqid_sync(oop);
13995 		open_owner_rele(oop);
13996 	}
13997 
13998 	(void) convoff(vp, flk, whence, offset);
13999 
14000 	lm_rel_sysid(ls);
14001 
14002 	/*
14003 	 * Record debug information in the event we get EINVAL.
14004 	 */
14005 	mutex_enter(&mi->mi_lock);
14006 	if (*errorp == EINVAL && (lock_args || locku_args) &&
14007 	    (!(mi->mi_flags & MI4_POSIX_LOCK))) {
14008 		if (!(mi->mi_flags & MI4_LOCK_DEBUG)) {
14009 			zcmn_err(getzoneid(), CE_NOTE,
14010 			    "%s operation failed with "
14011 			    "EINVAL probably since the server, %s,"
14012 			    " doesn't support POSIX style locking",
14013 			    lock_args ? "LOCK" : "LOCKU",
14014 			    mi->mi_curr_serv->sv_hostname);
14015 			mi->mi_flags |= MI4_LOCK_DEBUG;
14016 		}
14017 	}
14018 	mutex_exit(&mi->mi_lock);
14019 
14020 	if (cred_otw)
14021 		crfree(cred_otw);
14022 }
14023 
14024 /*
14025  * This calls the server and the local locking code.
14026  *
14027  * Client locks are registerred locally by oring the sysid with
14028  * LM_SYSID_CLIENT. The server registers locks locally using just the sysid.
14029  * We need to distinguish between the two to avoid collision in case one
14030  * machine is used as both client and server.
14031  *
14032  * Blocking lock requests will continually retry to acquire the lock
14033  * forever.
14034  *
14035  * The ctype is defined as follows:
14036  * NFS4_LCK_CTYPE_NORM: normal lock request.
14037  *
14038  * NFS4_LCK_CTYPE_RECLAIM:  bypass the usual calls for synchronizing with client
14039  * recovery, get the pid from flk instead of curproc, and don't reregister
14040  * the lock locally.
14041  *
14042  * NFS4_LCK_CTYPE_RESEND: same as NFS4_LCK_CTYPE_RECLAIM, with the addition
14043  * that we will use the information passed in via resend_rqstp to setup the
14044  * lock/locku request.  This resend is the exact same request as the 'lost
14045  * lock', and is initiated by the recovery framework. A successful resend
14046  * request can initiate one or more reinstate requests.
14047  *
14048  * NFS4_LCK_CTYPE_REINSTATE: same as NFS4_LCK_CTYPE_RESEND, except that it
14049  * does not trigger additional reinstate requests.  This lock call type is
14050  * set for setting the v4 server's locking state back to match what the
14051  * client's local locking state is in the event of a received 'lost lock'.
14052  *
14053  * Errors are returned via the nfs4_error_t parameter.
14054  */
14055 void
14056 nfs4frlock(nfs4_lock_call_type_t ctype, vnode_t *vp, int cmd, flock64_t *flk,
14057     int flag, u_offset_t offset, cred_t *cr, nfs4_error_t *ep,
14058     nfs4_lost_rqst_t *resend_rqstp, int *did_reclaimp)
14059 {
14060 	COMPOUND4args_clnt	args, *argsp = NULL;
14061 	COMPOUND4res_clnt	res, *resp = NULL;
14062 	nfs_argop4	*argop;
14063 	nfs_resop4	*resop;
14064 	rnode4_t	*rp;
14065 	int		doqueue = 1;
14066 	clock_t		tick_delay;  /* delay in clock ticks */
14067 	struct lm_sysid	*ls;
14068 	LOCK4args	*lock_args = NULL;
14069 	LOCKU4args	*locku_args = NULL;
14070 	LOCKT4args	*lockt_args = NULL;
14071 	nfs4_open_owner_t *oop = NULL;
14072 	nfs4_open_stream_t *osp = NULL;
14073 	nfs4_lock_owner_t *lop = NULL;
14074 	bool_t		needrecov = FALSE;
14075 	nfs4_recov_state_t recov_state;
14076 	short		whence;
14077 	nfs4_op_hint_t	op_hint;
14078 	nfs4_lost_rqst_t lost_rqst;
14079 	bool_t		retry = FALSE;
14080 	bool_t		did_start_fop = FALSE;
14081 	bool_t		skip_get_err = FALSE;
14082 	cred_t		*cred_otw = NULL;
14083 	bool_t		recovonly;	/* just queue request */
14084 	int		frc_no_reclaim = 0;
14085 #ifdef DEBUG
14086 	char *name;
14087 #endif
14088 
14089 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14090 
14091 #ifdef DEBUG
14092 	name = fn_name(VTOSV(vp)->sv_name);
14093 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4frlock: "
14094 	    "%s: cmd %d, type %d, offset %llu, start %"PRIx64", "
14095 	    "length %"PRIu64", pid %d, sysid %d, call type %s, "
14096 	    "resend request %s", name, cmd, flk->l_type, offset, flk->l_start,
14097 	    flk->l_len, ctype == NFS4_LCK_CTYPE_NORM ? curproc->p_pid :
14098 	    flk->l_pid, flk->l_sysid, nfs4frlock_get_call_type(ctype),
14099 	    resend_rqstp ? "TRUE" : "FALSE"));
14100 	kmem_free(name, MAXNAMELEN);
14101 #endif
14102 
14103 	nfs4_error_zinit(ep);
14104 	ep->error = nfs4frlock_validate_args(cmd, flk, flag, vp, offset);
14105 	if (ep->error)
14106 		return;
14107 	ep->error = nfs4frlock_get_sysid(&ls, vp, flk);
14108 	if (ep->error)
14109 		return;
14110 	nfs4frlock_pre_setup(&tick_delay, &recov_state, flk, &whence,
14111 	    vp, cr, &cred_otw);
14112 
14113 recov_retry:
14114 	nfs4frlock_call_init(&args, &argsp, &argop, &op_hint, flk, cmd,
14115 	    &retry, &did_start_fop, &resp, &skip_get_err, &lost_rqst);
14116 	rp = VTOR4(vp);
14117 
14118 	ep->error = nfs4frlock_start_call(ctype, vp, op_hint, &recov_state,
14119 	    &did_start_fop, &recovonly);
14120 
14121 	if (ep->error)
14122 		goto out;
14123 
14124 	if (recovonly) {
14125 		/*
14126 		 * Leave the request for the recovery system to deal with.
14127 		 */
14128 		ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
14129 		ASSERT(cmd != F_GETLK);
14130 		ASSERT(flk->l_type == F_UNLCK);
14131 
14132 		nfs4_error_init(ep, EINTR);
14133 		needrecov = TRUE;
14134 		lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14135 		if (lop != NULL) {
14136 			nfs4frlock_save_lost_rqst(ctype, ep->error, READ_LT,
14137 			    NULL, NULL, lop, flk, &lost_rqst, cr, vp);
14138 			(void) nfs4_start_recovery(ep,
14139 			    VTOMI4(vp), vp, NULL, NULL,
14140 			    (lost_rqst.lr_op == OP_LOCK ||
14141 			    lost_rqst.lr_op == OP_LOCKU) ?
14142 			    &lost_rqst : NULL, OP_LOCKU, NULL);
14143 			lock_owner_rele(lop);
14144 			lop = NULL;
14145 		}
14146 		flk->l_pid = curproc->p_pid;
14147 		nfs4_register_lock_locally(vp, flk, flag, offset);
14148 		goto out;
14149 	}
14150 
14151 	/* putfh directory fh */
14152 	argop[0].argop = OP_CPUTFH;
14153 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
14154 
14155 	/*
14156 	 * Set up the over-the-wire arguments and get references to the
14157 	 * open owner, etc.
14158 	 */
14159 
14160 	if (ctype == NFS4_LCK_CTYPE_RESEND ||
14161 	    ctype == NFS4_LCK_CTYPE_REINSTATE) {
14162 		nfs4frlock_setup_resend_lock_args(resend_rqstp, argsp,
14163 		    &argop[1], &lop, &oop, &osp, &lock_args, &locku_args);
14164 	} else {
14165 		bool_t go_otw = TRUE;
14166 
14167 		ASSERT(resend_rqstp == NULL);
14168 
14169 		switch (cmd) {
14170 		case F_GETLK:
14171 		case F_O_GETLK:
14172 			nfs4frlock_setup_lockt_args(ctype, &argop[1],
14173 			    &lockt_args, argsp, flk, rp);
14174 			break;
14175 		case F_SETLKW:
14176 		case F_SETLK:
14177 			if (flk->l_type == F_UNLCK)
14178 				nfs4frlock_setup_locku_args(ctype,
14179 				    &argop[1], &locku_args, flk,
14180 				    &lop, ep, argsp,
14181 				    vp, flag, offset, cr,
14182 				    &skip_get_err, &go_otw);
14183 			else
14184 				nfs4frlock_setup_lock_args(ctype,
14185 				    &lock_args, &oop, &osp, &lop, &argop[1],
14186 				    argsp, flk, cmd, vp, cr, ep);
14187 
14188 			if (ep->error)
14189 				goto out;
14190 
14191 			switch (ep->stat) {
14192 			case NFS4_OK:
14193 				break;
14194 			case NFS4ERR_DELAY:
14195 				/* recov thread never gets this error */
14196 				ASSERT(resend_rqstp == NULL);
14197 				ASSERT(did_start_fop);
14198 
14199 				nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
14200 				    &recov_state, TRUE);
14201 				did_start_fop = FALSE;
14202 				if (argop[1].argop == OP_LOCK)
14203 					nfs4args_lock_free(&argop[1]);
14204 				else if (argop[1].argop == OP_LOCKT)
14205 					nfs4args_lockt_free(&argop[1]);
14206 				kmem_free(argop, 2 * sizeof (nfs_argop4));
14207 				argsp = NULL;
14208 				goto recov_retry;
14209 			default:
14210 				ep->error = EIO;
14211 				goto out;
14212 			}
14213 			break;
14214 		default:
14215 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14216 			    "nfs4_frlock: invalid cmd %d", cmd));
14217 			ep->error = EINVAL;
14218 			goto out;
14219 		}
14220 
14221 		if (!go_otw)
14222 			goto out;
14223 	}
14224 
14225 	/* XXX should we use the local reclock as a cache ? */
14226 	/*
14227 	 * Unregister the lock with the local locking code before
14228 	 * contacting the server.  This avoids a potential race where
14229 	 * another process gets notified that it has been granted a lock
14230 	 * before we can unregister ourselves locally.
14231 	 */
14232 	if ((cmd == F_SETLK || cmd == F_SETLKW) && flk->l_type == F_UNLCK) {
14233 		if (ctype == NFS4_LCK_CTYPE_NORM)
14234 			flk->l_pid = ttoproc(curthread)->p_pid;
14235 		nfs4_register_lock_locally(vp, flk, flag, offset);
14236 	}
14237 
14238 	/*
14239 	 * Send the server the lock request.  Continually loop with a delay
14240 	 * if get error NFS4ERR_DENIED (for blocking locks) or NFS4ERR_GRACE.
14241 	 */
14242 	resp = &res;
14243 
14244 	NFS4_DEBUG((nfs4_client_call_debug || nfs4_client_lock_debug),
14245 	    (CE_NOTE,
14246 	    "nfs4frlock: %s call, rp %s", needrecov ? "recov" : "first",
14247 	    rnode4info(rp)));
14248 
14249 	if (lock_args && frc_no_reclaim) {
14250 		ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14251 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14252 		    "nfs4frlock: frc_no_reclaim: clearing reclaim"));
14253 		lock_args->reclaim = FALSE;
14254 		if (did_reclaimp)
14255 			*did_reclaimp = 0;
14256 	}
14257 
14258 	/*
14259 	 * Do the OTW call.
14260 	 */
14261 	rfs4call(VTOMI4(vp), argsp, resp, cred_otw, &doqueue, 0, ep);
14262 
14263 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14264 	    "nfs4frlock: error %d, status %d", ep->error, resp->status));
14265 
14266 	needrecov = nfs4_needs_recovery(ep, TRUE, vp->v_vfsp);
14267 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14268 	    "nfs4frlock: needrecov %d", needrecov));
14269 
14270 	if (ep->error == 0 && nfs4_need_to_bump_seqid(resp))
14271 		nfs4frlock_bump_seqid(lock_args, locku_args, oop, lop,
14272 		    args.ctag);
14273 
14274 	/*
14275 	 * Check if one of these mutually exclusive error cases has
14276 	 * happened:
14277 	 *   need to swap credentials due to access error
14278 	 *   recovery is needed
14279 	 *   different error (only known case is missing Kerberos ticket)
14280 	 */
14281 
14282 	if ((ep->error == EACCES ||
14283 	    (ep->error == 0 && resp->status == NFS4ERR_ACCESS)) &&
14284 	    cred_otw != cr) {
14285 		nfs4frlock_check_access(vp, op_hint, &recov_state, needrecov,
14286 		    &did_start_fop, &argsp, &resp, ep->error, &lop, &oop, &osp,
14287 		    cr, &cred_otw);
14288 		goto recov_retry;
14289 	}
14290 
14291 	if (needrecov) {
14292 		/*
14293 		 * LOCKT requests don't need to recover from lost
14294 		 * requests since they don't create/modify state.
14295 		 */
14296 		if ((ep->error == EINTR ||
14297 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) &&
14298 		    lockt_args)
14299 			goto out;
14300 		/*
14301 		 * Do not attempt recovery for requests initiated by
14302 		 * the recovery framework.  Let the framework redrive them.
14303 		 */
14304 		if (ctype != NFS4_LCK_CTYPE_NORM)
14305 			goto out;
14306 		else {
14307 			ASSERT(resend_rqstp == NULL);
14308 		}
14309 
14310 		nfs4frlock_save_lost_rqst(ctype, ep->error,
14311 		    flk_to_locktype(cmd, flk->l_type),
14312 		    oop, osp, lop, flk, &lost_rqst, cred_otw, vp);
14313 
14314 		retry = nfs4frlock_recovery(needrecov, ep, &argsp,
14315 		    &resp, lock_args, locku_args, &oop, &osp, &lop,
14316 		    rp, vp, &recov_state, op_hint, &did_start_fop,
14317 		    cmd != F_GETLK ? &lost_rqst : NULL, flk);
14318 
14319 		if (retry) {
14320 			ASSERT(oop == NULL);
14321 			ASSERT(osp == NULL);
14322 			ASSERT(lop == NULL);
14323 			goto recov_retry;
14324 		}
14325 		goto out;
14326 	}
14327 
14328 	/*
14329 	 * Bail out if have reached this point with ep->error set. Can
14330 	 * happen if (ep->error == EACCES && !needrecov && cred_otw == cr).
14331 	 * This happens if Kerberos ticket has expired or has been
14332 	 * destroyed.
14333 	 */
14334 	if (ep->error != 0)
14335 		goto out;
14336 
14337 	/*
14338 	 * Process the reply.
14339 	 */
14340 	switch (resp->status) {
14341 	case NFS4_OK:
14342 		resop = &resp->array[1];
14343 		nfs4frlock_results_ok(ctype, cmd, flk, vp, flag, offset,
14344 		    resend_rqstp);
14345 		/*
14346 		 * Have a successful lock operation, now update state.
14347 		 */
14348 		nfs4frlock_update_state(lock_args, locku_args, lockt_args,
14349 		    resop, lop, vp, flk, cr, resend_rqstp);
14350 		break;
14351 
14352 	case NFS4ERR_DENIED:
14353 		resop = &resp->array[1];
14354 		retry = nfs4frlock_results_denied(ctype, lock_args, lockt_args,
14355 		    &oop, &osp, &lop, cmd, vp, flk, op_hint,
14356 		    &recov_state, needrecov, &argsp, &resp,
14357 		    &tick_delay, &whence, &ep->error, resop, cr,
14358 		    &did_start_fop, &skip_get_err);
14359 
14360 		if (retry) {
14361 			ASSERT(oop == NULL);
14362 			ASSERT(osp == NULL);
14363 			ASSERT(lop == NULL);
14364 			goto recov_retry;
14365 		}
14366 		break;
14367 	/*
14368 	 * If the server won't let us reclaim, fall-back to trying to lock
14369 	 * the file from scratch. Code elsewhere will check the changeinfo
14370 	 * to ensure the file hasn't been changed.
14371 	 */
14372 	case NFS4ERR_NO_GRACE:
14373 		if (lock_args && lock_args->reclaim == TRUE) {
14374 			ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14375 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14376 			    "nfs4frlock: reclaim: NFS4ERR_NO_GRACE"));
14377 			frc_no_reclaim = 1;
14378 			/* clean up before retrying */
14379 			needrecov = 0;
14380 			(void) nfs4frlock_recovery(needrecov, ep, &argsp, &resp,
14381 			    lock_args, locku_args, &oop, &osp, &lop, rp, vp,
14382 			    &recov_state, op_hint, &did_start_fop, NULL, flk);
14383 			goto recov_retry;
14384 		}
14385 		/* FALLTHROUGH */
14386 
14387 	default:
14388 		nfs4frlock_results_default(resp, &ep->error);
14389 		break;
14390 	}
14391 out:
14392 	/*
14393 	 * Process and cleanup from error.  Make interrupted unlock
14394 	 * requests look successful, since they will be handled by the
14395 	 * client recovery code.
14396 	 */
14397 	nfs4frlock_final_cleanup(ctype, argsp, resp, vp, op_hint, &recov_state,
14398 	    needrecov, oop, osp, lop, flk, whence, offset, ls, &ep->error,
14399 	    lock_args, locku_args, did_start_fop,
14400 	    skip_get_err, cred_otw, cr);
14401 
14402 	if (ep->error == EINTR && flk->l_type == F_UNLCK &&
14403 	    (cmd == F_SETLK || cmd == F_SETLKW))
14404 		ep->error = 0;
14405 }
14406 
14407 /*
14408  * nfs4_safelock:
14409  *
14410  * Return non-zero if the given lock request can be handled without
14411  * violating the constraints on concurrent mapping and locking.
14412  */
14413 
14414 static int
14415 nfs4_safelock(vnode_t *vp, const struct flock64 *bfp, cred_t *cr)
14416 {
14417 	rnode4_t *rp = VTOR4(vp);
14418 	struct vattr va;
14419 	int error;
14420 
14421 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14422 	ASSERT(rp->r_mapcnt >= 0);
14423 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock %s: "
14424 	    "(%"PRIx64", %"PRIx64"); mapcnt = %ld", bfp->l_type == F_WRLCK ?
14425 	    "write" : bfp->l_type == F_RDLCK ? "read" : "unlock",
14426 	    bfp->l_start, bfp->l_len, rp->r_mapcnt));
14427 
14428 	if (rp->r_mapcnt == 0)
14429 		return (1);		/* always safe if not mapped */
14430 
14431 	/*
14432 	 * If the file is already mapped and there are locks, then they
14433 	 * should be all safe locks.  So adding or removing a lock is safe
14434 	 * as long as the new request is safe (i.e., whole-file, meaning
14435 	 * length and starting offset are both zero).
14436 	 */
14437 
14438 	if (bfp->l_start != 0 || bfp->l_len != 0) {
14439 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14440 		    "cannot lock a memory mapped file unless locking the "
14441 		    "entire file: start %"PRIx64", len %"PRIx64,
14442 		    bfp->l_start, bfp->l_len));
14443 		return (0);
14444 	}
14445 
14446 	/* mandatory locking and mapping don't mix */
14447 	va.va_mask = AT_MODE;
14448 	error = VOP_GETATTR(vp, &va, 0, cr, NULL);
14449 	if (error != 0) {
14450 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14451 		    "getattr error %d", error));
14452 		return (0);		/* treat errors conservatively */
14453 	}
14454 	if (MANDLOCK(vp, va.va_mode)) {
14455 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14456 		    "cannot mandatory lock and mmap a file"));
14457 		return (0);
14458 	}
14459 
14460 	return (1);
14461 }
14462 
14463 
14464 /*
14465  * Register the lock locally within Solaris.
14466  * As the client, we "or" the sysid with LM_SYSID_CLIENT when
14467  * recording locks locally.
14468  *
14469  * This should handle conflicts/cooperation with NFS v2/v3 since all locks
14470  * are registered locally.
14471  */
14472 void
14473 nfs4_register_lock_locally(vnode_t *vp, struct flock64 *flk, int flag,
14474     u_offset_t offset)
14475 {
14476 	int oldsysid;
14477 	int error;
14478 #ifdef DEBUG
14479 	char *name;
14480 #endif
14481 
14482 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14483 
14484 #ifdef DEBUG
14485 	name = fn_name(VTOSV(vp)->sv_name);
14486 	NFS4_DEBUG(nfs4_client_lock_debug,
14487 	    (CE_NOTE, "nfs4_register_lock_locally: %s: type %d, "
14488 	    "start %"PRIx64", length %"PRIx64", pid %ld, sysid %d",
14489 	    name, flk->l_type, flk->l_start, flk->l_len, (long)flk->l_pid,
14490 	    flk->l_sysid));
14491 	kmem_free(name, MAXNAMELEN);
14492 #endif
14493 
14494 	/* register the lock with local locking */
14495 	oldsysid = flk->l_sysid;
14496 	flk->l_sysid |= LM_SYSID_CLIENT;
14497 	error = reclock(vp, flk, SETFLCK, flag, offset, NULL);
14498 #ifdef DEBUG
14499 	if (error != 0) {
14500 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14501 		    "nfs4_register_lock_locally: could not register with"
14502 		    " local locking"));
14503 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14504 		    "error %d, vp 0x%p, pid %d, sysid 0x%x",
14505 		    error, (void *)vp, flk->l_pid, flk->l_sysid));
14506 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14507 		    "type %d off 0x%" PRIx64 " len 0x%" PRIx64,
14508 		    flk->l_type, flk->l_start, flk->l_len));
14509 		(void) reclock(vp, flk, 0, flag, offset, NULL);
14510 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_CONT,
14511 		    "blocked by pid %d sysid 0x%x type %d "
14512 		    "off 0x%" PRIx64 " len 0x%" PRIx64,
14513 		    flk->l_pid, flk->l_sysid, flk->l_type, flk->l_start,
14514 		    flk->l_len));
14515 	}
14516 #endif
14517 	flk->l_sysid = oldsysid;
14518 }
14519 
14520 /*
14521  * nfs4_lockrelease:
14522  *
14523  * Release any locks on the given vnode that are held by the current
14524  * process.  Also removes the lock owner (if one exists) from the rnode's
14525  * list.
14526  */
14527 static int
14528 nfs4_lockrelease(vnode_t *vp, int flag, offset_t offset, cred_t *cr)
14529 {
14530 	flock64_t ld;
14531 	int ret, error;
14532 	rnode4_t *rp;
14533 	nfs4_lock_owner_t *lop;
14534 	nfs4_recov_state_t recov_state;
14535 	mntinfo4_t *mi;
14536 	bool_t possible_orphan = FALSE;
14537 	bool_t recovonly;
14538 
14539 	ASSERT((uintptr_t)vp > KERNELBASE);
14540 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14541 
14542 	rp = VTOR4(vp);
14543 	mi = VTOMI4(vp);
14544 
14545 	/*
14546 	 * If we have not locked anything then we can
14547 	 * just return since we have no work to do.
14548 	 */
14549 	if (rp->r_lo_head.lo_next_rnode == &rp->r_lo_head) {
14550 		return (0);
14551 	}
14552 
14553 	/*
14554 	 * We need to comprehend that another thread may
14555 	 * kick off recovery and the lock_owner we have stashed
14556 	 * in lop might be invalid so we should NOT cache it
14557 	 * locally!
14558 	 */
14559 	recov_state.rs_flags = 0;
14560 	recov_state.rs_num_retry_despite_err = 0;
14561 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14562 	    &recovonly);
14563 	if (error) {
14564 		mutex_enter(&rp->r_statelock);
14565 		rp->r_flags |= R4LODANGLERS;
14566 		mutex_exit(&rp->r_statelock);
14567 		return (error);
14568 	}
14569 
14570 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14571 
14572 	/*
14573 	 * Check if the lock owner might have a lock (request was sent but
14574 	 * no response was received).  Also check if there are any remote
14575 	 * locks on the file.  (In theory we shouldn't have to make this
14576 	 * second check if there's no lock owner, but for now we'll be
14577 	 * conservative and do it anyway.)  If either condition is true,
14578 	 * send an unlock for the entire file to the server.
14579 	 *
14580 	 * Note that no explicit synchronization is needed here.  At worst,
14581 	 * flk_has_remote_locks() will return a false positive, in which case
14582 	 * the unlock call wastes time but doesn't harm correctness.
14583 	 */
14584 
14585 	if (lop) {
14586 		mutex_enter(&lop->lo_lock);
14587 		possible_orphan = lop->lo_pending_rqsts;
14588 		mutex_exit(&lop->lo_lock);
14589 		lock_owner_rele(lop);
14590 	}
14591 
14592 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14593 
14594 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14595 	    "nfs4_lockrelease: possible orphan %d, remote locks %d, for "
14596 	    "lop %p.", possible_orphan, flk_has_remote_locks(vp),
14597 	    (void *)lop));
14598 
14599 	if (possible_orphan || flk_has_remote_locks(vp)) {
14600 		ld.l_type = F_UNLCK;    /* set to unlock entire file */
14601 		ld.l_whence = 0;	/* unlock from start of file */
14602 		ld.l_start = 0;
14603 		ld.l_len = 0;		/* do entire file */
14604 
14605 		ret = VOP_FRLOCK(vp, F_SETLK, &ld, flag, offset, NULL,
14606 		    cr, NULL);
14607 
14608 		if (ret != 0) {
14609 			/*
14610 			 * If VOP_FRLOCK fails, make sure we unregister
14611 			 * local locks before we continue.
14612 			 */
14613 			ld.l_pid = ttoproc(curthread)->p_pid;
14614 			nfs4_register_lock_locally(vp, &ld, flag, offset);
14615 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14616 			    "nfs4_lockrelease: lock release error on vp"
14617 			    " %p: error %d.\n", (void *)vp, ret));
14618 		}
14619 	}
14620 
14621 	recov_state.rs_flags = 0;
14622 	recov_state.rs_num_retry_despite_err = 0;
14623 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14624 	    &recovonly);
14625 	if (error) {
14626 		mutex_enter(&rp->r_statelock);
14627 		rp->r_flags |= R4LODANGLERS;
14628 		mutex_exit(&rp->r_statelock);
14629 		return (error);
14630 	}
14631 
14632 	/*
14633 	 * So, here we're going to need to retrieve the lock-owner
14634 	 * again (in case recovery has done a switch-a-roo) and
14635 	 * remove it because we can.
14636 	 */
14637 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14638 
14639 	if (lop) {
14640 		nfs4_rnode_remove_lock_owner(rp, lop);
14641 		lock_owner_rele(lop);
14642 	}
14643 
14644 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14645 	return (0);
14646 }
14647 
14648 /*
14649  * Wait for 'tick_delay' clock ticks.
14650  * Implement exponential backoff until hit the lease_time of this nfs4_server.
14651  * NOTE: lock_lease_time is in seconds.
14652  *
14653  * XXX For future improvements, should implement a waiting queue scheme.
14654  */
14655 static int
14656 nfs4_block_and_wait(clock_t *tick_delay, rnode4_t *rp)
14657 {
14658 	long milliseconds_delay;
14659 	time_t lock_lease_time;
14660 
14661 	/* wait tick_delay clock ticks or siginteruptus */
14662 	if (delay_sig(*tick_delay)) {
14663 		return (EINTR);
14664 	}
14665 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_block_and_wait: "
14666 	    "reissue the lock request: blocked for %ld clock ticks: %ld "
14667 	    "milliseconds", *tick_delay, drv_hztousec(*tick_delay) / 1000));
14668 
14669 	/* get the lease time */
14670 	lock_lease_time = r2lease_time(rp);
14671 
14672 	/* drv_hztousec converts ticks to microseconds */
14673 	milliseconds_delay = drv_hztousec(*tick_delay) / 1000;
14674 	if (milliseconds_delay < lock_lease_time * 1000) {
14675 		*tick_delay = 2 * *tick_delay;
14676 		if (drv_hztousec(*tick_delay) > lock_lease_time * 1000 * 1000)
14677 			*tick_delay = drv_usectohz(lock_lease_time*1000*1000);
14678 	}
14679 	return (0);
14680 }
14681 
14682 
14683 void
14684 nfs4_vnops_init(void)
14685 {
14686 }
14687 
14688 void
14689 nfs4_vnops_fini(void)
14690 {
14691 }
14692 
14693 /*
14694  * Return a reference to the directory (parent) vnode for a given vnode,
14695  * using the saved pathname information and the directory file handle.  The
14696  * caller is responsible for disposing of the reference.
14697  * Returns zero or an errno value.
14698  *
14699  * Caller should set need_start_op to FALSE if it is the recovery
14700  * thread, or if a start_fop has already been done.  Otherwise, TRUE.
14701  */
14702 int
14703 vtodv(vnode_t *vp, vnode_t **dvpp, cred_t *cr, bool_t need_start_op)
14704 {
14705 	svnode_t *svnp;
14706 	vnode_t *dvp = NULL;
14707 	servinfo4_t *svp;
14708 	nfs4_fname_t *mfname;
14709 	int error;
14710 
14711 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14712 
14713 	if (vp->v_flag & VROOT) {
14714 		nfs4_sharedfh_t *sfh;
14715 		nfs_fh4 fh;
14716 		mntinfo4_t *mi;
14717 
14718 		ASSERT(vp->v_type == VREG);
14719 
14720 		mi = VTOMI4(vp);
14721 		svp = mi->mi_curr_serv;
14722 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14723 		fh.nfs_fh4_len = svp->sv_pfhandle.fh_len;
14724 		fh.nfs_fh4_val = svp->sv_pfhandle.fh_buf;
14725 		sfh = sfh4_get(&fh, VTOMI4(vp));
14726 		nfs_rw_exit(&svp->sv_lock);
14727 		mfname = mi->mi_fname;
14728 		fn_hold(mfname);
14729 		dvp = makenfs4node_by_fh(sfh, NULL, &mfname, NULL, mi, cr, 0);
14730 		sfh4_rele(&sfh);
14731 
14732 		if (dvp->v_type == VNON)
14733 			dvp->v_type = VDIR;
14734 		*dvpp = dvp;
14735 		return (0);
14736 	}
14737 
14738 	svnp = VTOSV(vp);
14739 
14740 	if (svnp == NULL) {
14741 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14742 		    "shadow node is NULL"));
14743 		return (EINVAL);
14744 	}
14745 
14746 	if (svnp->sv_name == NULL || svnp->sv_dfh == NULL) {
14747 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14748 		    "shadow node name or dfh val == NULL"));
14749 		return (EINVAL);
14750 	}
14751 
14752 	error = nfs4_make_dotdot(svnp->sv_dfh, 0, vp, cr, &dvp,
14753 	    (int)need_start_op);
14754 	if (error != 0) {
14755 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14756 		    "nfs4_make_dotdot returned %d", error));
14757 		return (error);
14758 	}
14759 	if (!dvp) {
14760 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14761 		    "nfs4_make_dotdot returned a NULL dvp"));
14762 		return (EIO);
14763 	}
14764 	if (dvp->v_type == VNON)
14765 		dvp->v_type = VDIR;
14766 	ASSERT(dvp->v_type == VDIR);
14767 	if (VTOR4(vp)->r_flags & R4ISXATTR) {
14768 		mutex_enter(&dvp->v_lock);
14769 		dvp->v_flag |= V_XATTRDIR;
14770 		mutex_exit(&dvp->v_lock);
14771 	}
14772 	*dvpp = dvp;
14773 	return (0);
14774 }
14775 
14776 /*
14777  * Copy the (final) component name of vp to fnamep.  maxlen is the maximum
14778  * length that fnamep can accept, including the trailing null.
14779  * Returns 0 if okay, returns an errno value if there was a problem.
14780  */
14781 
14782 int
14783 vtoname(vnode_t *vp, char *fnamep, ssize_t maxlen)
14784 {
14785 	char *fn;
14786 	int err = 0;
14787 	servinfo4_t *svp;
14788 	svnode_t *shvp;
14789 
14790 	/*
14791 	 * If the file being opened has VROOT set, then this is
14792 	 * a "file" mount.  sv_name will not be interesting, so
14793 	 * go back to the servinfo4 to get the original mount
14794 	 * path and strip off all but the final edge.  Otherwise
14795 	 * just return the name from the shadow vnode.
14796 	 */
14797 
14798 	if (vp->v_flag & VROOT) {
14799 
14800 		svp = VTOMI4(vp)->mi_curr_serv;
14801 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14802 
14803 		fn = strrchr(svp->sv_path, '/');
14804 		if (fn == NULL)
14805 			err = EINVAL;
14806 		else
14807 			fn++;
14808 	} else {
14809 		shvp = VTOSV(vp);
14810 		fn = fn_name(shvp->sv_name);
14811 	}
14812 
14813 	if (err == 0)
14814 		if (strlen(fn) < maxlen)
14815 			(void) strcpy(fnamep, fn);
14816 		else
14817 			err = ENAMETOOLONG;
14818 
14819 	if (vp->v_flag & VROOT)
14820 		nfs_rw_exit(&svp->sv_lock);
14821 	else
14822 		kmem_free(fn, MAXNAMELEN);
14823 
14824 	return (err);
14825 }
14826 
14827 /*
14828  * Bookkeeping for a close that doesn't need to go over the wire.
14829  * *have_lockp is set to 0 if 'os_sync_lock' is released; otherwise
14830  * it is left at 1.
14831  */
14832 void
14833 nfs4close_notw(vnode_t *vp, nfs4_open_stream_t *osp, int *have_lockp)
14834 {
14835 	rnode4_t		*rp;
14836 	mntinfo4_t		*mi;
14837 
14838 	mi = VTOMI4(vp);
14839 	rp = VTOR4(vp);
14840 
14841 	NFS4_DEBUG(nfs4close_notw_debug, (CE_NOTE, "nfs4close_notw: "
14842 	    "rp=%p osp=%p", (void *)rp, (void *)osp));
14843 	ASSERT(nfs_zone() == mi->mi_zone);
14844 	ASSERT(mutex_owned(&osp->os_sync_lock));
14845 	ASSERT(*have_lockp);
14846 
14847 	if (!osp->os_valid ||
14848 	    osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
14849 		return;
14850 	}
14851 
14852 	/*
14853 	 * This removes the reference obtained at OPEN; ie,
14854 	 * when the open stream structure was created.
14855 	 *
14856 	 * We don't have to worry about calling 'open_stream_rele'
14857 	 * since we our currently holding a reference to this
14858 	 * open stream which means the count can not go to 0 with
14859 	 * this decrement.
14860 	 */
14861 	ASSERT(osp->os_ref_count >= 2);
14862 	osp->os_ref_count--;
14863 	osp->os_valid = 0;
14864 	mutex_exit(&osp->os_sync_lock);
14865 	*have_lockp = 0;
14866 
14867 	nfs4_dec_state_ref_count(mi);
14868 }
14869 
14870 /*
14871  * Close all remaining open streams on the rnode.  These open streams
14872  * could be here because:
14873  * - The close attempted at either close or delmap failed
14874  * - Some kernel entity did VOP_OPEN but never did VOP_CLOSE
14875  * - Someone did mknod on a regular file but never opened it
14876  */
14877 int
14878 nfs4close_all(vnode_t *vp, cred_t *cr)
14879 {
14880 	nfs4_open_stream_t *osp;
14881 	int error;
14882 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
14883 	rnode4_t *rp;
14884 
14885 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14886 
14887 	error = 0;
14888 	rp = VTOR4(vp);
14889 
14890 	/*
14891 	 * At this point, all we know is that the last time
14892 	 * someone called vn_rele, the count was 1.  Since then,
14893 	 * the vnode could have been re-activated.  We want to
14894 	 * loop through the open streams and close each one, but
14895 	 * we have to be careful since once we release the rnode
14896 	 * hash bucket lock, someone else is free to come in and
14897 	 * re-activate the rnode and add new open streams.  The
14898 	 * strategy is take the rnode hash bucket lock, verify that
14899 	 * the count is still 1, grab the open stream off the
14900 	 * head of the list and mark it invalid, then release the
14901 	 * rnode hash bucket lock and proceed with that open stream.
14902 	 * This is ok because nfs4close_one() will acquire the proper
14903 	 * open/create to close/destroy synchronization for open
14904 	 * streams, and will ensure that if someone has reopened
14905 	 * the open stream after we've dropped the hash bucket lock
14906 	 * then we'll just simply return without destroying the
14907 	 * open stream.
14908 	 * Repeat until the list is empty.
14909 	 */
14910 
14911 	for (;;) {
14912 
14913 		/* make sure vnode hasn't been reactivated */
14914 		rw_enter(&rp->r_hashq->r_lock, RW_READER);
14915 		mutex_enter(&vp->v_lock);
14916 		if (vp->v_count > 1) {
14917 			mutex_exit(&vp->v_lock);
14918 			rw_exit(&rp->r_hashq->r_lock);
14919 			break;
14920 		}
14921 		/*
14922 		 * Grabbing r_os_lock before releasing v_lock prevents
14923 		 * a window where the rnode/open stream could get
14924 		 * reactivated (and os_force_close set to 0) before we
14925 		 * had a chance to set os_force_close to 1.
14926 		 */
14927 		mutex_enter(&rp->r_os_lock);
14928 		mutex_exit(&vp->v_lock);
14929 
14930 		osp = list_head(&rp->r_open_streams);
14931 		if (!osp) {
14932 			/* nothing left to CLOSE OTW, so return */
14933 			mutex_exit(&rp->r_os_lock);
14934 			rw_exit(&rp->r_hashq->r_lock);
14935 			break;
14936 		}
14937 
14938 		mutex_enter(&rp->r_statev4_lock);
14939 		/* the file can't still be mem mapped */
14940 		ASSERT(rp->r_mapcnt == 0);
14941 		if (rp->created_v4)
14942 			rp->created_v4 = 0;
14943 		mutex_exit(&rp->r_statev4_lock);
14944 
14945 		/*
14946 		 * Grab a ref on this open stream; nfs4close_one
14947 		 * will mark it as invalid
14948 		 */
14949 		mutex_enter(&osp->os_sync_lock);
14950 		osp->os_ref_count++;
14951 		osp->os_force_close = 1;
14952 		mutex_exit(&osp->os_sync_lock);
14953 		mutex_exit(&rp->r_os_lock);
14954 		rw_exit(&rp->r_hashq->r_lock);
14955 
14956 		nfs4close_one(vp, osp, cr, 0, NULL, &e, CLOSE_FORCE, 0, 0, 0);
14957 
14958 		/* Update error if it isn't already non-zero */
14959 		if (error == 0) {
14960 			if (e.error)
14961 				error = e.error;
14962 			else if (e.stat)
14963 				error = geterrno4(e.stat);
14964 		}
14965 
14966 #ifdef	DEBUG
14967 		nfs4close_all_cnt++;
14968 #endif
14969 		/* Release the ref on osp acquired above. */
14970 		open_stream_rele(osp, rp);
14971 
14972 		/* Proceed to the next open stream, if any */
14973 	}
14974 	return (error);
14975 }
14976 
14977 /*
14978  * nfs4close_one - close one open stream for a file if needed.
14979  *
14980  * "close_type" indicates which close path this is:
14981  * CLOSE_NORM: close initiated via VOP_CLOSE.
14982  * CLOSE_DELMAP: close initiated via VOP_DELMAP.
14983  * CLOSE_FORCE: close initiated via VOP_INACTIVE.  This path forces
14984  *	the close and release of client state for this open stream
14985  *	(unless someone else has the open stream open).
14986  * CLOSE_RESEND: indicates the request is a replay of an earlier request
14987  *	(e.g., due to abort because of a signal).
14988  * CLOSE_AFTER_RESEND: close initiated to "undo" a successful resent OPEN.
14989  *
14990  * CLOSE_RESEND and CLOSE_AFTER_RESEND will not attempt to retry after client
14991  * recovery.  Instead, the caller is expected to deal with retries.
14992  *
14993  * The caller can either pass in the osp ('provided_osp') or not.
14994  *
14995  * 'access_bits' represents the access we are closing/downgrading.
14996  *
14997  * 'len', 'prot', and 'mmap_flags' are used for CLOSE_DELMAP.  'len' is the
14998  * number of bytes we are unmapping, 'maxprot' is the mmap protection, and
14999  * 'mmap_flags' tells us the type of sharing (MAP_PRIVATE or MAP_SHARED).
15000  *
15001  * Errors are returned via the nfs4_error_t.
15002  */
15003 void
15004 nfs4close_one(vnode_t *vp, nfs4_open_stream_t *provided_osp, cred_t *cr,
15005     int access_bits, nfs4_lost_rqst_t *lrp, nfs4_error_t *ep,
15006     nfs4_close_type_t close_type, size_t len, uint_t maxprot,
15007     uint_t mmap_flags)
15008 {
15009 	nfs4_open_owner_t *oop;
15010 	nfs4_open_stream_t *osp = NULL;
15011 	int retry = 0;
15012 	int num_retries = NFS4_NUM_RECOV_RETRIES;
15013 	rnode4_t *rp;
15014 	mntinfo4_t *mi;
15015 	nfs4_recov_state_t recov_state;
15016 	cred_t *cred_otw = NULL;
15017 	bool_t recovonly = FALSE;
15018 	int isrecov;
15019 	int force_close;
15020 	int close_failed = 0;
15021 	int did_dec_count = 0;
15022 	int did_start_op = 0;
15023 	int did_force_recovlock = 0;
15024 	int did_start_seqid_sync = 0;
15025 	int have_sync_lock = 0;
15026 
15027 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
15028 
15029 	NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE, "closing vp %p osp %p, "
15030 	    "lrp %p, close type %d len %ld prot %x mmap flags %x bits %x",
15031 	    (void *)vp, (void *)provided_osp, (void *)lrp, close_type,
15032 	    len, maxprot, mmap_flags, access_bits));
15033 
15034 	nfs4_error_zinit(ep);
15035 	rp = VTOR4(vp);
15036 	mi = VTOMI4(vp);
15037 	isrecov = (close_type == CLOSE_RESEND ||
15038 	    close_type == CLOSE_AFTER_RESEND);
15039 
15040 	/*
15041 	 * First get the open owner.
15042 	 */
15043 	if (!provided_osp) {
15044 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
15045 	} else {
15046 		oop = provided_osp->os_open_owner;
15047 		ASSERT(oop != NULL);
15048 		open_owner_hold(oop);
15049 	}
15050 
15051 	if (!oop) {
15052 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15053 		    "nfs4close_one: no oop, rp %p, mi %p, cr %p, osp %p, "
15054 		    "close type %d", (void *)rp, (void *)mi, (void *)cr,
15055 		    (void *)provided_osp, close_type));
15056 		ep->error = EIO;
15057 		goto out;
15058 	}
15059 
15060 	cred_otw = nfs4_get_otw_cred(cr, mi, oop);
15061 recov_retry:
15062 	osp = NULL;
15063 	close_failed = 0;
15064 	force_close = (close_type == CLOSE_FORCE);
15065 	retry = 0;
15066 	did_start_op = 0;
15067 	did_force_recovlock = 0;
15068 	did_start_seqid_sync = 0;
15069 	have_sync_lock = 0;
15070 	recovonly = FALSE;
15071 	recov_state.rs_flags = 0;
15072 	recov_state.rs_num_retry_despite_err = 0;
15073 
15074 	/*
15075 	 * Second synchronize with recovery.
15076 	 */
15077 	if (!isrecov) {
15078 		ep->error = nfs4_start_fop(mi, vp, NULL, OH_CLOSE,
15079 		    &recov_state, &recovonly);
15080 		if (!ep->error) {
15081 			did_start_op = 1;
15082 		} else {
15083 			close_failed = 1;
15084 			/*
15085 			 * If we couldn't get start_fop, but have to
15086 			 * cleanup state, then at least acquire the
15087 			 * mi_recovlock so we can synchronize with
15088 			 * recovery.
15089 			 */
15090 			if (close_type == CLOSE_FORCE) {
15091 				(void) nfs_rw_enter_sig(&mi->mi_recovlock,
15092 				    RW_READER, FALSE);
15093 				did_force_recovlock = 1;
15094 			} else
15095 				goto out;
15096 		}
15097 	}
15098 
15099 	/*
15100 	 * We cannot attempt to get the open seqid sync if nfs4_start_fop
15101 	 * set 'recovonly' to TRUE since most likely this is due to
15102 	 * reovery being active (MI4_RECOV_ACTIV).  If recovery is active,
15103 	 * nfs4_start_open_seqid_sync() will fail with EAGAIN asking us
15104 	 * to retry, causing us to loop until recovery finishes.  Plus we
15105 	 * don't need protection over the open seqid since we're not going
15106 	 * OTW, hence don't need to use the seqid.
15107 	 */
15108 	if (recovonly == FALSE) {
15109 		/* need to grab the open owner sync before 'os_sync_lock' */
15110 		ep->error = nfs4_start_open_seqid_sync(oop, mi);
15111 		if (ep->error == EAGAIN) {
15112 			ASSERT(!isrecov);
15113 			if (did_start_op)
15114 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15115 				    &recov_state, TRUE);
15116 			if (did_force_recovlock)
15117 				nfs_rw_exit(&mi->mi_recovlock);
15118 			goto recov_retry;
15119 		}
15120 		did_start_seqid_sync = 1;
15121 	}
15122 
15123 	/*
15124 	 * Third get an open stream and acquire 'os_sync_lock' to
15125 	 * sychronize the opening/creating of an open stream with the
15126 	 * closing/destroying of an open stream.
15127 	 */
15128 	if (!provided_osp) {
15129 		/* returns with 'os_sync_lock' held */
15130 		osp = find_open_stream(oop, rp);
15131 		if (!osp) {
15132 			ep->error = EIO;
15133 			goto out;
15134 		}
15135 	} else {
15136 		osp = provided_osp;
15137 		open_stream_hold(osp);
15138 		mutex_enter(&osp->os_sync_lock);
15139 	}
15140 	have_sync_lock = 1;
15141 
15142 	ASSERT(oop == osp->os_open_owner);
15143 
15144 	/*
15145 	 * Fourth, do any special pre-OTW CLOSE processing
15146 	 * based on the specific close type.
15147 	 */
15148 	if ((close_type == CLOSE_NORM || close_type == CLOSE_AFTER_RESEND) &&
15149 	    !did_dec_count) {
15150 		ASSERT(osp->os_open_ref_count > 0);
15151 		osp->os_open_ref_count--;
15152 		did_dec_count = 1;
15153 		if (osp->os_open_ref_count == 0)
15154 			osp->os_final_close = 1;
15155 	}
15156 
15157 	if (close_type == CLOSE_FORCE) {
15158 		/* see if somebody reopened the open stream. */
15159 		if (!osp->os_force_close) {
15160 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
15161 			    "nfs4close_one: skip CLOSE_FORCE as osp %p "
15162 			    "was reopened, vp %p", (void *)osp, (void *)vp));
15163 			ep->error = 0;
15164 			ep->stat = NFS4_OK;
15165 			goto out;
15166 		}
15167 
15168 		if (!osp->os_final_close && !did_dec_count) {
15169 			osp->os_open_ref_count--;
15170 			did_dec_count = 1;
15171 		}
15172 
15173 		/*
15174 		 * We can't depend on os_open_ref_count being 0 due to the
15175 		 * way executables are opened (VN_RELE to match a VOP_OPEN).
15176 		 */
15177 #ifdef	NOTYET
15178 		ASSERT(osp->os_open_ref_count == 0);
15179 #endif
15180 		if (osp->os_open_ref_count != 0) {
15181 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
15182 			    "nfs4close_one: should panic here on an "
15183 			    "ASSERT(osp->os_open_ref_count == 0). Ignoring "
15184 			    "since this is probably the exec problem."));
15185 
15186 			osp->os_open_ref_count = 0;
15187 		}
15188 
15189 		/*
15190 		 * There is the possibility that nfs4close_one()
15191 		 * for close_type == CLOSE_DELMAP couldn't find the
15192 		 * open stream, thus couldn't decrement its os_mapcnt;
15193 		 * therefore we can't use this ASSERT yet.
15194 		 */
15195 #ifdef	NOTYET
15196 		ASSERT(osp->os_mapcnt == 0);
15197 #endif
15198 		osp->os_mapcnt = 0;
15199 	}
15200 
15201 	if (close_type == CLOSE_DELMAP && !did_dec_count) {
15202 		ASSERT(osp->os_mapcnt >= btopr(len));
15203 
15204 		if ((mmap_flags & MAP_SHARED) && (maxprot & PROT_WRITE))
15205 			osp->os_mmap_write -= btopr(len);
15206 		if (maxprot & PROT_READ)
15207 			osp->os_mmap_read -= btopr(len);
15208 		if (maxprot & PROT_EXEC)
15209 			osp->os_mmap_read -= btopr(len);
15210 		/* mirror the PROT_NONE check in nfs4_addmap() */
15211 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
15212 		    !(maxprot & PROT_EXEC))
15213 			osp->os_mmap_read -= btopr(len);
15214 		osp->os_mapcnt -= btopr(len);
15215 		did_dec_count = 1;
15216 	}
15217 
15218 	if (recovonly) {
15219 		nfs4_lost_rqst_t lost_rqst;
15220 
15221 		/* request should not already be in recovery queue */
15222 		ASSERT(lrp == NULL);
15223 		nfs4_error_init(ep, EINTR);
15224 		nfs4close_save_lost_rqst(ep->error, &lost_rqst, oop,
15225 		    osp, cred_otw, vp);
15226 		mutex_exit(&osp->os_sync_lock);
15227 		have_sync_lock = 0;
15228 		(void) nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15229 		    lost_rqst.lr_op == OP_CLOSE ?
15230 		    &lost_rqst : NULL, OP_CLOSE, NULL);
15231 		close_failed = 1;
15232 		force_close = 0;
15233 		goto close_cleanup;
15234 	}
15235 
15236 	/*
15237 	 * If a previous OTW call got NFS4ERR_BAD_SEQID, then
15238 	 * we stopped operating on the open owner's <old oo_name, old seqid>
15239 	 * space, which means we stopped operating on the open stream
15240 	 * too.  So don't go OTW (as the seqid is likely bad, and the
15241 	 * stateid could be stale, potentially triggering a false
15242 	 * setclientid), and just clean up the client's internal state.
15243 	 */
15244 	if (osp->os_orig_oo_name != oop->oo_name) {
15245 		NFS4_DEBUG(nfs4close_one_debug || nfs4_client_recov_debug,
15246 		    (CE_NOTE, "nfs4close_one: skip OTW close for osp %p "
15247 		    "oop %p due to bad seqid (orig oo_name %" PRIx64 " current "
15248 		    "oo_name %" PRIx64")",
15249 		    (void *)osp, (void *)oop, osp->os_orig_oo_name,
15250 		    oop->oo_name));
15251 		close_failed = 1;
15252 	}
15253 
15254 	/* If the file failed recovery, just quit. */
15255 	mutex_enter(&rp->r_statelock);
15256 	if (rp->r_flags & R4RECOVERR) {
15257 		close_failed = 1;
15258 	}
15259 	mutex_exit(&rp->r_statelock);
15260 
15261 	/*
15262 	 * If the force close path failed to obtain start_fop
15263 	 * then skip the OTW close and just remove the state.
15264 	 */
15265 	if (close_failed)
15266 		goto close_cleanup;
15267 
15268 	/*
15269 	 * Fifth, check to see if there are still mapped pages or other
15270 	 * opens using this open stream.  If there are then we can't
15271 	 * close yet but we can see if an OPEN_DOWNGRADE is necessary.
15272 	 */
15273 	if (osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
15274 		nfs4_lost_rqst_t	new_lost_rqst;
15275 		bool_t			needrecov = FALSE;
15276 		cred_t			*odg_cred_otw = NULL;
15277 		seqid4			open_dg_seqid = 0;
15278 
15279 		if (osp->os_delegation) {
15280 			/*
15281 			 * If this open stream was never OPENed OTW then we
15282 			 * surely can't DOWNGRADE it (especially since the
15283 			 * osp->open_stateid is really a delegation stateid
15284 			 * when os_delegation is 1).
15285 			 */
15286 			if (access_bits & FREAD)
15287 				osp->os_share_acc_read--;
15288 			if (access_bits & FWRITE)
15289 				osp->os_share_acc_write--;
15290 			osp->os_share_deny_none--;
15291 			nfs4_error_zinit(ep);
15292 			goto out;
15293 		}
15294 		nfs4_open_downgrade(access_bits, 0, oop, osp, vp, cr,
15295 		    lrp, ep, &odg_cred_otw, &open_dg_seqid);
15296 		needrecov = nfs4_needs_recovery(ep, TRUE, mi->mi_vfsp);
15297 		if (needrecov && !isrecov) {
15298 			bool_t abort;
15299 			nfs4_bseqid_entry_t *bsep = NULL;
15300 
15301 			if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID)
15302 				bsep = nfs4_create_bseqid_entry(oop, NULL,
15303 				    vp, 0,
15304 				    lrp ? TAG_OPEN_DG_LOST : TAG_OPEN_DG,
15305 				    open_dg_seqid);
15306 
15307 			nfs4open_dg_save_lost_rqst(ep->error, &new_lost_rqst,
15308 			    oop, osp, odg_cred_otw, vp, access_bits, 0);
15309 			mutex_exit(&osp->os_sync_lock);
15310 			have_sync_lock = 0;
15311 			abort = nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15312 			    new_lost_rqst.lr_op == OP_OPEN_DOWNGRADE ?
15313 			    &new_lost_rqst : NULL, OP_OPEN_DOWNGRADE,
15314 			    bsep);
15315 			if (odg_cred_otw)
15316 				crfree(odg_cred_otw);
15317 			if (bsep)
15318 				kmem_free(bsep, sizeof (*bsep));
15319 
15320 			if (abort == TRUE)
15321 				goto out;
15322 
15323 			if (did_start_seqid_sync) {
15324 				nfs4_end_open_seqid_sync(oop);
15325 				did_start_seqid_sync = 0;
15326 			}
15327 			open_stream_rele(osp, rp);
15328 
15329 			if (did_start_op)
15330 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15331 				    &recov_state, FALSE);
15332 			if (did_force_recovlock)
15333 				nfs_rw_exit(&mi->mi_recovlock);
15334 
15335 			goto recov_retry;
15336 		} else {
15337 			if (odg_cred_otw)
15338 				crfree(odg_cred_otw);
15339 		}
15340 		goto out;
15341 	}
15342 
15343 	/*
15344 	 * If this open stream was created as the results of an open
15345 	 * while holding a delegation, then just release it; no need
15346 	 * to do an OTW close.  Otherwise do a "normal" OTW close.
15347 	 */
15348 	if (osp->os_delegation) {
15349 		nfs4close_notw(vp, osp, &have_sync_lock);
15350 		nfs4_error_zinit(ep);
15351 		goto out;
15352 	}
15353 
15354 	/*
15355 	 * If this stream is not valid, we're done.
15356 	 */
15357 	if (!osp->os_valid) {
15358 		nfs4_error_zinit(ep);
15359 		goto out;
15360 	}
15361 
15362 	/*
15363 	 * Last open or mmap ref has vanished, need to do an OTW close.
15364 	 * First check to see if a close is still necessary.
15365 	 */
15366 	if (osp->os_failed_reopen) {
15367 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15368 		    "don't close OTW osp %p since reopen failed.",
15369 		    (void *)osp));
15370 		/*
15371 		 * Reopen of the open stream failed, hence the
15372 		 * stateid of the open stream is invalid/stale, and
15373 		 * sending this OTW would incorrectly cause another
15374 		 * round of recovery.  In this case, we need to set
15375 		 * the 'os_valid' bit to 0 so another thread doesn't
15376 		 * come in and re-open this open stream before
15377 		 * this "closing" thread cleans up state (decrementing
15378 		 * the nfs4_server_t's state_ref_count and decrementing
15379 		 * the os_ref_count).
15380 		 */
15381 		osp->os_valid = 0;
15382 		/*
15383 		 * This removes the reference obtained at OPEN; ie,
15384 		 * when the open stream structure was created.
15385 		 *
15386 		 * We don't have to worry about calling 'open_stream_rele'
15387 		 * since we our currently holding a reference to this
15388 		 * open stream which means the count can not go to 0 with
15389 		 * this decrement.
15390 		 */
15391 		ASSERT(osp->os_ref_count >= 2);
15392 		osp->os_ref_count--;
15393 		nfs4_error_zinit(ep);
15394 		close_failed = 0;
15395 		goto close_cleanup;
15396 	}
15397 
15398 	ASSERT(osp->os_ref_count > 1);
15399 
15400 	/*
15401 	 * Sixth, try the CLOSE OTW.
15402 	 */
15403 	nfs4close_otw(rp, cred_otw, oop, osp, &retry, &did_start_seqid_sync,
15404 	    close_type, ep, &have_sync_lock);
15405 
15406 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) {
15407 		/*
15408 		 * Let the recovery thread be responsible for
15409 		 * removing the state for CLOSE.
15410 		 */
15411 		close_failed = 1;
15412 		force_close = 0;
15413 		retry = 0;
15414 	}
15415 
15416 	/* See if we need to retry with a different cred */
15417 	if ((ep->error == EACCES ||
15418 	    (ep->error == 0 && ep->stat == NFS4ERR_ACCESS)) &&
15419 	    cred_otw != cr) {
15420 		crfree(cred_otw);
15421 		cred_otw = cr;
15422 		crhold(cred_otw);
15423 		retry = 1;
15424 	}
15425 
15426 	if (ep->error || ep->stat)
15427 		close_failed = 1;
15428 
15429 	if (retry && !isrecov && num_retries-- > 0) {
15430 		if (have_sync_lock) {
15431 			mutex_exit(&osp->os_sync_lock);
15432 			have_sync_lock = 0;
15433 		}
15434 		if (did_start_seqid_sync) {
15435 			nfs4_end_open_seqid_sync(oop);
15436 			did_start_seqid_sync = 0;
15437 		}
15438 		open_stream_rele(osp, rp);
15439 
15440 		if (did_start_op)
15441 			nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15442 			    &recov_state, FALSE);
15443 		if (did_force_recovlock)
15444 			nfs_rw_exit(&mi->mi_recovlock);
15445 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15446 		    "nfs4close_one: need to retry the close "
15447 		    "operation"));
15448 		goto recov_retry;
15449 	}
15450 close_cleanup:
15451 	/*
15452 	 * Seventh and lastly, process our results.
15453 	 */
15454 	if (close_failed && force_close) {
15455 		/*
15456 		 * It's ok to drop and regrab the 'os_sync_lock' since
15457 		 * nfs4close_notw() will recheck to make sure the
15458 		 * "close"/removal of state should happen.
15459 		 */
15460 		if (!have_sync_lock) {
15461 			mutex_enter(&osp->os_sync_lock);
15462 			have_sync_lock = 1;
15463 		}
15464 		/*
15465 		 * This is last call, remove the ref on the open
15466 		 * stream created by open and clean everything up.
15467 		 */
15468 		osp->os_pending_close = 0;
15469 		nfs4close_notw(vp, osp, &have_sync_lock);
15470 		nfs4_error_zinit(ep);
15471 	}
15472 
15473 	if (!close_failed) {
15474 		if (have_sync_lock) {
15475 			osp->os_pending_close = 0;
15476 			mutex_exit(&osp->os_sync_lock);
15477 			have_sync_lock = 0;
15478 		} else {
15479 			mutex_enter(&osp->os_sync_lock);
15480 			osp->os_pending_close = 0;
15481 			mutex_exit(&osp->os_sync_lock);
15482 		}
15483 		if (did_start_op && recov_state.rs_sp != NULL) {
15484 			mutex_enter(&recov_state.rs_sp->s_lock);
15485 			nfs4_dec_state_ref_count_nolock(recov_state.rs_sp, mi);
15486 			mutex_exit(&recov_state.rs_sp->s_lock);
15487 		} else {
15488 			nfs4_dec_state_ref_count(mi);
15489 		}
15490 		nfs4_error_zinit(ep);
15491 	}
15492 
15493 out:
15494 	if (have_sync_lock)
15495 		mutex_exit(&osp->os_sync_lock);
15496 	if (did_start_op)
15497 		nfs4_end_fop(mi, vp, NULL, OH_CLOSE, &recov_state,
15498 		    recovonly ? TRUE : FALSE);
15499 	if (did_force_recovlock)
15500 		nfs_rw_exit(&mi->mi_recovlock);
15501 	if (cred_otw)
15502 		crfree(cred_otw);
15503 	if (osp)
15504 		open_stream_rele(osp, rp);
15505 	if (oop) {
15506 		if (did_start_seqid_sync)
15507 			nfs4_end_open_seqid_sync(oop);
15508 		open_owner_rele(oop);
15509 	}
15510 }
15511 
15512 /*
15513  * Convert information returned by the server in the LOCK4denied
15514  * structure to the form required by fcntl.
15515  */
15516 static void
15517 denied_to_flk(LOCK4denied *lockt_denied, flock64_t *flk, LOCKT4args *lockt_args)
15518 {
15519 	nfs4_lo_name_t *lo;
15520 
15521 #ifdef	DEBUG
15522 	if (denied_to_flk_debug) {
15523 		lockt_denied_debug = lockt_denied;
15524 		debug_enter("lockt_denied");
15525 	}
15526 #endif
15527 
15528 	flk->l_type = lockt_denied->locktype == READ_LT ? F_RDLCK : F_WRLCK;
15529 	flk->l_whence = 0;	/* aka SEEK_SET */
15530 	flk->l_start = lockt_denied->offset;
15531 	flk->l_len = lockt_denied->length;
15532 
15533 	/*
15534 	 * If the blocking clientid matches our client id, then we can
15535 	 * interpret the lockowner (since we built it).  If not, then
15536 	 * fabricate a sysid and pid.  Note that the l_sysid field
15537 	 * in *flk already has the local sysid.
15538 	 */
15539 
15540 	if (lockt_denied->owner.clientid == lockt_args->owner.clientid) {
15541 
15542 		if (lockt_denied->owner.owner_len == sizeof (*lo)) {
15543 			lo = (nfs4_lo_name_t *)
15544 			    lockt_denied->owner.owner_val;
15545 
15546 			flk->l_pid = lo->ln_pid;
15547 		} else {
15548 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15549 			    "denied_to_flk: bad lock owner length\n"));
15550 
15551 			flk->l_pid = lo_to_pid(&lockt_denied->owner);
15552 		}
15553 	} else {
15554 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15555 		"denied_to_flk: foreign clientid\n"));
15556 
15557 		/*
15558 		 * Construct a new sysid which should be different from
15559 		 * sysids of other systems.
15560 		 */
15561 
15562 		flk->l_sysid++;
15563 		flk->l_pid = lo_to_pid(&lockt_denied->owner);
15564 	}
15565 }
15566 
15567 static pid_t
15568 lo_to_pid(lock_owner4 *lop)
15569 {
15570 	pid_t pid = 0;
15571 	uchar_t *cp;
15572 	int i;
15573 
15574 	cp = (uchar_t *)&lop->clientid;
15575 
15576 	for (i = 0; i < sizeof (lop->clientid); i++)
15577 		pid += (pid_t)*cp++;
15578 
15579 	cp = (uchar_t *)lop->owner_val;
15580 
15581 	for (i = 0; i < lop->owner_len; i++)
15582 		pid += (pid_t)*cp++;
15583 
15584 	return (pid);
15585 }
15586 
15587 /*
15588  * Given a lock pointer, returns the length of that lock.
15589  * "end" is the last locked offset the "l_len" covers from
15590  * the start of the lock.
15591  */
15592 static off64_t
15593 lock_to_end(flock64_t *lock)
15594 {
15595 	off64_t lock_end;
15596 
15597 	if (lock->l_len == 0)
15598 		lock_end = (off64_t)MAXEND;
15599 	else
15600 		lock_end = lock->l_start + lock->l_len - 1;
15601 
15602 	return (lock_end);
15603 }
15604 
15605 /*
15606  * Given the end of a lock, it will return you the length "l_len" for that lock.
15607  */
15608 static off64_t
15609 end_to_len(off64_t start, off64_t end)
15610 {
15611 	off64_t lock_len;
15612 
15613 	ASSERT(end >= start);
15614 	if (end == MAXEND)
15615 		lock_len = 0;
15616 	else
15617 		lock_len = end - start + 1;
15618 
15619 	return (lock_len);
15620 }
15621 
15622 /*
15623  * On given end for a lock it determines if it is the last locked offset
15624  * or not, if so keeps it as is, else adds one to return the length for
15625  * valid start.
15626  */
15627 static off64_t
15628 start_check(off64_t x)
15629 {
15630 	if (x == MAXEND)
15631 		return (x);
15632 	else
15633 		return (x + 1);
15634 }
15635 
15636 /*
15637  * See if these two locks overlap, and if so return 1;
15638  * otherwise, return 0.
15639  */
15640 static int
15641 locks_intersect(flock64_t *llfp, flock64_t *curfp)
15642 {
15643 	off64_t llfp_end, curfp_end;
15644 
15645 	llfp_end = lock_to_end(llfp);
15646 	curfp_end = lock_to_end(curfp);
15647 
15648 	if (((llfp_end >= curfp->l_start) &&
15649 	    (llfp->l_start <= curfp->l_start)) ||
15650 	    ((curfp->l_start <= llfp->l_start) && (curfp_end >= llfp->l_start)))
15651 		return (1);
15652 	return (0);
15653 }
15654 
15655 /*
15656  * Determine what the intersecting lock region is, and add that to the
15657  * 'nl_llpp' locklist in increasing order (by l_start).
15658  */
15659 static void
15660 nfs4_add_lock_range(flock64_t *lost_flp, flock64_t *local_flp,
15661     locklist_t **nl_llpp, vnode_t *vp)
15662 {
15663 	locklist_t *intersect_llp, *tmp_fllp, *cur_fllp;
15664 	off64_t lost_flp_end, local_flp_end, len, start;
15665 
15666 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range:"));
15667 
15668 	if (!locks_intersect(lost_flp, local_flp))
15669 		return;
15670 
15671 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15672 	    "locks intersect"));
15673 
15674 	lost_flp_end = lock_to_end(lost_flp);
15675 	local_flp_end = lock_to_end(local_flp);
15676 
15677 	/* Find the starting point of the intersecting region */
15678 	if (local_flp->l_start > lost_flp->l_start)
15679 		start = local_flp->l_start;
15680 	else
15681 		start = lost_flp->l_start;
15682 
15683 	/* Find the lenght of the intersecting region */
15684 	if (lost_flp_end < local_flp_end)
15685 		len = end_to_len(start, lost_flp_end);
15686 	else
15687 		len = end_to_len(start, local_flp_end);
15688 
15689 	/*
15690 	 * Prepare the flock structure for the intersection found and insert
15691 	 * it into the new list in increasing l_start order. This list contains
15692 	 * intersections of locks registered by the client with the local host
15693 	 * and the lost lock.
15694 	 * The lock type of this lock is the same as that of the local_flp.
15695 	 */
15696 	intersect_llp = (locklist_t *)kmem_alloc(sizeof (locklist_t), KM_SLEEP);
15697 	intersect_llp->ll_flock.l_start = start;
15698 	intersect_llp->ll_flock.l_len = len;
15699 	intersect_llp->ll_flock.l_type = local_flp->l_type;
15700 	intersect_llp->ll_flock.l_pid = local_flp->l_pid;
15701 	intersect_llp->ll_flock.l_sysid = local_flp->l_sysid;
15702 	intersect_llp->ll_flock.l_whence = 0;	/* aka SEEK_SET */
15703 	intersect_llp->ll_vp = vp;
15704 
15705 	tmp_fllp = *nl_llpp;
15706 	cur_fllp = NULL;
15707 	while (tmp_fllp != NULL && tmp_fllp->ll_flock.l_start <
15708 	    intersect_llp->ll_flock.l_start) {
15709 			cur_fllp = tmp_fllp;
15710 			tmp_fllp = tmp_fllp->ll_next;
15711 	}
15712 	if (cur_fllp == NULL) {
15713 		/* first on the list */
15714 		intersect_llp->ll_next = *nl_llpp;
15715 		*nl_llpp = intersect_llp;
15716 	} else {
15717 		intersect_llp->ll_next = cur_fllp->ll_next;
15718 		cur_fllp->ll_next = intersect_llp;
15719 	}
15720 
15721 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15722 	    "created lock region: start %"PRIx64" end %"PRIx64" : %s\n",
15723 	    intersect_llp->ll_flock.l_start,
15724 	    intersect_llp->ll_flock.l_start + intersect_llp->ll_flock.l_len,
15725 	    intersect_llp->ll_flock.l_type == F_RDLCK ? "READ" : "WRITE"));
15726 }
15727 
15728 /*
15729  * Our local locking current state is potentially different than
15730  * what the NFSv4 server thinks we have due to a lost lock that was
15731  * resent and then received.  We need to reset our "NFSv4" locking
15732  * state to match the current local locking state for this pid since
15733  * that is what the user/application sees as what the world is.
15734  *
15735  * We cannot afford to drop the open/lock seqid sync since then we can
15736  * get confused about what the current local locking state "is" versus
15737  * "was".
15738  *
15739  * If we are unable to fix up the locks, we send SIGLOST to the affected
15740  * process.  This is not done if the filesystem has been forcibly
15741  * unmounted, in case the process has already exited and a new process
15742  * exists with the same pid.
15743  */
15744 static void
15745 nfs4_reinstitute_local_lock_state(vnode_t *vp, flock64_t *lost_flp, cred_t *cr,
15746     nfs4_lock_owner_t *lop)
15747 {
15748 	locklist_t *locks, *llp, *ri_llp, *tmp_llp;
15749 	mntinfo4_t *mi = VTOMI4(vp);
15750 	const int cmd = F_SETLK;
15751 	off64_t cur_start, llp_ll_flock_end, lost_flp_end;
15752 	flock64_t ul_fl;
15753 
15754 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15755 	    "nfs4_reinstitute_local_lock_state"));
15756 
15757 	/*
15758 	 * Find active locks for this vp from the local locking code.
15759 	 * Scan through this list and find out the locks that intersect with
15760 	 * the lost lock. Once we find the lock that intersects, add the
15761 	 * intersection area as a new lock to a new list "ri_llp". The lock
15762 	 * type of the intersection region lock added to ri_llp is the same
15763 	 * as that found in the active lock list, "list". The intersecting
15764 	 * region locks are added to ri_llp in increasing l_start order.
15765 	 */
15766 	ASSERT(nfs_zone() == mi->mi_zone);
15767 
15768 	locks = flk_active_locks_for_vp(vp);
15769 	ri_llp = NULL;
15770 
15771 	for (llp = locks; llp != NULL; llp = llp->ll_next) {
15772 		ASSERT(llp->ll_vp == vp);
15773 		/*
15774 		 * Pick locks that belong to this pid/lockowner
15775 		 */
15776 		if (llp->ll_flock.l_pid != lost_flp->l_pid)
15777 			continue;
15778 
15779 		nfs4_add_lock_range(lost_flp, &llp->ll_flock, &ri_llp, vp);
15780 	}
15781 
15782 	/*
15783 	 * Now we have the list of intersections with the lost lock. These are
15784 	 * the locks that were/are active before the server replied to the
15785 	 * last/lost lock. Issue these locks to the server here. Playing these
15786 	 * locks to the server will re-establish aur current local locking state
15787 	 * with the v4 server.
15788 	 * If we get an error, send SIGLOST to the application for that lock.
15789 	 */
15790 
15791 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15792 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15793 		    "nfs4_reinstitute_local_lock_state: need to issue "
15794 		    "flock: [%"PRIx64" - %"PRIx64"] : %s",
15795 		    llp->ll_flock.l_start,
15796 		    llp->ll_flock.l_start + llp->ll_flock.l_len,
15797 		    llp->ll_flock.l_type == F_RDLCK ? "READ" :
15798 		    llp->ll_flock.l_type == F_WRLCK ? "WRITE" : "INVALID"));
15799 		/*
15800 		 * No need to relock what we already have
15801 		 */
15802 		if (llp->ll_flock.l_type == lost_flp->l_type)
15803 			continue;
15804 
15805 		push_reinstate(vp, cmd, &llp->ll_flock, cr, lop);
15806 	}
15807 
15808 	/*
15809 	 * Now keeping the start of the lost lock as our reference parse the
15810 	 * newly created ri_llp locklist to find the ranges that we have locked
15811 	 * with the v4 server but not in the current local locking. We need
15812 	 * to unlock these ranges.
15813 	 * These ranges can also be reffered to as those ranges, where the lost
15814 	 * lock does not overlap with the locks in the ri_llp but are locked
15815 	 * since the server replied to the lost lock.
15816 	 */
15817 	cur_start = lost_flp->l_start;
15818 	lost_flp_end = lock_to_end(lost_flp);
15819 
15820 	ul_fl.l_type = F_UNLCK;
15821 	ul_fl.l_whence = 0;	/* aka SEEK_SET */
15822 	ul_fl.l_sysid = lost_flp->l_sysid;
15823 	ul_fl.l_pid = lost_flp->l_pid;
15824 
15825 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15826 		llp_ll_flock_end = lock_to_end(&llp->ll_flock);
15827 
15828 		if (llp->ll_flock.l_start <= cur_start) {
15829 			cur_start = start_check(llp_ll_flock_end);
15830 			continue;
15831 		}
15832 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15833 		    "nfs4_reinstitute_local_lock_state: "
15834 		    "UNLOCK [%"PRIx64" - %"PRIx64"]",
15835 		    cur_start, llp->ll_flock.l_start));
15836 
15837 		ul_fl.l_start = cur_start;
15838 		ul_fl.l_len = end_to_len(cur_start,
15839 		    (llp->ll_flock.l_start - 1));
15840 
15841 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
15842 		cur_start = start_check(llp_ll_flock_end);
15843 	}
15844 
15845 	/*
15846 	 * In the case where the lost lock ends after all intersecting locks,
15847 	 * unlock the last part of the lost lock range.
15848 	 */
15849 	if (cur_start != start_check(lost_flp_end)) {
15850 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15851 		    "nfs4_reinstitute_local_lock_state: UNLOCK end of the "
15852 		    "lost lock region [%"PRIx64" - %"PRIx64"]",
15853 		    cur_start, lost_flp->l_start + lost_flp->l_len));
15854 
15855 		ul_fl.l_start = cur_start;
15856 		/*
15857 		 * Is it an to-EOF lock? if so unlock till the end
15858 		 */
15859 		if (lost_flp->l_len == 0)
15860 			ul_fl.l_len = 0;
15861 		else
15862 			ul_fl.l_len = start_check(lost_flp_end) - cur_start;
15863 
15864 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
15865 	}
15866 
15867 	if (locks != NULL)
15868 		flk_free_locklist(locks);
15869 
15870 	/* Free up our newly created locklist */
15871 	for (llp = ri_llp; llp != NULL; ) {
15872 		tmp_llp = llp->ll_next;
15873 		kmem_free(llp, sizeof (locklist_t));
15874 		llp = tmp_llp;
15875 	}
15876 
15877 	/*
15878 	 * Now return back to the original calling nfs4frlock()
15879 	 * and let us naturally drop our seqid syncs.
15880 	 */
15881 }
15882 
15883 /*
15884  * Create a lost state record for the given lock reinstantiation request
15885  * and push it onto the lost state queue.
15886  */
15887 static void
15888 push_reinstate(vnode_t *vp, int cmd, flock64_t *flk, cred_t *cr,
15889     nfs4_lock_owner_t *lop)
15890 {
15891 	nfs4_lost_rqst_t req;
15892 	nfs_lock_type4 locktype;
15893 	nfs4_error_t e = { EINTR, NFS4_OK, RPC_SUCCESS };
15894 
15895 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
15896 
15897 	locktype = flk_to_locktype(cmd, flk->l_type);
15898 	nfs4frlock_save_lost_rqst(NFS4_LCK_CTYPE_REINSTATE, EINTR, locktype,
15899 	    NULL, NULL, lop, flk, &req, cr, vp);
15900 	(void) nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
15901 	    (req.lr_op == OP_LOCK || req.lr_op == OP_LOCKU) ?
15902 	    &req : NULL, flk->l_type == F_UNLCK ? OP_LOCKU : OP_LOCK,
15903 	    NULL);
15904 }
15905