xref: /titanic_44/usr/src/uts/common/fs/nfs/nfs4_vnops.c (revision fe4018029bc4e914ec2678e3ca6ddb543d6dd959)
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 /*
23  * Copyright 2015 Nexenta Systems, Inc.  All rights reserved.
24  */
25 
26 /*
27  * Copyright 2010 Sun Microsystems, Inc.  All rights reserved.
28  * Use is subject to license terms.
29  */
30 
31 /*
32  *	Copyright 1983,1984,1985,1986,1987,1988,1989 AT&T.
33  *	All Rights Reserved
34  */
35 
36 /*
37  * Copyright (c) 2013, Joyent, Inc. All rights reserved.
38  */
39 
40 /*
41  * Copyright (c) 2014, STRATO AG. All rights reserved.
42  */
43 
44 #include <sys/param.h>
45 #include <sys/types.h>
46 #include <sys/systm.h>
47 #include <sys/cred.h>
48 #include <sys/time.h>
49 #include <sys/vnode.h>
50 #include <sys/vfs.h>
51 #include <sys/vfs_opreg.h>
52 #include <sys/file.h>
53 #include <sys/filio.h>
54 #include <sys/uio.h>
55 #include <sys/buf.h>
56 #include <sys/mman.h>
57 #include <sys/pathname.h>
58 #include <sys/dirent.h>
59 #include <sys/debug.h>
60 #include <sys/vmsystm.h>
61 #include <sys/fcntl.h>
62 #include <sys/flock.h>
63 #include <sys/swap.h>
64 #include <sys/errno.h>
65 #include <sys/strsubr.h>
66 #include <sys/sysmacros.h>
67 #include <sys/kmem.h>
68 #include <sys/cmn_err.h>
69 #include <sys/pathconf.h>
70 #include <sys/utsname.h>
71 #include <sys/dnlc.h>
72 #include <sys/acl.h>
73 #include <sys/systeminfo.h>
74 #include <sys/policy.h>
75 #include <sys/sdt.h>
76 #include <sys/list.h>
77 #include <sys/stat.h>
78 #include <sys/zone.h>
79 
80 #include <rpc/types.h>
81 #include <rpc/auth.h>
82 #include <rpc/clnt.h>
83 
84 #include <nfs/nfs.h>
85 #include <nfs/nfs_clnt.h>
86 #include <nfs/nfs_acl.h>
87 #include <nfs/lm.h>
88 #include <nfs/nfs4.h>
89 #include <nfs/nfs4_kprot.h>
90 #include <nfs/rnode4.h>
91 #include <nfs/nfs4_clnt.h>
92 
93 #include <vm/hat.h>
94 #include <vm/as.h>
95 #include <vm/page.h>
96 #include <vm/pvn.h>
97 #include <vm/seg.h>
98 #include <vm/seg_map.h>
99 #include <vm/seg_kpm.h>
100 #include <vm/seg_vn.h>
101 
102 #include <fs/fs_subr.h>
103 
104 #include <sys/ddi.h>
105 #include <sys/int_fmtio.h>
106 #include <sys/fs/autofs.h>
107 
108 typedef struct {
109 	nfs4_ga_res_t	*di_garp;
110 	cred_t		*di_cred;
111 	hrtime_t	di_time_call;
112 } dirattr_info_t;
113 
114 typedef enum nfs4_acl_op {
115 	NFS4_ACL_GET,
116 	NFS4_ACL_SET
117 } nfs4_acl_op_t;
118 
119 static struct lm_sysid *nfs4_find_sysid(mntinfo4_t *mi);
120 static int nfs4frlock_get_sysid(struct lm_sysid **, vnode_t *, flock64_t *);
121 
122 static void	nfs4_update_dircaches(change_info4 *, vnode_t *, vnode_t *,
123 			char *, dirattr_info_t *);
124 
125 static void	nfs4close_otw(rnode4_t *, cred_t *, nfs4_open_owner_t *,
126 		    nfs4_open_stream_t *, int *, int *, nfs4_close_type_t,
127 		    nfs4_error_t *, int *);
128 static int	nfs4_rdwrlbn(vnode_t *, page_t *, u_offset_t, size_t, int,
129 			cred_t *);
130 static int	nfs4write(vnode_t *, caddr_t, u_offset_t, int, cred_t *,
131 			stable_how4 *);
132 static int	nfs4read(vnode_t *, caddr_t, offset_t, int, size_t *,
133 			cred_t *, bool_t, struct uio *);
134 static int	nfs4setattr(vnode_t *, struct vattr *, int, cred_t *,
135 			vsecattr_t *);
136 static int	nfs4openattr(vnode_t *, vnode_t **, int, cred_t *);
137 static int	nfs4lookup(vnode_t *, char *, vnode_t **, cred_t *, int);
138 static int	nfs4lookup_xattr(vnode_t *, char *, vnode_t **, int, cred_t *);
139 static int	nfs4lookupvalidate_otw(vnode_t *, char *, vnode_t **, cred_t *);
140 static int	nfs4lookupnew_otw(vnode_t *, char *, vnode_t **, cred_t *);
141 static int	nfs4mknod(vnode_t *, char *, struct vattr *, enum vcexcl,
142 			int, vnode_t **, cred_t *);
143 static int	nfs4open_otw(vnode_t *, char *, struct vattr *, vnode_t **,
144 			cred_t *, int, int, enum createmode4, int);
145 static int	nfs4rename(vnode_t *, char *, vnode_t *, char *, cred_t *,
146 			caller_context_t *);
147 static int	nfs4rename_persistent_fh(vnode_t *, char *, vnode_t *,
148 			vnode_t *, char *, cred_t *, nfsstat4 *);
149 static int	nfs4rename_volatile_fh(vnode_t *, char *, vnode_t *,
150 			vnode_t *, char *, cred_t *, nfsstat4 *);
151 static int	do_nfs4readdir(vnode_t *, rddir4_cache *, cred_t *);
152 static void	nfs4readdir(vnode_t *, rddir4_cache *, cred_t *);
153 static int	nfs4_bio(struct buf *, stable_how4 *, cred_t *, bool_t);
154 static int	nfs4_getapage(vnode_t *, u_offset_t, size_t, uint_t *,
155 			page_t *[], size_t, struct seg *, caddr_t,
156 			enum seg_rw, cred_t *);
157 static void	nfs4_readahead(vnode_t *, u_offset_t, caddr_t, struct seg *,
158 			cred_t *);
159 static int	nfs4_sync_putapage(vnode_t *, page_t *, u_offset_t, size_t,
160 			int, cred_t *);
161 static int	nfs4_sync_pageio(vnode_t *, page_t *, u_offset_t, size_t,
162 			int, cred_t *);
163 static int	nfs4_commit(vnode_t *, offset4, count4, cred_t *);
164 static void	nfs4_set_mod(vnode_t *);
165 static void	nfs4_get_commit(vnode_t *);
166 static void	nfs4_get_commit_range(vnode_t *, u_offset_t, size_t);
167 static int	nfs4_putpage_commit(vnode_t *, offset_t, size_t, cred_t *);
168 static int	nfs4_commit_vp(vnode_t *, u_offset_t, size_t, cred_t *, int);
169 static int	nfs4_sync_commit(vnode_t *, page_t *, offset3, count3,
170 			cred_t *);
171 static void	do_nfs4_async_commit(vnode_t *, page_t *, offset3, count3,
172 			cred_t *);
173 static int	nfs4_update_attrcache(nfsstat4, nfs4_ga_res_t *,
174 			hrtime_t, vnode_t *, cred_t *);
175 static int	nfs4_open_non_reg_file(vnode_t **, int, cred_t *);
176 static int	nfs4_safelock(vnode_t *, const struct flock64 *, cred_t *);
177 static int	nfs4_lockrelease(vnode_t *, int, offset_t, cred_t *);
178 static int	nfs4_block_and_wait(clock_t *);
179 static cred_t  *state_to_cred(nfs4_open_stream_t *);
180 static void	denied_to_flk(LOCK4denied *, flock64_t *, LOCKT4args *);
181 static pid_t	lo_to_pid(lock_owner4 *);
182 static void	nfs4_reinstitute_local_lock_state(vnode_t *, flock64_t *,
183 			cred_t *, nfs4_lock_owner_t *);
184 static void	push_reinstate(vnode_t *, int, flock64_t *, cred_t *,
185 			nfs4_lock_owner_t *);
186 static int	open_and_get_osp(vnode_t *, cred_t *, nfs4_open_stream_t **);
187 static void	nfs4_delmap_callback(struct as *, void *, uint_t);
188 static void	nfs4_free_delmapcall(nfs4_delmapcall_t *);
189 static nfs4_delmapcall_t	*nfs4_init_delmapcall();
190 static int	nfs4_find_and_delete_delmapcall(rnode4_t *, int *);
191 static int	nfs4_is_acl_mask_valid(uint_t, nfs4_acl_op_t);
192 static int	nfs4_create_getsecattr_return(vsecattr_t *, vsecattr_t *,
193 			uid_t, gid_t, int);
194 
195 /*
196  * Routines that implement the setting of v4 args for the misc. ops
197  */
198 static void	nfs4args_lock_free(nfs_argop4 *);
199 static void	nfs4args_lockt_free(nfs_argop4 *);
200 static void	nfs4args_setattr(nfs_argop4 *, vattr_t *, vsecattr_t *,
201 			int, rnode4_t *, cred_t *, bitmap4, int *,
202 			nfs4_stateid_types_t *);
203 static void	nfs4args_setattr_free(nfs_argop4 *);
204 static int	nfs4args_verify(nfs_argop4 *, vattr_t *, enum nfs_opnum4,
205 			bitmap4);
206 static void	nfs4args_verify_free(nfs_argop4 *);
207 static void	nfs4args_write(nfs_argop4 *, stable_how4, rnode4_t *, cred_t *,
208 			WRITE4args **, nfs4_stateid_types_t *);
209 
210 /*
211  * These are the vnode ops functions that implement the vnode interface to
212  * the networked file system.  See more comments below at nfs4_vnodeops.
213  */
214 static int	nfs4_open(vnode_t **, int, cred_t *, caller_context_t *);
215 static int	nfs4_close(vnode_t *, int, int, offset_t, cred_t *,
216 			caller_context_t *);
217 static int	nfs4_read(vnode_t *, struct uio *, int, cred_t *,
218 			caller_context_t *);
219 static int	nfs4_write(vnode_t *, struct uio *, int, cred_t *,
220 			caller_context_t *);
221 static int	nfs4_ioctl(vnode_t *, int, intptr_t, int, cred_t *, int *,
222 			caller_context_t *);
223 static int	nfs4_setattr(vnode_t *, struct vattr *, int, cred_t *,
224 			caller_context_t *);
225 static int	nfs4_access(vnode_t *, int, int, cred_t *, caller_context_t *);
226 static int	nfs4_readlink(vnode_t *, struct uio *, cred_t *,
227 			caller_context_t *);
228 static int	nfs4_fsync(vnode_t *, int, cred_t *, caller_context_t *);
229 static int	nfs4_create(vnode_t *, char *, struct vattr *, enum vcexcl,
230 			int, vnode_t **, cred_t *, int, caller_context_t *,
231 			vsecattr_t *);
232 static int	nfs4_remove(vnode_t *, char *, cred_t *, caller_context_t *,
233 			int);
234 static int	nfs4_link(vnode_t *, vnode_t *, char *, cred_t *,
235 			caller_context_t *, int);
236 static int	nfs4_rename(vnode_t *, char *, vnode_t *, char *, cred_t *,
237 			caller_context_t *, int);
238 static int	nfs4_mkdir(vnode_t *, char *, struct vattr *, vnode_t **,
239 			cred_t *, caller_context_t *, int, vsecattr_t *);
240 static int	nfs4_rmdir(vnode_t *, char *, vnode_t *, cred_t *,
241 			caller_context_t *, int);
242 static int	nfs4_symlink(vnode_t *, char *, struct vattr *, char *,
243 			cred_t *, caller_context_t *, int);
244 static int	nfs4_readdir(vnode_t *, struct uio *, cred_t *, int *,
245 			caller_context_t *, int);
246 static int	nfs4_seek(vnode_t *, offset_t, offset_t *, caller_context_t *);
247 static int	nfs4_getpage(vnode_t *, offset_t, size_t, uint_t *,
248 			page_t *[], size_t, struct seg *, caddr_t,
249 			enum seg_rw, cred_t *, caller_context_t *);
250 static int	nfs4_putpage(vnode_t *, offset_t, size_t, int, cred_t *,
251 			caller_context_t *);
252 static int	nfs4_map(vnode_t *, offset_t, struct as *, caddr_t *, size_t,
253 			uchar_t, uchar_t, uint_t, cred_t *, caller_context_t *);
254 static int	nfs4_addmap(vnode_t *, offset_t, struct as *, caddr_t, size_t,
255 			uchar_t, uchar_t, uint_t, cred_t *, caller_context_t *);
256 static int	nfs4_cmp(vnode_t *, vnode_t *, caller_context_t *);
257 static int	nfs4_frlock(vnode_t *, int, struct flock64 *, int, offset_t,
258 			struct flk_callback *, cred_t *, caller_context_t *);
259 static int	nfs4_space(vnode_t *, int, struct flock64 *, int, offset_t,
260 			cred_t *, caller_context_t *);
261 static int	nfs4_delmap(vnode_t *, offset_t, struct as *, caddr_t, size_t,
262 			uint_t, uint_t, uint_t, cred_t *, caller_context_t *);
263 static int	nfs4_pageio(vnode_t *, page_t *, u_offset_t, size_t, int,
264 			cred_t *, caller_context_t *);
265 static void	nfs4_dispose(vnode_t *, page_t *, int, int, cred_t *,
266 			caller_context_t *);
267 static int	nfs4_setsecattr(vnode_t *, vsecattr_t *, int, cred_t *,
268 			caller_context_t *);
269 /*
270  * These vnode ops are required to be called from outside this source file,
271  * e.g. by ephemeral mount stub vnode ops, and so may not be declared
272  * as static.
273  */
274 int	nfs4_getattr(vnode_t *, struct vattr *, int, cred_t *,
275 	    caller_context_t *);
276 void	nfs4_inactive(vnode_t *, cred_t *, caller_context_t *);
277 int	nfs4_lookup(vnode_t *, char *, vnode_t **,
278 	    struct pathname *, int, vnode_t *, cred_t *,
279 	    caller_context_t *, int *, pathname_t *);
280 int	nfs4_fid(vnode_t *, fid_t *, caller_context_t *);
281 int	nfs4_rwlock(vnode_t *, int, caller_context_t *);
282 void	nfs4_rwunlock(vnode_t *, int, caller_context_t *);
283 int	nfs4_realvp(vnode_t *, vnode_t **, caller_context_t *);
284 int	nfs4_pathconf(vnode_t *, int, ulong_t *, cred_t *,
285 	    caller_context_t *);
286 int	nfs4_getsecattr(vnode_t *, vsecattr_t *, int, cred_t *,
287 	    caller_context_t *);
288 int	nfs4_shrlock(vnode_t *, int, struct shrlock *, int, cred_t *,
289 	    caller_context_t *);
290 
291 /*
292  * Used for nfs4_commit_vp() to indicate if we should
293  * wait on pending writes.
294  */
295 #define	NFS4_WRITE_NOWAIT	0
296 #define	NFS4_WRITE_WAIT		1
297 
298 /*
299  * Error flags used to pass information about certain special errors
300  * which need to be handled specially.
301  */
302 #define	NFS_EOF			-98
303 #define	NFS_VERF_MISMATCH	-97
304 
305 /*
306  * Flags used to differentiate between which operation drove the
307  * potential CLOSE OTW. (see nfs4_close_otw_if_necessary)
308  */
309 #define	NFS4_CLOSE_OP		0x1
310 #define	NFS4_DELMAP_OP		0x2
311 #define	NFS4_INACTIVE_OP	0x3
312 
313 #define	ISVDEV(t) ((t == VBLK) || (t == VCHR) || (t == VFIFO))
314 
315 /* ALIGN64 aligns the given buffer and adjust buffer size to 64 bit */
316 #define	ALIGN64(x, ptr, sz)						\
317 	x = ((uintptr_t)(ptr)) & (sizeof (uint64_t) - 1);		\
318 	if (x) {							\
319 		x = sizeof (uint64_t) - (x);				\
320 		sz -= (x);						\
321 		ptr += (x);						\
322 	}
323 
324 #ifdef DEBUG
325 int nfs4_client_attr_debug = 0;
326 int nfs4_client_state_debug = 0;
327 int nfs4_client_shadow_debug = 0;
328 int nfs4_client_lock_debug = 0;
329 int nfs4_seqid_sync = 0;
330 int nfs4_client_map_debug = 0;
331 static int nfs4_pageio_debug = 0;
332 int nfs4_client_inactive_debug = 0;
333 int nfs4_client_recov_debug = 0;
334 int nfs4_client_failover_debug = 0;
335 int nfs4_client_call_debug = 0;
336 int nfs4_client_lookup_debug = 0;
337 int nfs4_client_zone_debug = 0;
338 int nfs4_lost_rqst_debug = 0;
339 int nfs4_rdattrerr_debug = 0;
340 int nfs4_open_stream_debug = 0;
341 
342 int nfs4read_error_inject;
343 
344 static int nfs4_create_misses = 0;
345 
346 static int nfs4_readdir_cache_shorts = 0;
347 static int nfs4_readdir_readahead = 0;
348 
349 static int nfs4_bio_do_stop = 0;
350 
351 static int nfs4_lostpage = 0;	/* number of times we lost original page */
352 
353 int nfs4_mmap_debug = 0;
354 
355 static int nfs4_pathconf_cache_hits = 0;
356 static int nfs4_pathconf_cache_misses = 0;
357 
358 int nfs4close_all_cnt;
359 int nfs4close_one_debug = 0;
360 int nfs4close_notw_debug = 0;
361 
362 int denied_to_flk_debug = 0;
363 void *lockt_denied_debug;
364 
365 #endif
366 
367 /*
368  * In milliseconds. Should be less than half of the lease time or better,
369  * less than one second.
370  */
371 int nfs4_base_wait_time = 20;
372 int nfs4_max_base_wait_time = 1 * 1000;	/* 1 sec */
373 
374 /*
375  * How long to wait before trying again if OPEN_CONFIRM gets ETIMEDOUT
376  * or NFS4ERR_RESOURCE.
377  */
378 static int confirm_retry_sec = 30;
379 
380 static int nfs4_lookup_neg_cache = 1;
381 
382 /*
383  * number of pages to read ahead
384  * optimized for 100 base-T.
385  */
386 static int nfs4_nra = 4;
387 
388 static int nfs4_do_symlink_cache = 1;
389 
390 static int nfs4_pathconf_disable_cache = 0;
391 
392 /*
393  * These are the vnode ops routines which implement the vnode interface to
394  * the networked file system.  These routines just take their parameters,
395  * make them look networkish by putting the right info into interface structs,
396  * and then calling the appropriate remote routine(s) to do the work.
397  *
398  * Note on directory name lookup cacheing:  If we detect a stale fhandle,
399  * we purge the directory cache relative to that vnode.  This way, the
400  * user won't get burned by the cache repeatedly.  See <nfs/rnode4.h> for
401  * more details on rnode locking.
402  */
403 
404 struct vnodeops *nfs4_vnodeops;
405 
406 const fs_operation_def_t nfs4_vnodeops_template[] = {
407 	VOPNAME_OPEN,		{ .vop_open = nfs4_open },
408 	VOPNAME_CLOSE,		{ .vop_close = nfs4_close },
409 	VOPNAME_READ,		{ .vop_read = nfs4_read },
410 	VOPNAME_WRITE,		{ .vop_write = nfs4_write },
411 	VOPNAME_IOCTL,		{ .vop_ioctl = nfs4_ioctl },
412 	VOPNAME_GETATTR,	{ .vop_getattr = nfs4_getattr },
413 	VOPNAME_SETATTR,	{ .vop_setattr = nfs4_setattr },
414 	VOPNAME_ACCESS,		{ .vop_access = nfs4_access },
415 	VOPNAME_LOOKUP,		{ .vop_lookup = nfs4_lookup },
416 	VOPNAME_CREATE,		{ .vop_create = nfs4_create },
417 	VOPNAME_REMOVE,		{ .vop_remove = nfs4_remove },
418 	VOPNAME_LINK,		{ .vop_link = nfs4_link },
419 	VOPNAME_RENAME,		{ .vop_rename = nfs4_rename },
420 	VOPNAME_MKDIR,		{ .vop_mkdir = nfs4_mkdir },
421 	VOPNAME_RMDIR,		{ .vop_rmdir = nfs4_rmdir },
422 	VOPNAME_READDIR,	{ .vop_readdir = nfs4_readdir },
423 	VOPNAME_SYMLINK,	{ .vop_symlink = nfs4_symlink },
424 	VOPNAME_READLINK,	{ .vop_readlink = nfs4_readlink },
425 	VOPNAME_FSYNC,		{ .vop_fsync = nfs4_fsync },
426 	VOPNAME_INACTIVE,	{ .vop_inactive = nfs4_inactive },
427 	VOPNAME_FID,		{ .vop_fid = nfs4_fid },
428 	VOPNAME_RWLOCK,		{ .vop_rwlock = nfs4_rwlock },
429 	VOPNAME_RWUNLOCK,	{ .vop_rwunlock = nfs4_rwunlock },
430 	VOPNAME_SEEK,		{ .vop_seek = nfs4_seek },
431 	VOPNAME_FRLOCK,		{ .vop_frlock = nfs4_frlock },
432 	VOPNAME_SPACE,		{ .vop_space = nfs4_space },
433 	VOPNAME_REALVP,		{ .vop_realvp = nfs4_realvp },
434 	VOPNAME_GETPAGE,	{ .vop_getpage = nfs4_getpage },
435 	VOPNAME_PUTPAGE,	{ .vop_putpage = nfs4_putpage },
436 	VOPNAME_MAP,		{ .vop_map = nfs4_map },
437 	VOPNAME_ADDMAP,		{ .vop_addmap = nfs4_addmap },
438 	VOPNAME_DELMAP,		{ .vop_delmap = nfs4_delmap },
439 	/* no separate nfs4_dump */
440 	VOPNAME_DUMP,		{ .vop_dump = nfs_dump },
441 	VOPNAME_PATHCONF,	{ .vop_pathconf = nfs4_pathconf },
442 	VOPNAME_PAGEIO,		{ .vop_pageio = nfs4_pageio },
443 	VOPNAME_DISPOSE,	{ .vop_dispose = nfs4_dispose },
444 	VOPNAME_SETSECATTR,	{ .vop_setsecattr = nfs4_setsecattr },
445 	VOPNAME_GETSECATTR,	{ .vop_getsecattr = nfs4_getsecattr },
446 	VOPNAME_SHRLOCK,	{ .vop_shrlock = nfs4_shrlock },
447 	VOPNAME_VNEVENT,	{ .vop_vnevent = fs_vnevent_support },
448 	NULL,			NULL
449 };
450 
451 /*
452  * The following are subroutines and definitions to set args or get res
453  * for the different nfsv4 ops
454  */
455 
456 void
nfs4args_lookup_free(nfs_argop4 * argop,int arglen)457 nfs4args_lookup_free(nfs_argop4 *argop, int arglen)
458 {
459 	int		i;
460 
461 	for (i = 0; i < arglen; i++) {
462 		if (argop[i].argop == OP_LOOKUP) {
463 			kmem_free(
464 			    argop[i].nfs_argop4_u.oplookup.
465 			    objname.utf8string_val,
466 			    argop[i].nfs_argop4_u.oplookup.
467 			    objname.utf8string_len);
468 		}
469 	}
470 }
471 
472 static void
nfs4args_lock_free(nfs_argop4 * argop)473 nfs4args_lock_free(nfs_argop4 *argop)
474 {
475 	locker4 *locker = &argop->nfs_argop4_u.oplock.locker;
476 
477 	if (locker->new_lock_owner == TRUE) {
478 		open_to_lock_owner4 *open_owner;
479 
480 		open_owner = &locker->locker4_u.open_owner;
481 		if (open_owner->lock_owner.owner_val != NULL) {
482 			kmem_free(open_owner->lock_owner.owner_val,
483 			    open_owner->lock_owner.owner_len);
484 		}
485 	}
486 }
487 
488 static void
nfs4args_lockt_free(nfs_argop4 * argop)489 nfs4args_lockt_free(nfs_argop4 *argop)
490 {
491 	lock_owner4 *lowner = &argop->nfs_argop4_u.oplockt.owner;
492 
493 	if (lowner->owner_val != NULL) {
494 		kmem_free(lowner->owner_val, lowner->owner_len);
495 	}
496 }
497 
498 static void
nfs4args_setattr(nfs_argop4 * argop,vattr_t * vap,vsecattr_t * vsap,int flags,rnode4_t * rp,cred_t * cr,bitmap4 supp,int * error,nfs4_stateid_types_t * sid_types)499 nfs4args_setattr(nfs_argop4 *argop, vattr_t *vap, vsecattr_t *vsap, int flags,
500     rnode4_t *rp, cred_t *cr, bitmap4 supp, int *error,
501     nfs4_stateid_types_t *sid_types)
502 {
503 	fattr4		*attr = &argop->nfs_argop4_u.opsetattr.obj_attributes;
504 	mntinfo4_t	*mi;
505 
506 	argop->argop = OP_SETATTR;
507 	/*
508 	 * The stateid is set to 0 if client is not modifying the size
509 	 * and otherwise to whatever nfs4_get_stateid() returns.
510 	 *
511 	 * XXX Note: nfs4_get_stateid() returns 0 if no lockowner and/or no
512 	 * state struct could be found for the process/file pair.  We may
513 	 * want to change this in the future (by OPENing the file).  See
514 	 * bug # 4474852.
515 	 */
516 	if (vap->va_mask & AT_SIZE) {
517 
518 		ASSERT(rp != NULL);
519 		mi = VTOMI4(RTOV4(rp));
520 
521 		argop->nfs_argop4_u.opsetattr.stateid =
522 		    nfs4_get_stateid(cr, rp, curproc->p_pidp->pid_id, mi,
523 		    OP_SETATTR, sid_types, FALSE);
524 	} else {
525 		bzero(&argop->nfs_argop4_u.opsetattr.stateid,
526 		    sizeof (stateid4));
527 	}
528 
529 	*error = vattr_to_fattr4(vap, vsap, attr, flags, OP_SETATTR, supp);
530 	if (*error)
531 		bzero(attr, sizeof (*attr));
532 }
533 
534 static void
nfs4args_setattr_free(nfs_argop4 * argop)535 nfs4args_setattr_free(nfs_argop4 *argop)
536 {
537 	nfs4_fattr4_free(&argop->nfs_argop4_u.opsetattr.obj_attributes);
538 }
539 
540 static int
nfs4args_verify(nfs_argop4 * argop,vattr_t * vap,enum nfs_opnum4 op,bitmap4 supp)541 nfs4args_verify(nfs_argop4 *argop, vattr_t *vap, enum nfs_opnum4 op,
542     bitmap4 supp)
543 {
544 	fattr4 *attr;
545 	int error = 0;
546 
547 	argop->argop = op;
548 	switch (op) {
549 	case OP_VERIFY:
550 		attr = &argop->nfs_argop4_u.opverify.obj_attributes;
551 		break;
552 	case OP_NVERIFY:
553 		attr = &argop->nfs_argop4_u.opnverify.obj_attributes;
554 		break;
555 	default:
556 		return (EINVAL);
557 	}
558 	if (!error)
559 		error = vattr_to_fattr4(vap, NULL, attr, 0, op, supp);
560 	if (error)
561 		bzero(attr, sizeof (*attr));
562 	return (error);
563 }
564 
565 static void
nfs4args_verify_free(nfs_argop4 * argop)566 nfs4args_verify_free(nfs_argop4 *argop)
567 {
568 	switch (argop->argop) {
569 	case OP_VERIFY:
570 		nfs4_fattr4_free(&argop->nfs_argop4_u.opverify.obj_attributes);
571 		break;
572 	case OP_NVERIFY:
573 		nfs4_fattr4_free(&argop->nfs_argop4_u.opnverify.obj_attributes);
574 		break;
575 	default:
576 		break;
577 	}
578 }
579 
580 static void
nfs4args_write(nfs_argop4 * argop,stable_how4 stable,rnode4_t * rp,cred_t * cr,WRITE4args ** wargs_pp,nfs4_stateid_types_t * sid_tp)581 nfs4args_write(nfs_argop4 *argop, stable_how4 stable, rnode4_t *rp, cred_t *cr,
582     WRITE4args **wargs_pp, nfs4_stateid_types_t *sid_tp)
583 {
584 	WRITE4args *wargs = &argop->nfs_argop4_u.opwrite;
585 	mntinfo4_t *mi = VTOMI4(RTOV4(rp));
586 
587 	argop->argop = OP_WRITE;
588 	wargs->stable = stable;
589 	wargs->stateid = nfs4_get_w_stateid(cr, rp, curproc->p_pidp->pid_id,
590 	    mi, OP_WRITE, sid_tp);
591 	wargs->mblk = NULL;
592 	*wargs_pp = wargs;
593 }
594 
595 void
nfs4args_copen_free(OPEN4cargs * open_args)596 nfs4args_copen_free(OPEN4cargs *open_args)
597 {
598 	if (open_args->owner.owner_val) {
599 		kmem_free(open_args->owner.owner_val,
600 		    open_args->owner.owner_len);
601 	}
602 	if ((open_args->opentype == OPEN4_CREATE) &&
603 	    (open_args->mode != EXCLUSIVE4)) {
604 		nfs4_fattr4_free(&open_args->createhow4_u.createattrs);
605 	}
606 }
607 
608 /*
609  * XXX:  This is referenced in modstubs.s
610  */
611 struct vnodeops *
nfs4_getvnodeops(void)612 nfs4_getvnodeops(void)
613 {
614 	return (nfs4_vnodeops);
615 }
616 
617 /*
618  * The OPEN operation opens a regular file.
619  */
620 /*ARGSUSED3*/
621 static int
nfs4_open(vnode_t ** vpp,int flag,cred_t * cr,caller_context_t * ct)622 nfs4_open(vnode_t **vpp, int flag, cred_t *cr, caller_context_t *ct)
623 {
624 	vnode_t *dvp = NULL;
625 	rnode4_t *rp, *drp;
626 	int error;
627 	int just_been_created;
628 	char fn[MAXNAMELEN];
629 
630 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4_open: "));
631 	if (nfs_zone() != VTOMI4(*vpp)->mi_zone)
632 		return (EIO);
633 	rp = VTOR4(*vpp);
634 
635 	/*
636 	 * Check to see if opening something besides a regular file;
637 	 * if so skip the OTW call
638 	 */
639 	if ((*vpp)->v_type != VREG) {
640 		error = nfs4_open_non_reg_file(vpp, flag, cr);
641 		return (error);
642 	}
643 
644 	/*
645 	 * XXX - would like a check right here to know if the file is
646 	 * executable or not, so as to skip OTW
647 	 */
648 
649 	if ((error = vtodv(*vpp, &dvp, cr, TRUE)) != 0)
650 		return (error);
651 
652 	drp = VTOR4(dvp);
653 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
654 		return (EINTR);
655 
656 	if ((error = vtoname(*vpp, fn, MAXNAMELEN)) != 0) {
657 		nfs_rw_exit(&drp->r_rwlock);
658 		return (error);
659 	}
660 
661 	/*
662 	 * See if this file has just been CREATEd.
663 	 * If so, clear the flag and update the dnlc, which was previously
664 	 * skipped in nfs4_create.
665 	 * XXX need better serilization on this.
666 	 * XXX move this into the nf4open_otw call, after we have
667 	 * XXX acquired the open owner seqid sync.
668 	 */
669 	mutex_enter(&rp->r_statev4_lock);
670 	if (rp->created_v4) {
671 		rp->created_v4 = 0;
672 		mutex_exit(&rp->r_statev4_lock);
673 
674 		dnlc_update(dvp, fn, *vpp);
675 		/* This is needed so we don't bump the open ref count */
676 		just_been_created = 1;
677 	} else {
678 		mutex_exit(&rp->r_statev4_lock);
679 		just_been_created = 0;
680 	}
681 
682 	/*
683 	 * If caller specified O_TRUNC/FTRUNC, then be sure to set
684 	 * FWRITE (to drive successful setattr(size=0) after open)
685 	 */
686 	if (flag & FTRUNC)
687 		flag |= FWRITE;
688 
689 	error = nfs4open_otw(dvp, fn, NULL, vpp, cr, 0, flag, 0,
690 	    just_been_created);
691 
692 	if (!error && !((*vpp)->v_flag & VROOT))
693 		dnlc_update(dvp, fn, *vpp);
694 
695 	nfs_rw_exit(&drp->r_rwlock);
696 
697 	/* release the hold from vtodv */
698 	VN_RELE(dvp);
699 
700 	/* exchange the shadow for the master vnode, if needed */
701 
702 	if (error == 0 && IS_SHADOW(*vpp, rp))
703 		sv_exchange(vpp);
704 
705 	return (error);
706 }
707 
708 /*
709  * See if there's a "lost open" request to be saved and recovered.
710  */
711 static void
nfs4open_save_lost_rqst(int error,nfs4_lost_rqst_t * lost_rqstp,nfs4_open_owner_t * oop,cred_t * cr,vnode_t * vp,vnode_t * dvp,OPEN4cargs * open_args)712 nfs4open_save_lost_rqst(int error, nfs4_lost_rqst_t *lost_rqstp,
713     nfs4_open_owner_t *oop, cred_t *cr, vnode_t *vp,
714     vnode_t *dvp, OPEN4cargs *open_args)
715 {
716 	vfs_t *vfsp;
717 	char *srccfp;
718 
719 	vfsp = (dvp ? dvp->v_vfsp : vp->v_vfsp);
720 
721 	if (error != ETIMEDOUT && error != EINTR &&
722 	    !NFS4_FRC_UNMT_ERR(error, vfsp)) {
723 		lost_rqstp->lr_op = 0;
724 		return;
725 	}
726 
727 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
728 	    "nfs4open_save_lost_rqst: error %d", error));
729 
730 	lost_rqstp->lr_op = OP_OPEN;
731 
732 	/*
733 	 * The vp (if it is not NULL) and dvp are held and rele'd via
734 	 * the recovery code.  See nfs4_save_lost_rqst.
735 	 */
736 	lost_rqstp->lr_vp = vp;
737 	lost_rqstp->lr_dvp = dvp;
738 	lost_rqstp->lr_oop = oop;
739 	lost_rqstp->lr_osp = NULL;
740 	lost_rqstp->lr_lop = NULL;
741 	lost_rqstp->lr_cr = cr;
742 	lost_rqstp->lr_flk = NULL;
743 	lost_rqstp->lr_oacc = open_args->share_access;
744 	lost_rqstp->lr_odeny = open_args->share_deny;
745 	lost_rqstp->lr_oclaim = open_args->claim;
746 	if (open_args->claim == CLAIM_DELEGATE_CUR) {
747 		lost_rqstp->lr_ostateid =
748 		    open_args->open_claim4_u.delegate_cur_info.delegate_stateid;
749 		srccfp = open_args->open_claim4_u.delegate_cur_info.cfile;
750 	} else {
751 		srccfp = open_args->open_claim4_u.cfile;
752 	}
753 	lost_rqstp->lr_ofile.utf8string_len = 0;
754 	lost_rqstp->lr_ofile.utf8string_val = NULL;
755 	(void) str_to_utf8(srccfp, &lost_rqstp->lr_ofile);
756 	lost_rqstp->lr_putfirst = FALSE;
757 }
758 
759 struct nfs4_excl_time {
760 	uint32 seconds;
761 	uint32 nseconds;
762 };
763 
764 /*
765  * The OPEN operation creates and/or opens a regular file
766  *
767  * ARGSUSED
768  */
769 static int
nfs4open_otw(vnode_t * dvp,char * file_name,struct vattr * in_va,vnode_t ** vpp,cred_t * cr,int create_flag,int open_flag,enum createmode4 createmode,int file_just_been_created)770 nfs4open_otw(vnode_t *dvp, char *file_name, struct vattr *in_va,
771     vnode_t **vpp, cred_t *cr, int create_flag, int open_flag,
772     enum createmode4 createmode, int file_just_been_created)
773 {
774 	rnode4_t *rp;
775 	rnode4_t *drp = VTOR4(dvp);
776 	vnode_t *vp = NULL;
777 	vnode_t *vpi = *vpp;
778 	bool_t needrecov = FALSE;
779 
780 	int doqueue = 1;
781 
782 	COMPOUND4args_clnt args;
783 	COMPOUND4res_clnt res;
784 	nfs_argop4 *argop;
785 	nfs_resop4 *resop;
786 	int argoplist_size;
787 	int idx_open, idx_fattr;
788 
789 	GETFH4res *gf_res = NULL;
790 	OPEN4res *op_res = NULL;
791 	nfs4_ga_res_t *garp;
792 	fattr4 *attr = NULL;
793 	struct nfs4_excl_time verf;
794 	bool_t did_excl_setup = FALSE;
795 	int created_osp;
796 
797 	OPEN4cargs *open_args;
798 	nfs4_open_owner_t	*oop = NULL;
799 	nfs4_open_stream_t	*osp = NULL;
800 	seqid4 seqid = 0;
801 	bool_t retry_open = FALSE;
802 	nfs4_recov_state_t recov_state;
803 	nfs4_lost_rqst_t lost_rqst;
804 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
805 	hrtime_t t;
806 	int acc = 0;
807 	cred_t *cred_otw = NULL;	/* cred used to do the RPC call */
808 	cred_t *ncr = NULL;
809 
810 	nfs4_sharedfh_t *otw_sfh;
811 	nfs4_sharedfh_t *orig_sfh;
812 	int fh_differs = 0;
813 	int numops, setgid_flag;
814 	int num_bseqid_retry = NFS4_NUM_RETRY_BAD_SEQID + 1;
815 
816 	/*
817 	 * Make sure we properly deal with setting the right gid on
818 	 * a newly created file to reflect the parent's setgid bit
819 	 */
820 	setgid_flag = 0;
821 	if (create_flag && in_va) {
822 
823 		/*
824 		 * If there is grpid mount flag used or
825 		 * the parent's directory has the setgid bit set
826 		 * _and_ the client was able to get a valid mapping
827 		 * for the parent dir's owner_group, we want to
828 		 * append NVERIFY(owner_group == dva.va_gid) and
829 		 * SETATTR to the CREATE compound.
830 		 */
831 		mutex_enter(&drp->r_statelock);
832 		if ((VTOMI4(dvp)->mi_flags & MI4_GRPID ||
833 		    drp->r_attr.va_mode & VSGID) &&
834 		    drp->r_attr.va_gid != GID_NOBODY) {
835 			in_va->va_mask |= AT_GID;
836 			in_va->va_gid = drp->r_attr.va_gid;
837 			setgid_flag = 1;
838 		}
839 		mutex_exit(&drp->r_statelock);
840 	}
841 
842 	/*
843 	 * Normal/non-create compound:
844 	 * PUTFH(dfh) + OPEN(create) + GETFH + GETATTR(new)
845 	 *
846 	 * Open(create) compound no setgid:
847 	 * PUTFH(dfh) + SAVEFH + OPEN(create) + GETFH + GETATTR(new) +
848 	 * RESTOREFH + GETATTR
849 	 *
850 	 * Open(create) setgid:
851 	 * PUTFH(dfh) + OPEN(create) + GETFH + GETATTR(new) +
852 	 * SAVEFH + PUTFH(dfh) + GETATTR(dvp) + RESTOREFH +
853 	 * NVERIFY(grp) + SETATTR
854 	 */
855 	if (setgid_flag) {
856 		numops = 10;
857 		idx_open = 1;
858 		idx_fattr = 3;
859 	} else if (create_flag) {
860 		numops = 7;
861 		idx_open = 2;
862 		idx_fattr = 4;
863 	} else {
864 		numops = 4;
865 		idx_open = 1;
866 		idx_fattr = 3;
867 	}
868 
869 	args.array_len = numops;
870 	argoplist_size = numops * sizeof (nfs_argop4);
871 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
872 
873 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4open_otw: "
874 	    "open %s open flag 0x%x cred %p", file_name, open_flag,
875 	    (void *)cr));
876 
877 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
878 	if (create_flag) {
879 		/*
880 		 * We are to create a file.  Initialize the passed in vnode
881 		 * pointer.
882 		 */
883 		vpi = NULL;
884 	} else {
885 		/*
886 		 * Check to see if the client owns a read delegation and is
887 		 * trying to open for write.  If so, then return the delegation
888 		 * to avoid the server doing a cb_recall and returning DELAY.
889 		 * NB - we don't use the statev4_lock here because we'd have
890 		 * to drop the lock anyway and the result would be stale.
891 		 */
892 		if ((open_flag & FWRITE) &&
893 		    VTOR4(vpi)->r_deleg_type == OPEN_DELEGATE_READ)
894 			(void) nfs4delegreturn(VTOR4(vpi), NFS4_DR_REOPEN);
895 
896 		/*
897 		 * If the file has a delegation, then do an access check up
898 		 * front.  This avoids having to an access check later after
899 		 * we've already done start_op, which could deadlock.
900 		 */
901 		if (VTOR4(vpi)->r_deleg_type != OPEN_DELEGATE_NONE) {
902 			if (open_flag & FREAD &&
903 			    nfs4_access(vpi, VREAD, 0, cr, NULL) == 0)
904 				acc |= VREAD;
905 			if (open_flag & FWRITE &&
906 			    nfs4_access(vpi, VWRITE, 0, cr, NULL) == 0)
907 				acc |= VWRITE;
908 		}
909 	}
910 
911 	drp = VTOR4(dvp);
912 
913 	recov_state.rs_flags = 0;
914 	recov_state.rs_num_retry_despite_err = 0;
915 	cred_otw = cr;
916 
917 recov_retry:
918 	fh_differs = 0;
919 	nfs4_error_zinit(&e);
920 
921 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, vpi, &recov_state);
922 	if (e.error) {
923 		if (ncr != NULL)
924 			crfree(ncr);
925 		kmem_free(argop, argoplist_size);
926 		return (e.error);
927 	}
928 
929 	args.ctag = TAG_OPEN;
930 	args.array_len = numops;
931 	args.array = argop;
932 
933 	/* putfh directory fh */
934 	argop[0].argop = OP_CPUTFH;
935 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
936 
937 	/* OPEN: either op 1 or op 2 depending upon create/setgid flags */
938 	argop[idx_open].argop = OP_COPEN;
939 	open_args = &argop[idx_open].nfs_argop4_u.opcopen;
940 	open_args->claim = CLAIM_NULL;
941 
942 	/* name of file */
943 	open_args->open_claim4_u.cfile = file_name;
944 	open_args->owner.owner_len = 0;
945 	open_args->owner.owner_val = NULL;
946 
947 	if (create_flag) {
948 		/* CREATE a file */
949 		open_args->opentype = OPEN4_CREATE;
950 		open_args->mode = createmode;
951 		if (createmode == EXCLUSIVE4) {
952 			if (did_excl_setup == FALSE) {
953 				verf.seconds = zone_get_hostid(NULL);
954 				if (verf.seconds != 0)
955 					verf.nseconds = newnum();
956 				else {
957 					timestruc_t now;
958 
959 					gethrestime(&now);
960 					verf.seconds = now.tv_sec;
961 					verf.nseconds = now.tv_nsec;
962 				}
963 				/*
964 				 * Since the server will use this value for the
965 				 * mtime, make sure that it can't overflow. Zero
966 				 * out the MSB. The actual value does not matter
967 				 * here, only its uniqeness.
968 				 */
969 				verf.seconds &= INT32_MAX;
970 				did_excl_setup = TRUE;
971 			}
972 
973 			/* Now copy over verifier to OPEN4args. */
974 			open_args->createhow4_u.createverf = *(uint64_t *)&verf;
975 		} else {
976 			int v_error;
977 			bitmap4 supp_attrs;
978 			servinfo4_t *svp;
979 
980 			attr = &open_args->createhow4_u.createattrs;
981 
982 			svp = drp->r_server;
983 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
984 			supp_attrs = svp->sv_supp_attrs;
985 			nfs_rw_exit(&svp->sv_lock);
986 
987 			/* GUARDED4 or UNCHECKED4 */
988 			v_error = vattr_to_fattr4(in_va, NULL, attr, 0, OP_OPEN,
989 			    supp_attrs);
990 			if (v_error) {
991 				bzero(attr, sizeof (*attr));
992 				nfs4args_copen_free(open_args);
993 				nfs4_end_op(VTOMI4(dvp), dvp, vpi,
994 				    &recov_state, FALSE);
995 				if (ncr != NULL)
996 					crfree(ncr);
997 				kmem_free(argop, argoplist_size);
998 				return (v_error);
999 			}
1000 		}
1001 	} else {
1002 		/* NO CREATE */
1003 		open_args->opentype = OPEN4_NOCREATE;
1004 	}
1005 
1006 	if (recov_state.rs_sp != NULL) {
1007 		mutex_enter(&recov_state.rs_sp->s_lock);
1008 		open_args->owner.clientid = recov_state.rs_sp->clientid;
1009 		mutex_exit(&recov_state.rs_sp->s_lock);
1010 	} else {
1011 		/* XXX should we just fail here? */
1012 		open_args->owner.clientid = 0;
1013 	}
1014 
1015 	/*
1016 	 * This increments oop's ref count or creates a temporary 'just_created'
1017 	 * open owner that will become valid when this OPEN/OPEN_CONFIRM call
1018 	 * completes.
1019 	 */
1020 	mutex_enter(&VTOMI4(dvp)->mi_lock);
1021 
1022 	/* See if a permanent or just created open owner exists */
1023 	oop = find_open_owner_nolock(cr, NFS4_JUST_CREATED, VTOMI4(dvp));
1024 	if (!oop) {
1025 		/*
1026 		 * This open owner does not exist so create a temporary
1027 		 * just created one.
1028 		 */
1029 		oop = create_open_owner(cr, VTOMI4(dvp));
1030 		ASSERT(oop != NULL);
1031 	}
1032 	mutex_exit(&VTOMI4(dvp)->mi_lock);
1033 
1034 	/* this length never changes, do alloc before seqid sync */
1035 	open_args->owner.owner_len = sizeof (oop->oo_name);
1036 	open_args->owner.owner_val =
1037 	    kmem_alloc(open_args->owner.owner_len, KM_SLEEP);
1038 
1039 	e.error = nfs4_start_open_seqid_sync(oop, VTOMI4(dvp));
1040 	if (e.error == EAGAIN) {
1041 		open_owner_rele(oop);
1042 		nfs4args_copen_free(open_args);
1043 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, TRUE);
1044 		if (ncr != NULL) {
1045 			crfree(ncr);
1046 			ncr = NULL;
1047 		}
1048 		goto recov_retry;
1049 	}
1050 
1051 	/* Check to see if we need to do the OTW call */
1052 	if (!create_flag) {
1053 		if (!nfs4_is_otw_open_necessary(oop, open_flag, vpi,
1054 		    file_just_been_created, &e.error, acc, &recov_state)) {
1055 
1056 			/*
1057 			 * The OTW open is not necessary.  Either
1058 			 * the open can succeed without it (eg.
1059 			 * delegation, error == 0) or the open
1060 			 * must fail due to an access failure
1061 			 * (error != 0).  In either case, tidy
1062 			 * up and return.
1063 			 */
1064 
1065 			nfs4_end_open_seqid_sync(oop);
1066 			open_owner_rele(oop);
1067 			nfs4args_copen_free(open_args);
1068 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, FALSE);
1069 			if (ncr != NULL)
1070 				crfree(ncr);
1071 			kmem_free(argop, argoplist_size);
1072 			return (e.error);
1073 		}
1074 	}
1075 
1076 	bcopy(&oop->oo_name, open_args->owner.owner_val,
1077 	    open_args->owner.owner_len);
1078 
1079 	seqid = nfs4_get_open_seqid(oop) + 1;
1080 	open_args->seqid = seqid;
1081 	open_args->share_access = 0;
1082 	if (open_flag & FREAD)
1083 		open_args->share_access |= OPEN4_SHARE_ACCESS_READ;
1084 	if (open_flag & FWRITE)
1085 		open_args->share_access |= OPEN4_SHARE_ACCESS_WRITE;
1086 	open_args->share_deny = OPEN4_SHARE_DENY_NONE;
1087 
1088 
1089 
1090 	/*
1091 	 * getfh w/sanity check for idx_open/idx_fattr
1092 	 */
1093 	ASSERT((idx_open + 1) == (idx_fattr - 1));
1094 	argop[idx_open + 1].argop = OP_GETFH;
1095 
1096 	/* getattr */
1097 	argop[idx_fattr].argop = OP_GETATTR;
1098 	argop[idx_fattr].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1099 	argop[idx_fattr].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1100 
1101 	if (setgid_flag) {
1102 		vattr_t	_v;
1103 		servinfo4_t *svp;
1104 		bitmap4	supp_attrs;
1105 
1106 		svp = drp->r_server;
1107 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
1108 		supp_attrs = svp->sv_supp_attrs;
1109 		nfs_rw_exit(&svp->sv_lock);
1110 
1111 		/*
1112 		 * For setgid case, we need to:
1113 		 * 4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
1114 		 */
1115 		argop[4].argop = OP_SAVEFH;
1116 
1117 		argop[5].argop = OP_CPUTFH;
1118 		argop[5].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
1119 
1120 		argop[6].argop = OP_GETATTR;
1121 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1122 		argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1123 
1124 		argop[7].argop = OP_RESTOREFH;
1125 
1126 		/*
1127 		 * nverify
1128 		 */
1129 		_v.va_mask = AT_GID;
1130 		_v.va_gid = in_va->va_gid;
1131 		if (!(e.error = nfs4args_verify(&argop[8], &_v, OP_NVERIFY,
1132 		    supp_attrs))) {
1133 
1134 			/*
1135 			 * setattr
1136 			 *
1137 			 * We _know_ we're not messing with AT_SIZE or
1138 			 * AT_XTIME, so no need for stateid or flags.
1139 			 * Also we specify NULL rp since we're only
1140 			 * interested in setting owner_group attributes.
1141 			 */
1142 			nfs4args_setattr(&argop[9], &_v, NULL, 0, NULL, cr,
1143 			    supp_attrs, &e.error, 0);
1144 			if (e.error)
1145 				nfs4args_verify_free(&argop[8]);
1146 		}
1147 
1148 		if (e.error) {
1149 			/*
1150 			 * XXX - Revisit the last argument to nfs4_end_op()
1151 			 *	 once 5020486 is fixed.
1152 			 */
1153 			nfs4_end_open_seqid_sync(oop);
1154 			open_owner_rele(oop);
1155 			nfs4args_copen_free(open_args);
1156 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, TRUE);
1157 			if (ncr != NULL)
1158 				crfree(ncr);
1159 			kmem_free(argop, argoplist_size);
1160 			return (e.error);
1161 		}
1162 	} else if (create_flag) {
1163 		argop[1].argop = OP_SAVEFH;
1164 
1165 		argop[5].argop = OP_RESTOREFH;
1166 
1167 		argop[6].argop = OP_GETATTR;
1168 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1169 		argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
1170 	}
1171 
1172 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
1173 	    "nfs4open_otw: %s call, nm %s, rp %s",
1174 	    needrecov ? "recov" : "first", file_name,
1175 	    rnode4info(VTOR4(dvp))));
1176 
1177 	t = gethrtime();
1178 
1179 	rfs4call(VTOMI4(dvp), &args, &res, cred_otw, &doqueue, 0, &e);
1180 
1181 	if (!e.error && nfs4_need_to_bump_seqid(&res))
1182 		nfs4_set_open_seqid(seqid, oop, args.ctag);
1183 
1184 	needrecov = nfs4_needs_recovery(&e, TRUE, dvp->v_vfsp);
1185 
1186 	if (e.error || needrecov) {
1187 		bool_t abort = FALSE;
1188 
1189 		if (needrecov) {
1190 			nfs4_bseqid_entry_t *bsep = NULL;
1191 
1192 			nfs4open_save_lost_rqst(e.error, &lost_rqst, oop,
1193 			    cred_otw, vpi, dvp, open_args);
1194 
1195 			if (!e.error && res.status == NFS4ERR_BAD_SEQID) {
1196 				bsep = nfs4_create_bseqid_entry(oop, NULL,
1197 				    vpi, 0, args.ctag, open_args->seqid);
1198 				num_bseqid_retry--;
1199 			}
1200 
1201 			abort = nfs4_start_recovery(&e, VTOMI4(dvp), dvp, vpi,
1202 			    NULL, lost_rqst.lr_op == OP_OPEN ?
1203 			    &lost_rqst : NULL, OP_OPEN, bsep, NULL, NULL);
1204 
1205 			if (bsep)
1206 				kmem_free(bsep, sizeof (*bsep));
1207 			/* give up if we keep getting BAD_SEQID */
1208 			if (num_bseqid_retry == 0)
1209 				abort = TRUE;
1210 			if (abort == TRUE && e.error == 0)
1211 				e.error = geterrno4(res.status);
1212 		}
1213 		nfs4_end_open_seqid_sync(oop);
1214 		open_owner_rele(oop);
1215 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1216 		nfs4args_copen_free(open_args);
1217 		if (setgid_flag) {
1218 			nfs4args_verify_free(&argop[8]);
1219 			nfs4args_setattr_free(&argop[9]);
1220 		}
1221 		if (!e.error)
1222 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1223 		if (ncr != NULL) {
1224 			crfree(ncr);
1225 			ncr = NULL;
1226 		}
1227 		if (!needrecov || abort == TRUE || e.error == EINTR ||
1228 		    NFS4_FRC_UNMT_ERR(e.error, dvp->v_vfsp)) {
1229 			kmem_free(argop, argoplist_size);
1230 			return (e.error);
1231 		}
1232 		goto recov_retry;
1233 	}
1234 
1235 	/*
1236 	 * Will check and update lease after checking the rflag for
1237 	 * OPEN_CONFIRM in the successful OPEN call.
1238 	 */
1239 	if (res.status != NFS4_OK && res.array_len <= idx_fattr + 1) {
1240 
1241 		/*
1242 		 * XXX what if we're crossing mount points from server1:/drp
1243 		 * to server2:/drp/rp.
1244 		 */
1245 
1246 		/* Signal our end of use of the open seqid */
1247 		nfs4_end_open_seqid_sync(oop);
1248 
1249 		/*
1250 		 * This will destroy the open owner if it was just created,
1251 		 * and no one else has put a reference on it.
1252 		 */
1253 		open_owner_rele(oop);
1254 		if (create_flag && (createmode != EXCLUSIVE4) &&
1255 		    res.status == NFS4ERR_BADOWNER)
1256 			nfs4_log_badowner(VTOMI4(dvp), OP_OPEN);
1257 
1258 		e.error = geterrno4(res.status);
1259 		nfs4args_copen_free(open_args);
1260 		if (setgid_flag) {
1261 			nfs4args_verify_free(&argop[8]);
1262 			nfs4args_setattr_free(&argop[9]);
1263 		}
1264 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1265 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1266 		/*
1267 		 * If the reply is NFS4ERR_ACCESS, it may be because
1268 		 * we are root (no root net access).  If the real uid
1269 		 * is not root, then retry with the real uid instead.
1270 		 */
1271 		if (ncr != NULL) {
1272 			crfree(ncr);
1273 			ncr = NULL;
1274 		}
1275 		if (res.status == NFS4ERR_ACCESS &&
1276 		    (ncr = crnetadjust(cred_otw)) != NULL) {
1277 			cred_otw = ncr;
1278 			goto recov_retry;
1279 		}
1280 		kmem_free(argop, argoplist_size);
1281 		return (e.error);
1282 	}
1283 
1284 	resop = &res.array[idx_open];  /* open res */
1285 	op_res = &resop->nfs_resop4_u.opopen;
1286 
1287 #ifdef DEBUG
1288 	/*
1289 	 * verify attrset bitmap
1290 	 */
1291 	if (create_flag &&
1292 	    (createmode == UNCHECKED4 || createmode == GUARDED4)) {
1293 		/* make sure attrset returned is what we asked for */
1294 		/* XXX Ignore this 'error' for now */
1295 		if (attr->attrmask != op_res->attrset)
1296 			/* EMPTY */;
1297 	}
1298 #endif
1299 
1300 	if (op_res->rflags & OPEN4_RESULT_LOCKTYPE_POSIX) {
1301 		mutex_enter(&VTOMI4(dvp)->mi_lock);
1302 		VTOMI4(dvp)->mi_flags |= MI4_POSIX_LOCK;
1303 		mutex_exit(&VTOMI4(dvp)->mi_lock);
1304 	}
1305 
1306 	resop = &res.array[idx_open + 1];  /* getfh res */
1307 	gf_res = &resop->nfs_resop4_u.opgetfh;
1308 
1309 	otw_sfh = sfh4_get(&gf_res->object, VTOMI4(dvp));
1310 
1311 	/*
1312 	 * The open stateid has been updated on the server but not
1313 	 * on the client yet.  There is a path: makenfs4node->nfs4_attr_cache->
1314 	 * flush_pages->VOP_PUTPAGE->...->nfs4write where we will issue an OTW
1315 	 * WRITE call.  That, however, will use the old stateid, so go ahead
1316 	 * and upate the open stateid now, before any call to makenfs4node.
1317 	 */
1318 	if (vpi) {
1319 		nfs4_open_stream_t	*tmp_osp;
1320 		rnode4_t		*tmp_rp = VTOR4(vpi);
1321 
1322 		tmp_osp = find_open_stream(oop, tmp_rp);
1323 		if (tmp_osp) {
1324 			tmp_osp->open_stateid = op_res->stateid;
1325 			mutex_exit(&tmp_osp->os_sync_lock);
1326 			open_stream_rele(tmp_osp, tmp_rp);
1327 		}
1328 
1329 		/*
1330 		 * We must determine if the file handle given by the otw open
1331 		 * is the same as the file handle which was passed in with
1332 		 * *vpp.  This case can be reached if the file we are trying
1333 		 * to open has been removed and another file has been created
1334 		 * having the same file name.  The passed in vnode is released
1335 		 * later.
1336 		 */
1337 		orig_sfh = VTOR4(vpi)->r_fh;
1338 		fh_differs = nfs4cmpfh(&orig_sfh->sfh_fh, &otw_sfh->sfh_fh);
1339 	}
1340 
1341 	garp = &res.array[idx_fattr].nfs_resop4_u.opgetattr.ga_res;
1342 
1343 	if (create_flag || fh_differs) {
1344 		int rnode_err = 0;
1345 
1346 		vp = makenfs4node(otw_sfh, garp, dvp->v_vfsp, t, cr,
1347 		    dvp, fn_get(VTOSV(dvp)->sv_name, file_name, otw_sfh));
1348 
1349 		if (e.error)
1350 			PURGE_ATTRCACHE4(vp);
1351 		/*
1352 		 * For the newly created vp case, make sure the rnode
1353 		 * isn't bad before using it.
1354 		 */
1355 		mutex_enter(&(VTOR4(vp))->r_statelock);
1356 		if (VTOR4(vp)->r_flags & R4RECOVERR)
1357 			rnode_err = EIO;
1358 		mutex_exit(&(VTOR4(vp))->r_statelock);
1359 
1360 		if (rnode_err) {
1361 			nfs4_end_open_seqid_sync(oop);
1362 			nfs4args_copen_free(open_args);
1363 			if (setgid_flag) {
1364 				nfs4args_verify_free(&argop[8]);
1365 				nfs4args_setattr_free(&argop[9]);
1366 			}
1367 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1368 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state,
1369 			    needrecov);
1370 			open_owner_rele(oop);
1371 			VN_RELE(vp);
1372 			if (ncr != NULL)
1373 				crfree(ncr);
1374 			sfh4_rele(&otw_sfh);
1375 			kmem_free(argop, argoplist_size);
1376 			return (EIO);
1377 		}
1378 	} else {
1379 		vp = vpi;
1380 	}
1381 	sfh4_rele(&otw_sfh);
1382 
1383 	/*
1384 	 * It seems odd to get a full set of attrs and then not update
1385 	 * the object's attrcache in the non-create case.  Create case uses
1386 	 * the attrs since makenfs4node checks to see if the attrs need to
1387 	 * be updated (and then updates them).  The non-create case should
1388 	 * update attrs also.
1389 	 */
1390 	if (! create_flag && ! fh_differs && !e.error) {
1391 		nfs4_attr_cache(vp, garp, t, cr, TRUE, NULL);
1392 	}
1393 
1394 	nfs4_error_zinit(&e);
1395 	if (op_res->rflags & OPEN4_RESULT_CONFIRM) {
1396 		/* This does not do recovery for vp explicitly. */
1397 		nfs4open_confirm(vp, &seqid, &op_res->stateid, cred_otw, FALSE,
1398 		    &retry_open, oop, FALSE, &e, &num_bseqid_retry);
1399 
1400 		if (e.error || e.stat) {
1401 			nfs4_end_open_seqid_sync(oop);
1402 			nfs4args_copen_free(open_args);
1403 			if (setgid_flag) {
1404 				nfs4args_verify_free(&argop[8]);
1405 				nfs4args_setattr_free(&argop[9]);
1406 			}
1407 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1408 			nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state,
1409 			    needrecov);
1410 			open_owner_rele(oop);
1411 			if (create_flag || fh_differs) {
1412 				/* rele the makenfs4node */
1413 				VN_RELE(vp);
1414 			}
1415 			if (ncr != NULL) {
1416 				crfree(ncr);
1417 				ncr = NULL;
1418 			}
1419 			if (retry_open == TRUE) {
1420 				NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
1421 				    "nfs4open_otw: retry the open since OPEN "
1422 				    "CONFIRM failed with error %d stat %d",
1423 				    e.error, e.stat));
1424 				if (create_flag && createmode == GUARDED4) {
1425 					NFS4_DEBUG(nfs4_client_recov_debug,
1426 					    (CE_NOTE, "nfs4open_otw: switch "
1427 					    "createmode from GUARDED4 to "
1428 					    "UNCHECKED4"));
1429 					createmode = UNCHECKED4;
1430 				}
1431 				goto recov_retry;
1432 			}
1433 			if (!e.error) {
1434 				if (create_flag && (createmode != EXCLUSIVE4) &&
1435 				    e.stat == NFS4ERR_BADOWNER)
1436 					nfs4_log_badowner(VTOMI4(dvp), OP_OPEN);
1437 
1438 				e.error = geterrno4(e.stat);
1439 			}
1440 			kmem_free(argop, argoplist_size);
1441 			return (e.error);
1442 		}
1443 	}
1444 
1445 	rp = VTOR4(vp);
1446 
1447 	mutex_enter(&rp->r_statev4_lock);
1448 	if (create_flag)
1449 		rp->created_v4 = 1;
1450 	mutex_exit(&rp->r_statev4_lock);
1451 
1452 	mutex_enter(&oop->oo_lock);
1453 	/* Doesn't matter if 'oo_just_created' already was set as this */
1454 	oop->oo_just_created = NFS4_PERM_CREATED;
1455 	if (oop->oo_cred_otw)
1456 		crfree(oop->oo_cred_otw);
1457 	oop->oo_cred_otw = cred_otw;
1458 	crhold(oop->oo_cred_otw);
1459 	mutex_exit(&oop->oo_lock);
1460 
1461 	/* returns with 'os_sync_lock' held */
1462 	osp = find_or_create_open_stream(oop, rp, &created_osp);
1463 	if (!osp) {
1464 		NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
1465 		    "nfs4open_otw: failed to create an open stream"));
1466 		NFS4_DEBUG(nfs4_seqid_sync, (CE_NOTE, "nfs4open_otw: "
1467 		    "signal our end of use of the open seqid"));
1468 
1469 		nfs4_end_open_seqid_sync(oop);
1470 		open_owner_rele(oop);
1471 		nfs4args_copen_free(open_args);
1472 		if (setgid_flag) {
1473 			nfs4args_verify_free(&argop[8]);
1474 			nfs4args_setattr_free(&argop[9]);
1475 		}
1476 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1477 		nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1478 		if (create_flag || fh_differs)
1479 			VN_RELE(vp);
1480 		if (ncr != NULL)
1481 			crfree(ncr);
1482 
1483 		kmem_free(argop, argoplist_size);
1484 		return (EINVAL);
1485 
1486 	}
1487 
1488 	osp->open_stateid = op_res->stateid;
1489 
1490 	if (open_flag & FREAD)
1491 		osp->os_share_acc_read++;
1492 	if (open_flag & FWRITE)
1493 		osp->os_share_acc_write++;
1494 	osp->os_share_deny_none++;
1495 
1496 	/*
1497 	 * Need to reset this bitfield for the possible case where we were
1498 	 * going to OTW CLOSE the file, got a non-recoverable error, and before
1499 	 * we could retry the CLOSE, OPENed the file again.
1500 	 */
1501 	ASSERT(osp->os_open_owner->oo_seqid_inuse);
1502 	osp->os_final_close = 0;
1503 	osp->os_force_close = 0;
1504 #ifdef DEBUG
1505 	if (osp->os_failed_reopen)
1506 		NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE, "nfs4open_otw:"
1507 		    " clearing os_failed_reopen for osp %p, cr %p, rp %s",
1508 		    (void *)osp, (void *)cr, rnode4info(rp)));
1509 #endif
1510 	osp->os_failed_reopen = 0;
1511 
1512 	mutex_exit(&osp->os_sync_lock);
1513 
1514 	nfs4_end_open_seqid_sync(oop);
1515 
1516 	if (created_osp && recov_state.rs_sp != NULL) {
1517 		mutex_enter(&recov_state.rs_sp->s_lock);
1518 		nfs4_inc_state_ref_count_nolock(recov_state.rs_sp, VTOMI4(dvp));
1519 		mutex_exit(&recov_state.rs_sp->s_lock);
1520 	}
1521 
1522 	/* get rid of our reference to find oop */
1523 	open_owner_rele(oop);
1524 
1525 	open_stream_rele(osp, rp);
1526 
1527 	/* accept delegation, if any */
1528 	nfs4_delegation_accept(rp, CLAIM_NULL, op_res, garp, cred_otw);
1529 
1530 	nfs4_end_op(VTOMI4(dvp), dvp, vpi, &recov_state, needrecov);
1531 
1532 	if (createmode == EXCLUSIVE4 &&
1533 	    (in_va->va_mask & ~(AT_GID | AT_SIZE))) {
1534 		NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4open_otw:"
1535 		    " EXCLUSIVE4: sending a SETATTR"));
1536 		/*
1537 		 * If doing an exclusive create, then generate
1538 		 * a SETATTR to set the initial attributes.
1539 		 * Try to set the mtime and the atime to the
1540 		 * server's current time.  It is somewhat
1541 		 * expected that these fields will be used to
1542 		 * store the exclusive create cookie.  If not,
1543 		 * server implementors will need to know that
1544 		 * a SETATTR will follow an exclusive create
1545 		 * and the cookie should be destroyed if
1546 		 * appropriate.
1547 		 *
1548 		 * The AT_GID and AT_SIZE bits are turned off
1549 		 * so that the SETATTR request will not attempt
1550 		 * to process these.  The gid will be set
1551 		 * separately if appropriate.  The size is turned
1552 		 * off because it is assumed that a new file will
1553 		 * be created empty and if the file wasn't empty,
1554 		 * then the exclusive create will have failed
1555 		 * because the file must have existed already.
1556 		 * Therefore, no truncate operation is needed.
1557 		 */
1558 		in_va->va_mask &= ~(AT_GID | AT_SIZE);
1559 		in_va->va_mask |= (AT_MTIME | AT_ATIME);
1560 
1561 		e.error = nfs4setattr(vp, in_va, 0, cr, NULL);
1562 		if (e.error) {
1563 			nfs4_error_t err;
1564 
1565 			/*
1566 			 * Couldn't correct the attributes of
1567 			 * the newly created file and the
1568 			 * attributes are wrong.  Remove the
1569 			 * file and return an error to the
1570 			 * application.
1571 			 */
1572 			/* XXX will this take care of client state ? */
1573 			NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
1574 			    "nfs4open_otw: EXCLUSIVE4: error %d on SETATTR:"
1575 			    " remove file", e.error));
1576 
1577 			/*
1578 			 * The file is currently open so try to close it first.
1579 			 *
1580 			 * If we do not close the file explicitly here then the
1581 			 * VN_RELE() would do an (implicit and asynchronous)
1582 			 * close for us.  But such async close could race with
1583 			 * the nfs4_remove() below.  If the async close is
1584 			 * slower than nfs4_remove() then nfs4_remove()
1585 			 * wouldn't remove the file but rename it to .nfsXXXX
1586 			 * instead.
1587 			 */
1588 			nfs4close_one(vp, NULL, cr, open_flag, NULL, &err,
1589 			    CLOSE_NORM, 0, 0, 0);
1590 			VN_RELE(vp);
1591 			(void) nfs4_remove(dvp, file_name, cr, NULL, 0);
1592 
1593 			/*
1594 			 * Since we've reled the vnode and removed
1595 			 * the file we now need to return the error.
1596 			 * At this point we don't want to update the
1597 			 * dircaches, call nfs4_waitfor_purge_complete
1598 			 * or set vpp to vp so we need to skip these
1599 			 * as well.
1600 			 */
1601 			goto skip_update_dircaches;
1602 		}
1603 	}
1604 
1605 	/*
1606 	 * If we created or found the correct vnode, due to create_flag or
1607 	 * fh_differs being set, then update directory cache attribute, readdir
1608 	 * and dnlc caches.
1609 	 */
1610 	if (create_flag || fh_differs) {
1611 		dirattr_info_t dinfo, *dinfop;
1612 
1613 		/*
1614 		 * Make sure getattr succeeded before using results.
1615 		 * note: op 7 is getattr(dir) for both flavors of
1616 		 * open(create).
1617 		 */
1618 		if (create_flag && res.status == NFS4_OK) {
1619 			dinfo.di_time_call = t;
1620 			dinfo.di_cred = cr;
1621 			dinfo.di_garp =
1622 			    &res.array[6].nfs_resop4_u.opgetattr.ga_res;
1623 			dinfop = &dinfo;
1624 		} else {
1625 			dinfop = NULL;
1626 		}
1627 
1628 		nfs4_update_dircaches(&op_res->cinfo, dvp, vp, file_name,
1629 		    dinfop);
1630 	}
1631 
1632 	/*
1633 	 * If the page cache for this file was flushed from actions
1634 	 * above, it was done asynchronously and if that is true,
1635 	 * there is a need to wait here for it to complete.  This must
1636 	 * be done outside of start_fop/end_fop.
1637 	 */
1638 	(void) nfs4_waitfor_purge_complete(vp);
1639 
1640 	/*
1641 	 * It is implicit that we are in the open case (create_flag == 0) since
1642 	 * fh_differs can only be set to a non-zero value in the open case.
1643 	 */
1644 	if (fh_differs != 0 && vpi != NULL)
1645 		VN_RELE(vpi);
1646 
1647 	/*
1648 	 * Be sure to set *vpp to the correct value before returning.
1649 	 */
1650 	*vpp = vp;
1651 
1652 skip_update_dircaches:
1653 
1654 	nfs4args_copen_free(open_args);
1655 	if (setgid_flag) {
1656 		nfs4args_verify_free(&argop[8]);
1657 		nfs4args_setattr_free(&argop[9]);
1658 	}
1659 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1660 
1661 	if (ncr)
1662 		crfree(ncr);
1663 	kmem_free(argop, argoplist_size);
1664 	return (e.error);
1665 }
1666 
1667 /*
1668  * Reopen an open instance.  cf. nfs4open_otw().
1669  *
1670  * Errors are returned by the nfs4_error_t parameter.
1671  * - ep->error contains an errno value or zero.
1672  * - if it is zero, ep->stat is set to an NFS status code, if any.
1673  *   If the file could not be reopened, but the caller should continue, the
1674  *   file is marked dead and no error values are returned.  If the caller
1675  *   should stop recovering open files and start over, either the ep->error
1676  *   value or ep->stat will indicate an error (either something that requires
1677  *   recovery or EAGAIN).  Note that some recovery (e.g., expired volatile
1678  *   filehandles) may be handled silently by this routine.
1679  * - if it is EINTR, ETIMEDOUT, or NFS4_FRC_UNMT_ERR, recovery for lost state
1680  *   will be started, so the caller should not do it.
1681  *
1682  * Gotos:
1683  * - kill_file : reopen failed in such a fashion to constitute marking the
1684  *    file dead and setting the open stream's 'os_failed_reopen' as 1.  This
1685  *   is for cases where recovery is not possible.
1686  * - failed_reopen : same as above, except that the file has already been
1687  *   marked dead, so no need to do it again.
1688  * - bailout : reopen failed but we are able to recover and retry the reopen -
1689  *   either within this function immediately or via the calling function.
1690  */
1691 
1692 void
nfs4_reopen(vnode_t * vp,nfs4_open_stream_t * osp,nfs4_error_t * ep,open_claim_type4 claim,bool_t frc_use_claim_previous,bool_t is_recov)1693 nfs4_reopen(vnode_t *vp, nfs4_open_stream_t *osp, nfs4_error_t *ep,
1694     open_claim_type4 claim, bool_t frc_use_claim_previous,
1695     bool_t is_recov)
1696 {
1697 	COMPOUND4args_clnt args;
1698 	COMPOUND4res_clnt res;
1699 	nfs_argop4 argop[4];
1700 	nfs_resop4 *resop;
1701 	OPEN4res *op_res = NULL;
1702 	OPEN4cargs *open_args;
1703 	GETFH4res *gf_res;
1704 	rnode4_t *rp = VTOR4(vp);
1705 	int doqueue = 1;
1706 	cred_t *cr = NULL, *cred_otw = NULL;
1707 	nfs4_open_owner_t *oop = NULL;
1708 	seqid4 seqid;
1709 	nfs4_ga_res_t *garp;
1710 	char fn[MAXNAMELEN];
1711 	nfs4_recov_state_t recov = {NULL, 0};
1712 	nfs4_lost_rqst_t lost_rqst;
1713 	mntinfo4_t *mi = VTOMI4(vp);
1714 	bool_t abort;
1715 	char *failed_msg = "";
1716 	int fh_different;
1717 	hrtime_t t;
1718 	nfs4_bseqid_entry_t *bsep = NULL;
1719 
1720 	ASSERT(nfs4_consistent_type(vp));
1721 	ASSERT(nfs_zone() == mi->mi_zone);
1722 
1723 	nfs4_error_zinit(ep);
1724 
1725 	/* this is the cred used to find the open owner */
1726 	cr = state_to_cred(osp);
1727 	if (cr == NULL) {
1728 		failed_msg = "Couldn't reopen: no cred";
1729 		goto kill_file;
1730 	}
1731 	/* use this cred for OTW operations */
1732 	cred_otw = nfs4_get_otw_cred(cr, mi, osp->os_open_owner);
1733 
1734 top:
1735 	nfs4_error_zinit(ep);
1736 
1737 	if (mi->mi_vfsp->vfs_flag & VFS_UNMOUNTED) {
1738 		/* File system has been unmounted, quit */
1739 		ep->error = EIO;
1740 		failed_msg = "Couldn't reopen: file system has been unmounted";
1741 		goto kill_file;
1742 	}
1743 
1744 	oop = osp->os_open_owner;
1745 
1746 	ASSERT(oop != NULL);
1747 	if (oop == NULL) {	/* be defensive in non-DEBUG */
1748 		failed_msg = "can't reopen: no open owner";
1749 		goto kill_file;
1750 	}
1751 	open_owner_hold(oop);
1752 
1753 	ep->error = nfs4_start_open_seqid_sync(oop, mi);
1754 	if (ep->error) {
1755 		open_owner_rele(oop);
1756 		oop = NULL;
1757 		goto bailout;
1758 	}
1759 
1760 	/*
1761 	 * If the rnode has a delegation and the delegation has been
1762 	 * recovered and the server didn't request a recall and the caller
1763 	 * didn't specifically ask for CLAIM_PREVIOUS (nfs4frlock during
1764 	 * recovery) and the rnode hasn't been marked dead, then install
1765 	 * the delegation stateid in the open stream.  Otherwise, proceed
1766 	 * with a CLAIM_PREVIOUS or CLAIM_NULL OPEN.
1767 	 */
1768 	mutex_enter(&rp->r_statev4_lock);
1769 	if (rp->r_deleg_type != OPEN_DELEGATE_NONE &&
1770 	    !rp->r_deleg_return_pending &&
1771 	    (rp->r_deleg_needs_recovery == OPEN_DELEGATE_NONE) &&
1772 	    !rp->r_deleg_needs_recall &&
1773 	    claim != CLAIM_DELEGATE_CUR && !frc_use_claim_previous &&
1774 	    !(rp->r_flags & R4RECOVERR)) {
1775 		mutex_enter(&osp->os_sync_lock);
1776 		osp->os_delegation = 1;
1777 		osp->open_stateid = rp->r_deleg_stateid;
1778 		mutex_exit(&osp->os_sync_lock);
1779 		mutex_exit(&rp->r_statev4_lock);
1780 		goto bailout;
1781 	}
1782 	mutex_exit(&rp->r_statev4_lock);
1783 
1784 	/*
1785 	 * If the file failed recovery, just quit.  This failure need not
1786 	 * affect other reopens, so don't return an error.
1787 	 */
1788 	mutex_enter(&rp->r_statelock);
1789 	if (rp->r_flags & R4RECOVERR) {
1790 		mutex_exit(&rp->r_statelock);
1791 		ep->error = 0;
1792 		goto failed_reopen;
1793 	}
1794 	mutex_exit(&rp->r_statelock);
1795 
1796 	/*
1797 	 * argop is empty here
1798 	 *
1799 	 * PUTFH, OPEN, GETATTR
1800 	 */
1801 	args.ctag = TAG_REOPEN;
1802 	args.array_len = 4;
1803 	args.array = argop;
1804 
1805 	NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
1806 	    "nfs4_reopen: file is type %d, id %s",
1807 	    vp->v_type, rnode4info(VTOR4(vp))));
1808 
1809 	argop[0].argop = OP_CPUTFH;
1810 
1811 	if (claim != CLAIM_PREVIOUS) {
1812 		/*
1813 		 * if this is a file mount then
1814 		 * use the mntinfo parentfh
1815 		 */
1816 		argop[0].nfs_argop4_u.opcputfh.sfh =
1817 		    (vp->v_flag & VROOT) ? mi->mi_srvparentfh :
1818 		    VTOSV(vp)->sv_dfh;
1819 	} else {
1820 		/* putfh fh to reopen */
1821 		argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
1822 	}
1823 
1824 	argop[1].argop = OP_COPEN;
1825 	open_args = &argop[1].nfs_argop4_u.opcopen;
1826 	open_args->claim = claim;
1827 
1828 	if (claim == CLAIM_NULL) {
1829 
1830 		if ((ep->error = vtoname(vp, fn, MAXNAMELEN)) != 0) {
1831 			nfs_cmn_err(ep->error, CE_WARN, "nfs4_reopen: vtoname "
1832 			    "failed for vp 0x%p for CLAIM_NULL with %m",
1833 			    (void *)vp);
1834 			failed_msg = "Couldn't reopen: vtoname failed for "
1835 			    "CLAIM_NULL";
1836 			/* nothing allocated yet */
1837 			goto kill_file;
1838 		}
1839 
1840 		open_args->open_claim4_u.cfile = fn;
1841 	} else if (claim == CLAIM_PREVIOUS) {
1842 
1843 		/*
1844 		 * We have two cases to deal with here:
1845 		 * 1) We're being called to reopen files in order to satisfy
1846 		 *    a lock operation request which requires us to explicitly
1847 		 *    reopen files which were opened under a delegation.  If
1848 		 *    we're in recovery, we *must* use CLAIM_PREVIOUS.  In
1849 		 *    that case, frc_use_claim_previous is TRUE and we must
1850 		 *    use the rnode's current delegation type (r_deleg_type).
1851 		 * 2) We're reopening files during some form of recovery.
1852 		 *    In this case, frc_use_claim_previous is FALSE and we
1853 		 *    use the delegation type appropriate for recovery
1854 		 *    (r_deleg_needs_recovery).
1855 		 */
1856 		mutex_enter(&rp->r_statev4_lock);
1857 		open_args->open_claim4_u.delegate_type =
1858 		    frc_use_claim_previous ?
1859 		    rp->r_deleg_type :
1860 		    rp->r_deleg_needs_recovery;
1861 		mutex_exit(&rp->r_statev4_lock);
1862 
1863 	} else if (claim == CLAIM_DELEGATE_CUR) {
1864 
1865 		if ((ep->error = vtoname(vp, fn, MAXNAMELEN)) != 0) {
1866 			nfs_cmn_err(ep->error, CE_WARN, "nfs4_reopen: vtoname "
1867 			    "failed for vp 0x%p for CLAIM_DELEGATE_CUR "
1868 			    "with %m", (void *)vp);
1869 			failed_msg = "Couldn't reopen: vtoname failed for "
1870 			    "CLAIM_DELEGATE_CUR";
1871 			/* nothing allocated yet */
1872 			goto kill_file;
1873 		}
1874 
1875 		mutex_enter(&rp->r_statev4_lock);
1876 		open_args->open_claim4_u.delegate_cur_info.delegate_stateid =
1877 		    rp->r_deleg_stateid;
1878 		mutex_exit(&rp->r_statev4_lock);
1879 
1880 		open_args->open_claim4_u.delegate_cur_info.cfile = fn;
1881 	}
1882 	open_args->opentype = OPEN4_NOCREATE;
1883 	open_args->owner.clientid = mi2clientid(mi);
1884 	open_args->owner.owner_len = sizeof (oop->oo_name);
1885 	open_args->owner.owner_val =
1886 	    kmem_alloc(open_args->owner.owner_len, KM_SLEEP);
1887 	bcopy(&oop->oo_name, open_args->owner.owner_val,
1888 	    open_args->owner.owner_len);
1889 	open_args->share_access = 0;
1890 	open_args->share_deny = 0;
1891 
1892 	mutex_enter(&osp->os_sync_lock);
1893 	NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE, "nfs4_reopen: osp %p rp "
1894 	    "%p: read acc %"PRIu64" write acc %"PRIu64": open ref count %d: "
1895 	    "mmap read %"PRIu64" mmap write %"PRIu64" claim %d ",
1896 	    (void *)osp, (void *)rp, osp->os_share_acc_read,
1897 	    osp->os_share_acc_write, osp->os_open_ref_count,
1898 	    osp->os_mmap_read, osp->os_mmap_write, claim));
1899 
1900 	if (osp->os_share_acc_read || osp->os_mmap_read)
1901 		open_args->share_access |= OPEN4_SHARE_ACCESS_READ;
1902 	if (osp->os_share_acc_write || osp->os_mmap_write)
1903 		open_args->share_access |= OPEN4_SHARE_ACCESS_WRITE;
1904 	if (osp->os_share_deny_read)
1905 		open_args->share_deny |= OPEN4_SHARE_DENY_READ;
1906 	if (osp->os_share_deny_write)
1907 		open_args->share_deny |= OPEN4_SHARE_DENY_WRITE;
1908 	mutex_exit(&osp->os_sync_lock);
1909 
1910 	seqid = nfs4_get_open_seqid(oop) + 1;
1911 	open_args->seqid = seqid;
1912 
1913 	/* Construct the getfh part of the compound */
1914 	argop[2].argop = OP_GETFH;
1915 
1916 	/* Construct the getattr part of the compound */
1917 	argop[3].argop = OP_GETATTR;
1918 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
1919 	argop[3].nfs_argop4_u.opgetattr.mi = mi;
1920 
1921 	t = gethrtime();
1922 
1923 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, ep);
1924 
1925 	if (ep->error) {
1926 		if (!is_recov && !frc_use_claim_previous &&
1927 		    (ep->error == EINTR || ep->error == ETIMEDOUT ||
1928 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp))) {
1929 			nfs4open_save_lost_rqst(ep->error, &lost_rqst, oop,
1930 			    cred_otw, vp, NULL, open_args);
1931 			abort = nfs4_start_recovery(ep,
1932 			    VTOMI4(vp), vp, NULL, NULL,
1933 			    lost_rqst.lr_op == OP_OPEN ?
1934 			    &lost_rqst : NULL, OP_OPEN, NULL, NULL, NULL);
1935 			nfs4args_copen_free(open_args);
1936 			goto bailout;
1937 		}
1938 
1939 		nfs4args_copen_free(open_args);
1940 
1941 		if (ep->error == EACCES && cred_otw != cr) {
1942 			crfree(cred_otw);
1943 			cred_otw = cr;
1944 			crhold(cred_otw);
1945 			nfs4_end_open_seqid_sync(oop);
1946 			open_owner_rele(oop);
1947 			oop = NULL;
1948 			goto top;
1949 		}
1950 		if (ep->error == ETIMEDOUT)
1951 			goto bailout;
1952 		failed_msg = "Couldn't reopen: rpc error";
1953 		goto kill_file;
1954 	}
1955 
1956 	if (nfs4_need_to_bump_seqid(&res))
1957 		nfs4_set_open_seqid(seqid, oop, args.ctag);
1958 
1959 	switch (res.status) {
1960 	case NFS4_OK:
1961 		if (recov.rs_flags & NFS4_RS_DELAY_MSG) {
1962 			mutex_enter(&rp->r_statelock);
1963 			rp->r_delay_interval = 0;
1964 			mutex_exit(&rp->r_statelock);
1965 		}
1966 		break;
1967 	case NFS4ERR_BAD_SEQID:
1968 		bsep = nfs4_create_bseqid_entry(oop, NULL, vp, 0,
1969 		    args.ctag, open_args->seqid);
1970 
1971 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL,
1972 		    NULL, lost_rqst.lr_op == OP_OPEN ? &lost_rqst :
1973 		    NULL, OP_OPEN, bsep, NULL, NULL);
1974 
1975 		nfs4args_copen_free(open_args);
1976 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1977 		nfs4_end_open_seqid_sync(oop);
1978 		open_owner_rele(oop);
1979 		oop = NULL;
1980 		kmem_free(bsep, sizeof (*bsep));
1981 
1982 		goto kill_file;
1983 	case NFS4ERR_NO_GRACE:
1984 		nfs4args_copen_free(open_args);
1985 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
1986 		nfs4_end_open_seqid_sync(oop);
1987 		open_owner_rele(oop);
1988 		oop = NULL;
1989 		if (claim == CLAIM_PREVIOUS) {
1990 			/*
1991 			 * Retry as a plain open. We don't need to worry about
1992 			 * checking the changeinfo: it is acceptable for a
1993 			 * client to re-open a file and continue processing
1994 			 * (in the absence of locks).
1995 			 */
1996 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
1997 			    "nfs4_reopen: CLAIM_PREVIOUS: NFS4ERR_NO_GRACE; "
1998 			    "will retry as CLAIM_NULL"));
1999 			claim = CLAIM_NULL;
2000 			nfs4_mi_kstat_inc_no_grace(mi);
2001 			goto top;
2002 		}
2003 		failed_msg =
2004 		    "Couldn't reopen: tried reclaim outside grace period. ";
2005 		goto kill_file;
2006 	case NFS4ERR_GRACE:
2007 		nfs4_set_grace_wait(mi);
2008 		nfs4args_copen_free(open_args);
2009 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2010 		nfs4_end_open_seqid_sync(oop);
2011 		open_owner_rele(oop);
2012 		oop = NULL;
2013 		ep->error = nfs4_wait_for_grace(mi, &recov);
2014 		if (ep->error != 0)
2015 			goto bailout;
2016 		goto top;
2017 	case NFS4ERR_DELAY:
2018 		nfs4_set_delay_wait(vp);
2019 		nfs4args_copen_free(open_args);
2020 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2021 		nfs4_end_open_seqid_sync(oop);
2022 		open_owner_rele(oop);
2023 		oop = NULL;
2024 		ep->error = nfs4_wait_for_delay(vp, &recov);
2025 		nfs4_mi_kstat_inc_delay(mi);
2026 		if (ep->error != 0)
2027 			goto bailout;
2028 		goto top;
2029 	case NFS4ERR_FHEXPIRED:
2030 		/* recover filehandle and retry */
2031 		abort = nfs4_start_recovery(ep,
2032 		    mi, vp, NULL, NULL, NULL, OP_OPEN, NULL, NULL, NULL);
2033 		nfs4args_copen_free(open_args);
2034 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2035 		nfs4_end_open_seqid_sync(oop);
2036 		open_owner_rele(oop);
2037 		oop = NULL;
2038 		if (abort == FALSE)
2039 			goto top;
2040 		failed_msg = "Couldn't reopen: recovery aborted";
2041 		goto kill_file;
2042 	case NFS4ERR_RESOURCE:
2043 	case NFS4ERR_STALE_CLIENTID:
2044 	case NFS4ERR_WRONGSEC:
2045 	case NFS4ERR_EXPIRED:
2046 		/*
2047 		 * Do not mark the file dead and let the calling
2048 		 * function initiate recovery.
2049 		 */
2050 		nfs4args_copen_free(open_args);
2051 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2052 		nfs4_end_open_seqid_sync(oop);
2053 		open_owner_rele(oop);
2054 		oop = NULL;
2055 		goto bailout;
2056 	case NFS4ERR_ACCESS:
2057 		if (cred_otw != cr) {
2058 			crfree(cred_otw);
2059 			cred_otw = cr;
2060 			crhold(cred_otw);
2061 			nfs4args_copen_free(open_args);
2062 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2063 			nfs4_end_open_seqid_sync(oop);
2064 			open_owner_rele(oop);
2065 			oop = NULL;
2066 			goto top;
2067 		}
2068 		/* fall through */
2069 	default:
2070 		NFS4_DEBUG(nfs4_client_failover_debug, (CE_NOTE,
2071 		    "nfs4_reopen: r_server 0x%p, mi_curr_serv 0x%p, rnode %s",
2072 		    (void*)VTOR4(vp)->r_server, (void*)mi->mi_curr_serv,
2073 		    rnode4info(VTOR4(vp))));
2074 		failed_msg = "Couldn't reopen: NFSv4 error";
2075 		nfs4args_copen_free(open_args);
2076 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2077 		goto kill_file;
2078 	}
2079 
2080 	resop = &res.array[1];  /* open res */
2081 	op_res = &resop->nfs_resop4_u.opopen;
2082 
2083 	garp = &res.array[3].nfs_resop4_u.opgetattr.ga_res;
2084 
2085 	/*
2086 	 * Check if the path we reopened really is the same
2087 	 * file. We could end up in a situation where the file
2088 	 * was removed and a new file created with the same name.
2089 	 */
2090 	resop = &res.array[2];
2091 	gf_res = &resop->nfs_resop4_u.opgetfh;
2092 	(void) nfs_rw_enter_sig(&mi->mi_fh_lock, RW_READER, 0);
2093 	fh_different = (nfs4cmpfh(&rp->r_fh->sfh_fh, &gf_res->object) != 0);
2094 	if (fh_different) {
2095 		if (mi->mi_fh_expire_type == FH4_PERSISTENT ||
2096 		    mi->mi_fh_expire_type & FH4_NOEXPIRE_WITH_OPEN) {
2097 			/* Oops, we don't have the same file */
2098 			if (mi->mi_fh_expire_type == FH4_PERSISTENT)
2099 				failed_msg = "Couldn't reopen: Persistent "
2100 				    "file handle changed";
2101 			else
2102 				failed_msg = "Couldn't reopen: Volatile "
2103 				    "(no expire on open) file handle changed";
2104 
2105 			nfs4args_copen_free(open_args);
2106 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2107 			nfs_rw_exit(&mi->mi_fh_lock);
2108 			goto kill_file;
2109 
2110 		} else {
2111 			/*
2112 			 * We have volatile file handles that don't compare.
2113 			 * If the fids are the same then we assume that the
2114 			 * file handle expired but the rnode still refers to
2115 			 * the same file object.
2116 			 *
2117 			 * First check that we have fids or not.
2118 			 * If we don't we have a dumb server so we will
2119 			 * just assume every thing is ok for now.
2120 			 */
2121 			if (!ep->error && garp->n4g_va.va_mask & AT_NODEID &&
2122 			    rp->r_attr.va_mask & AT_NODEID &&
2123 			    rp->r_attr.va_nodeid != garp->n4g_va.va_nodeid) {
2124 				/*
2125 				 * We have fids, but they don't
2126 				 * compare. So kill the file.
2127 				 */
2128 				failed_msg =
2129 				    "Couldn't reopen: file handle changed"
2130 				    " due to mismatched fids";
2131 				nfs4args_copen_free(open_args);
2132 				(void) xdr_free(xdr_COMPOUND4res_clnt,
2133 				    (caddr_t)&res);
2134 				nfs_rw_exit(&mi->mi_fh_lock);
2135 				goto kill_file;
2136 			} else {
2137 				/*
2138 				 * We have volatile file handles that refers
2139 				 * to the same file (at least they have the
2140 				 * same fid) or we don't have fids so we
2141 				 * can't tell. :(. We'll be a kind and accepting
2142 				 * client so we'll update the rnode's file
2143 				 * handle with the otw handle.
2144 				 *
2145 				 * We need to drop mi->mi_fh_lock since
2146 				 * sh4_update acquires it. Since there is
2147 				 * only one recovery thread there is no
2148 				 * race.
2149 				 */
2150 				nfs_rw_exit(&mi->mi_fh_lock);
2151 				sfh4_update(rp->r_fh, &gf_res->object);
2152 			}
2153 		}
2154 	} else {
2155 		nfs_rw_exit(&mi->mi_fh_lock);
2156 	}
2157 
2158 	ASSERT(nfs4_consistent_type(vp));
2159 
2160 	/*
2161 	 * If the server wanted an OPEN_CONFIRM but that fails, just start
2162 	 * over.  Presumably if there is a persistent error it will show up
2163 	 * when we resend the OPEN.
2164 	 */
2165 	if (op_res->rflags & OPEN4_RESULT_CONFIRM) {
2166 		bool_t retry_open = FALSE;
2167 
2168 		nfs4open_confirm(vp, &seqid, &op_res->stateid,
2169 		    cred_otw, is_recov, &retry_open,
2170 		    oop, FALSE, ep, NULL);
2171 		if (ep->error || ep->stat) {
2172 			nfs4args_copen_free(open_args);
2173 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2174 			nfs4_end_open_seqid_sync(oop);
2175 			open_owner_rele(oop);
2176 			oop = NULL;
2177 			goto top;
2178 		}
2179 	}
2180 
2181 	mutex_enter(&osp->os_sync_lock);
2182 	osp->open_stateid = op_res->stateid;
2183 	osp->os_delegation = 0;
2184 	/*
2185 	 * Need to reset this bitfield for the possible case where we were
2186 	 * going to OTW CLOSE the file, got a non-recoverable error, and before
2187 	 * we could retry the CLOSE, OPENed the file again.
2188 	 */
2189 	ASSERT(osp->os_open_owner->oo_seqid_inuse);
2190 	osp->os_final_close = 0;
2191 	osp->os_force_close = 0;
2192 	if (claim == CLAIM_DELEGATE_CUR || claim == CLAIM_PREVIOUS)
2193 		osp->os_dc_openacc = open_args->share_access;
2194 	mutex_exit(&osp->os_sync_lock);
2195 
2196 	nfs4_end_open_seqid_sync(oop);
2197 
2198 	/* accept delegation, if any */
2199 	nfs4_delegation_accept(rp, claim, op_res, garp, cred_otw);
2200 
2201 	nfs4args_copen_free(open_args);
2202 
2203 	nfs4_attr_cache(vp, garp, t, cr, TRUE, NULL);
2204 
2205 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2206 
2207 	ASSERT(nfs4_consistent_type(vp));
2208 
2209 	open_owner_rele(oop);
2210 	crfree(cr);
2211 	crfree(cred_otw);
2212 	return;
2213 
2214 kill_file:
2215 	nfs4_fail_recov(vp, failed_msg, ep->error, ep->stat);
2216 failed_reopen:
2217 	NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
2218 	    "nfs4_reopen: setting os_failed_reopen for osp %p, cr %p, rp %s",
2219 	    (void *)osp, (void *)cr, rnode4info(rp)));
2220 	mutex_enter(&osp->os_sync_lock);
2221 	osp->os_failed_reopen = 1;
2222 	mutex_exit(&osp->os_sync_lock);
2223 bailout:
2224 	if (oop != NULL) {
2225 		nfs4_end_open_seqid_sync(oop);
2226 		open_owner_rele(oop);
2227 	}
2228 	if (cr != NULL)
2229 		crfree(cr);
2230 	if (cred_otw != NULL)
2231 		crfree(cred_otw);
2232 }
2233 
2234 /* for . and .. OPENs */
2235 /* ARGSUSED */
2236 static int
nfs4_open_non_reg_file(vnode_t ** vpp,int flag,cred_t * cr)2237 nfs4_open_non_reg_file(vnode_t **vpp, int flag, cred_t *cr)
2238 {
2239 	rnode4_t *rp;
2240 	nfs4_ga_res_t gar;
2241 
2242 	ASSERT(nfs_zone() == VTOMI4(*vpp)->mi_zone);
2243 
2244 	/*
2245 	 * If close-to-open consistency checking is turned off or
2246 	 * if there is no cached data, we can avoid
2247 	 * the over the wire getattr.  Otherwise, force a
2248 	 * call to the server to get fresh attributes and to
2249 	 * check caches. This is required for close-to-open
2250 	 * consistency.
2251 	 */
2252 	rp = VTOR4(*vpp);
2253 	if (VTOMI4(*vpp)->mi_flags & MI4_NOCTO ||
2254 	    (rp->r_dir == NULL && !nfs4_has_pages(*vpp)))
2255 		return (0);
2256 
2257 	return (nfs4_getattr_otw(*vpp, &gar, cr, 0));
2258 }
2259 
2260 /*
2261  * CLOSE a file
2262  */
2263 /* ARGSUSED */
2264 static int
nfs4_close(vnode_t * vp,int flag,int count,offset_t offset,cred_t * cr,caller_context_t * ct)2265 nfs4_close(vnode_t *vp, int flag, int count, offset_t offset, cred_t *cr,
2266     caller_context_t *ct)
2267 {
2268 	rnode4_t	*rp;
2269 	int		 error = 0;
2270 	int		 r_error = 0;
2271 	int		 n4error = 0;
2272 	nfs4_error_t	 e = { 0, NFS4_OK, RPC_SUCCESS };
2273 
2274 	/*
2275 	 * Remove client state for this (lockowner, file) pair.
2276 	 * Issue otw v4 call to have the server do the same.
2277 	 */
2278 
2279 	rp = VTOR4(vp);
2280 
2281 	/*
2282 	 * zone_enter(2) prevents processes from changing zones with NFS files
2283 	 * open; if we happen to get here from the wrong zone we can't do
2284 	 * anything over the wire.
2285 	 */
2286 	if (VTOMI4(vp)->mi_zone != nfs_zone()) {
2287 		/*
2288 		 * We could attempt to clean up locks, except we're sure
2289 		 * that the current process didn't acquire any locks on
2290 		 * the file: any attempt to lock a file belong to another zone
2291 		 * will fail, and one can't lock an NFS file and then change
2292 		 * zones, as that fails too.
2293 		 *
2294 		 * Returning an error here is the sane thing to do.  A
2295 		 * subsequent call to VN_RELE() which translates to a
2296 		 * nfs4_inactive() will clean up state: if the zone of the
2297 		 * vnode's origin is still alive and kicking, the inactive
2298 		 * thread will handle the request (from the correct zone), and
2299 		 * everything (minus the OTW close call) should be OK.  If the
2300 		 * zone is going away nfs4_async_inactive() will throw away
2301 		 * delegations, open streams and cached pages inline.
2302 		 */
2303 		return (EIO);
2304 	}
2305 
2306 	/*
2307 	 * If we are using local locking for this filesystem, then
2308 	 * release all of the SYSV style record locks.  Otherwise,
2309 	 * we are doing network locking and we need to release all
2310 	 * of the network locks.  All of the locks held by this
2311 	 * process on this file are released no matter what the
2312 	 * incoming reference count is.
2313 	 */
2314 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK) {
2315 		cleanlocks(vp, ttoproc(curthread)->p_pid, 0);
2316 		cleanshares(vp, ttoproc(curthread)->p_pid);
2317 	} else
2318 		e.error = nfs4_lockrelease(vp, flag, offset, cr);
2319 
2320 	if (e.error) {
2321 		struct lm_sysid *lmsid;
2322 		lmsid = nfs4_find_sysid(VTOMI4(vp));
2323 		if (lmsid == NULL) {
2324 			DTRACE_PROBE2(unknown__sysid, int, e.error,
2325 			    vnode_t *, vp);
2326 		} else {
2327 			cleanlocks(vp, ttoproc(curthread)->p_pid,
2328 			    (lm_sysidt(lmsid) | LM_SYSID_CLIENT));
2329 
2330 			lm_rel_sysid(lmsid);
2331 		}
2332 		return (e.error);
2333 	}
2334 
2335 	if (count > 1)
2336 		return (0);
2337 
2338 	/*
2339 	 * If the file has been `unlinked', then purge the
2340 	 * DNLC so that this vnode will get reycled quicker
2341 	 * and the .nfs* file on the server will get removed.
2342 	 */
2343 	if (rp->r_unldvp != NULL)
2344 		dnlc_purge_vp(vp);
2345 
2346 	/*
2347 	 * If the file was open for write and there are pages,
2348 	 * do a synchronous flush and commit of all of the
2349 	 * dirty and uncommitted pages.
2350 	 */
2351 	ASSERT(!e.error);
2352 	if ((flag & FWRITE) && nfs4_has_pages(vp))
2353 		error = nfs4_putpage_commit(vp, 0, 0, cr);
2354 
2355 	mutex_enter(&rp->r_statelock);
2356 	r_error = rp->r_error;
2357 	rp->r_error = 0;
2358 	mutex_exit(&rp->r_statelock);
2359 
2360 	/*
2361 	 * If this file type is one for which no explicit 'open' was
2362 	 * done, then bail now (ie. no need for protocol 'close'). If
2363 	 * there was an error w/the vm subsystem, return _that_ error,
2364 	 * otherwise, return any errors that may've been reported via
2365 	 * the rnode.
2366 	 */
2367 	if (vp->v_type != VREG)
2368 		return (error ? error : r_error);
2369 
2370 	/*
2371 	 * The sync putpage commit may have failed above, but since
2372 	 * we're working w/a regular file, we need to do the protocol
2373 	 * 'close' (nfs4close_one will figure out if an otw close is
2374 	 * needed or not). Report any errors _after_ doing the protocol
2375 	 * 'close'.
2376 	 */
2377 	nfs4close_one(vp, NULL, cr, flag, NULL, &e, CLOSE_NORM, 0, 0, 0);
2378 	n4error = e.error ? e.error : geterrno4(e.stat);
2379 
2380 	/*
2381 	 * Error reporting prio (Hi -> Lo)
2382 	 *
2383 	 *   i) nfs4_putpage_commit (error)
2384 	 *  ii) rnode's (r_error)
2385 	 * iii) nfs4close_one (n4error)
2386 	 */
2387 	return (error ? error : (r_error ? r_error : n4error));
2388 }
2389 
2390 /*
2391  * Initialize *lost_rqstp.
2392  */
2393 
2394 static void
nfs4close_save_lost_rqst(int error,nfs4_lost_rqst_t * lost_rqstp,nfs4_open_owner_t * oop,nfs4_open_stream_t * osp,cred_t * cr,vnode_t * vp)2395 nfs4close_save_lost_rqst(int error, nfs4_lost_rqst_t *lost_rqstp,
2396     nfs4_open_owner_t *oop, nfs4_open_stream_t *osp, cred_t *cr,
2397     vnode_t *vp)
2398 {
2399 	if (error != ETIMEDOUT && error != EINTR &&
2400 	    !NFS4_FRC_UNMT_ERR(error, vp->v_vfsp)) {
2401 		lost_rqstp->lr_op = 0;
2402 		return;
2403 	}
2404 
2405 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
2406 	    "nfs4close_save_lost_rqst: error %d", error));
2407 
2408 	lost_rqstp->lr_op = OP_CLOSE;
2409 	/*
2410 	 * The vp is held and rele'd via the recovery code.
2411 	 * See nfs4_save_lost_rqst.
2412 	 */
2413 	lost_rqstp->lr_vp = vp;
2414 	lost_rqstp->lr_dvp = NULL;
2415 	lost_rqstp->lr_oop = oop;
2416 	lost_rqstp->lr_osp = osp;
2417 	ASSERT(osp != NULL);
2418 	ASSERT(mutex_owned(&osp->os_sync_lock));
2419 	osp->os_pending_close = 1;
2420 	lost_rqstp->lr_lop = NULL;
2421 	lost_rqstp->lr_cr = cr;
2422 	lost_rqstp->lr_flk = NULL;
2423 	lost_rqstp->lr_putfirst = FALSE;
2424 }
2425 
2426 /*
2427  * Assumes you already have the open seqid sync grabbed as well as the
2428  * 'os_sync_lock'.  Note: this will release the open seqid sync and
2429  * 'os_sync_lock' if client recovery starts.  Calling functions have to
2430  * be prepared to handle this.
2431  *
2432  * 'recov' is returned as 1 if the CLOSE operation detected client recovery
2433  * was needed and was started, and that the calling function should retry
2434  * this function; otherwise it is returned as 0.
2435  *
2436  * Errors are returned via the nfs4_error_t parameter.
2437  */
2438 static void
nfs4close_otw(rnode4_t * rp,cred_t * cred_otw,nfs4_open_owner_t * oop,nfs4_open_stream_t * osp,int * recov,int * did_start_seqid_syncp,nfs4_close_type_t close_type,nfs4_error_t * ep,int * have_sync_lockp)2439 nfs4close_otw(rnode4_t *rp, cred_t *cred_otw, nfs4_open_owner_t *oop,
2440     nfs4_open_stream_t *osp, int *recov, int *did_start_seqid_syncp,
2441     nfs4_close_type_t close_type, nfs4_error_t *ep, int *have_sync_lockp)
2442 {
2443 	COMPOUND4args_clnt args;
2444 	COMPOUND4res_clnt res;
2445 	CLOSE4args *close_args;
2446 	nfs_resop4 *resop;
2447 	nfs_argop4 argop[3];
2448 	int doqueue = 1;
2449 	mntinfo4_t *mi;
2450 	seqid4 seqid;
2451 	vnode_t *vp;
2452 	bool_t needrecov = FALSE;
2453 	nfs4_lost_rqst_t lost_rqst;
2454 	hrtime_t t;
2455 
2456 	ASSERT(nfs_zone() == VTOMI4(RTOV4(rp))->mi_zone);
2457 
2458 	ASSERT(MUTEX_HELD(&osp->os_sync_lock));
2459 
2460 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4close_otw"));
2461 
2462 	/* Only set this to 1 if recovery is started */
2463 	*recov = 0;
2464 
2465 	/* do the OTW call to close the file */
2466 
2467 	if (close_type == CLOSE_RESEND)
2468 		args.ctag = TAG_CLOSE_LOST;
2469 	else if (close_type == CLOSE_AFTER_RESEND)
2470 		args.ctag = TAG_CLOSE_UNDO;
2471 	else
2472 		args.ctag = TAG_CLOSE;
2473 
2474 	args.array_len = 3;
2475 	args.array = argop;
2476 
2477 	vp = RTOV4(rp);
2478 
2479 	mi = VTOMI4(vp);
2480 
2481 	/* putfh target fh */
2482 	argop[0].argop = OP_CPUTFH;
2483 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
2484 
2485 	argop[1].argop = OP_GETATTR;
2486 	argop[1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
2487 	argop[1].nfs_argop4_u.opgetattr.mi = mi;
2488 
2489 	argop[2].argop = OP_CLOSE;
2490 	close_args = &argop[2].nfs_argop4_u.opclose;
2491 
2492 	seqid = nfs4_get_open_seqid(oop) + 1;
2493 
2494 	close_args->seqid = seqid;
2495 	close_args->open_stateid = osp->open_stateid;
2496 
2497 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
2498 	    "nfs4close_otw: %s call, rp %s", needrecov ? "recov" : "first",
2499 	    rnode4info(rp)));
2500 
2501 	t = gethrtime();
2502 
2503 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, ep);
2504 
2505 	if (!ep->error && nfs4_need_to_bump_seqid(&res)) {
2506 		nfs4_set_open_seqid(seqid, oop, args.ctag);
2507 	}
2508 
2509 	needrecov = nfs4_needs_recovery(ep, TRUE, mi->mi_vfsp);
2510 	if (ep->error && !needrecov) {
2511 		/*
2512 		 * if there was an error and no recovery is to be done
2513 		 * then then set up the file to flush its cache if
2514 		 * needed for the next caller.
2515 		 */
2516 		mutex_enter(&rp->r_statelock);
2517 		PURGE_ATTRCACHE4_LOCKED(rp);
2518 		rp->r_flags &= ~R4WRITEMODIFIED;
2519 		mutex_exit(&rp->r_statelock);
2520 		return;
2521 	}
2522 
2523 	if (needrecov) {
2524 		bool_t abort;
2525 		nfs4_bseqid_entry_t *bsep = NULL;
2526 
2527 		if (close_type != CLOSE_RESEND)
2528 			nfs4close_save_lost_rqst(ep->error, &lost_rqst, oop,
2529 			    osp, cred_otw, vp);
2530 
2531 		if (!ep->error && res.status == NFS4ERR_BAD_SEQID)
2532 			bsep = nfs4_create_bseqid_entry(oop, NULL, vp,
2533 			    0, args.ctag, close_args->seqid);
2534 
2535 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
2536 		    "nfs4close_otw: initiating recovery. error %d "
2537 		    "res.status %d", ep->error, res.status));
2538 
2539 		/*
2540 		 * Drop the 'os_sync_lock' here so we don't hit
2541 		 * a potential recursive mutex_enter via an
2542 		 * 'open_stream_hold()'.
2543 		 */
2544 		mutex_exit(&osp->os_sync_lock);
2545 		*have_sync_lockp = 0;
2546 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL, NULL,
2547 		    (close_type != CLOSE_RESEND &&
2548 		    lost_rqst.lr_op == OP_CLOSE) ? &lost_rqst : NULL,
2549 		    OP_CLOSE, bsep, NULL, NULL);
2550 
2551 		/* drop open seq sync, and let the calling function regrab it */
2552 		nfs4_end_open_seqid_sync(oop);
2553 		*did_start_seqid_syncp = 0;
2554 
2555 		if (bsep)
2556 			kmem_free(bsep, sizeof (*bsep));
2557 		/*
2558 		 * For signals, the caller wants to quit, so don't say to
2559 		 * retry.  For forced unmount, if it's a user thread, it
2560 		 * wants to quit.  If it's a recovery thread, the retry
2561 		 * will happen higher-up on the call stack.  Either way,
2562 		 * don't say to retry.
2563 		 */
2564 		if (abort == FALSE && ep->error != EINTR &&
2565 		    !NFS4_FRC_UNMT_ERR(ep->error, mi->mi_vfsp) &&
2566 		    close_type != CLOSE_RESEND &&
2567 		    close_type != CLOSE_AFTER_RESEND)
2568 			*recov = 1;
2569 		else
2570 			*recov = 0;
2571 
2572 		if (!ep->error)
2573 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2574 		return;
2575 	}
2576 
2577 	if (res.status) {
2578 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2579 		return;
2580 	}
2581 
2582 	mutex_enter(&rp->r_statev4_lock);
2583 	rp->created_v4 = 0;
2584 	mutex_exit(&rp->r_statev4_lock);
2585 
2586 	resop = &res.array[2];
2587 	osp->open_stateid = resop->nfs_resop4_u.opclose.open_stateid;
2588 	osp->os_valid = 0;
2589 
2590 	/*
2591 	 * This removes the reference obtained at OPEN; ie, when the
2592 	 * open stream structure was created.
2593 	 *
2594 	 * We don't have to worry about calling 'open_stream_rele'
2595 	 * since we our currently holding a reference to the open
2596 	 * stream which means the count cannot go to 0 with this
2597 	 * decrement.
2598 	 */
2599 	ASSERT(osp->os_ref_count >= 2);
2600 	osp->os_ref_count--;
2601 
2602 	if (ep->error == 0) {
2603 		mutex_exit(&osp->os_sync_lock);
2604 		*have_sync_lockp = 0;
2605 
2606 		nfs4_attr_cache(vp,
2607 		    &res.array[1].nfs_resop4_u.opgetattr.ga_res,
2608 		    t, cred_otw, TRUE, NULL);
2609 	}
2610 
2611 	NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE, "nfs4close_otw:"
2612 	    " returning %d", ep->error));
2613 
2614 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
2615 }
2616 
2617 /* ARGSUSED */
2618 static int
nfs4_read(vnode_t * vp,struct uio * uiop,int ioflag,cred_t * cr,caller_context_t * ct)2619 nfs4_read(vnode_t *vp, struct uio *uiop, int ioflag, cred_t *cr,
2620     caller_context_t *ct)
2621 {
2622 	rnode4_t *rp;
2623 	u_offset_t off;
2624 	offset_t diff;
2625 	uint_t on;
2626 	uint_t n;
2627 	caddr_t base;
2628 	uint_t flags;
2629 	int error;
2630 	mntinfo4_t *mi;
2631 
2632 	rp = VTOR4(vp);
2633 
2634 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
2635 
2636 	if (IS_SHADOW(vp, rp))
2637 		vp = RTOV4(rp);
2638 
2639 	if (vp->v_type != VREG)
2640 		return (EISDIR);
2641 
2642 	mi = VTOMI4(vp);
2643 
2644 	if (nfs_zone() != mi->mi_zone)
2645 		return (EIO);
2646 
2647 	if (uiop->uio_resid == 0)
2648 		return (0);
2649 
2650 	if (uiop->uio_loffset < 0 || uiop->uio_loffset + uiop->uio_resid < 0)
2651 		return (EINVAL);
2652 
2653 	mutex_enter(&rp->r_statelock);
2654 	if (rp->r_flags & R4RECOVERRP)
2655 		error = (rp->r_error ? rp->r_error : EIO);
2656 	else
2657 		error = 0;
2658 	mutex_exit(&rp->r_statelock);
2659 	if (error)
2660 		return (error);
2661 
2662 	/*
2663 	 * Bypass VM if caching has been disabled (e.g., locking) or if
2664 	 * using client-side direct I/O and the file is not mmap'd and
2665 	 * there are no cached pages.
2666 	 */
2667 	if ((vp->v_flag & VNOCACHE) ||
2668 	    (((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO)) &&
2669 	    rp->r_mapcnt == 0 && rp->r_inmap == 0 && !nfs4_has_pages(vp))) {
2670 		size_t resid = 0;
2671 
2672 		return (nfs4read(vp, NULL, uiop->uio_loffset,
2673 		    uiop->uio_resid, &resid, cr, FALSE, uiop));
2674 	}
2675 
2676 	error = 0;
2677 
2678 	do {
2679 		off = uiop->uio_loffset & MAXBMASK; /* mapping offset */
2680 		on = uiop->uio_loffset & MAXBOFFSET; /* Relative offset */
2681 		n = MIN(MAXBSIZE - on, uiop->uio_resid);
2682 
2683 		if (error = nfs4_validate_caches(vp, cr))
2684 			break;
2685 
2686 		mutex_enter(&rp->r_statelock);
2687 		while (rp->r_flags & R4INCACHEPURGE) {
2688 			if (!cv_wait_sig(&rp->r_cv, &rp->r_statelock)) {
2689 				mutex_exit(&rp->r_statelock);
2690 				return (EINTR);
2691 			}
2692 		}
2693 		diff = rp->r_size - uiop->uio_loffset;
2694 		mutex_exit(&rp->r_statelock);
2695 		if (diff <= 0)
2696 			break;
2697 		if (diff < n)
2698 			n = (uint_t)diff;
2699 
2700 		if (vpm_enable) {
2701 			/*
2702 			 * Copy data.
2703 			 */
2704 			error = vpm_data_copy(vp, off + on, n, uiop,
2705 			    1, NULL, 0, S_READ);
2706 		} else {
2707 			base = segmap_getmapflt(segkmap, vp, off + on, n, 1,
2708 			    S_READ);
2709 
2710 			error = uiomove(base + on, n, UIO_READ, uiop);
2711 		}
2712 
2713 		if (!error) {
2714 			/*
2715 			 * If read a whole block or read to eof,
2716 			 * won't need this buffer again soon.
2717 			 */
2718 			mutex_enter(&rp->r_statelock);
2719 			if (n + on == MAXBSIZE ||
2720 			    uiop->uio_loffset == rp->r_size)
2721 				flags = SM_DONTNEED;
2722 			else
2723 				flags = 0;
2724 			mutex_exit(&rp->r_statelock);
2725 			if (vpm_enable) {
2726 				error = vpm_sync_pages(vp, off, n, flags);
2727 			} else {
2728 				error = segmap_release(segkmap, base, flags);
2729 			}
2730 		} else {
2731 			if (vpm_enable) {
2732 				(void) vpm_sync_pages(vp, off, n, 0);
2733 			} else {
2734 				(void) segmap_release(segkmap, base, 0);
2735 			}
2736 		}
2737 	} while (!error && uiop->uio_resid > 0);
2738 
2739 	return (error);
2740 }
2741 
2742 /* ARGSUSED */
2743 static int
nfs4_write(vnode_t * vp,struct uio * uiop,int ioflag,cred_t * cr,caller_context_t * ct)2744 nfs4_write(vnode_t *vp, struct uio *uiop, int ioflag, cred_t *cr,
2745     caller_context_t *ct)
2746 {
2747 	rlim64_t limit = uiop->uio_llimit;
2748 	rnode4_t *rp;
2749 	u_offset_t off;
2750 	caddr_t base;
2751 	uint_t flags;
2752 	int remainder;
2753 	size_t n;
2754 	int on;
2755 	int error;
2756 	int resid;
2757 	u_offset_t offset;
2758 	mntinfo4_t *mi;
2759 	uint_t bsize;
2760 
2761 	rp = VTOR4(vp);
2762 
2763 	if (IS_SHADOW(vp, rp))
2764 		vp = RTOV4(rp);
2765 
2766 	if (vp->v_type != VREG)
2767 		return (EISDIR);
2768 
2769 	mi = VTOMI4(vp);
2770 
2771 	if (nfs_zone() != mi->mi_zone)
2772 		return (EIO);
2773 
2774 	if (uiop->uio_resid == 0)
2775 		return (0);
2776 
2777 	mutex_enter(&rp->r_statelock);
2778 	if (rp->r_flags & R4RECOVERRP)
2779 		error = (rp->r_error ? rp->r_error : EIO);
2780 	else
2781 		error = 0;
2782 	mutex_exit(&rp->r_statelock);
2783 	if (error)
2784 		return (error);
2785 
2786 	if (ioflag & FAPPEND) {
2787 		struct vattr va;
2788 
2789 		/*
2790 		 * Must serialize if appending.
2791 		 */
2792 		if (nfs_rw_lock_held(&rp->r_rwlock, RW_READER)) {
2793 			nfs_rw_exit(&rp->r_rwlock);
2794 			if (nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER,
2795 			    INTR4(vp)))
2796 				return (EINTR);
2797 		}
2798 
2799 		va.va_mask = AT_SIZE;
2800 		error = nfs4getattr(vp, &va, cr);
2801 		if (error)
2802 			return (error);
2803 		uiop->uio_loffset = va.va_size;
2804 	}
2805 
2806 	offset = uiop->uio_loffset + uiop->uio_resid;
2807 
2808 	if (uiop->uio_loffset < (offset_t)0 || offset < 0)
2809 		return (EINVAL);
2810 
2811 	if (limit == RLIM64_INFINITY || limit > MAXOFFSET_T)
2812 		limit = MAXOFFSET_T;
2813 
2814 	/*
2815 	 * Check to make sure that the process will not exceed
2816 	 * its limit on file size.  It is okay to write up to
2817 	 * the limit, but not beyond.  Thus, the write which
2818 	 * reaches the limit will be short and the next write
2819 	 * will return an error.
2820 	 */
2821 	remainder = 0;
2822 	if (offset > uiop->uio_llimit) {
2823 		remainder = offset - uiop->uio_llimit;
2824 		uiop->uio_resid = uiop->uio_llimit - uiop->uio_loffset;
2825 		if (uiop->uio_resid <= 0) {
2826 			proc_t *p = ttoproc(curthread);
2827 
2828 			uiop->uio_resid += remainder;
2829 			mutex_enter(&p->p_lock);
2830 			(void) rctl_action(rctlproc_legacy[RLIMIT_FSIZE],
2831 			    p->p_rctls, p, RCA_UNSAFE_SIGINFO);
2832 			mutex_exit(&p->p_lock);
2833 			return (EFBIG);
2834 		}
2835 	}
2836 
2837 	/* update the change attribute, if we have a write delegation */
2838 
2839 	mutex_enter(&rp->r_statev4_lock);
2840 	if (rp->r_deleg_type == OPEN_DELEGATE_WRITE)
2841 		rp->r_deleg_change++;
2842 
2843 	mutex_exit(&rp->r_statev4_lock);
2844 
2845 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_WRITER, INTR4(vp)))
2846 		return (EINTR);
2847 
2848 	/*
2849 	 * Bypass VM if caching has been disabled (e.g., locking) or if
2850 	 * using client-side direct I/O and the file is not mmap'd and
2851 	 * there are no cached pages.
2852 	 */
2853 	if ((vp->v_flag & VNOCACHE) ||
2854 	    (((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO)) &&
2855 	    rp->r_mapcnt == 0 && rp->r_inmap == 0 && !nfs4_has_pages(vp))) {
2856 		size_t bufsize;
2857 		int count;
2858 		u_offset_t org_offset;
2859 		stable_how4 stab_comm;
2860 nfs4_fwrite:
2861 		if (rp->r_flags & R4STALE) {
2862 			resid = uiop->uio_resid;
2863 			offset = uiop->uio_loffset;
2864 			error = rp->r_error;
2865 			/*
2866 			 * A close may have cleared r_error, if so,
2867 			 * propagate ESTALE error return properly
2868 			 */
2869 			if (error == 0)
2870 				error = ESTALE;
2871 			goto bottom;
2872 		}
2873 
2874 		bufsize = MIN(uiop->uio_resid, mi->mi_stsize);
2875 		base = kmem_alloc(bufsize, KM_SLEEP);
2876 		do {
2877 			if (ioflag & FDSYNC)
2878 				stab_comm = DATA_SYNC4;
2879 			else
2880 				stab_comm = FILE_SYNC4;
2881 			resid = uiop->uio_resid;
2882 			offset = uiop->uio_loffset;
2883 			count = MIN(uiop->uio_resid, bufsize);
2884 			org_offset = uiop->uio_loffset;
2885 			error = uiomove(base, count, UIO_WRITE, uiop);
2886 			if (!error) {
2887 				error = nfs4write(vp, base, org_offset,
2888 				    count, cr, &stab_comm);
2889 				if (!error) {
2890 					mutex_enter(&rp->r_statelock);
2891 					if (rp->r_size < uiop->uio_loffset)
2892 						rp->r_size = uiop->uio_loffset;
2893 					mutex_exit(&rp->r_statelock);
2894 				}
2895 			}
2896 		} while (!error && uiop->uio_resid > 0);
2897 		kmem_free(base, bufsize);
2898 		goto bottom;
2899 	}
2900 
2901 	bsize = vp->v_vfsp->vfs_bsize;
2902 
2903 	do {
2904 		off = uiop->uio_loffset & MAXBMASK; /* mapping offset */
2905 		on = uiop->uio_loffset & MAXBOFFSET; /* Relative offset */
2906 		n = MIN(MAXBSIZE - on, uiop->uio_resid);
2907 
2908 		resid = uiop->uio_resid;
2909 		offset = uiop->uio_loffset;
2910 
2911 		if (rp->r_flags & R4STALE) {
2912 			error = rp->r_error;
2913 			/*
2914 			 * A close may have cleared r_error, if so,
2915 			 * propagate ESTALE error return properly
2916 			 */
2917 			if (error == 0)
2918 				error = ESTALE;
2919 			break;
2920 		}
2921 
2922 		/*
2923 		 * Don't create dirty pages faster than they
2924 		 * can be cleaned so that the system doesn't
2925 		 * get imbalanced.  If the async queue is
2926 		 * maxed out, then wait for it to drain before
2927 		 * creating more dirty pages.  Also, wait for
2928 		 * any threads doing pagewalks in the vop_getattr
2929 		 * entry points so that they don't block for
2930 		 * long periods.
2931 		 */
2932 		mutex_enter(&rp->r_statelock);
2933 		while ((mi->mi_max_threads != 0 &&
2934 		    rp->r_awcount > 2 * mi->mi_max_threads) ||
2935 		    rp->r_gcount > 0) {
2936 			if (INTR4(vp)) {
2937 				klwp_t *lwp = ttolwp(curthread);
2938 
2939 				if (lwp != NULL)
2940 					lwp->lwp_nostop++;
2941 				if (!cv_wait_sig(&rp->r_cv, &rp->r_statelock)) {
2942 					mutex_exit(&rp->r_statelock);
2943 					if (lwp != NULL)
2944 						lwp->lwp_nostop--;
2945 					error = EINTR;
2946 					goto bottom;
2947 				}
2948 				if (lwp != NULL)
2949 					lwp->lwp_nostop--;
2950 			} else
2951 				cv_wait(&rp->r_cv, &rp->r_statelock);
2952 		}
2953 		mutex_exit(&rp->r_statelock);
2954 
2955 		/*
2956 		 * Touch the page and fault it in if it is not in core
2957 		 * before segmap_getmapflt or vpm_data_copy can lock it.
2958 		 * This is to avoid the deadlock if the buffer is mapped
2959 		 * to the same file through mmap which we want to write.
2960 		 */
2961 		uio_prefaultpages((long)n, uiop);
2962 
2963 		if (vpm_enable) {
2964 			/*
2965 			 * It will use kpm mappings, so no need to
2966 			 * pass an address.
2967 			 */
2968 			error = writerp4(rp, NULL, n, uiop, 0);
2969 		} else  {
2970 			if (segmap_kpm) {
2971 				int pon = uiop->uio_loffset & PAGEOFFSET;
2972 				size_t pn = MIN(PAGESIZE - pon,
2973 				    uiop->uio_resid);
2974 				int pagecreate;
2975 
2976 				mutex_enter(&rp->r_statelock);
2977 				pagecreate = (pon == 0) && (pn == PAGESIZE ||
2978 				    uiop->uio_loffset + pn >= rp->r_size);
2979 				mutex_exit(&rp->r_statelock);
2980 
2981 				base = segmap_getmapflt(segkmap, vp, off + on,
2982 				    pn, !pagecreate, S_WRITE);
2983 
2984 				error = writerp4(rp, base + pon, n, uiop,
2985 				    pagecreate);
2986 
2987 			} else {
2988 				base = segmap_getmapflt(segkmap, vp, off + on,
2989 				    n, 0, S_READ);
2990 				error = writerp4(rp, base + on, n, uiop, 0);
2991 			}
2992 		}
2993 
2994 		if (!error) {
2995 			if (mi->mi_flags & MI4_NOAC)
2996 				flags = SM_WRITE;
2997 			else if ((uiop->uio_loffset % bsize) == 0 ||
2998 			    IS_SWAPVP(vp)) {
2999 				/*
3000 				 * Have written a whole block.
3001 				 * Start an asynchronous write
3002 				 * and mark the buffer to
3003 				 * indicate that it won't be
3004 				 * needed again soon.
3005 				 */
3006 				flags = SM_WRITE | SM_ASYNC | SM_DONTNEED;
3007 			} else
3008 				flags = 0;
3009 			if ((ioflag & (FSYNC|FDSYNC)) ||
3010 			    (rp->r_flags & R4OUTOFSPACE)) {
3011 				flags &= ~SM_ASYNC;
3012 				flags |= SM_WRITE;
3013 			}
3014 			if (vpm_enable) {
3015 				error = vpm_sync_pages(vp, off, n, flags);
3016 			} else {
3017 				error = segmap_release(segkmap, base, flags);
3018 			}
3019 		} else {
3020 			if (vpm_enable) {
3021 				(void) vpm_sync_pages(vp, off, n, 0);
3022 			} else {
3023 				(void) segmap_release(segkmap, base, 0);
3024 			}
3025 			/*
3026 			 * In the event that we got an access error while
3027 			 * faulting in a page for a write-only file just
3028 			 * force a write.
3029 			 */
3030 			if (error == EACCES)
3031 				goto nfs4_fwrite;
3032 		}
3033 	} while (!error && uiop->uio_resid > 0);
3034 
3035 bottom:
3036 	if (error) {
3037 		uiop->uio_resid = resid + remainder;
3038 		uiop->uio_loffset = offset;
3039 	} else {
3040 		uiop->uio_resid += remainder;
3041 
3042 		mutex_enter(&rp->r_statev4_lock);
3043 		if (rp->r_deleg_type == OPEN_DELEGATE_WRITE) {
3044 			gethrestime(&rp->r_attr.va_mtime);
3045 			rp->r_attr.va_ctime = rp->r_attr.va_mtime;
3046 		}
3047 		mutex_exit(&rp->r_statev4_lock);
3048 	}
3049 
3050 	nfs_rw_exit(&rp->r_lkserlock);
3051 
3052 	return (error);
3053 }
3054 
3055 /*
3056  * Flags are composed of {B_ASYNC, B_INVAL, B_FREE, B_DONTNEED}
3057  */
3058 static int
nfs4_rdwrlbn(vnode_t * vp,page_t * pp,u_offset_t off,size_t len,int flags,cred_t * cr)3059 nfs4_rdwrlbn(vnode_t *vp, page_t *pp, u_offset_t off, size_t len,
3060     int flags, cred_t *cr)
3061 {
3062 	struct buf *bp;
3063 	int error;
3064 	page_t *savepp;
3065 	uchar_t fsdata;
3066 	stable_how4 stab_comm;
3067 
3068 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
3069 	bp = pageio_setup(pp, len, vp, flags);
3070 	ASSERT(bp != NULL);
3071 
3072 	/*
3073 	 * pageio_setup should have set b_addr to 0.  This
3074 	 * is correct since we want to do I/O on a page
3075 	 * boundary.  bp_mapin will use this addr to calculate
3076 	 * an offset, and then set b_addr to the kernel virtual
3077 	 * address it allocated for us.
3078 	 */
3079 	ASSERT(bp->b_un.b_addr == 0);
3080 
3081 	bp->b_edev = 0;
3082 	bp->b_dev = 0;
3083 	bp->b_lblkno = lbtodb(off);
3084 	bp->b_file = vp;
3085 	bp->b_offset = (offset_t)off;
3086 	bp_mapin(bp);
3087 
3088 	if ((flags & (B_WRITE|B_ASYNC)) == (B_WRITE|B_ASYNC) &&
3089 	    freemem > desfree)
3090 		stab_comm = UNSTABLE4;
3091 	else
3092 		stab_comm = FILE_SYNC4;
3093 
3094 	error = nfs4_bio(bp, &stab_comm, cr, FALSE);
3095 
3096 	bp_mapout(bp);
3097 	pageio_done(bp);
3098 
3099 	if (stab_comm == UNSTABLE4)
3100 		fsdata = C_DELAYCOMMIT;
3101 	else
3102 		fsdata = C_NOCOMMIT;
3103 
3104 	savepp = pp;
3105 	do {
3106 		pp->p_fsdata = fsdata;
3107 	} while ((pp = pp->p_next) != savepp);
3108 
3109 	return (error);
3110 }
3111 
3112 /*
3113  */
3114 static int
nfs4rdwr_check_osid(vnode_t * vp,nfs4_error_t * ep,cred_t * cr)3115 nfs4rdwr_check_osid(vnode_t *vp, nfs4_error_t *ep, cred_t *cr)
3116 {
3117 	nfs4_open_owner_t	*oop;
3118 	nfs4_open_stream_t	*osp;
3119 	rnode4_t		*rp = VTOR4(vp);
3120 	mntinfo4_t		*mi = VTOMI4(vp);
3121 	int			reopen_needed;
3122 
3123 	ASSERT(nfs_zone() == mi->mi_zone);
3124 
3125 
3126 	oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
3127 	if (!oop)
3128 		return (EIO);
3129 
3130 	/* returns with 'os_sync_lock' held */
3131 	osp = find_open_stream(oop, rp);
3132 	if (!osp) {
3133 		open_owner_rele(oop);
3134 		return (EIO);
3135 	}
3136 
3137 	if (osp->os_failed_reopen) {
3138 		mutex_exit(&osp->os_sync_lock);
3139 		open_stream_rele(osp, rp);
3140 		open_owner_rele(oop);
3141 		return (EIO);
3142 	}
3143 
3144 	/*
3145 	 * Determine whether a reopen is needed.  If this
3146 	 * is a delegation open stream, then the os_delegation bit
3147 	 * should be set.
3148 	 */
3149 
3150 	reopen_needed = osp->os_delegation;
3151 
3152 	mutex_exit(&osp->os_sync_lock);
3153 	open_owner_rele(oop);
3154 
3155 	if (reopen_needed) {
3156 		nfs4_error_zinit(ep);
3157 		nfs4_reopen(vp, osp, ep, CLAIM_NULL, FALSE, FALSE);
3158 		mutex_enter(&osp->os_sync_lock);
3159 		if (ep->error || ep->stat || osp->os_failed_reopen) {
3160 			mutex_exit(&osp->os_sync_lock);
3161 			open_stream_rele(osp, rp);
3162 			return (EIO);
3163 		}
3164 		mutex_exit(&osp->os_sync_lock);
3165 	}
3166 	open_stream_rele(osp, rp);
3167 
3168 	return (0);
3169 }
3170 
3171 /*
3172  * Write to file.  Writes to remote server in largest size
3173  * chunks that the server can handle.  Write is synchronous.
3174  */
3175 static int
nfs4write(vnode_t * vp,caddr_t base,u_offset_t offset,int count,cred_t * cr,stable_how4 * stab_comm)3176 nfs4write(vnode_t *vp, caddr_t base, u_offset_t offset, int count, cred_t *cr,
3177     stable_how4 *stab_comm)
3178 {
3179 	mntinfo4_t *mi;
3180 	COMPOUND4args_clnt args;
3181 	COMPOUND4res_clnt res;
3182 	WRITE4args *wargs;
3183 	WRITE4res *wres;
3184 	nfs_argop4 argop[2];
3185 	nfs_resop4 *resop;
3186 	int tsize;
3187 	stable_how4 stable;
3188 	rnode4_t *rp;
3189 	int doqueue = 1;
3190 	bool_t needrecov;
3191 	nfs4_recov_state_t recov_state;
3192 	nfs4_stateid_types_t sid_types;
3193 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3194 	int recov;
3195 
3196 	rp = VTOR4(vp);
3197 	mi = VTOMI4(vp);
3198 
3199 	ASSERT(nfs_zone() == mi->mi_zone);
3200 
3201 	stable = *stab_comm;
3202 	*stab_comm = FILE_SYNC4;
3203 
3204 	needrecov = FALSE;
3205 	recov_state.rs_flags = 0;
3206 	recov_state.rs_num_retry_despite_err = 0;
3207 	nfs4_init_stateid_types(&sid_types);
3208 
3209 	/* Is curthread the recovery thread? */
3210 	mutex_enter(&mi->mi_lock);
3211 	recov = (mi->mi_recovthread == curthread);
3212 	mutex_exit(&mi->mi_lock);
3213 
3214 recov_retry:
3215 	args.ctag = TAG_WRITE;
3216 	args.array_len = 2;
3217 	args.array = argop;
3218 
3219 	if (!recov) {
3220 		e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3221 		    &recov_state, NULL);
3222 		if (e.error)
3223 			return (e.error);
3224 	}
3225 
3226 	/* 0. putfh target fh */
3227 	argop[0].argop = OP_CPUTFH;
3228 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3229 
3230 	/* 1. write */
3231 	nfs4args_write(&argop[1], stable, rp, cr, &wargs, &sid_types);
3232 
3233 	do {
3234 
3235 		wargs->offset = (offset4)offset;
3236 		wargs->data_val = base;
3237 
3238 		if (mi->mi_io_kstats) {
3239 			mutex_enter(&mi->mi_lock);
3240 			kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
3241 			mutex_exit(&mi->mi_lock);
3242 		}
3243 
3244 		if ((vp->v_flag & VNOCACHE) ||
3245 		    (rp->r_flags & R4DIRECTIO) ||
3246 		    (mi->mi_flags & MI4_DIRECTIO))
3247 			tsize = MIN(mi->mi_stsize, count);
3248 		else
3249 			tsize = MIN(mi->mi_curwrite, count);
3250 		wargs->data_len = (uint_t)tsize;
3251 		rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
3252 
3253 		if (mi->mi_io_kstats) {
3254 			mutex_enter(&mi->mi_lock);
3255 			kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
3256 			mutex_exit(&mi->mi_lock);
3257 		}
3258 
3259 		if (!recov) {
3260 			needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
3261 			if (e.error && !needrecov) {
3262 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3263 				    &recov_state, needrecov);
3264 				return (e.error);
3265 			}
3266 		} else {
3267 			if (e.error)
3268 				return (e.error);
3269 		}
3270 
3271 		/*
3272 		 * Do handling of OLD_STATEID outside
3273 		 * of the normal recovery framework.
3274 		 *
3275 		 * If write receives a BAD stateid error while using a
3276 		 * delegation stateid, retry using the open stateid (if it
3277 		 * exists).  If it doesn't have an open stateid, reopen the
3278 		 * file first, then retry.
3279 		 */
3280 		if (!e.error && res.status == NFS4ERR_OLD_STATEID &&
3281 		    sid_types.cur_sid_type != SPEC_SID) {
3282 			nfs4_save_stateid(&wargs->stateid, &sid_types);
3283 			if (!recov)
3284 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3285 				    &recov_state, needrecov);
3286 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3287 			goto recov_retry;
3288 		} else if (e.error == 0 && res.status == NFS4ERR_BAD_STATEID &&
3289 		    sid_types.cur_sid_type == DEL_SID) {
3290 			nfs4_save_stateid(&wargs->stateid, &sid_types);
3291 			mutex_enter(&rp->r_statev4_lock);
3292 			rp->r_deleg_return_pending = TRUE;
3293 			mutex_exit(&rp->r_statev4_lock);
3294 			if (nfs4rdwr_check_osid(vp, &e, cr)) {
3295 				if (!recov)
3296 					nfs4_end_fop(mi, vp, NULL, OH_WRITE,
3297 					    &recov_state, needrecov);
3298 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3299 				    (caddr_t)&res);
3300 				return (EIO);
3301 			}
3302 			if (!recov)
3303 				nfs4_end_fop(mi, vp, NULL, OH_WRITE,
3304 				    &recov_state, needrecov);
3305 			/* hold needed for nfs4delegreturn_thread */
3306 			VN_HOLD(vp);
3307 			nfs4delegreturn_async(rp, (NFS4_DR_PUSH|NFS4_DR_REOPEN|
3308 			    NFS4_DR_DISCARD), FALSE);
3309 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3310 			goto recov_retry;
3311 		}
3312 
3313 		if (needrecov) {
3314 			bool_t abort;
3315 
3316 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
3317 			    "nfs4write: client got error %d, res.status %d"
3318 			    ", so start recovery", e.error, res.status));
3319 
3320 			abort = nfs4_start_recovery(&e,
3321 			    VTOMI4(vp), vp, NULL, &wargs->stateid,
3322 			    NULL, OP_WRITE, NULL, NULL, NULL);
3323 			if (!e.error) {
3324 				e.error = geterrno4(res.status);
3325 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3326 				    (caddr_t)&res);
3327 			}
3328 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3329 			    &recov_state, needrecov);
3330 			if (abort == FALSE)
3331 				goto recov_retry;
3332 			return (e.error);
3333 		}
3334 
3335 		if (res.status) {
3336 			e.error = geterrno4(res.status);
3337 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3338 			if (!recov)
3339 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3340 				    &recov_state, needrecov);
3341 			return (e.error);
3342 		}
3343 
3344 		resop = &res.array[1];	/* write res */
3345 		wres = &resop->nfs_resop4_u.opwrite;
3346 
3347 		if ((int)wres->count > tsize) {
3348 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3349 
3350 			zcmn_err(getzoneid(), CE_WARN,
3351 			    "nfs4write: server wrote %u, requested was %u",
3352 			    (int)wres->count, tsize);
3353 			if (!recov)
3354 				nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE,
3355 				    &recov_state, needrecov);
3356 			return (EIO);
3357 		}
3358 		if (wres->committed == UNSTABLE4) {
3359 			*stab_comm = UNSTABLE4;
3360 			if (wargs->stable == DATA_SYNC4 ||
3361 			    wargs->stable == FILE_SYNC4) {
3362 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3363 				    (caddr_t)&res);
3364 				zcmn_err(getzoneid(), CE_WARN,
3365 				    "nfs4write: server %s did not commit "
3366 				    "to stable storage",
3367 				    rp->r_server->sv_hostname);
3368 				if (!recov)
3369 					nfs4_end_fop(VTOMI4(vp), vp, NULL,
3370 					    OH_WRITE, &recov_state, needrecov);
3371 				return (EIO);
3372 			}
3373 		}
3374 
3375 		tsize = (int)wres->count;
3376 		count -= tsize;
3377 		base += tsize;
3378 		offset += tsize;
3379 		if (mi->mi_io_kstats) {
3380 			mutex_enter(&mi->mi_lock);
3381 			KSTAT_IO_PTR(mi->mi_io_kstats)->writes++;
3382 			KSTAT_IO_PTR(mi->mi_io_kstats)->nwritten +=
3383 			    tsize;
3384 			mutex_exit(&mi->mi_lock);
3385 		}
3386 		lwp_stat_update(LWP_STAT_OUBLK, 1);
3387 		mutex_enter(&rp->r_statelock);
3388 		if (rp->r_flags & R4HAVEVERF) {
3389 			if (rp->r_writeverf != wres->writeverf) {
3390 				nfs4_set_mod(vp);
3391 				rp->r_writeverf = wres->writeverf;
3392 			}
3393 		} else {
3394 			rp->r_writeverf = wres->writeverf;
3395 			rp->r_flags |= R4HAVEVERF;
3396 		}
3397 		PURGE_ATTRCACHE4_LOCKED(rp);
3398 		rp->r_flags |= R4WRITEMODIFIED;
3399 		gethrestime(&rp->r_attr.va_mtime);
3400 		rp->r_attr.va_ctime = rp->r_attr.va_mtime;
3401 		mutex_exit(&rp->r_statelock);
3402 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3403 	} while (count);
3404 
3405 	if (!recov)
3406 		nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_WRITE, &recov_state,
3407 		    needrecov);
3408 
3409 	return (e.error);
3410 }
3411 
3412 /*
3413  * Read from a file.  Reads data in largest chunks our interface can handle.
3414  */
3415 static int
nfs4read(vnode_t * vp,caddr_t base,offset_t offset,int count,size_t * residp,cred_t * cr,bool_t async,struct uio * uiop)3416 nfs4read(vnode_t *vp, caddr_t base, offset_t offset, int count,
3417     size_t *residp, cred_t *cr, bool_t async, struct uio *uiop)
3418 {
3419 	mntinfo4_t *mi;
3420 	COMPOUND4args_clnt args;
3421 	COMPOUND4res_clnt res;
3422 	READ4args *rargs;
3423 	nfs_argop4 argop[2];
3424 	int tsize;
3425 	int doqueue;
3426 	rnode4_t *rp;
3427 	int data_len;
3428 	bool_t is_eof;
3429 	bool_t needrecov = FALSE;
3430 	nfs4_recov_state_t recov_state;
3431 	nfs4_stateid_types_t sid_types;
3432 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3433 
3434 	rp = VTOR4(vp);
3435 	mi = VTOMI4(vp);
3436 	doqueue = 1;
3437 
3438 	ASSERT(nfs_zone() == mi->mi_zone);
3439 
3440 	args.ctag = async ? TAG_READAHEAD : TAG_READ;
3441 
3442 	args.array_len = 2;
3443 	args.array = argop;
3444 
3445 	nfs4_init_stateid_types(&sid_types);
3446 
3447 	recov_state.rs_flags = 0;
3448 	recov_state.rs_num_retry_despite_err = 0;
3449 
3450 recov_retry:
3451 	e.error = nfs4_start_fop(mi, vp, NULL, OH_READ,
3452 	    &recov_state, NULL);
3453 	if (e.error)
3454 		return (e.error);
3455 
3456 	/* putfh target fh */
3457 	argop[0].argop = OP_CPUTFH;
3458 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3459 
3460 	/* read */
3461 	argop[1].argop = OP_READ;
3462 	rargs = &argop[1].nfs_argop4_u.opread;
3463 	rargs->stateid = nfs4_get_stateid(cr, rp, curproc->p_pidp->pid_id, mi,
3464 	    OP_READ, &sid_types, async);
3465 
3466 	do {
3467 		if (mi->mi_io_kstats) {
3468 			mutex_enter(&mi->mi_lock);
3469 			kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
3470 			mutex_exit(&mi->mi_lock);
3471 		}
3472 
3473 		NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
3474 		    "nfs4read: %s call, rp %s",
3475 		    needrecov ? "recov" : "first",
3476 		    rnode4info(rp)));
3477 
3478 		if ((vp->v_flag & VNOCACHE) ||
3479 		    (rp->r_flags & R4DIRECTIO) ||
3480 		    (mi->mi_flags & MI4_DIRECTIO))
3481 			tsize = MIN(mi->mi_tsize, count);
3482 		else
3483 			tsize = MIN(mi->mi_curread, count);
3484 
3485 		rargs->offset = (offset4)offset;
3486 		rargs->count = (count4)tsize;
3487 		rargs->res_data_val_alt = NULL;
3488 		rargs->res_mblk = NULL;
3489 		rargs->res_uiop = NULL;
3490 		rargs->res_maxsize = 0;
3491 		rargs->wlist = NULL;
3492 
3493 		if (uiop)
3494 			rargs->res_uiop = uiop;
3495 		else
3496 			rargs->res_data_val_alt = base;
3497 		rargs->res_maxsize = tsize;
3498 
3499 		rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
3500 #ifdef	DEBUG
3501 		if (nfs4read_error_inject) {
3502 			res.status = nfs4read_error_inject;
3503 			nfs4read_error_inject = 0;
3504 		}
3505 #endif
3506 
3507 		if (mi->mi_io_kstats) {
3508 			mutex_enter(&mi->mi_lock);
3509 			kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
3510 			mutex_exit(&mi->mi_lock);
3511 		}
3512 
3513 		needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
3514 		if (e.error != 0 && !needrecov) {
3515 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3516 			    &recov_state, needrecov);
3517 			return (e.error);
3518 		}
3519 
3520 		/*
3521 		 * Do proper retry for OLD and BAD stateid errors outside
3522 		 * of the normal recovery framework.  There are two differences
3523 		 * between async and sync reads.  The first is that we allow
3524 		 * retry on BAD_STATEID for async reads, but not sync reads.
3525 		 * The second is that we mark the file dead for a failed
3526 		 * attempt with a special stateid for sync reads, but just
3527 		 * return EIO for async reads.
3528 		 *
3529 		 * If a sync read receives a BAD stateid error while using a
3530 		 * delegation stateid, retry using the open stateid (if it
3531 		 * exists).  If it doesn't have an open stateid, reopen the
3532 		 * file first, then retry.
3533 		 */
3534 		if (e.error == 0 && (res.status == NFS4ERR_OLD_STATEID ||
3535 		    res.status == NFS4ERR_BAD_STATEID) && async) {
3536 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3537 			    &recov_state, needrecov);
3538 			if (sid_types.cur_sid_type == SPEC_SID) {
3539 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3540 				    (caddr_t)&res);
3541 				return (EIO);
3542 			}
3543 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3544 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3545 			goto recov_retry;
3546 		} else if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3547 		    !async && sid_types.cur_sid_type != SPEC_SID) {
3548 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3549 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3550 			    &recov_state, needrecov);
3551 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3552 			goto recov_retry;
3553 		} else if (e.error == 0 && res.status == NFS4ERR_BAD_STATEID &&
3554 		    sid_types.cur_sid_type == DEL_SID) {
3555 			nfs4_save_stateid(&rargs->stateid, &sid_types);
3556 			mutex_enter(&rp->r_statev4_lock);
3557 			rp->r_deleg_return_pending = TRUE;
3558 			mutex_exit(&rp->r_statev4_lock);
3559 			if (nfs4rdwr_check_osid(vp, &e, cr)) {
3560 				nfs4_end_fop(mi, vp, NULL, OH_READ,
3561 				    &recov_state, needrecov);
3562 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3563 				    (caddr_t)&res);
3564 				return (EIO);
3565 			}
3566 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3567 			    &recov_state, needrecov);
3568 			/* hold needed for nfs4delegreturn_thread */
3569 			VN_HOLD(vp);
3570 			nfs4delegreturn_async(rp, (NFS4_DR_PUSH|NFS4_DR_REOPEN|
3571 			    NFS4_DR_DISCARD), FALSE);
3572 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3573 			goto recov_retry;
3574 		}
3575 		if (needrecov) {
3576 			bool_t abort;
3577 
3578 			NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
3579 			    "nfs4read: initiating recovery\n"));
3580 			abort = nfs4_start_recovery(&e,
3581 			    mi, vp, NULL, &rargs->stateid,
3582 			    NULL, OP_READ, NULL, NULL, NULL);
3583 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3584 			    &recov_state, needrecov);
3585 			/*
3586 			 * Do not retry if we got OLD_STATEID using a special
3587 			 * stateid.  This avoids looping with a broken server.
3588 			 */
3589 			if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
3590 			    sid_types.cur_sid_type == SPEC_SID)
3591 				abort = TRUE;
3592 
3593 			if (abort == FALSE) {
3594 				/*
3595 				 * Need to retry all possible stateids in
3596 				 * case the recovery error wasn't stateid
3597 				 * related or the stateids have become
3598 				 * stale (server reboot).
3599 				 */
3600 				nfs4_init_stateid_types(&sid_types);
3601 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3602 				    (caddr_t)&res);
3603 				goto recov_retry;
3604 			}
3605 
3606 			if (!e.error) {
3607 				e.error = geterrno4(res.status);
3608 				(void) xdr_free(xdr_COMPOUND4res_clnt,
3609 				    (caddr_t)&res);
3610 			}
3611 			return (e.error);
3612 		}
3613 
3614 		if (res.status) {
3615 			e.error = geterrno4(res.status);
3616 			nfs4_end_fop(mi, vp, NULL, OH_READ,
3617 			    &recov_state, needrecov);
3618 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3619 			return (e.error);
3620 		}
3621 
3622 		data_len = res.array[1].nfs_resop4_u.opread.data_len;
3623 		count -= data_len;
3624 		if (base)
3625 			base += data_len;
3626 		offset += data_len;
3627 		if (mi->mi_io_kstats) {
3628 			mutex_enter(&mi->mi_lock);
3629 			KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
3630 			KSTAT_IO_PTR(mi->mi_io_kstats)->nread += data_len;
3631 			mutex_exit(&mi->mi_lock);
3632 		}
3633 		lwp_stat_update(LWP_STAT_INBLK, 1);
3634 		is_eof = res.array[1].nfs_resop4_u.opread.eof;
3635 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
3636 
3637 	} while (count && !is_eof);
3638 
3639 	*residp = count;
3640 
3641 	nfs4_end_fop(mi, vp, NULL, OH_READ, &recov_state, needrecov);
3642 
3643 	return (e.error);
3644 }
3645 
3646 /* ARGSUSED */
3647 static int
nfs4_ioctl(vnode_t * vp,int cmd,intptr_t arg,int flag,cred_t * cr,int * rvalp,caller_context_t * ct)3648 nfs4_ioctl(vnode_t *vp, int cmd, intptr_t arg, int flag, cred_t *cr, int *rvalp,
3649     caller_context_t *ct)
3650 {
3651 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3652 		return (EIO);
3653 	switch (cmd) {
3654 		case _FIODIRECTIO:
3655 			return (nfs4_directio(vp, (int)arg, cr));
3656 		default:
3657 			return (ENOTTY);
3658 	}
3659 }
3660 
3661 /* ARGSUSED */
3662 int
nfs4_getattr(vnode_t * vp,struct vattr * vap,int flags,cred_t * cr,caller_context_t * ct)3663 nfs4_getattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3664     caller_context_t *ct)
3665 {
3666 	int error;
3667 	rnode4_t *rp = VTOR4(vp);
3668 
3669 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3670 		return (EIO);
3671 	/*
3672 	 * If it has been specified that the return value will
3673 	 * just be used as a hint, and we are only being asked
3674 	 * for size, fsid or rdevid, then return the client's
3675 	 * notion of these values without checking to make sure
3676 	 * that the attribute cache is up to date.
3677 	 * The whole point is to avoid an over the wire GETATTR
3678 	 * call.
3679 	 */
3680 	if (flags & ATTR_HINT) {
3681 		if (!(vap->va_mask & ~(AT_SIZE | AT_FSID | AT_RDEV))) {
3682 			mutex_enter(&rp->r_statelock);
3683 			if (vap->va_mask & AT_SIZE)
3684 				vap->va_size = rp->r_size;
3685 			if (vap->va_mask & AT_FSID)
3686 				vap->va_fsid = rp->r_attr.va_fsid;
3687 			if (vap->va_mask & AT_RDEV)
3688 				vap->va_rdev = rp->r_attr.va_rdev;
3689 			mutex_exit(&rp->r_statelock);
3690 			return (0);
3691 		}
3692 	}
3693 
3694 	/*
3695 	 * Only need to flush pages if asking for the mtime
3696 	 * and if there any dirty pages or any outstanding
3697 	 * asynchronous (write) requests for this file.
3698 	 */
3699 	if (vap->va_mask & AT_MTIME) {
3700 		rp = VTOR4(vp);
3701 		if (nfs4_has_pages(vp)) {
3702 			mutex_enter(&rp->r_statev4_lock);
3703 			if (rp->r_deleg_type != OPEN_DELEGATE_WRITE) {
3704 				mutex_exit(&rp->r_statev4_lock);
3705 				if (rp->r_flags & R4DIRTY ||
3706 				    rp->r_awcount > 0) {
3707 					mutex_enter(&rp->r_statelock);
3708 					rp->r_gcount++;
3709 					mutex_exit(&rp->r_statelock);
3710 					error =
3711 					    nfs4_putpage(vp, (u_offset_t)0,
3712 					    0, 0, cr, NULL);
3713 					mutex_enter(&rp->r_statelock);
3714 					if (error && (error == ENOSPC ||
3715 					    error == EDQUOT)) {
3716 						if (!rp->r_error)
3717 							rp->r_error = error;
3718 					}
3719 					if (--rp->r_gcount == 0)
3720 						cv_broadcast(&rp->r_cv);
3721 					mutex_exit(&rp->r_statelock);
3722 				}
3723 			} else {
3724 				mutex_exit(&rp->r_statev4_lock);
3725 			}
3726 		}
3727 	}
3728 	return (nfs4getattr(vp, vap, cr));
3729 }
3730 
3731 int
nfs4_compare_modes(mode_t from_server,mode_t on_client)3732 nfs4_compare_modes(mode_t from_server, mode_t on_client)
3733 {
3734 	/*
3735 	 * If these are the only two bits cleared
3736 	 * on the server then return 0 (OK) else
3737 	 * return 1 (BAD).
3738 	 */
3739 	on_client &= ~(S_ISUID|S_ISGID);
3740 	if (on_client == from_server)
3741 		return (0);
3742 	else
3743 		return (1);
3744 }
3745 
3746 /*ARGSUSED4*/
3747 static int
nfs4_setattr(vnode_t * vp,struct vattr * vap,int flags,cred_t * cr,caller_context_t * ct)3748 nfs4_setattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3749     caller_context_t *ct)
3750 {
3751 	int error;
3752 
3753 	if (vap->va_mask & AT_NOSET)
3754 		return (EINVAL);
3755 
3756 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
3757 		return (EIO);
3758 
3759 	/*
3760 	 * Don't call secpolicy_vnode_setattr, the client cannot
3761 	 * use its cached attributes to make security decisions
3762 	 * as the server may be faking mode bits or mapping uid/gid.
3763 	 * Always just let the server to the checking.
3764 	 * If we provide the ability to remove basic priviledges
3765 	 * to setattr (e.g. basic without chmod) then we will
3766 	 * need to add a check here before calling the server.
3767 	 */
3768 	error = nfs4setattr(vp, vap, flags, cr, NULL);
3769 
3770 	if (error == 0 && (vap->va_mask & AT_SIZE) && vap->va_size == 0)
3771 		vnevent_truncate(vp, ct);
3772 
3773 	return (error);
3774 }
3775 
3776 /*
3777  * To replace the "guarded" version 3 setattr, we use two types of compound
3778  * setattr requests:
3779  * 1. The "normal" setattr, used when the size of the file isn't being
3780  *    changed - { Putfh <fh>; Setattr; Getattr }/
3781  * 2. If the size is changed, precede Setattr with: Getattr; Verify
3782  *    with only ctime as the argument. If the server ctime differs from
3783  *    what is cached on the client, the verify will fail, but we would
3784  *    already have the ctime from the preceding getattr, so just set it
3785  *    and retry. Thus the compound here is - { Putfh <fh>; Getattr; Verify;
3786  *	Setattr; Getattr }.
3787  *
3788  * The vsecattr_t * input parameter will be non-NULL if ACLs are being set in
3789  * this setattr and NULL if they are not.
3790  */
3791 static int
nfs4setattr(vnode_t * vp,struct vattr * vap,int flags,cred_t * cr,vsecattr_t * vsap)3792 nfs4setattr(vnode_t *vp, struct vattr *vap, int flags, cred_t *cr,
3793     vsecattr_t *vsap)
3794 {
3795 	COMPOUND4args_clnt args;
3796 	COMPOUND4res_clnt res, *resp = NULL;
3797 	nfs4_ga_res_t *garp = NULL;
3798 	int numops = 3;			/* { Putfh; Setattr; Getattr } */
3799 	nfs_argop4 argop[5];
3800 	int verify_argop = -1;
3801 	int setattr_argop = 1;
3802 	nfs_resop4 *resop;
3803 	vattr_t va;
3804 	rnode4_t *rp;
3805 	int doqueue = 1;
3806 	uint_t mask = vap->va_mask;
3807 	mode_t omode;
3808 	vsecattr_t *vsp;
3809 	timestruc_t ctime;
3810 	bool_t needrecov = FALSE;
3811 	nfs4_recov_state_t recov_state;
3812 	nfs4_stateid_types_t sid_types;
3813 	stateid4 stateid;
3814 	hrtime_t t;
3815 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
3816 	servinfo4_t *svp;
3817 	bitmap4 supp_attrs;
3818 
3819 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
3820 	rp = VTOR4(vp);
3821 	nfs4_init_stateid_types(&sid_types);
3822 
3823 	/*
3824 	 * Only need to flush pages if there are any pages and
3825 	 * if the file is marked as dirty in some fashion.  The
3826 	 * file must be flushed so that we can accurately
3827 	 * determine the size of the file and the cached data
3828 	 * after the SETATTR returns.  A file is considered to
3829 	 * be dirty if it is either marked with R4DIRTY, has
3830 	 * outstanding i/o's active, or is mmap'd.  In this
3831 	 * last case, we can't tell whether there are dirty
3832 	 * pages, so we flush just to be sure.
3833 	 */
3834 	if (nfs4_has_pages(vp) &&
3835 	    ((rp->r_flags & R4DIRTY) ||
3836 	    rp->r_count > 0 ||
3837 	    rp->r_mapcnt > 0)) {
3838 		ASSERT(vp->v_type != VCHR);
3839 		e.error = nfs4_putpage(vp, (offset_t)0, 0, 0, cr, NULL);
3840 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
3841 			mutex_enter(&rp->r_statelock);
3842 			if (!rp->r_error)
3843 				rp->r_error = e.error;
3844 			mutex_exit(&rp->r_statelock);
3845 		}
3846 	}
3847 
3848 	if (mask & AT_SIZE) {
3849 		/*
3850 		 * Verification setattr compound for non-deleg AT_SIZE:
3851 		 *	{ Putfh; Getattr; Verify; Setattr; Getattr }
3852 		 * Set ctime local here (outside the do_again label)
3853 		 * so that subsequent retries (after failed VERIFY)
3854 		 * will use ctime from GETATTR results (from failed
3855 		 * verify compound) as VERIFY arg.
3856 		 * If file has delegation, then VERIFY(time_metadata)
3857 		 * is of little added value, so don't bother.
3858 		 */
3859 		mutex_enter(&rp->r_statev4_lock);
3860 		if (rp->r_deleg_type == OPEN_DELEGATE_NONE ||
3861 		    rp->r_deleg_return_pending) {
3862 			numops = 5;
3863 			ctime = rp->r_attr.va_ctime;
3864 		}
3865 		mutex_exit(&rp->r_statev4_lock);
3866 	}
3867 
3868 	recov_state.rs_flags = 0;
3869 	recov_state.rs_num_retry_despite_err = 0;
3870 
3871 	args.ctag = TAG_SETATTR;
3872 do_again:
3873 recov_retry:
3874 	setattr_argop = numops - 2;
3875 
3876 	args.array = argop;
3877 	args.array_len = numops;
3878 
3879 	e.error = nfs4_start_op(VTOMI4(vp), vp, NULL, &recov_state);
3880 	if (e.error)
3881 		return (e.error);
3882 
3883 
3884 	/* putfh target fh */
3885 	argop[0].argop = OP_CPUTFH;
3886 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
3887 
3888 	if (numops == 5) {
3889 		/*
3890 		 * We only care about the ctime, but need to get mtime
3891 		 * and size for proper cache update.
3892 		 */
3893 		/* getattr */
3894 		argop[1].argop = OP_GETATTR;
3895 		argop[1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
3896 		argop[1].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
3897 
3898 		/* verify - set later in loop */
3899 		verify_argop = 2;
3900 	}
3901 
3902 	/* setattr */
3903 	svp = rp->r_server;
3904 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
3905 	supp_attrs = svp->sv_supp_attrs;
3906 	nfs_rw_exit(&svp->sv_lock);
3907 
3908 	nfs4args_setattr(&argop[setattr_argop], vap, vsap, flags, rp, cr,
3909 	    supp_attrs, &e.error, &sid_types);
3910 	stateid = argop[setattr_argop].nfs_argop4_u.opsetattr.stateid;
3911 	if (e.error) {
3912 		/* req time field(s) overflow - return immediately */
3913 		nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
3914 		nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
3915 		    opsetattr.obj_attributes);
3916 		return (e.error);
3917 	}
3918 	omode = rp->r_attr.va_mode;
3919 
3920 	/* getattr */
3921 	argop[numops-1].argop = OP_GETATTR;
3922 	argop[numops-1].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
3923 	/*
3924 	 * If we are setting the ACL (indicated only by vsap != NULL), request
3925 	 * the ACL in this getattr.  The ACL returned from this getattr will be
3926 	 * used in updating the ACL cache.
3927 	 */
3928 	if (vsap != NULL)
3929 		argop[numops-1].nfs_argop4_u.opgetattr.attr_request |=
3930 		    FATTR4_ACL_MASK;
3931 	argop[numops-1].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
3932 
3933 	/*
3934 	 * setattr iterates if the object size is set and the cached ctime
3935 	 * does not match the file ctime. In that case, verify the ctime first.
3936 	 */
3937 
3938 	do {
3939 		if (verify_argop != -1) {
3940 			/*
3941 			 * Verify that the ctime match before doing setattr.
3942 			 */
3943 			va.va_mask = AT_CTIME;
3944 			va.va_ctime = ctime;
3945 			svp = rp->r_server;
3946 			(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
3947 			supp_attrs = svp->sv_supp_attrs;
3948 			nfs_rw_exit(&svp->sv_lock);
3949 			e.error = nfs4args_verify(&argop[verify_argop], &va,
3950 			    OP_VERIFY, supp_attrs);
3951 			if (e.error) {
3952 				/* req time field(s) overflow - return */
3953 				nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3954 				    needrecov);
3955 				break;
3956 			}
3957 		}
3958 
3959 		doqueue = 1;
3960 
3961 		t = gethrtime();
3962 
3963 		rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, &e);
3964 
3965 		/*
3966 		 * Purge the access cache and ACL cache if changing either the
3967 		 * owner of the file, the group owner, or the mode.  These may
3968 		 * change the access permissions of the file, so purge old
3969 		 * information and start over again.
3970 		 */
3971 		if (mask & (AT_UID | AT_GID | AT_MODE)) {
3972 			(void) nfs4_access_purge_rp(rp);
3973 			if (rp->r_secattr != NULL) {
3974 				mutex_enter(&rp->r_statelock);
3975 				vsp = rp->r_secattr;
3976 				rp->r_secattr = NULL;
3977 				mutex_exit(&rp->r_statelock);
3978 				if (vsp != NULL)
3979 					nfs4_acl_free_cache(vsp);
3980 			}
3981 		}
3982 
3983 		/*
3984 		 * If res.array_len == numops, then everything succeeded,
3985 		 * except for possibly the final getattr.  If only the
3986 		 * last getattr failed, give up, and don't try recovery.
3987 		 */
3988 		if (res.array_len == numops) {
3989 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
3990 			    needrecov);
3991 			if (! e.error)
3992 				resp = &res;
3993 			break;
3994 		}
3995 
3996 		/*
3997 		 * if either rpc call failed or completely succeeded - done
3998 		 */
3999 		needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4000 		if (e.error) {
4001 			PURGE_ATTRCACHE4(vp);
4002 			if (!needrecov) {
4003 				nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
4004 				    needrecov);
4005 				break;
4006 			}
4007 		}
4008 
4009 		/*
4010 		 * Do proper retry for OLD_STATEID outside of the normal
4011 		 * recovery framework.
4012 		 */
4013 		if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
4014 		    sid_types.cur_sid_type != SPEC_SID &&
4015 		    sid_types.cur_sid_type != NO_SID) {
4016 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
4017 			    needrecov);
4018 			nfs4_save_stateid(&stateid, &sid_types);
4019 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4020 			    opsetattr.obj_attributes);
4021 			if (verify_argop != -1) {
4022 				nfs4args_verify_free(&argop[verify_argop]);
4023 				verify_argop = -1;
4024 			}
4025 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4026 			goto recov_retry;
4027 		}
4028 
4029 		if (needrecov) {
4030 			bool_t abort;
4031 
4032 			abort = nfs4_start_recovery(&e,
4033 			    VTOMI4(vp), vp, NULL, NULL, NULL,
4034 			    OP_SETATTR, NULL, NULL, NULL);
4035 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
4036 			    needrecov);
4037 			/*
4038 			 * Do not retry if we failed with OLD_STATEID using
4039 			 * a special stateid.  This is done to avoid looping
4040 			 * with a broken server.
4041 			 */
4042 			if (e.error == 0 && res.status == NFS4ERR_OLD_STATEID &&
4043 			    (sid_types.cur_sid_type == SPEC_SID ||
4044 			    sid_types.cur_sid_type == NO_SID))
4045 				abort = TRUE;
4046 			if (!e.error) {
4047 				if (res.status == NFS4ERR_BADOWNER)
4048 					nfs4_log_badowner(VTOMI4(vp),
4049 					    OP_SETATTR);
4050 
4051 				e.error = geterrno4(res.status);
4052 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4053 				    (caddr_t)&res);
4054 			}
4055 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4056 			    opsetattr.obj_attributes);
4057 			if (verify_argop != -1) {
4058 				nfs4args_verify_free(&argop[verify_argop]);
4059 				verify_argop = -1;
4060 			}
4061 			if (abort == FALSE) {
4062 				/*
4063 				 * Need to retry all possible stateids in
4064 				 * case the recovery error wasn't stateid
4065 				 * related or the stateids have become
4066 				 * stale (server reboot).
4067 				 */
4068 				nfs4_init_stateid_types(&sid_types);
4069 				goto recov_retry;
4070 			}
4071 			return (e.error);
4072 		}
4073 
4074 		/*
4075 		 * Need to call nfs4_end_op before nfs4getattr to
4076 		 * avoid potential nfs4_start_op deadlock. See RFE
4077 		 * 4777612.  Calls to nfs4_invalidate_pages() and
4078 		 * nfs4_purge_stale_fh() might also generate over the
4079 		 * wire calls which my cause nfs4_start_op() deadlock.
4080 		 */
4081 		nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
4082 
4083 		/*
4084 		 * Check to update lease.
4085 		 */
4086 		resp = &res;
4087 		if (res.status == NFS4_OK) {
4088 			break;
4089 		}
4090 
4091 		/*
4092 		 * Check if verify failed to see if try again
4093 		 */
4094 		if ((verify_argop == -1) || (res.array_len != 3)) {
4095 			/*
4096 			 * can't continue...
4097 			 */
4098 			if (res.status == NFS4ERR_BADOWNER)
4099 				nfs4_log_badowner(VTOMI4(vp), OP_SETATTR);
4100 
4101 			e.error = geterrno4(res.status);
4102 		} else {
4103 			/*
4104 			 * When the verify request fails, the client ctime is
4105 			 * not in sync with the server. This is the same as
4106 			 * the version 3 "not synchronized" error, and we
4107 			 * handle it in a similar manner (XXX do we need to???).
4108 			 * Use the ctime returned in the first getattr for
4109 			 * the input to the next verify.
4110 			 * If we couldn't get the attributes, then we give up
4111 			 * because we can't complete the operation as required.
4112 			 */
4113 			garp = &res.array[1].nfs_resop4_u.opgetattr.ga_res;
4114 		}
4115 		if (e.error) {
4116 			PURGE_ATTRCACHE4(vp);
4117 			nfs4_purge_stale_fh(e.error, vp, cr);
4118 		} else {
4119 			/*
4120 			 * retry with a new verify value
4121 			 */
4122 			ctime = garp->n4g_va.va_ctime;
4123 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4124 			resp = NULL;
4125 		}
4126 		if (!e.error) {
4127 			nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4128 			    opsetattr.obj_attributes);
4129 			if (verify_argop != -1) {
4130 				nfs4args_verify_free(&argop[verify_argop]);
4131 				verify_argop = -1;
4132 			}
4133 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4134 			goto do_again;
4135 		}
4136 	} while (!e.error);
4137 
4138 	if (e.error) {
4139 		/*
4140 		 * If we are here, rfs4call has an irrecoverable error - return
4141 		 */
4142 		nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4143 		    opsetattr.obj_attributes);
4144 		if (verify_argop != -1) {
4145 			nfs4args_verify_free(&argop[verify_argop]);
4146 			verify_argop = -1;
4147 		}
4148 		if (resp)
4149 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
4150 		return (e.error);
4151 	}
4152 
4153 
4154 
4155 	/*
4156 	 * If changing the size of the file, invalidate
4157 	 * any local cached data which is no longer part
4158 	 * of the file.  We also possibly invalidate the
4159 	 * last page in the file.  We could use
4160 	 * pvn_vpzero(), but this would mark the page as
4161 	 * modified and require it to be written back to
4162 	 * the server for no particularly good reason.
4163 	 * This way, if we access it, then we bring it
4164 	 * back in.  A read should be cheaper than a
4165 	 * write.
4166 	 */
4167 	if (mask & AT_SIZE) {
4168 		nfs4_invalidate_pages(vp, (vap->va_size & PAGEMASK), cr);
4169 	}
4170 
4171 	/* either no error or one of the postop getattr failed */
4172 
4173 	/*
4174 	 * XXX Perform a simplified version of wcc checking. Instead of
4175 	 * have another getattr to get pre-op, just purge cache if
4176 	 * any of the ops prior to and including the getattr failed.
4177 	 * If the getattr succeeded then update the attrcache accordingly.
4178 	 */
4179 
4180 	garp = NULL;
4181 	if (res.status == NFS4_OK) {
4182 		/*
4183 		 * Last getattr
4184 		 */
4185 		resop = &res.array[numops - 1];
4186 		garp = &resop->nfs_resop4_u.opgetattr.ga_res;
4187 	}
4188 	/*
4189 	 * In certain cases, nfs4_update_attrcache() will purge the attrcache,
4190 	 * rather than filling it.  See the function itself for details.
4191 	 */
4192 	e.error = nfs4_update_attrcache(res.status, garp, t, vp, cr);
4193 	if (garp != NULL) {
4194 		if (garp->n4g_resbmap & FATTR4_ACL_MASK) {
4195 			nfs4_acl_fill_cache(rp, &garp->n4g_vsa);
4196 			vs_ace4_destroy(&garp->n4g_vsa);
4197 		} else {
4198 			if (vsap != NULL) {
4199 				/*
4200 				 * The ACL was supposed to be set and to be
4201 				 * returned in the last getattr of this
4202 				 * compound, but for some reason the getattr
4203 				 * result doesn't contain the ACL.  In this
4204 				 * case, purge the ACL cache.
4205 				 */
4206 				if (rp->r_secattr != NULL) {
4207 					mutex_enter(&rp->r_statelock);
4208 					vsp = rp->r_secattr;
4209 					rp->r_secattr = NULL;
4210 					mutex_exit(&rp->r_statelock);
4211 					if (vsp != NULL)
4212 						nfs4_acl_free_cache(vsp);
4213 				}
4214 			}
4215 		}
4216 	}
4217 
4218 	if (res.status == NFS4_OK && (mask & AT_SIZE)) {
4219 		/*
4220 		 * Set the size, rather than relying on getting it updated
4221 		 * via a GETATTR.  With delegations the client tries to
4222 		 * suppress GETATTR calls.
4223 		 */
4224 		mutex_enter(&rp->r_statelock);
4225 		rp->r_size = vap->va_size;
4226 		mutex_exit(&rp->r_statelock);
4227 	}
4228 
4229 	/*
4230 	 * Can free up request args and res
4231 	 */
4232 	nfs4_fattr4_free(&argop[setattr_argop].nfs_argop4_u.
4233 	    opsetattr.obj_attributes);
4234 	if (verify_argop != -1) {
4235 		nfs4args_verify_free(&argop[verify_argop]);
4236 		verify_argop = -1;
4237 	}
4238 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4239 
4240 	/*
4241 	 * Some servers will change the mode to clear the setuid
4242 	 * and setgid bits when changing the uid or gid.  The
4243 	 * client needs to compensate appropriately.
4244 	 */
4245 	if (mask & (AT_UID | AT_GID)) {
4246 		int terror, do_setattr;
4247 
4248 		do_setattr = 0;
4249 		va.va_mask = AT_MODE;
4250 		terror = nfs4getattr(vp, &va, cr);
4251 		if (!terror &&
4252 		    (((mask & AT_MODE) && va.va_mode != vap->va_mode) ||
4253 		    (!(mask & AT_MODE) && va.va_mode != omode))) {
4254 			va.va_mask = AT_MODE;
4255 			if (mask & AT_MODE) {
4256 				/*
4257 				 * We asked the mode to be changed and what
4258 				 * we just got from the server in getattr is
4259 				 * not what we wanted it to be, so set it now.
4260 				 */
4261 				va.va_mode = vap->va_mode;
4262 				do_setattr = 1;
4263 			} else {
4264 				/*
4265 				 * We did not ask the mode to be changed,
4266 				 * Check to see that the server just cleared
4267 				 * I_SUID and I_GUID from it. If not then
4268 				 * set mode to omode with UID/GID cleared.
4269 				 */
4270 				if (nfs4_compare_modes(va.va_mode, omode)) {
4271 					omode &= ~(S_ISUID|S_ISGID);
4272 					va.va_mode = omode;
4273 					do_setattr = 1;
4274 				}
4275 			}
4276 
4277 			if (do_setattr)
4278 				(void) nfs4setattr(vp, &va, 0, cr, NULL);
4279 		}
4280 	}
4281 
4282 	return (e.error);
4283 }
4284 
4285 /* ARGSUSED */
4286 static int
nfs4_access(vnode_t * vp,int mode,int flags,cred_t * cr,caller_context_t * ct)4287 nfs4_access(vnode_t *vp, int mode, int flags, cred_t *cr, caller_context_t *ct)
4288 {
4289 	COMPOUND4args_clnt args;
4290 	COMPOUND4res_clnt res;
4291 	int doqueue;
4292 	uint32_t acc, resacc, argacc;
4293 	rnode4_t *rp;
4294 	cred_t *cred, *ncr, *ncrfree = NULL;
4295 	nfs4_access_type_t cacc;
4296 	int num_ops;
4297 	nfs_argop4 argop[3];
4298 	nfs_resop4 *resop;
4299 	bool_t needrecov = FALSE, do_getattr;
4300 	nfs4_recov_state_t recov_state;
4301 	int rpc_error;
4302 	hrtime_t t;
4303 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4304 	mntinfo4_t *mi = VTOMI4(vp);
4305 
4306 	if (nfs_zone() != mi->mi_zone)
4307 		return (EIO);
4308 
4309 	acc = 0;
4310 	if (mode & VREAD)
4311 		acc |= ACCESS4_READ;
4312 	if (mode & VWRITE) {
4313 		if ((vp->v_vfsp->vfs_flag & VFS_RDONLY) && !ISVDEV(vp->v_type))
4314 			return (EROFS);
4315 		if (vp->v_type == VDIR)
4316 			acc |= ACCESS4_DELETE;
4317 		acc |= ACCESS4_MODIFY | ACCESS4_EXTEND;
4318 	}
4319 	if (mode & VEXEC) {
4320 		if (vp->v_type == VDIR)
4321 			acc |= ACCESS4_LOOKUP;
4322 		else
4323 			acc |= ACCESS4_EXECUTE;
4324 	}
4325 
4326 	if (VTOR4(vp)->r_acache != NULL) {
4327 		e.error = nfs4_validate_caches(vp, cr);
4328 		if (e.error)
4329 			return (e.error);
4330 	}
4331 
4332 	rp = VTOR4(vp);
4333 	if (vp->v_type == VDIR)
4334 		argacc = ACCESS4_READ | ACCESS4_DELETE | ACCESS4_MODIFY |
4335 		    ACCESS4_EXTEND | ACCESS4_LOOKUP;
4336 	else
4337 		argacc = ACCESS4_READ | ACCESS4_MODIFY | ACCESS4_EXTEND |
4338 		    ACCESS4_EXECUTE;
4339 	recov_state.rs_flags = 0;
4340 	recov_state.rs_num_retry_despite_err = 0;
4341 
4342 	cred = cr;
4343 	/*
4344 	 * ncr and ncrfree both initially
4345 	 * point to the memory area returned
4346 	 * by crnetadjust();
4347 	 * ncrfree not NULL when exiting means
4348 	 * that we need to release it
4349 	 */
4350 	ncr = crnetadjust(cred);
4351 	ncrfree = ncr;
4352 
4353 tryagain:
4354 	cacc = nfs4_access_check(rp, acc, cred);
4355 	if (cacc == NFS4_ACCESS_ALLOWED) {
4356 		if (ncrfree != NULL)
4357 			crfree(ncrfree);
4358 		return (0);
4359 	}
4360 	if (cacc == NFS4_ACCESS_DENIED) {
4361 		/*
4362 		 * If the cred can be adjusted, try again
4363 		 * with the new cred.
4364 		 */
4365 		if (ncr != NULL) {
4366 			cred = ncr;
4367 			ncr = NULL;
4368 			goto tryagain;
4369 		}
4370 		if (ncrfree != NULL)
4371 			crfree(ncrfree);
4372 		return (EACCES);
4373 	}
4374 
4375 recov_retry:
4376 	/*
4377 	 * Don't take with r_statev4_lock here. r_deleg_type could
4378 	 * change as soon as lock is released.  Since it is an int,
4379 	 * there is no atomicity issue.
4380 	 */
4381 	do_getattr = (rp->r_deleg_type == OPEN_DELEGATE_NONE);
4382 	num_ops = do_getattr ? 3 : 2;
4383 
4384 	args.ctag = TAG_ACCESS;
4385 
4386 	args.array_len = num_ops;
4387 	args.array = argop;
4388 
4389 	if (e.error = nfs4_start_fop(mi, vp, NULL, OH_ACCESS,
4390 	    &recov_state, NULL)) {
4391 		if (ncrfree != NULL)
4392 			crfree(ncrfree);
4393 		return (e.error);
4394 	}
4395 
4396 	/* putfh target fh */
4397 	argop[0].argop = OP_CPUTFH;
4398 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4399 
4400 	/* access */
4401 	argop[1].argop = OP_ACCESS;
4402 	argop[1].nfs_argop4_u.opaccess.access = argacc;
4403 
4404 	/* getattr */
4405 	if (do_getattr) {
4406 		argop[2].argop = OP_GETATTR;
4407 		argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4408 		argop[2].nfs_argop4_u.opgetattr.mi = mi;
4409 	}
4410 
4411 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4412 	    "nfs4_access: %s call, rp %s", needrecov ? "recov" : "first",
4413 	    rnode4info(VTOR4(vp))));
4414 
4415 	doqueue = 1;
4416 	t = gethrtime();
4417 	rfs4call(VTOMI4(vp), &args, &res, cred, &doqueue, 0, &e);
4418 	rpc_error = e.error;
4419 
4420 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4421 	if (needrecov) {
4422 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4423 		    "nfs4_access: initiating recovery\n"));
4424 
4425 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4426 		    NULL, OP_ACCESS, NULL, NULL, NULL) == FALSE) {
4427 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_ACCESS,
4428 			    &recov_state, needrecov);
4429 			if (!e.error)
4430 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4431 				    (caddr_t)&res);
4432 			goto recov_retry;
4433 		}
4434 	}
4435 	nfs4_end_fop(mi, vp, NULL, OH_ACCESS, &recov_state, needrecov);
4436 
4437 	if (e.error)
4438 		goto out;
4439 
4440 	if (res.status) {
4441 		e.error = geterrno4(res.status);
4442 		/*
4443 		 * This might generate over the wire calls throught
4444 		 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
4445 		 * here to avoid a deadlock.
4446 		 */
4447 		nfs4_purge_stale_fh(e.error, vp, cr);
4448 		goto out;
4449 	}
4450 	resop = &res.array[1];	/* access res */
4451 
4452 	resacc = resop->nfs_resop4_u.opaccess.access;
4453 
4454 	if (do_getattr) {
4455 		resop++;	/* getattr res */
4456 		nfs4_attr_cache(vp, &resop->nfs_resop4_u.opgetattr.ga_res,
4457 		    t, cr, FALSE, NULL);
4458 	}
4459 
4460 	if (!e.error) {
4461 		nfs4_access_cache(rp, argacc, resacc, cred);
4462 		/*
4463 		 * we just cached results with cred; if cred is the
4464 		 * adjusted credentials from crnetadjust, we do not want
4465 		 * to release them before exiting: hence setting ncrfree
4466 		 * to NULL
4467 		 */
4468 		if (cred != cr)
4469 			ncrfree = NULL;
4470 		/* XXX check the supported bits too? */
4471 		if ((acc & resacc) != acc) {
4472 			/*
4473 			 * The following code implements the semantic
4474 			 * that a setuid root program has *at least* the
4475 			 * permissions of the user that is running the
4476 			 * program.  See rfs3call() for more portions
4477 			 * of the implementation of this functionality.
4478 			 */
4479 			/* XXX-LP */
4480 			if (ncr != NULL) {
4481 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4482 				    (caddr_t)&res);
4483 				cred = ncr;
4484 				ncr = NULL;
4485 				goto tryagain;
4486 			}
4487 			e.error = EACCES;
4488 		}
4489 	}
4490 
4491 out:
4492 	if (!rpc_error)
4493 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4494 
4495 	if (ncrfree != NULL)
4496 		crfree(ncrfree);
4497 
4498 	return (e.error);
4499 }
4500 
4501 /* ARGSUSED */
4502 static int
nfs4_readlink(vnode_t * vp,struct uio * uiop,cred_t * cr,caller_context_t * ct)4503 nfs4_readlink(vnode_t *vp, struct uio *uiop, cred_t *cr, caller_context_t *ct)
4504 {
4505 	COMPOUND4args_clnt args;
4506 	COMPOUND4res_clnt res;
4507 	int doqueue;
4508 	rnode4_t *rp;
4509 	nfs_argop4 argop[3];
4510 	nfs_resop4 *resop;
4511 	READLINK4res *lr_res;
4512 	nfs4_ga_res_t *garp;
4513 	uint_t len;
4514 	char *linkdata;
4515 	bool_t needrecov = FALSE;
4516 	nfs4_recov_state_t recov_state;
4517 	hrtime_t t;
4518 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4519 
4520 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
4521 		return (EIO);
4522 	/*
4523 	 * Can't readlink anything other than a symbolic link.
4524 	 */
4525 	if (vp->v_type != VLNK)
4526 		return (EINVAL);
4527 
4528 	rp = VTOR4(vp);
4529 	if (nfs4_do_symlink_cache && rp->r_symlink.contents != NULL) {
4530 		e.error = nfs4_validate_caches(vp, cr);
4531 		if (e.error)
4532 			return (e.error);
4533 		mutex_enter(&rp->r_statelock);
4534 		if (rp->r_symlink.contents != NULL) {
4535 			e.error = uiomove(rp->r_symlink.contents,
4536 			    rp->r_symlink.len, UIO_READ, uiop);
4537 			mutex_exit(&rp->r_statelock);
4538 			return (e.error);
4539 		}
4540 		mutex_exit(&rp->r_statelock);
4541 	}
4542 	recov_state.rs_flags = 0;
4543 	recov_state.rs_num_retry_despite_err = 0;
4544 
4545 recov_retry:
4546 	args.array_len = 3;
4547 	args.array = argop;
4548 	args.ctag = TAG_READLINK;
4549 
4550 	e.error = nfs4_start_op(VTOMI4(vp), vp, NULL, &recov_state);
4551 	if (e.error) {
4552 		return (e.error);
4553 	}
4554 
4555 	/* 0. putfh symlink fh */
4556 	argop[0].argop = OP_CPUTFH;
4557 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
4558 
4559 	/* 1. readlink */
4560 	argop[1].argop = OP_READLINK;
4561 
4562 	/* 2. getattr */
4563 	argop[2].argop = OP_GETATTR;
4564 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
4565 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(vp);
4566 
4567 	doqueue = 1;
4568 
4569 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
4570 	    "nfs4_readlink: %s call, rp %s", needrecov ? "recov" : "first",
4571 	    rnode4info(VTOR4(vp))));
4572 
4573 	t = gethrtime();
4574 
4575 	rfs4call(VTOMI4(vp), &args, &res, cr, &doqueue, 0, &e);
4576 
4577 	needrecov = nfs4_needs_recovery(&e, FALSE, vp->v_vfsp);
4578 	if (needrecov) {
4579 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
4580 		    "nfs4_readlink: initiating recovery\n"));
4581 
4582 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
4583 		    NULL, OP_READLINK, NULL, NULL, NULL) == FALSE) {
4584 			if (!e.error)
4585 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4586 				    (caddr_t)&res);
4587 
4588 			nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state,
4589 			    needrecov);
4590 			goto recov_retry;
4591 		}
4592 	}
4593 
4594 	nfs4_end_op(VTOMI4(vp), vp, NULL, &recov_state, needrecov);
4595 
4596 	if (e.error)
4597 		return (e.error);
4598 
4599 	/*
4600 	 * There is an path in the code below which calls
4601 	 * nfs4_purge_stale_fh(), which may generate otw calls through
4602 	 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
4603 	 * here to avoid nfs4_start_op() deadlock.
4604 	 */
4605 
4606 	if (res.status && (res.array_len < args.array_len)) {
4607 		/*
4608 		 * either Putfh or Link failed
4609 		 */
4610 		e.error = geterrno4(res.status);
4611 		nfs4_purge_stale_fh(e.error, vp, cr);
4612 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4613 		return (e.error);
4614 	}
4615 
4616 	resop = &res.array[1];	/* readlink res */
4617 	lr_res = &resop->nfs_resop4_u.opreadlink;
4618 
4619 	/*
4620 	 * treat symlink names as data
4621 	 */
4622 	linkdata = utf8_to_str((utf8string *)&lr_res->link, &len, NULL);
4623 	if (linkdata != NULL) {
4624 		int uio_len = len - 1;
4625 		/* len includes null byte, which we won't uiomove */
4626 		e.error = uiomove(linkdata, uio_len, UIO_READ, uiop);
4627 		if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
4628 			mutex_enter(&rp->r_statelock);
4629 			if (rp->r_symlink.contents == NULL) {
4630 				rp->r_symlink.contents = linkdata;
4631 				rp->r_symlink.len = uio_len;
4632 				rp->r_symlink.size = len;
4633 				mutex_exit(&rp->r_statelock);
4634 			} else {
4635 				mutex_exit(&rp->r_statelock);
4636 				kmem_free(linkdata, len);
4637 			}
4638 		} else {
4639 			kmem_free(linkdata, len);
4640 		}
4641 	}
4642 	if (res.status == NFS4_OK) {
4643 		resop++;	/* getattr res */
4644 		garp = &resop->nfs_resop4_u.opgetattr.ga_res;
4645 	}
4646 	e.error = nfs4_update_attrcache(res.status, garp, t, vp, cr);
4647 
4648 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
4649 
4650 	/*
4651 	 * The over the wire error for attempting to readlink something
4652 	 * other than a symbolic link is ENXIO.  However, we need to
4653 	 * return EINVAL instead of ENXIO, so we map it here.
4654 	 */
4655 	return (e.error == ENXIO ? EINVAL : e.error);
4656 }
4657 
4658 /*
4659  * Flush local dirty pages to stable storage on the server.
4660  *
4661  * If FNODSYNC is specified, then there is nothing to do because
4662  * metadata changes are not cached on the client before being
4663  * sent to the server.
4664  */
4665 /* ARGSUSED */
4666 static int
nfs4_fsync(vnode_t * vp,int syncflag,cred_t * cr,caller_context_t * ct)4667 nfs4_fsync(vnode_t *vp, int syncflag, cred_t *cr, caller_context_t *ct)
4668 {
4669 	int error;
4670 
4671 	if ((syncflag & FNODSYNC) || IS_SWAPVP(vp))
4672 		return (0);
4673 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
4674 		return (EIO);
4675 	error = nfs4_putpage_commit(vp, (offset_t)0, 0, cr);
4676 	if (!error)
4677 		error = VTOR4(vp)->r_error;
4678 	return (error);
4679 }
4680 
4681 /*
4682  * Weirdness: if the file was removed or the target of a rename
4683  * operation while it was open, it got renamed instead.  Here we
4684  * remove the renamed file.
4685  */
4686 /* ARGSUSED */
4687 void
nfs4_inactive(vnode_t * vp,cred_t * cr,caller_context_t * ct)4688 nfs4_inactive(vnode_t *vp, cred_t *cr, caller_context_t *ct)
4689 {
4690 	rnode4_t *rp;
4691 
4692 	ASSERT(vp != DNLC_NO_VNODE);
4693 
4694 	rp = VTOR4(vp);
4695 
4696 	if (IS_SHADOW(vp, rp)) {
4697 		sv_inactive(vp);
4698 		return;
4699 	}
4700 
4701 	/*
4702 	 * If this is coming from the wrong zone, we let someone in the right
4703 	 * zone take care of it asynchronously.  We can get here due to
4704 	 * VN_RELE() being called from pageout() or fsflush().  This call may
4705 	 * potentially turn into an expensive no-op if, for instance, v_count
4706 	 * gets incremented in the meantime, but it's still correct.
4707 	 */
4708 	if (nfs_zone() != VTOMI4(vp)->mi_zone) {
4709 		nfs4_async_inactive(vp, cr);
4710 		return;
4711 	}
4712 
4713 	/*
4714 	 * Some of the cleanup steps might require over-the-wire
4715 	 * operations.  Since VOP_INACTIVE can get called as a result of
4716 	 * other over-the-wire operations (e.g., an attribute cache update
4717 	 * can lead to a DNLC purge), doing those steps now would lead to a
4718 	 * nested call to the recovery framework, which can deadlock.  So
4719 	 * do any over-the-wire cleanups asynchronously, in a separate
4720 	 * thread.
4721 	 */
4722 
4723 	mutex_enter(&rp->r_os_lock);
4724 	mutex_enter(&rp->r_statelock);
4725 	mutex_enter(&rp->r_statev4_lock);
4726 
4727 	if (vp->v_type == VREG && list_head(&rp->r_open_streams) != NULL) {
4728 		mutex_exit(&rp->r_statev4_lock);
4729 		mutex_exit(&rp->r_statelock);
4730 		mutex_exit(&rp->r_os_lock);
4731 		nfs4_async_inactive(vp, cr);
4732 		return;
4733 	}
4734 
4735 	if (rp->r_deleg_type == OPEN_DELEGATE_READ ||
4736 	    rp->r_deleg_type == OPEN_DELEGATE_WRITE) {
4737 		mutex_exit(&rp->r_statev4_lock);
4738 		mutex_exit(&rp->r_statelock);
4739 		mutex_exit(&rp->r_os_lock);
4740 		nfs4_async_inactive(vp, cr);
4741 		return;
4742 	}
4743 
4744 	if (rp->r_unldvp != NULL) {
4745 		mutex_exit(&rp->r_statev4_lock);
4746 		mutex_exit(&rp->r_statelock);
4747 		mutex_exit(&rp->r_os_lock);
4748 		nfs4_async_inactive(vp, cr);
4749 		return;
4750 	}
4751 	mutex_exit(&rp->r_statev4_lock);
4752 	mutex_exit(&rp->r_statelock);
4753 	mutex_exit(&rp->r_os_lock);
4754 
4755 	rp4_addfree(rp, cr);
4756 }
4757 
4758 /*
4759  * nfs4_inactive_otw - nfs4_inactive, plus over-the-wire calls to free up
4760  * various bits of state.  The caller must not refer to vp after this call.
4761  */
4762 
4763 void
nfs4_inactive_otw(vnode_t * vp,cred_t * cr)4764 nfs4_inactive_otw(vnode_t *vp, cred_t *cr)
4765 {
4766 	rnode4_t *rp = VTOR4(vp);
4767 	nfs4_recov_state_t recov_state;
4768 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
4769 	vnode_t *unldvp;
4770 	char *unlname;
4771 	cred_t *unlcred;
4772 	COMPOUND4args_clnt args;
4773 	COMPOUND4res_clnt res, *resp;
4774 	nfs_argop4 argop[2];
4775 	int doqueue;
4776 #ifdef DEBUG
4777 	char *name;
4778 #endif
4779 
4780 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
4781 	ASSERT(!IS_SHADOW(vp, rp));
4782 
4783 #ifdef DEBUG
4784 	name = fn_name(VTOSV(vp)->sv_name);
4785 	NFS4_DEBUG(nfs4_client_inactive_debug, (CE_NOTE, "nfs4_inactive_otw: "
4786 	    "release vnode %s", name));
4787 	kmem_free(name, MAXNAMELEN);
4788 #endif
4789 
4790 	if (vp->v_type == VREG) {
4791 		bool_t recov_failed = FALSE;
4792 
4793 		e.error = nfs4close_all(vp, cr);
4794 		if (e.error) {
4795 			/* Check to see if recovery failed */
4796 			mutex_enter(&(VTOMI4(vp)->mi_lock));
4797 			if (VTOMI4(vp)->mi_flags & MI4_RECOV_FAIL)
4798 				recov_failed = TRUE;
4799 			mutex_exit(&(VTOMI4(vp)->mi_lock));
4800 			if (!recov_failed) {
4801 				mutex_enter(&rp->r_statelock);
4802 				if (rp->r_flags & R4RECOVERR)
4803 					recov_failed = TRUE;
4804 				mutex_exit(&rp->r_statelock);
4805 			}
4806 			if (recov_failed) {
4807 				NFS4_DEBUG(nfs4_client_recov_debug,
4808 				    (CE_NOTE, "nfs4_inactive_otw: "
4809 				    "close failed (recovery failure)"));
4810 			}
4811 		}
4812 	}
4813 
4814 redo:
4815 	if (rp->r_unldvp == NULL) {
4816 		rp4_addfree(rp, cr);
4817 		return;
4818 	}
4819 
4820 	/*
4821 	 * Save the vnode pointer for the directory where the
4822 	 * unlinked-open file got renamed, then set it to NULL
4823 	 * to prevent another thread from getting here before
4824 	 * we're done with the remove.  While we have the
4825 	 * statelock, make local copies of the pertinent rnode
4826 	 * fields.  If we weren't to do this in an atomic way, the
4827 	 * the unl* fields could become inconsistent with respect
4828 	 * to each other due to a race condition between this
4829 	 * code and nfs_remove().  See bug report 1034328.
4830 	 */
4831 	mutex_enter(&rp->r_statelock);
4832 	if (rp->r_unldvp == NULL) {
4833 		mutex_exit(&rp->r_statelock);
4834 		rp4_addfree(rp, cr);
4835 		return;
4836 	}
4837 
4838 	unldvp = rp->r_unldvp;
4839 	rp->r_unldvp = NULL;
4840 	unlname = rp->r_unlname;
4841 	rp->r_unlname = NULL;
4842 	unlcred = rp->r_unlcred;
4843 	rp->r_unlcred = NULL;
4844 	mutex_exit(&rp->r_statelock);
4845 
4846 	/*
4847 	 * If there are any dirty pages left, then flush
4848 	 * them.  This is unfortunate because they just
4849 	 * may get thrown away during the remove operation,
4850 	 * but we have to do this for correctness.
4851 	 */
4852 	if (nfs4_has_pages(vp) &&
4853 	    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
4854 		ASSERT(vp->v_type != VCHR);
4855 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr, NULL);
4856 		if (e.error) {
4857 			mutex_enter(&rp->r_statelock);
4858 			if (!rp->r_error)
4859 				rp->r_error = e.error;
4860 			mutex_exit(&rp->r_statelock);
4861 		}
4862 	}
4863 
4864 	recov_state.rs_flags = 0;
4865 	recov_state.rs_num_retry_despite_err = 0;
4866 recov_retry_remove:
4867 	/*
4868 	 * Do the remove operation on the renamed file
4869 	 */
4870 	args.ctag = TAG_INACTIVE;
4871 
4872 	/*
4873 	 * Remove ops: putfh dir; remove
4874 	 */
4875 	args.array_len = 2;
4876 	args.array = argop;
4877 
4878 	e.error = nfs4_start_op(VTOMI4(unldvp), unldvp, NULL, &recov_state);
4879 	if (e.error) {
4880 		kmem_free(unlname, MAXNAMELEN);
4881 		crfree(unlcred);
4882 		VN_RELE(unldvp);
4883 		/*
4884 		 * Try again; this time around r_unldvp will be NULL, so we'll
4885 		 * just call rp4_addfree() and return.
4886 		 */
4887 		goto redo;
4888 	}
4889 
4890 	/* putfh directory */
4891 	argop[0].argop = OP_CPUTFH;
4892 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(unldvp)->r_fh;
4893 
4894 	/* remove */
4895 	argop[1].argop = OP_CREMOVE;
4896 	argop[1].nfs_argop4_u.opcremove.ctarget = unlname;
4897 
4898 	doqueue = 1;
4899 	resp = &res;
4900 
4901 #if 0 /* notyet */
4902 	/*
4903 	 * Can't do this yet.  We may be being called from
4904 	 * dnlc_purge_XXX while that routine is holding a
4905 	 * mutex lock to the nc_rele list.  The calls to
4906 	 * nfs3_cache_wcc_data may result in calls to
4907 	 * dnlc_purge_XXX.  This will result in a deadlock.
4908 	 */
4909 	rfs4call(VTOMI4(unldvp), &args, &res, unlcred, &doqueue, 0, &e);
4910 	if (e.error) {
4911 		PURGE_ATTRCACHE4(unldvp);
4912 		resp = NULL;
4913 	} else if (res.status) {
4914 		e.error = geterrno4(res.status);
4915 		PURGE_ATTRCACHE4(unldvp);
4916 		/*
4917 		 * This code is inactive right now
4918 		 * but if made active there should
4919 		 * be a nfs4_end_op() call before
4920 		 * nfs4_purge_stale_fh to avoid start_op()
4921 		 * deadlock. See BugId: 4948726
4922 		 */
4923 		nfs4_purge_stale_fh(error, unldvp, cr);
4924 	} else {
4925 		nfs_resop4 *resop;
4926 		REMOVE4res *rm_res;
4927 
4928 		resop = &res.array[1];
4929 		rm_res = &resop->nfs_resop4_u.opremove;
4930 		/*
4931 		 * Update directory cache attribute,
4932 		 * readdir and dnlc caches.
4933 		 */
4934 		nfs4_update_dircaches(&rm_res->cinfo, unldvp, NULL, NULL, NULL);
4935 	}
4936 #else
4937 	rfs4call(VTOMI4(unldvp), &args, &res, unlcred, &doqueue, 0, &e);
4938 
4939 	PURGE_ATTRCACHE4(unldvp);
4940 #endif
4941 
4942 	if (nfs4_needs_recovery(&e, FALSE, unldvp->v_vfsp)) {
4943 		if (nfs4_start_recovery(&e, VTOMI4(unldvp), unldvp, NULL,
4944 		    NULL, NULL, OP_REMOVE, NULL, NULL, NULL) == FALSE) {
4945 			if (!e.error)
4946 				(void) xdr_free(xdr_COMPOUND4res_clnt,
4947 				    (caddr_t)&res);
4948 			nfs4_end_op(VTOMI4(unldvp), unldvp, NULL,
4949 			    &recov_state, TRUE);
4950 			goto recov_retry_remove;
4951 		}
4952 	}
4953 	nfs4_end_op(VTOMI4(unldvp), unldvp, NULL, &recov_state, FALSE);
4954 
4955 	/*
4956 	 * Release stuff held for the remove
4957 	 */
4958 	VN_RELE(unldvp);
4959 	if (!e.error && resp)
4960 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
4961 
4962 	kmem_free(unlname, MAXNAMELEN);
4963 	crfree(unlcred);
4964 	goto redo;
4965 }
4966 
4967 /*
4968  * Remote file system operations having to do with directory manipulation.
4969  */
4970 /* ARGSUSED3 */
4971 int
nfs4_lookup(vnode_t * dvp,char * nm,vnode_t ** vpp,struct pathname * pnp,int flags,vnode_t * rdir,cred_t * cr,caller_context_t * ct,int * direntflags,pathname_t * realpnp)4972 nfs4_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, struct pathname *pnp,
4973     int flags, vnode_t *rdir, cred_t *cr, caller_context_t *ct,
4974     int *direntflags, pathname_t *realpnp)
4975 {
4976 	int error;
4977 	vnode_t *vp, *avp = NULL;
4978 	rnode4_t *drp;
4979 
4980 	*vpp = NULL;
4981 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
4982 		return (EPERM);
4983 	/*
4984 	 * if LOOKUP_XATTR, must replace dvp (object) with
4985 	 * object's attrdir before continuing with lookup
4986 	 */
4987 	if (flags & LOOKUP_XATTR) {
4988 		error = nfs4lookup_xattr(dvp, nm, &avp, flags, cr);
4989 		if (error)
4990 			return (error);
4991 
4992 		dvp = avp;
4993 
4994 		/*
4995 		 * If lookup is for "", just return dvp now.  The attrdir
4996 		 * has already been activated (from nfs4lookup_xattr), and
4997 		 * the caller will RELE the original dvp -- not
4998 		 * the attrdir.  So, set vpp and return.
4999 		 * Currently, when the LOOKUP_XATTR flag is
5000 		 * passed to VOP_LOOKUP, the name is always empty, and
5001 		 * shortcircuiting here avoids 3 unneeded lock/unlock
5002 		 * pairs.
5003 		 *
5004 		 * If a non-empty name was provided, then it is the
5005 		 * attribute name, and it will be looked up below.
5006 		 */
5007 		if (*nm == '\0') {
5008 			*vpp = dvp;
5009 			return (0);
5010 		}
5011 
5012 		/*
5013 		 * The vfs layer never sends a name when asking for the
5014 		 * attrdir, so we should never get here (unless of course
5015 		 * name is passed at some time in future -- at which time
5016 		 * we'll blow up here).
5017 		 */
5018 		ASSERT(0);
5019 	}
5020 
5021 	drp = VTOR4(dvp);
5022 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
5023 		return (EINTR);
5024 
5025 	error = nfs4lookup(dvp, nm, vpp, cr, 0);
5026 	nfs_rw_exit(&drp->r_rwlock);
5027 
5028 	/*
5029 	 * If vnode is a device, create special vnode.
5030 	 */
5031 	if (!error && ISVDEV((*vpp)->v_type)) {
5032 		vp = *vpp;
5033 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
5034 		VN_RELE(vp);
5035 	}
5036 
5037 	return (error);
5038 }
5039 
5040 /* ARGSUSED */
5041 static int
nfs4lookup_xattr(vnode_t * dvp,char * nm,vnode_t ** vpp,int flags,cred_t * cr)5042 nfs4lookup_xattr(vnode_t *dvp, char *nm, vnode_t **vpp, int flags, cred_t *cr)
5043 {
5044 	int error;
5045 	rnode4_t *drp;
5046 	int cflag = ((flags & CREATE_XATTR_DIR) != 0);
5047 	mntinfo4_t *mi;
5048 
5049 	mi = VTOMI4(dvp);
5050 	if (!(mi->mi_vfsp->vfs_flag & VFS_XATTR) &&
5051 	    !vfs_has_feature(mi->mi_vfsp, VFSFT_SYSATTR_VIEWS))
5052 		return (EINVAL);
5053 
5054 	drp = VTOR4(dvp);
5055 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp)))
5056 		return (EINTR);
5057 
5058 	mutex_enter(&drp->r_statelock);
5059 	/*
5060 	 * If the server doesn't support xattrs just return EINVAL
5061 	 */
5062 	if (drp->r_xattr_dir == NFS4_XATTR_DIR_NOTSUPP) {
5063 		mutex_exit(&drp->r_statelock);
5064 		nfs_rw_exit(&drp->r_rwlock);
5065 		return (EINVAL);
5066 	}
5067 
5068 	/*
5069 	 * If there is a cached xattr directory entry,
5070 	 * use it as long as the attributes are valid. If the
5071 	 * attributes are not valid, take the simple approach and
5072 	 * free the cached value and re-fetch a new value.
5073 	 *
5074 	 * We don't negative entry cache for now, if we did we
5075 	 * would need to check if the file has changed on every
5076 	 * lookup. But xattrs don't exist very often and failing
5077 	 * an openattr is not much more expensive than and NVERIFY or GETATTR
5078 	 * so do an openattr over the wire for now.
5079 	 */
5080 	if (drp->r_xattr_dir != NULL) {
5081 		if (ATTRCACHE4_VALID(dvp)) {
5082 			VN_HOLD(drp->r_xattr_dir);
5083 			*vpp = drp->r_xattr_dir;
5084 			mutex_exit(&drp->r_statelock);
5085 			nfs_rw_exit(&drp->r_rwlock);
5086 			return (0);
5087 		}
5088 		VN_RELE(drp->r_xattr_dir);
5089 		drp->r_xattr_dir = NULL;
5090 	}
5091 	mutex_exit(&drp->r_statelock);
5092 
5093 	error = nfs4openattr(dvp, vpp, cflag, cr);
5094 
5095 	nfs_rw_exit(&drp->r_rwlock);
5096 
5097 	return (error);
5098 }
5099 
5100 static int
nfs4lookup(vnode_t * dvp,char * nm,vnode_t ** vpp,cred_t * cr,int skipdnlc)5101 nfs4lookup(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr, int skipdnlc)
5102 {
5103 	int error;
5104 	rnode4_t *drp;
5105 
5106 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5107 
5108 	/*
5109 	 * If lookup is for "", just return dvp.  Don't need
5110 	 * to send it over the wire, look it up in the dnlc,
5111 	 * or perform any access checks.
5112 	 */
5113 	if (*nm == '\0') {
5114 		VN_HOLD(dvp);
5115 		*vpp = dvp;
5116 		return (0);
5117 	}
5118 
5119 	/*
5120 	 * Can't do lookups in non-directories.
5121 	 */
5122 	if (dvp->v_type != VDIR)
5123 		return (ENOTDIR);
5124 
5125 	/*
5126 	 * If lookup is for ".", just return dvp.  Don't need
5127 	 * to send it over the wire or look it up in the dnlc,
5128 	 * just need to check access.
5129 	 */
5130 	if (nm[0] == '.' && nm[1] == '\0') {
5131 		error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5132 		if (error)
5133 			return (error);
5134 		VN_HOLD(dvp);
5135 		*vpp = dvp;
5136 		return (0);
5137 	}
5138 
5139 	drp = VTOR4(dvp);
5140 	if (!(drp->r_flags & R4LOOKUP)) {
5141 		mutex_enter(&drp->r_statelock);
5142 		drp->r_flags |= R4LOOKUP;
5143 		mutex_exit(&drp->r_statelock);
5144 	}
5145 
5146 	*vpp = NULL;
5147 	/*
5148 	 * Lookup this name in the DNLC.  If there is no entry
5149 	 * lookup over the wire.
5150 	 */
5151 	if (!skipdnlc)
5152 		*vpp = dnlc_lookup(dvp, nm);
5153 	if (*vpp == NULL) {
5154 		/*
5155 		 * We need to go over the wire to lookup the name.
5156 		 */
5157 		return (nfs4lookupnew_otw(dvp, nm, vpp, cr));
5158 	}
5159 
5160 	/*
5161 	 * We hit on the dnlc
5162 	 */
5163 	if (*vpp != DNLC_NO_VNODE ||
5164 	    (dvp->v_vfsp->vfs_flag & VFS_RDONLY)) {
5165 		/*
5166 		 * But our attrs may not be valid.
5167 		 */
5168 		if (ATTRCACHE4_VALID(dvp)) {
5169 			error = nfs4_waitfor_purge_complete(dvp);
5170 			if (error) {
5171 				VN_RELE(*vpp);
5172 				*vpp = NULL;
5173 				return (error);
5174 			}
5175 
5176 			/*
5177 			 * If after the purge completes, check to make sure
5178 			 * our attrs are still valid.
5179 			 */
5180 			if (ATTRCACHE4_VALID(dvp)) {
5181 				/*
5182 				 * If we waited for a purge we may have
5183 				 * lost our vnode so look it up again.
5184 				 */
5185 				VN_RELE(*vpp);
5186 				*vpp = dnlc_lookup(dvp, nm);
5187 				if (*vpp == NULL)
5188 					return (nfs4lookupnew_otw(dvp,
5189 					    nm, vpp, cr));
5190 
5191 				/*
5192 				 * The access cache should almost always hit
5193 				 */
5194 				error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5195 
5196 				if (error) {
5197 					VN_RELE(*vpp);
5198 					*vpp = NULL;
5199 					return (error);
5200 				}
5201 				if (*vpp == DNLC_NO_VNODE) {
5202 					VN_RELE(*vpp);
5203 					*vpp = NULL;
5204 					return (ENOENT);
5205 				}
5206 				return (0);
5207 			}
5208 		}
5209 	}
5210 
5211 	ASSERT(*vpp != NULL);
5212 
5213 	/*
5214 	 * We may have gotten here we have one of the following cases:
5215 	 *	1) vpp != DNLC_NO_VNODE, our attrs have timed out so we
5216 	 *		need to validate them.
5217 	 *	2) vpp == DNLC_NO_VNODE, a negative entry that we always
5218 	 *		must validate.
5219 	 *
5220 	 * Go to the server and check if the directory has changed, if
5221 	 * it hasn't we are done and can use the dnlc entry.
5222 	 */
5223 	return (nfs4lookupvalidate_otw(dvp, nm, vpp, cr));
5224 }
5225 
5226 /*
5227  * Go to the server and check if the directory has changed, if
5228  * it hasn't we are done and can use the dnlc entry.  If it
5229  * has changed we get a new copy of its attributes and check
5230  * the access for VEXEC, then relookup the filename and
5231  * get its filehandle and attributes.
5232  *
5233  * PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR
5234  *	if the NVERIFY failed we must
5235  *		purge the caches
5236  *		cache new attributes (will set r_time_attr_inval)
5237  *		cache new access
5238  *		recheck VEXEC access
5239  *		add name to dnlc, possibly negative
5240  *		if LOOKUP succeeded
5241  *			cache new attributes
5242  *	else
5243  *		set a new r_time_attr_inval for dvp
5244  *		check to make sure we have access
5245  *
5246  * The vpp returned is the vnode passed in if the directory is valid,
5247  * a new vnode if successful lookup, or NULL on error.
5248  */
5249 static int
nfs4lookupvalidate_otw(vnode_t * dvp,char * nm,vnode_t ** vpp,cred_t * cr)5250 nfs4lookupvalidate_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5251 {
5252 	COMPOUND4args_clnt args;
5253 	COMPOUND4res_clnt res;
5254 	fattr4 *ver_fattr;
5255 	fattr4_change dchange;
5256 	int32_t *ptr;
5257 	int argoplist_size  = 7 * sizeof (nfs_argop4);
5258 	nfs_argop4 *argop;
5259 	int doqueue;
5260 	mntinfo4_t *mi;
5261 	nfs4_recov_state_t recov_state;
5262 	hrtime_t t;
5263 	int isdotdot;
5264 	vnode_t *nvp;
5265 	nfs_fh4 *fhp;
5266 	nfs4_sharedfh_t *sfhp;
5267 	nfs4_access_type_t cacc;
5268 	rnode4_t *nrp;
5269 	rnode4_t *drp = VTOR4(dvp);
5270 	nfs4_ga_res_t *garp = NULL;
5271 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5272 
5273 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5274 	ASSERT(nm != NULL);
5275 	ASSERT(nm[0] != '\0');
5276 	ASSERT(dvp->v_type == VDIR);
5277 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5278 	ASSERT(*vpp != NULL);
5279 
5280 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5281 		isdotdot = 1;
5282 		args.ctag = TAG_LOOKUP_VPARENT;
5283 	} else {
5284 		/*
5285 		 * If dvp were a stub, it should have triggered and caused
5286 		 * a mount for us to get this far.
5287 		 */
5288 		ASSERT(!RP_ISSTUB(VTOR4(dvp)));
5289 
5290 		isdotdot = 0;
5291 		args.ctag = TAG_LOOKUP_VALID;
5292 	}
5293 
5294 	mi = VTOMI4(dvp);
5295 	recov_state.rs_flags = 0;
5296 	recov_state.rs_num_retry_despite_err = 0;
5297 
5298 	nvp = NULL;
5299 
5300 	/* Save the original mount point security information */
5301 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5302 
5303 recov_retry:
5304 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5305 	    &recov_state, NULL);
5306 	if (e.error) {
5307 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5308 		VN_RELE(*vpp);
5309 		*vpp = NULL;
5310 		return (e.error);
5311 	}
5312 
5313 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5314 
5315 	/* PUTFH dfh NVERIFY GETATTR ACCESS LOOKUP GETFH GETATTR */
5316 	args.array_len = 7;
5317 	args.array = argop;
5318 
5319 	/* 0. putfh file */
5320 	argop[0].argop = OP_CPUTFH;
5321 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5322 
5323 	/* 1. nverify the change info */
5324 	argop[1].argop = OP_NVERIFY;
5325 	ver_fattr = &argop[1].nfs_argop4_u.opnverify.obj_attributes;
5326 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5327 	ver_fattr->attrlist4 = (char *)&dchange;
5328 	ptr = (int32_t *)&dchange;
5329 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5330 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5331 
5332 	/* 2. getattr directory */
5333 	argop[2].argop = OP_GETATTR;
5334 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5335 	argop[2].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5336 
5337 	/* 3. access directory */
5338 	argop[3].argop = OP_ACCESS;
5339 	argop[3].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5340 	    ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5341 
5342 	/* 4. lookup name */
5343 	if (isdotdot) {
5344 		argop[4].argop = OP_LOOKUPP;
5345 	} else {
5346 		argop[4].argop = OP_CLOOKUP;
5347 		argop[4].nfs_argop4_u.opclookup.cname = nm;
5348 	}
5349 
5350 	/* 5. resulting file handle */
5351 	argop[5].argop = OP_GETFH;
5352 
5353 	/* 6. resulting file attributes */
5354 	argop[6].argop = OP_GETATTR;
5355 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5356 	argop[6].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5357 
5358 	doqueue = 1;
5359 	t = gethrtime();
5360 
5361 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5362 
5363 	if (!isdotdot && res.status == NFS4ERR_MOVED) {
5364 		e.error = nfs4_setup_referral(dvp, nm, vpp, cr);
5365 		if (e.error != 0 && *vpp != NULL)
5366 			VN_RELE(*vpp);
5367 		nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5368 		    &recov_state, FALSE);
5369 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5370 		kmem_free(argop, argoplist_size);
5371 		return (e.error);
5372 	}
5373 
5374 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5375 		/*
5376 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5377 		 * from this thread, do not go thru the recovery thread since
5378 		 * we need the nm information.
5379 		 *
5380 		 * Not doing dotdot case because there is no specification
5381 		 * for (PUTFH, SECINFO "..") yet.
5382 		 */
5383 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5384 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr)))
5385 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5386 				    &recov_state, FALSE);
5387 			else
5388 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5389 				    &recov_state, TRUE);
5390 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5391 			kmem_free(argop, argoplist_size);
5392 			if (!e.error)
5393 				goto recov_retry;
5394 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5395 			VN_RELE(*vpp);
5396 			*vpp = NULL;
5397 			return (e.error);
5398 		}
5399 
5400 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5401 		    OP_LOOKUP, NULL, NULL, NULL) == FALSE) {
5402 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5403 			    &recov_state, TRUE);
5404 
5405 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5406 			kmem_free(argop, argoplist_size);
5407 			goto recov_retry;
5408 		}
5409 	}
5410 
5411 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5412 
5413 	if (e.error || res.array_len == 0) {
5414 		/*
5415 		 * If e.error isn't set, then reply has no ops (or we couldn't
5416 		 * be here).  The only legal way to reply without an op array
5417 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5418 		 * be in the reply for all other status values.
5419 		 *
5420 		 * For valid replies without an ops array, return ENOTSUP
5421 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5422 		 * return EIO -- don't trust status.
5423 		 */
5424 		if (e.error == 0)
5425 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5426 			    ENOTSUP : EIO;
5427 		VN_RELE(*vpp);
5428 		*vpp = NULL;
5429 		kmem_free(argop, argoplist_size);
5430 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5431 		return (e.error);
5432 	}
5433 
5434 	if (res.status != NFS4ERR_SAME) {
5435 		e.error = geterrno4(res.status);
5436 
5437 		/*
5438 		 * The NVERIFY "failed" so the directory has changed
5439 		 * First make sure PUTFH succeeded and NVERIFY "failed"
5440 		 * cleanly.
5441 		 */
5442 		if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5443 		    (res.array[1].nfs_resop4_u.opnverify.status != NFS4_OK)) {
5444 			nfs4_purge_stale_fh(e.error, dvp, cr);
5445 			VN_RELE(*vpp);
5446 			*vpp = NULL;
5447 			goto exit;
5448 		}
5449 
5450 		/*
5451 		 * We know the NVERIFY "failed" so we must:
5452 		 *	purge the caches (access and indirectly dnlc if needed)
5453 		 */
5454 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5455 
5456 		if (res.array[2].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5457 			nfs4_purge_stale_fh(e.error, dvp, cr);
5458 			VN_RELE(*vpp);
5459 			*vpp = NULL;
5460 			goto exit;
5461 		}
5462 
5463 		/*
5464 		 * Install new cached attributes for the directory
5465 		 */
5466 		nfs4_attr_cache(dvp,
5467 		    &res.array[2].nfs_resop4_u.opgetattr.ga_res,
5468 		    t, cr, FALSE, NULL);
5469 
5470 		if (res.array[3].nfs_resop4_u.opaccess.status != NFS4_OK) {
5471 			nfs4_purge_stale_fh(e.error, dvp, cr);
5472 			VN_RELE(*vpp);
5473 			*vpp = NULL;
5474 			e.error = geterrno4(res.status);
5475 			goto exit;
5476 		}
5477 
5478 		/*
5479 		 * Now we know the directory is valid,
5480 		 * cache new directory access
5481 		 */
5482 		nfs4_access_cache(drp,
5483 		    args.array[3].nfs_argop4_u.opaccess.access,
5484 		    res.array[3].nfs_resop4_u.opaccess.access, cr);
5485 
5486 		/*
5487 		 * recheck VEXEC access
5488 		 */
5489 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5490 		if (cacc != NFS4_ACCESS_ALLOWED) {
5491 			/*
5492 			 * Directory permissions might have been revoked
5493 			 */
5494 			if (cacc == NFS4_ACCESS_DENIED) {
5495 				e.error = EACCES;
5496 				VN_RELE(*vpp);
5497 				*vpp = NULL;
5498 				goto exit;
5499 			}
5500 
5501 			/*
5502 			 * Somehow we must not have asked for enough
5503 			 * so try a singleton ACCESS, should never happen.
5504 			 */
5505 			e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5506 			if (e.error) {
5507 				VN_RELE(*vpp);
5508 				*vpp = NULL;
5509 				goto exit;
5510 			}
5511 		}
5512 
5513 		e.error = geterrno4(res.status);
5514 		if (res.array[4].nfs_resop4_u.oplookup.status != NFS4_OK) {
5515 			/*
5516 			 * The lookup failed, probably no entry
5517 			 */
5518 			if (e.error == ENOENT && nfs4_lookup_neg_cache) {
5519 				dnlc_update(dvp, nm, DNLC_NO_VNODE);
5520 			} else {
5521 				/*
5522 				 * Might be some other error, so remove
5523 				 * the dnlc entry to make sure we start all
5524 				 * over again, next time.
5525 				 */
5526 				dnlc_remove(dvp, nm);
5527 			}
5528 			VN_RELE(*vpp);
5529 			*vpp = NULL;
5530 			goto exit;
5531 		}
5532 
5533 		if (res.array[5].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5534 			/*
5535 			 * The file exists but we can't get its fh for
5536 			 * some unknown reason.  Remove it from the dnlc
5537 			 * and error out to be safe.
5538 			 */
5539 			dnlc_remove(dvp, nm);
5540 			VN_RELE(*vpp);
5541 			*vpp = NULL;
5542 			goto exit;
5543 		}
5544 		fhp = &res.array[5].nfs_resop4_u.opgetfh.object;
5545 		if (fhp->nfs_fh4_len == 0) {
5546 			/*
5547 			 * The file exists but a bogus fh
5548 			 * some unknown reason.  Remove it from the dnlc
5549 			 * and error out to be safe.
5550 			 */
5551 			e.error = ENOENT;
5552 			dnlc_remove(dvp, nm);
5553 			VN_RELE(*vpp);
5554 			*vpp = NULL;
5555 			goto exit;
5556 		}
5557 		sfhp = sfh4_get(fhp, mi);
5558 
5559 		if (res.array[6].nfs_resop4_u.opgetattr.status == NFS4_OK)
5560 			garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
5561 
5562 		/*
5563 		 * Make the new rnode
5564 		 */
5565 		if (isdotdot) {
5566 			e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
5567 			if (e.error) {
5568 				sfh4_rele(&sfhp);
5569 				VN_RELE(*vpp);
5570 				*vpp = NULL;
5571 				goto exit;
5572 			}
5573 			/*
5574 			 * XXX if nfs4_make_dotdot uses an existing rnode
5575 			 * XXX it doesn't update the attributes.
5576 			 * XXX for now just save them again to save an OTW
5577 			 */
5578 			nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
5579 		} else {
5580 			nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
5581 			    dvp, fn_get(VTOSV(dvp)->sv_name, nm, sfhp));
5582 			/*
5583 			 * If v_type == VNON, then garp was NULL because
5584 			 * the last op in the compound failed and makenfs4node
5585 			 * could not find the vnode for sfhp. It created
5586 			 * a new vnode, so we have nothing to purge here.
5587 			 */
5588 			if (nvp->v_type == VNON) {
5589 				vattr_t vattr;
5590 
5591 				vattr.va_mask = AT_TYPE;
5592 				/*
5593 				 * N.B. We've already called nfs4_end_fop above.
5594 				 */
5595 				e.error = nfs4getattr(nvp, &vattr, cr);
5596 				if (e.error) {
5597 					sfh4_rele(&sfhp);
5598 					VN_RELE(*vpp);
5599 					*vpp = NULL;
5600 					VN_RELE(nvp);
5601 					goto exit;
5602 				}
5603 				nvp->v_type = vattr.va_type;
5604 			}
5605 		}
5606 		sfh4_rele(&sfhp);
5607 
5608 		nrp = VTOR4(nvp);
5609 		mutex_enter(&nrp->r_statev4_lock);
5610 		if (!nrp->created_v4) {
5611 			mutex_exit(&nrp->r_statev4_lock);
5612 			dnlc_update(dvp, nm, nvp);
5613 		} else
5614 			mutex_exit(&nrp->r_statev4_lock);
5615 
5616 		VN_RELE(*vpp);
5617 		*vpp = nvp;
5618 	} else {
5619 		hrtime_t now;
5620 		hrtime_t delta = 0;
5621 
5622 		e.error = 0;
5623 
5624 		/*
5625 		 * Because the NVERIFY "succeeded" we know that the
5626 		 * directory attributes are still valid
5627 		 * so update r_time_attr_inval
5628 		 */
5629 		now = gethrtime();
5630 		mutex_enter(&drp->r_statelock);
5631 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
5632 			delta = now - drp->r_time_attr_saved;
5633 			if (delta < mi->mi_acdirmin)
5634 				delta = mi->mi_acdirmin;
5635 			else if (delta > mi->mi_acdirmax)
5636 				delta = mi->mi_acdirmax;
5637 		}
5638 		drp->r_time_attr_inval = now + delta;
5639 		mutex_exit(&drp->r_statelock);
5640 		dnlc_update(dvp, nm, *vpp);
5641 
5642 		/*
5643 		 * Even though we have a valid directory attr cache
5644 		 * and dnlc entry, we may not have access.
5645 		 * This should almost always hit the cache.
5646 		 */
5647 		e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5648 		if (e.error) {
5649 			VN_RELE(*vpp);
5650 			*vpp = NULL;
5651 		}
5652 
5653 		if (*vpp == DNLC_NO_VNODE) {
5654 			VN_RELE(*vpp);
5655 			*vpp = NULL;
5656 			e.error = ENOENT;
5657 		}
5658 	}
5659 
5660 exit:
5661 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5662 	kmem_free(argop, argoplist_size);
5663 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5664 	return (e.error);
5665 }
5666 
5667 /*
5668  * We need to go over the wire to lookup the name, but
5669  * while we are there verify the directory has not
5670  * changed but if it has, get new attributes and check access
5671  *
5672  * PUTFH dfh SAVEFH LOOKUP nm GETFH GETATTR RESTOREFH
5673  *					NVERIFY GETATTR ACCESS
5674  *
5675  * With the results:
5676  *	if the NVERIFY failed we must purge the caches, add new attributes,
5677  *		and cache new access.
5678  *	set a new r_time_attr_inval
5679  *	add name to dnlc, possibly negative
5680  *	if LOOKUP succeeded
5681  *		cache new attributes
5682  */
5683 static int
nfs4lookupnew_otw(vnode_t * dvp,char * nm,vnode_t ** vpp,cred_t * cr)5684 nfs4lookupnew_otw(vnode_t *dvp, char *nm, vnode_t **vpp, cred_t *cr)
5685 {
5686 	COMPOUND4args_clnt args;
5687 	COMPOUND4res_clnt res;
5688 	fattr4 *ver_fattr;
5689 	fattr4_change dchange;
5690 	int32_t *ptr;
5691 	nfs4_ga_res_t *garp = NULL;
5692 	int argoplist_size  = 9 * sizeof (nfs_argop4);
5693 	nfs_argop4 *argop;
5694 	int doqueue;
5695 	mntinfo4_t *mi;
5696 	nfs4_recov_state_t recov_state;
5697 	hrtime_t t;
5698 	int isdotdot;
5699 	vnode_t *nvp;
5700 	nfs_fh4 *fhp;
5701 	nfs4_sharedfh_t *sfhp;
5702 	nfs4_access_type_t cacc;
5703 	rnode4_t *nrp;
5704 	rnode4_t *drp = VTOR4(dvp);
5705 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
5706 
5707 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
5708 	ASSERT(nm != NULL);
5709 	ASSERT(nm[0] != '\0');
5710 	ASSERT(dvp->v_type == VDIR);
5711 	ASSERT(nm[0] != '.' || nm[1] != '\0');
5712 	ASSERT(*vpp == NULL);
5713 
5714 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0') {
5715 		isdotdot = 1;
5716 		args.ctag = TAG_LOOKUP_PARENT;
5717 	} else {
5718 		/*
5719 		 * If dvp were a stub, it should have triggered and caused
5720 		 * a mount for us to get this far.
5721 		 */
5722 		ASSERT(!RP_ISSTUB(VTOR4(dvp)));
5723 
5724 		isdotdot = 0;
5725 		args.ctag = TAG_LOOKUP;
5726 	}
5727 
5728 	mi = VTOMI4(dvp);
5729 	recov_state.rs_flags = 0;
5730 	recov_state.rs_num_retry_despite_err = 0;
5731 
5732 	nvp = NULL;
5733 
5734 	/* Save the original mount point security information */
5735 	(void) save_mnt_secinfo(mi->mi_curr_serv);
5736 
5737 recov_retry:
5738 	e.error = nfs4_start_fop(mi, dvp, NULL, OH_LOOKUP,
5739 	    &recov_state, NULL);
5740 	if (e.error) {
5741 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5742 		return (e.error);
5743 	}
5744 
5745 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
5746 
5747 	/* PUTFH SAVEFH LOOKUP GETFH GETATTR RESTOREFH NVERIFY GETATTR ACCESS */
5748 	args.array_len = 9;
5749 	args.array = argop;
5750 
5751 	/* 0. putfh file */
5752 	argop[0].argop = OP_CPUTFH;
5753 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(dvp)->r_fh;
5754 
5755 	/* 1. savefh for the nverify */
5756 	argop[1].argop = OP_SAVEFH;
5757 
5758 	/* 2. lookup name */
5759 	if (isdotdot) {
5760 		argop[2].argop = OP_LOOKUPP;
5761 	} else {
5762 		argop[2].argop = OP_CLOOKUP;
5763 		argop[2].nfs_argop4_u.opclookup.cname = nm;
5764 	}
5765 
5766 	/* 3. resulting file handle */
5767 	argop[3].argop = OP_GETFH;
5768 
5769 	/* 4. resulting file attributes */
5770 	argop[4].argop = OP_GETATTR;
5771 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5772 	argop[4].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5773 
5774 	/* 5. restorefh back the directory for the nverify */
5775 	argop[5].argop = OP_RESTOREFH;
5776 
5777 	/* 6. nverify the change info */
5778 	argop[6].argop = OP_NVERIFY;
5779 	ver_fattr = &argop[6].nfs_argop4_u.opnverify.obj_attributes;
5780 	ver_fattr->attrmask = FATTR4_CHANGE_MASK;
5781 	ver_fattr->attrlist4 = (char *)&dchange;
5782 	ptr = (int32_t *)&dchange;
5783 	IXDR_PUT_HYPER(ptr, VTOR4(dvp)->r_change);
5784 	ver_fattr->attrlist4_len = sizeof (fattr4_change);
5785 
5786 	/* 7. getattr directory */
5787 	argop[7].argop = OP_GETATTR;
5788 	argop[7].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
5789 	argop[7].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
5790 
5791 	/* 8. access directory */
5792 	argop[8].argop = OP_ACCESS;
5793 	argop[8].nfs_argop4_u.opaccess.access = ACCESS4_READ | ACCESS4_DELETE |
5794 	    ACCESS4_MODIFY | ACCESS4_EXTEND | ACCESS4_LOOKUP;
5795 
5796 	doqueue = 1;
5797 	t = gethrtime();
5798 
5799 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
5800 
5801 	if (!isdotdot && res.status == NFS4ERR_MOVED) {
5802 		e.error = nfs4_setup_referral(dvp, nm, vpp, cr);
5803 		if (e.error != 0 && *vpp != NULL)
5804 			VN_RELE(*vpp);
5805 		nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5806 		    &recov_state, FALSE);
5807 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5808 		kmem_free(argop, argoplist_size);
5809 		return (e.error);
5810 	}
5811 
5812 	if (nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp)) {
5813 		/*
5814 		 * For WRONGSEC of a non-dotdot case, send secinfo directly
5815 		 * from this thread, do not go thru the recovery thread since
5816 		 * we need the nm information.
5817 		 *
5818 		 * Not doing dotdot case because there is no specification
5819 		 * for (PUTFH, SECINFO "..") yet.
5820 		 */
5821 		if (!isdotdot && res.status == NFS4ERR_WRONGSEC) {
5822 			if ((e.error = nfs4_secinfo_vnode_otw(dvp, nm, cr)))
5823 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5824 				    &recov_state, FALSE);
5825 			else
5826 				nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5827 				    &recov_state, TRUE);
5828 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5829 			kmem_free(argop, argoplist_size);
5830 			if (!e.error)
5831 				goto recov_retry;
5832 			(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5833 			return (e.error);
5834 		}
5835 
5836 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
5837 		    OP_LOOKUP, NULL, NULL, NULL) == FALSE) {
5838 			nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP,
5839 			    &recov_state, TRUE);
5840 
5841 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
5842 			kmem_free(argop, argoplist_size);
5843 			goto recov_retry;
5844 		}
5845 	}
5846 
5847 	nfs4_end_fop(mi, dvp, NULL, OH_LOOKUP, &recov_state, FALSE);
5848 
5849 	if (e.error || res.array_len == 0) {
5850 		/*
5851 		 * If e.error isn't set, then reply has no ops (or we couldn't
5852 		 * be here).  The only legal way to reply without an op array
5853 		 * is via NFS4ERR_MINOR_VERS_MISMATCH.  An ops array should
5854 		 * be in the reply for all other status values.
5855 		 *
5856 		 * For valid replies without an ops array, return ENOTSUP
5857 		 * (geterrno4 xlation of VERS_MISMATCH).  For illegal replies,
5858 		 * return EIO -- don't trust status.
5859 		 */
5860 		if (e.error == 0)
5861 			e.error = (res.status == NFS4ERR_MINOR_VERS_MISMATCH) ?
5862 			    ENOTSUP : EIO;
5863 
5864 		kmem_free(argop, argoplist_size);
5865 		(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
5866 		return (e.error);
5867 	}
5868 
5869 	e.error = geterrno4(res.status);
5870 
5871 	/*
5872 	 * The PUTFH and SAVEFH may have failed.
5873 	 */
5874 	if ((res.array[0].nfs_resop4_u.opputfh.status != NFS4_OK) ||
5875 	    (res.array[1].nfs_resop4_u.opsavefh.status != NFS4_OK)) {
5876 		nfs4_purge_stale_fh(e.error, dvp, cr);
5877 		goto exit;
5878 	}
5879 
5880 	/*
5881 	 * Check if the file exists, if it does delay entering
5882 	 * into the dnlc until after we update the directory
5883 	 * attributes so we don't cause it to get purged immediately.
5884 	 */
5885 	if (res.array[2].nfs_resop4_u.oplookup.status != NFS4_OK) {
5886 		/*
5887 		 * The lookup failed, probably no entry
5888 		 */
5889 		if (e.error == ENOENT && nfs4_lookup_neg_cache)
5890 			dnlc_update(dvp, nm, DNLC_NO_VNODE);
5891 		goto exit;
5892 	}
5893 
5894 	if (res.array[3].nfs_resop4_u.opgetfh.status != NFS4_OK) {
5895 		/*
5896 		 * The file exists but we can't get its fh for
5897 		 * some unknown reason. Error out to be safe.
5898 		 */
5899 		goto exit;
5900 	}
5901 
5902 	fhp = &res.array[3].nfs_resop4_u.opgetfh.object;
5903 	if (fhp->nfs_fh4_len == 0) {
5904 		/*
5905 		 * The file exists but a bogus fh
5906 		 * some unknown reason.  Error out to be safe.
5907 		 */
5908 		e.error = EIO;
5909 		goto exit;
5910 	}
5911 	sfhp = sfh4_get(fhp, mi);
5912 
5913 	if (res.array[4].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5914 		sfh4_rele(&sfhp);
5915 		goto exit;
5916 	}
5917 	garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
5918 
5919 	/*
5920 	 * The RESTOREFH may have failed
5921 	 */
5922 	if (res.array[5].nfs_resop4_u.oprestorefh.status != NFS4_OK) {
5923 		sfh4_rele(&sfhp);
5924 		e.error = EIO;
5925 		goto exit;
5926 	}
5927 
5928 	if (res.array[6].nfs_resop4_u.opnverify.status != NFS4ERR_SAME) {
5929 		/*
5930 		 * First make sure the NVERIFY failed as we expected,
5931 		 * if it didn't then be conservative and error out
5932 		 * as we can't trust the directory.
5933 		 */
5934 		if (res.array[6].nfs_resop4_u.opnverify.status != NFS4_OK) {
5935 			sfh4_rele(&sfhp);
5936 			e.error = EIO;
5937 			goto exit;
5938 		}
5939 
5940 		/*
5941 		 * We know the NVERIFY "failed" so the directory has changed,
5942 		 * so we must:
5943 		 *	purge the caches (access and indirectly dnlc if needed)
5944 		 */
5945 		nfs4_purge_caches(dvp, NFS4_NOPURGE_DNLC, cr, TRUE);
5946 
5947 		if (res.array[7].nfs_resop4_u.opgetattr.status != NFS4_OK) {
5948 			sfh4_rele(&sfhp);
5949 			goto exit;
5950 		}
5951 		nfs4_attr_cache(dvp,
5952 		    &res.array[7].nfs_resop4_u.opgetattr.ga_res,
5953 		    t, cr, FALSE, NULL);
5954 
5955 		if (res.array[8].nfs_resop4_u.opaccess.status != NFS4_OK) {
5956 			nfs4_purge_stale_fh(e.error, dvp, cr);
5957 			sfh4_rele(&sfhp);
5958 			e.error = geterrno4(res.status);
5959 			goto exit;
5960 		}
5961 
5962 		/*
5963 		 * Now we know the directory is valid,
5964 		 * cache new directory access
5965 		 */
5966 		nfs4_access_cache(drp,
5967 		    args.array[8].nfs_argop4_u.opaccess.access,
5968 		    res.array[8].nfs_resop4_u.opaccess.access, cr);
5969 
5970 		/*
5971 		 * recheck VEXEC access
5972 		 */
5973 		cacc = nfs4_access_check(drp, ACCESS4_LOOKUP, cr);
5974 		if (cacc != NFS4_ACCESS_ALLOWED) {
5975 			/*
5976 			 * Directory permissions might have been revoked
5977 			 */
5978 			if (cacc == NFS4_ACCESS_DENIED) {
5979 				sfh4_rele(&sfhp);
5980 				e.error = EACCES;
5981 				goto exit;
5982 			}
5983 
5984 			/*
5985 			 * Somehow we must not have asked for enough
5986 			 * so try a singleton ACCESS should never happen
5987 			 */
5988 			e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
5989 			if (e.error) {
5990 				sfh4_rele(&sfhp);
5991 				goto exit;
5992 			}
5993 		}
5994 
5995 		e.error = geterrno4(res.status);
5996 	} else {
5997 		hrtime_t now;
5998 		hrtime_t delta = 0;
5999 
6000 		e.error = 0;
6001 
6002 		/*
6003 		 * Because the NVERIFY "succeeded" we know that the
6004 		 * directory attributes are still valid
6005 		 * so update r_time_attr_inval
6006 		 */
6007 		now = gethrtime();
6008 		mutex_enter(&drp->r_statelock);
6009 		if (!(mi->mi_flags & MI4_NOAC) && !(dvp->v_flag & VNOCACHE)) {
6010 			delta = now - drp->r_time_attr_saved;
6011 			if (delta < mi->mi_acdirmin)
6012 				delta = mi->mi_acdirmin;
6013 			else if (delta > mi->mi_acdirmax)
6014 				delta = mi->mi_acdirmax;
6015 		}
6016 		drp->r_time_attr_inval = now + delta;
6017 		mutex_exit(&drp->r_statelock);
6018 
6019 		/*
6020 		 * Even though we have a valid directory attr cache,
6021 		 * we may not have access.
6022 		 * This should almost always hit the cache.
6023 		 */
6024 		e.error = nfs4_access(dvp, VEXEC, 0, cr, NULL);
6025 		if (e.error) {
6026 			sfh4_rele(&sfhp);
6027 			goto exit;
6028 		}
6029 	}
6030 
6031 	/*
6032 	 * Now we have successfully completed the lookup, if the
6033 	 * directory has changed we now have the valid attributes.
6034 	 * We also know we have directory access.
6035 	 * Create the new rnode and insert it in the dnlc.
6036 	 */
6037 	if (isdotdot) {
6038 		e.error = nfs4_make_dotdot(sfhp, t, dvp, cr, &nvp, 1);
6039 		if (e.error) {
6040 			sfh4_rele(&sfhp);
6041 			goto exit;
6042 		}
6043 		/*
6044 		 * XXX if nfs4_make_dotdot uses an existing rnode
6045 		 * XXX it doesn't update the attributes.
6046 		 * XXX for now just save them again to save an OTW
6047 		 */
6048 		nfs4_attr_cache(nvp, garp, t, cr, FALSE, NULL);
6049 	} else {
6050 		nvp = makenfs4node(sfhp, garp, dvp->v_vfsp, t, cr,
6051 		    dvp, fn_get(VTOSV(dvp)->sv_name, nm, sfhp));
6052 	}
6053 	sfh4_rele(&sfhp);
6054 
6055 	nrp = VTOR4(nvp);
6056 	mutex_enter(&nrp->r_statev4_lock);
6057 	if (!nrp->created_v4) {
6058 		mutex_exit(&nrp->r_statev4_lock);
6059 		dnlc_update(dvp, nm, nvp);
6060 	} else
6061 		mutex_exit(&nrp->r_statev4_lock);
6062 
6063 	*vpp = nvp;
6064 
6065 exit:
6066 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6067 	kmem_free(argop, argoplist_size);
6068 	(void) check_mnt_secinfo(mi->mi_curr_serv, nvp);
6069 	return (e.error);
6070 }
6071 
6072 #ifdef DEBUG
6073 void
nfs4lookup_dump_compound(char * where,nfs_argop4 * argbase,int argcnt)6074 nfs4lookup_dump_compound(char *where, nfs_argop4 *argbase, int argcnt)
6075 {
6076 	uint_t i, len;
6077 	zoneid_t zoneid = getzoneid();
6078 	char *s;
6079 
6080 	zcmn_err(zoneid, CE_NOTE, "%s: dumping cmpd", where);
6081 	for (i = 0; i < argcnt; i++) {
6082 		nfs_argop4 *op = &argbase[i];
6083 		switch (op->argop) {
6084 		case OP_CPUTFH:
6085 		case OP_PUTFH:
6086 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putfh", i);
6087 			break;
6088 		case OP_PUTROOTFH:
6089 			zcmn_err(zoneid, CE_NOTE, "\t op %d, putrootfh", i);
6090 			break;
6091 		case OP_CLOOKUP:
6092 			s = op->nfs_argop4_u.opclookup.cname;
6093 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
6094 			break;
6095 		case OP_LOOKUP:
6096 			s = utf8_to_str(&op->nfs_argop4_u.oplookup.objname,
6097 			    &len, NULL);
6098 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookup %s", i, s);
6099 			kmem_free(s, len);
6100 			break;
6101 		case OP_LOOKUPP:
6102 			zcmn_err(zoneid, CE_NOTE, "\t op %d, lookupp ..", i);
6103 			break;
6104 		case OP_GETFH:
6105 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getfh", i);
6106 			break;
6107 		case OP_GETATTR:
6108 			zcmn_err(zoneid, CE_NOTE, "\t op %d, getattr", i);
6109 			break;
6110 		case OP_OPENATTR:
6111 			zcmn_err(zoneid, CE_NOTE, "\t op %d, openattr", i);
6112 			break;
6113 		default:
6114 			zcmn_err(zoneid, CE_NOTE, "\t op %d, opcode %d", i,
6115 			    op->argop);
6116 			break;
6117 		}
6118 	}
6119 }
6120 #endif
6121 
6122 /*
6123  * nfs4lookup_setup - constructs a multi-lookup compound request.
6124  *
6125  * Given the path "nm1/nm2/.../nmn", the following compound requests
6126  * may be created:
6127  *
6128  * Note: Getfh is not be needed because filehandle attr is mandatory, but it
6129  * is faster, for now.
6130  *
6131  * l4_getattrs indicates the type of compound requested.
6132  *
6133  * LKP4_NO_ATTRIBUTE - no attributes (used by secinfo):
6134  *
6135  *	compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ...  Lookup {nmn} }
6136  *
6137  *   total number of ops is n + 1.
6138  *
6139  * LKP4_LAST_NAMED_ATTR - multi-component path for a named
6140  *      attribute: create lookups plus one OPENATTR/GETFH/GETATTR
6141  *      before the last component, and only get attributes
6142  *      for the last component.  Note that the second-to-last
6143  *	pathname component is XATTR_RPATH, which does NOT go
6144  *	over-the-wire as a lookup.
6145  *
6146  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Lookup {nmn-2};
6147  *		Openattr; Getfh; Getattr; Lookup {nmn}; Getfh; Getattr }
6148  *
6149  *   and total number of ops is n + 5.
6150  *
6151  * LKP4_LAST_ATTRDIR - multi-component path for the hidden named
6152  *      attribute directory: create lookups plus an OPENATTR
6153  *	replacing the last lookup.  Note that the last pathname
6154  *	component is XATTR_RPATH, which does NOT go over-the-wire
6155  *	as a lookup.
6156  *
6157  *      compound { Put*fh; Lookup {nm1}; Lookup {nm2}; ... Getfh; Getattr;
6158  *		Openattr; Getfh; Getattr }
6159  *
6160  *   and total number of ops is n + 5.
6161  *
6162  * LKP4_ALL_ATTRIBUTES - create lookups and get attributes for intermediate
6163  *	nodes too.
6164  *
6165  *	compound { Put*fh; Lookup {nm1}; Getfh; Getattr;
6166  *		Lookup {nm2}; ...  Lookup {nmn}; Getfh; Getattr }
6167  *
6168  *   and total number of ops is 3*n + 1.
6169  *
6170  * All cases: returns the index in the arg array of the final LOOKUP op, or
6171  * -1 if no LOOKUPs were used.
6172  */
6173 int
nfs4lookup_setup(char * nm,lookup4_param_t * lookupargp,int needgetfh)6174 nfs4lookup_setup(char *nm, lookup4_param_t *lookupargp, int needgetfh)
6175 {
6176 	enum lkp4_attr_setup l4_getattrs = lookupargp->l4_getattrs;
6177 	nfs_argop4 *argbase, *argop;
6178 	int arglen, argcnt;
6179 	int n = 1;	/* number of components */
6180 	int nga = 1;	/* number of Getattr's in request */
6181 	char c = '\0', *s, *p;
6182 	int lookup_idx = -1;
6183 	int argoplist_size;
6184 
6185 	/* set lookuparg response result to 0 */
6186 	lookupargp->resp->status = NFS4_OK;
6187 
6188 	/* skip leading "/" or "." e.g. ".//./" if there is */
6189 	for (; ; nm++) {
6190 		if (*nm != '/' && *nm != '.')
6191 			break;
6192 
6193 		/* ".." is counted as 1 component */
6194 		if (*nm == '.' && *(nm + 1) != '/')
6195 			break;
6196 	}
6197 
6198 	/*
6199 	 * Find n = number of components - nm must be null terminated
6200 	 * Skip "." components.
6201 	 */
6202 	if (*nm != '\0')
6203 		for (n = 1, s = nm; *s != '\0'; s++) {
6204 			if ((*s == '/') && (*(s + 1) != '/') &&
6205 			    (*(s + 1) != '\0') &&
6206 			    !(*(s + 1) == '.' && (*(s + 2) == '/' ||
6207 			    *(s + 2) == '\0')))
6208 				n++;
6209 		}
6210 	else
6211 		n = 0;
6212 
6213 	/*
6214 	 * nga is number of components that need Getfh+Getattr
6215 	 */
6216 	switch (l4_getattrs) {
6217 	case LKP4_NO_ATTRIBUTES:
6218 		nga = 0;
6219 		break;
6220 	case LKP4_ALL_ATTRIBUTES:
6221 		nga = n;
6222 		/*
6223 		 * Always have at least 1 getfh, getattr pair
6224 		 */
6225 		if (nga == 0)
6226 			nga++;
6227 		break;
6228 	case LKP4_LAST_ATTRDIR:
6229 	case LKP4_LAST_NAMED_ATTR:
6230 		nga = n+1;
6231 		break;
6232 	}
6233 
6234 	/*
6235 	 * If change to use the filehandle attr instead of getfh
6236 	 * the following line can be deleted.
6237 	 */
6238 	nga *= 2;
6239 
6240 	/*
6241 	 * calculate number of ops in request as
6242 	 * header + trailer + lookups + getattrs
6243 	 */
6244 	arglen = lookupargp->header_len + lookupargp->trailer_len + n + nga;
6245 
6246 	argoplist_size = arglen * sizeof (nfs_argop4);
6247 	argop = argbase = kmem_alloc(argoplist_size, KM_SLEEP);
6248 	lookupargp->argsp->array = argop;
6249 
6250 	argcnt = lookupargp->header_len;
6251 	argop += argcnt;
6252 
6253 	/*
6254 	 * loop and create a lookup op and possibly getattr/getfh for
6255 	 * each component. Skip "." components.
6256 	 */
6257 	for (s = nm; *s != '\0'; s = p) {
6258 		/*
6259 		 * Set up a pathname struct for each component if needed
6260 		 */
6261 		while (*s == '/')
6262 			s++;
6263 		if (*s == '\0')
6264 			break;
6265 
6266 		for (p = s; (*p != '/') && (*p != '\0'); p++)
6267 			;
6268 		c = *p;
6269 		*p = '\0';
6270 
6271 		if (s[0] == '.' && s[1] == '\0') {
6272 			*p = c;
6273 			continue;
6274 		}
6275 		if (l4_getattrs == LKP4_LAST_ATTRDIR &&
6276 		    strcmp(s, XATTR_RPATH) == 0) {
6277 			/* getfh XXX may not be needed in future */
6278 			argop->argop = OP_GETFH;
6279 			argop++;
6280 			argcnt++;
6281 
6282 			/* getattr */
6283 			argop->argop = OP_GETATTR;
6284 			argop->nfs_argop4_u.opgetattr.attr_request =
6285 			    lookupargp->ga_bits;
6286 			argop->nfs_argop4_u.opgetattr.mi =
6287 			    lookupargp->mi;
6288 			argop++;
6289 			argcnt++;
6290 
6291 			/* openattr */
6292 			argop->argop = OP_OPENATTR;
6293 		} else if (l4_getattrs == LKP4_LAST_NAMED_ATTR &&
6294 		    strcmp(s, XATTR_RPATH) == 0) {
6295 			/* openattr */
6296 			argop->argop = OP_OPENATTR;
6297 			argop++;
6298 			argcnt++;
6299 
6300 			/* getfh XXX may not be needed in future */
6301 			argop->argop = OP_GETFH;
6302 			argop++;
6303 			argcnt++;
6304 
6305 			/* getattr */
6306 			argop->argop = OP_GETATTR;
6307 			argop->nfs_argop4_u.opgetattr.attr_request =
6308 			    lookupargp->ga_bits;
6309 			argop->nfs_argop4_u.opgetattr.mi =
6310 			    lookupargp->mi;
6311 			argop++;
6312 			argcnt++;
6313 			*p = c;
6314 			continue;
6315 		} else if (s[0] == '.' && s[1] == '.' && s[2] == '\0') {
6316 			/* lookupp */
6317 			argop->argop = OP_LOOKUPP;
6318 		} else {
6319 			/* lookup */
6320 			argop->argop = OP_LOOKUP;
6321 			(void) str_to_utf8(s,
6322 			    &argop->nfs_argop4_u.oplookup.objname);
6323 		}
6324 		lookup_idx = argcnt;
6325 		argop++;
6326 		argcnt++;
6327 
6328 		*p = c;
6329 
6330 		if (l4_getattrs == LKP4_ALL_ATTRIBUTES) {
6331 			/* getfh XXX may not be needed in future */
6332 			argop->argop = OP_GETFH;
6333 			argop++;
6334 			argcnt++;
6335 
6336 			/* getattr */
6337 			argop->argop = OP_GETATTR;
6338 			argop->nfs_argop4_u.opgetattr.attr_request =
6339 			    lookupargp->ga_bits;
6340 			argop->nfs_argop4_u.opgetattr.mi =
6341 			    lookupargp->mi;
6342 			argop++;
6343 			argcnt++;
6344 		}
6345 	}
6346 
6347 	if ((l4_getattrs != LKP4_NO_ATTRIBUTES) &&
6348 	    ((l4_getattrs != LKP4_ALL_ATTRIBUTES) || (lookup_idx < 0))) {
6349 		if (needgetfh) {
6350 			/* stick in a post-lookup getfh */
6351 			argop->argop = OP_GETFH;
6352 			argcnt++;
6353 			argop++;
6354 		}
6355 		/* post-lookup getattr */
6356 		argop->argop = OP_GETATTR;
6357 		argop->nfs_argop4_u.opgetattr.attr_request =
6358 		    lookupargp->ga_bits;
6359 		argop->nfs_argop4_u.opgetattr.mi = lookupargp->mi;
6360 		argcnt++;
6361 	}
6362 	argcnt += lookupargp->trailer_len;	/* actual op count */
6363 	lookupargp->argsp->array_len = argcnt;
6364 	lookupargp->arglen = arglen;
6365 
6366 #ifdef DEBUG
6367 	if (nfs4_client_lookup_debug)
6368 		nfs4lookup_dump_compound("nfs4lookup_setup", argbase, argcnt);
6369 #endif
6370 
6371 	return (lookup_idx);
6372 }
6373 
6374 static int
nfs4openattr(vnode_t * dvp,vnode_t ** avp,int cflag,cred_t * cr)6375 nfs4openattr(vnode_t *dvp, vnode_t **avp, int cflag, cred_t *cr)
6376 {
6377 	COMPOUND4args_clnt	args;
6378 	COMPOUND4res_clnt	res;
6379 	GETFH4res	*gf_res = NULL;
6380 	nfs_argop4	argop[4];
6381 	nfs_resop4	*resop = NULL;
6382 	nfs4_sharedfh_t *sfhp;
6383 	hrtime_t t;
6384 	nfs4_error_t	e;
6385 
6386 	rnode4_t	*drp;
6387 	int		doqueue = 1;
6388 	vnode_t		*vp;
6389 	int		needrecov = 0;
6390 	nfs4_recov_state_t recov_state;
6391 
6392 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
6393 
6394 	*avp = NULL;
6395 	recov_state.rs_flags = 0;
6396 	recov_state.rs_num_retry_despite_err = 0;
6397 
6398 recov_retry:
6399 	/* COMPOUND: putfh, openattr, getfh, getattr */
6400 	args.array_len = 4;
6401 	args.array = argop;
6402 	args.ctag = TAG_OPENATTR;
6403 
6404 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
6405 	if (e.error)
6406 		return (e.error);
6407 
6408 	drp = VTOR4(dvp);
6409 
6410 	/* putfh */
6411 	argop[0].argop = OP_CPUTFH;
6412 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6413 
6414 	/* openattr */
6415 	argop[1].argop = OP_OPENATTR;
6416 	argop[1].nfs_argop4_u.opopenattr.createdir = (cflag ? TRUE : FALSE);
6417 
6418 	/* getfh */
6419 	argop[2].argop = OP_GETFH;
6420 
6421 	/* getattr */
6422 	argop[3].argop = OP_GETATTR;
6423 	argop[3].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6424 	argop[3].nfs_argop4_u.opgetattr.mi = VTOMI4(dvp);
6425 
6426 	NFS4_DEBUG(nfs4_client_call_debug, (CE_NOTE,
6427 	    "nfs4openattr: %s call, drp %s", needrecov ? "recov" : "first",
6428 	    rnode4info(drp)));
6429 
6430 	t = gethrtime();
6431 
6432 	rfs4call(VTOMI4(dvp), &args, &res, cr, &doqueue, 0, &e);
6433 
6434 	needrecov = nfs4_needs_recovery(&e, FALSE, dvp->v_vfsp);
6435 	if (needrecov) {
6436 		bool_t abort;
6437 
6438 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
6439 		    "nfs4openattr: initiating recovery\n"));
6440 
6441 		abort = nfs4_start_recovery(&e,
6442 		    VTOMI4(dvp), dvp, NULL, NULL, NULL,
6443 		    OP_OPENATTR, NULL, NULL, NULL);
6444 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6445 		if (!e.error) {
6446 			e.error = geterrno4(res.status);
6447 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6448 		}
6449 		if (abort == FALSE)
6450 			goto recov_retry;
6451 		return (e.error);
6452 	}
6453 
6454 	if (e.error) {
6455 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6456 		return (e.error);
6457 	}
6458 
6459 	if (res.status) {
6460 		/*
6461 		 * If OTW errro is NOTSUPP, then it should be
6462 		 * translated to EINVAL.  All Solaris file system
6463 		 * implementations return EINVAL to the syscall layer
6464 		 * when the attrdir cannot be created due to an
6465 		 * implementation restriction or noxattr mount option.
6466 		 */
6467 		if (res.status == NFS4ERR_NOTSUPP) {
6468 			mutex_enter(&drp->r_statelock);
6469 			if (drp->r_xattr_dir)
6470 				VN_RELE(drp->r_xattr_dir);
6471 			VN_HOLD(NFS4_XATTR_DIR_NOTSUPP);
6472 			drp->r_xattr_dir = NFS4_XATTR_DIR_NOTSUPP;
6473 			mutex_exit(&drp->r_statelock);
6474 
6475 			e.error = EINVAL;
6476 		} else {
6477 			e.error = geterrno4(res.status);
6478 		}
6479 
6480 		if (e.error) {
6481 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6482 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
6483 			    needrecov);
6484 			return (e.error);
6485 		}
6486 	}
6487 
6488 	resop = &res.array[0];  /* putfh res */
6489 	ASSERT(resop->nfs_resop4_u.opgetfh.status == NFS4_OK);
6490 
6491 	resop = &res.array[1];  /* openattr res */
6492 	ASSERT(resop->nfs_resop4_u.opopenattr.status == NFS4_OK);
6493 
6494 	resop = &res.array[2];  /* getfh res */
6495 	gf_res = &resop->nfs_resop4_u.opgetfh;
6496 	if (gf_res->object.nfs_fh4_len == 0) {
6497 		*avp = NULL;
6498 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6499 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6500 		return (ENOENT);
6501 	}
6502 
6503 	sfhp = sfh4_get(&gf_res->object, VTOMI4(dvp));
6504 	vp = makenfs4node(sfhp, &res.array[3].nfs_resop4_u.opgetattr.ga_res,
6505 	    dvp->v_vfsp, t, cr, dvp,
6506 	    fn_get(VTOSV(dvp)->sv_name, XATTR_RPATH, sfhp));
6507 	sfh4_rele(&sfhp);
6508 
6509 	if (e.error)
6510 		PURGE_ATTRCACHE4(vp);
6511 
6512 	mutex_enter(&vp->v_lock);
6513 	vp->v_flag |= V_XATTRDIR;
6514 	mutex_exit(&vp->v_lock);
6515 
6516 	*avp = vp;
6517 
6518 	mutex_enter(&drp->r_statelock);
6519 	if (drp->r_xattr_dir)
6520 		VN_RELE(drp->r_xattr_dir);
6521 	VN_HOLD(vp);
6522 	drp->r_xattr_dir = vp;
6523 
6524 	/*
6525 	 * Invalidate pathconf4 cache because r_xattr_dir is no longer
6526 	 * NULL.  xattrs could be created at any time, and we have no
6527 	 * way to update pc4_xattr_exists in the base object if/when
6528 	 * it happens.
6529 	 */
6530 	drp->r_pathconf.pc4_xattr_valid = 0;
6531 
6532 	mutex_exit(&drp->r_statelock);
6533 
6534 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
6535 
6536 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
6537 
6538 	return (0);
6539 }
6540 
6541 /* ARGSUSED */
6542 static int
nfs4_create(vnode_t * dvp,char * nm,struct vattr * va,enum vcexcl exclusive,int mode,vnode_t ** vpp,cred_t * cr,int flags,caller_context_t * ct,vsecattr_t * vsecp)6543 nfs4_create(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
6544     int mode, vnode_t **vpp, cred_t *cr, int flags, caller_context_t *ct,
6545     vsecattr_t *vsecp)
6546 {
6547 	int error;
6548 	vnode_t *vp = NULL;
6549 	rnode4_t *rp;
6550 	struct vattr vattr;
6551 	rnode4_t *drp;
6552 	vnode_t *tempvp;
6553 	enum createmode4 createmode;
6554 	bool_t must_trunc = FALSE;
6555 	int	truncating = 0;
6556 
6557 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
6558 		return (EPERM);
6559 	if (exclusive == EXCL && (dvp->v_flag & V_XATTRDIR)) {
6560 		return (EINVAL);
6561 	}
6562 
6563 	/* . and .. have special meaning in the protocol, reject them. */
6564 
6565 	if (nm[0] == '.' && (nm[1] == '\0' || (nm[1] == '.' && nm[2] == '\0')))
6566 		return (EISDIR);
6567 
6568 	drp = VTOR4(dvp);
6569 
6570 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
6571 		return (EINTR);
6572 
6573 top:
6574 	/*
6575 	 * We make a copy of the attributes because the caller does not
6576 	 * expect us to change what va points to.
6577 	 */
6578 	vattr = *va;
6579 
6580 	/*
6581 	 * If the pathname is "", then dvp is the root vnode of
6582 	 * a remote file mounted over a local directory.
6583 	 * All that needs to be done is access
6584 	 * checking and truncation.  Note that we avoid doing
6585 	 * open w/ create because the parent directory might
6586 	 * be in pseudo-fs and the open would fail.
6587 	 */
6588 	if (*nm == '\0') {
6589 		error = 0;
6590 		VN_HOLD(dvp);
6591 		vp = dvp;
6592 		must_trunc = TRUE;
6593 	} else {
6594 		/*
6595 		 * We need to go over the wire, just to be sure whether the
6596 		 * file exists or not.  Using the DNLC can be dangerous in
6597 		 * this case when making a decision regarding existence.
6598 		 */
6599 		error = nfs4lookup(dvp, nm, &vp, cr, 1);
6600 	}
6601 
6602 	if (exclusive)
6603 		createmode = EXCLUSIVE4;
6604 	else
6605 		createmode = GUARDED4;
6606 
6607 	/*
6608 	 * error would be set if the file does not exist on the
6609 	 * server, so lets go create it.
6610 	 */
6611 	if (error) {
6612 		goto create_otw;
6613 	}
6614 
6615 	/*
6616 	 * File does exist on the server
6617 	 */
6618 	if (exclusive == EXCL)
6619 		error = EEXIST;
6620 	else if (vp->v_type == VDIR && (mode & VWRITE))
6621 		error = EISDIR;
6622 	else {
6623 		/*
6624 		 * If vnode is a device, create special vnode.
6625 		 */
6626 		if (ISVDEV(vp->v_type)) {
6627 			tempvp = vp;
6628 			vp = specvp(vp, vp->v_rdev, vp->v_type, cr);
6629 			VN_RELE(tempvp);
6630 		}
6631 		if (!(error = VOP_ACCESS(vp, mode, 0, cr, ct))) {
6632 			if ((vattr.va_mask & AT_SIZE) &&
6633 			    vp->v_type == VREG) {
6634 				rp = VTOR4(vp);
6635 				/*
6636 				 * Check here for large file handled
6637 				 * by LF-unaware process (as
6638 				 * ufs_create() does)
6639 				 */
6640 				if (!(flags & FOFFMAX)) {
6641 					mutex_enter(&rp->r_statelock);
6642 					if (rp->r_size > MAXOFF32_T)
6643 						error = EOVERFLOW;
6644 					mutex_exit(&rp->r_statelock);
6645 				}
6646 
6647 				/* if error is set then we need to return */
6648 				if (error) {
6649 					nfs_rw_exit(&drp->r_rwlock);
6650 					VN_RELE(vp);
6651 					return (error);
6652 				}
6653 
6654 				if (must_trunc) {
6655 					vattr.va_mask = AT_SIZE;
6656 					error = nfs4setattr(vp, &vattr, 0, cr,
6657 					    NULL);
6658 				} else {
6659 				/*
6660 				 * we know we have a regular file that already
6661 				 * exists and we may end up truncating the file
6662 				 * as a result of the open_otw, so flush out
6663 				 * any dirty pages for this file first.
6664 				 */
6665 					if (nfs4_has_pages(vp) &&
6666 					    ((rp->r_flags & R4DIRTY) ||
6667 					    rp->r_count > 0 ||
6668 					    rp->r_mapcnt > 0)) {
6669 						error = nfs4_putpage(vp,
6670 						    (offset_t)0, 0, 0, cr, ct);
6671 						if (error && (error == ENOSPC ||
6672 						    error == EDQUOT)) {
6673 							mutex_enter(
6674 							    &rp->r_statelock);
6675 							if (!rp->r_error)
6676 								rp->r_error =
6677 								    error;
6678 							mutex_exit(
6679 							    &rp->r_statelock);
6680 						}
6681 					}
6682 					vattr.va_mask = (AT_SIZE |
6683 					    AT_TYPE | AT_MODE);
6684 					vattr.va_type = VREG;
6685 					createmode = UNCHECKED4;
6686 					truncating = 1;
6687 					goto create_otw;
6688 				}
6689 			}
6690 		}
6691 	}
6692 	nfs_rw_exit(&drp->r_rwlock);
6693 	if (error) {
6694 		VN_RELE(vp);
6695 	} else {
6696 		vnode_t *tvp;
6697 		rnode4_t *trp;
6698 		tvp = vp;
6699 		if (vp->v_type == VREG) {
6700 			trp = VTOR4(vp);
6701 			if (IS_SHADOW(vp, trp))
6702 				tvp = RTOV4(trp);
6703 		}
6704 
6705 		if (must_trunc) {
6706 			/*
6707 			 * existing file got truncated, notify.
6708 			 */
6709 			vnevent_create(tvp, ct);
6710 		}
6711 
6712 		*vpp = vp;
6713 	}
6714 	return (error);
6715 
6716 create_otw:
6717 	dnlc_remove(dvp, nm);
6718 
6719 	ASSERT(vattr.va_mask & AT_TYPE);
6720 
6721 	/*
6722 	 * If not a regular file let nfs4mknod() handle it.
6723 	 */
6724 	if (vattr.va_type != VREG) {
6725 		error = nfs4mknod(dvp, nm, &vattr, exclusive, mode, vpp, cr);
6726 		nfs_rw_exit(&drp->r_rwlock);
6727 		return (error);
6728 	}
6729 
6730 	/*
6731 	 * It _is_ a regular file.
6732 	 */
6733 	ASSERT(vattr.va_mask & AT_MODE);
6734 	if (MANDMODE(vattr.va_mode)) {
6735 		nfs_rw_exit(&drp->r_rwlock);
6736 		return (EACCES);
6737 	}
6738 
6739 	/*
6740 	 * If this happens to be a mknod of a regular file, then flags will
6741 	 * have neither FREAD or FWRITE.  However, we must set at least one
6742 	 * for the call to nfs4open_otw.  If it's open(O_CREAT) driving
6743 	 * nfs4_create, then either FREAD, FWRITE, or FRDWR has already been
6744 	 * set (based on openmode specified by app).
6745 	 */
6746 	if ((flags & (FREAD|FWRITE)) == 0)
6747 		flags |= (FREAD|FWRITE);
6748 
6749 	error = nfs4open_otw(dvp, nm, &vattr, vpp, cr, 1, flags, createmode, 0);
6750 
6751 	if (vp != NULL) {
6752 		/* if create was successful, throw away the file's pages */
6753 		if (!error && (vattr.va_mask & AT_SIZE))
6754 			nfs4_invalidate_pages(vp, (vattr.va_size & PAGEMASK),
6755 			    cr);
6756 		/* release the lookup hold */
6757 		VN_RELE(vp);
6758 		vp = NULL;
6759 	}
6760 
6761 	/*
6762 	 * validate that we opened a regular file. This handles a misbehaving
6763 	 * server that returns an incorrect FH.
6764 	 */
6765 	if ((error == 0) && *vpp && (*vpp)->v_type != VREG) {
6766 		error = EISDIR;
6767 		VN_RELE(*vpp);
6768 	}
6769 
6770 	/*
6771 	 * If this is not an exclusive create, then the CREATE
6772 	 * request will be made with the GUARDED mode set.  This
6773 	 * means that the server will return EEXIST if the file
6774 	 * exists.  The file could exist because of a retransmitted
6775 	 * request.  In this case, we recover by starting over and
6776 	 * checking to see whether the file exists.  This second
6777 	 * time through it should and a CREATE request will not be
6778 	 * sent.
6779 	 *
6780 	 * This handles the problem of a dangling CREATE request
6781 	 * which contains attributes which indicate that the file
6782 	 * should be truncated.  This retransmitted request could
6783 	 * possibly truncate valid data in the file if not caught
6784 	 * by the duplicate request mechanism on the server or if
6785 	 * not caught by other means.  The scenario is:
6786 	 *
6787 	 * Client transmits CREATE request with size = 0
6788 	 * Client times out, retransmits request.
6789 	 * Response to the first request arrives from the server
6790 	 *  and the client proceeds on.
6791 	 * Client writes data to the file.
6792 	 * The server now processes retransmitted CREATE request
6793 	 *  and truncates file.
6794 	 *
6795 	 * The use of the GUARDED CREATE request prevents this from
6796 	 * happening because the retransmitted CREATE would fail
6797 	 * with EEXIST and would not truncate the file.
6798 	 */
6799 	if (error == EEXIST && exclusive == NONEXCL) {
6800 #ifdef DEBUG
6801 		nfs4_create_misses++;
6802 #endif
6803 		goto top;
6804 	}
6805 	nfs_rw_exit(&drp->r_rwlock);
6806 	if (truncating && !error && *vpp) {
6807 		vnode_t *tvp;
6808 		rnode4_t *trp;
6809 		/*
6810 		 * existing file got truncated, notify.
6811 		 */
6812 		tvp = *vpp;
6813 		trp = VTOR4(tvp);
6814 		if (IS_SHADOW(tvp, trp))
6815 			tvp = RTOV4(trp);
6816 		vnevent_create(tvp, ct);
6817 	}
6818 	return (error);
6819 }
6820 
6821 /*
6822  * Create compound (for mkdir, mknod, symlink):
6823  * { Putfh <dfh>; Create; Getfh; Getattr }
6824  * It's okay if setattr failed to set gid - this is not considered
6825  * an error, but purge attrs in that case.
6826  */
6827 static int
call_nfs4_create_req(vnode_t * dvp,char * nm,void * data,struct vattr * va,vnode_t ** vpp,cred_t * cr,nfs_ftype4 type)6828 call_nfs4_create_req(vnode_t *dvp, char *nm, void *data, struct vattr *va,
6829     vnode_t **vpp, cred_t *cr, nfs_ftype4 type)
6830 {
6831 	int need_end_op = FALSE;
6832 	COMPOUND4args_clnt args;
6833 	COMPOUND4res_clnt res, *resp = NULL;
6834 	nfs_argop4 *argop;
6835 	nfs_resop4 *resop;
6836 	int doqueue;
6837 	mntinfo4_t *mi;
6838 	rnode4_t *drp = VTOR4(dvp);
6839 	change_info4 *cinfo;
6840 	GETFH4res *gf_res;
6841 	struct vattr vattr;
6842 	vnode_t *vp;
6843 	fattr4 *crattr;
6844 	bool_t needrecov = FALSE;
6845 	nfs4_recov_state_t recov_state;
6846 	nfs4_sharedfh_t *sfhp = NULL;
6847 	hrtime_t t;
6848 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
6849 	int numops, argoplist_size, setgid_flag, idx_create, idx_fattr;
6850 	dirattr_info_t dinfo, *dinfop;
6851 	servinfo4_t *svp;
6852 	bitmap4 supp_attrs;
6853 
6854 	ASSERT(type == NF4DIR || type == NF4LNK || type == NF4BLK ||
6855 	    type == NF4CHR || type == NF4SOCK || type == NF4FIFO);
6856 
6857 	mi = VTOMI4(dvp);
6858 
6859 	/*
6860 	 * Make sure we properly deal with setting the right gid
6861 	 * on a new directory to reflect the parent's setgid bit
6862 	 */
6863 	setgid_flag = 0;
6864 	if (type == NF4DIR) {
6865 		struct vattr dva;
6866 
6867 		va->va_mode &= ~VSGID;
6868 		dva.va_mask = AT_MODE | AT_GID;
6869 		if (VOP_GETATTR(dvp, &dva, 0, cr, NULL) == 0) {
6870 
6871 			/*
6872 			 * If the parent's directory has the setgid bit set
6873 			 * _and_ the client was able to get a valid mapping
6874 			 * for the parent dir's owner_group, we want to
6875 			 * append NVERIFY(owner_group == dva.va_gid) and
6876 			 * SETTATTR to the CREATE compound.
6877 			 */
6878 			if (mi->mi_flags & MI4_GRPID || dva.va_mode & VSGID) {
6879 				setgid_flag = 1;
6880 				va->va_mode |= VSGID;
6881 				if (dva.va_gid != GID_NOBODY) {
6882 					va->va_mask |= AT_GID;
6883 					va->va_gid = dva.va_gid;
6884 				}
6885 			}
6886 		}
6887 	}
6888 
6889 	/*
6890 	 * Create ops:
6891 	 *	0:putfh(dir) 1:savefh(dir) 2:create 3:getfh(new) 4:getattr(new)
6892 	 *	5:restorefh(dir) 6:getattr(dir)
6893 	 *
6894 	 * if (setgid)
6895 	 *	0:putfh(dir) 1:create 2:getfh(new) 3:getattr(new)
6896 	 *	4:savefh(new) 5:putfh(dir) 6:getattr(dir) 7:restorefh(new)
6897 	 *	8:nverify 9:setattr
6898 	 */
6899 	if (setgid_flag) {
6900 		numops = 10;
6901 		idx_create = 1;
6902 		idx_fattr = 3;
6903 	} else {
6904 		numops = 7;
6905 		idx_create = 2;
6906 		idx_fattr = 4;
6907 	}
6908 
6909 	ASSERT(nfs_zone() == mi->mi_zone);
6910 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp))) {
6911 		return (EINTR);
6912 	}
6913 	recov_state.rs_flags = 0;
6914 	recov_state.rs_num_retry_despite_err = 0;
6915 
6916 	argoplist_size = numops * sizeof (nfs_argop4);
6917 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
6918 
6919 recov_retry:
6920 	if (type == NF4LNK)
6921 		args.ctag = TAG_SYMLINK;
6922 	else if (type == NF4DIR)
6923 		args.ctag = TAG_MKDIR;
6924 	else
6925 		args.ctag = TAG_MKNOD;
6926 
6927 	args.array_len = numops;
6928 	args.array = argop;
6929 
6930 	if (e.error = nfs4_start_op(mi, dvp, NULL, &recov_state)) {
6931 		nfs_rw_exit(&drp->r_rwlock);
6932 		kmem_free(argop, argoplist_size);
6933 		return (e.error);
6934 	}
6935 	need_end_op = TRUE;
6936 
6937 
6938 	/* 0: putfh directory */
6939 	argop[0].argop = OP_CPUTFH;
6940 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6941 
6942 	/* 1/2: Create object */
6943 	argop[idx_create].argop = OP_CCREATE;
6944 	argop[idx_create].nfs_argop4_u.opccreate.cname = nm;
6945 	argop[idx_create].nfs_argop4_u.opccreate.type = type;
6946 	if (type == NF4LNK) {
6947 		/*
6948 		 * symlink, treat name as data
6949 		 */
6950 		ASSERT(data != NULL);
6951 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.clinkdata =
6952 		    (char *)data;
6953 	}
6954 	if (type == NF4BLK || type == NF4CHR) {
6955 		ASSERT(data != NULL);
6956 		argop[idx_create].nfs_argop4_u.opccreate.ftype4_u.devdata =
6957 		    *((specdata4 *)data);
6958 	}
6959 
6960 	crattr = &argop[idx_create].nfs_argop4_u.opccreate.createattrs;
6961 
6962 	svp = drp->r_server;
6963 	(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
6964 	supp_attrs = svp->sv_supp_attrs;
6965 	nfs_rw_exit(&svp->sv_lock);
6966 
6967 	if (vattr_to_fattr4(va, NULL, crattr, 0, OP_CREATE, supp_attrs)) {
6968 		nfs_rw_exit(&drp->r_rwlock);
6969 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
6970 		e.error = EINVAL;
6971 		kmem_free(argop, argoplist_size);
6972 		return (e.error);
6973 	}
6974 
6975 	/* 2/3: getfh fh of created object */
6976 	ASSERT(idx_create + 1 == idx_fattr - 1);
6977 	argop[idx_create + 1].argop = OP_GETFH;
6978 
6979 	/* 3/4: getattr of new object */
6980 	argop[idx_fattr].argop = OP_GETATTR;
6981 	argop[idx_fattr].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6982 	argop[idx_fattr].nfs_argop4_u.opgetattr.mi = mi;
6983 
6984 	if (setgid_flag) {
6985 		vattr_t	_v;
6986 
6987 		argop[4].argop = OP_SAVEFH;
6988 
6989 		argop[5].argop = OP_CPUTFH;
6990 		argop[5].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
6991 
6992 		argop[6].argop = OP_GETATTR;
6993 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
6994 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
6995 
6996 		argop[7].argop = OP_RESTOREFH;
6997 
6998 		/*
6999 		 * nverify
7000 		 *
7001 		 * XXX - Revisit the last argument to nfs4_end_op()
7002 		 *	 once 5020486 is fixed.
7003 		 */
7004 		_v.va_mask = AT_GID;
7005 		_v.va_gid = va->va_gid;
7006 		if (e.error = nfs4args_verify(&argop[8], &_v, OP_NVERIFY,
7007 		    supp_attrs)) {
7008 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
7009 			nfs_rw_exit(&drp->r_rwlock);
7010 			nfs4_fattr4_free(crattr);
7011 			kmem_free(argop, argoplist_size);
7012 			return (e.error);
7013 		}
7014 
7015 		/*
7016 		 * setattr
7017 		 *
7018 		 * We _know_ we're not messing with AT_SIZE or AT_XTIME,
7019 		 * so no need for stateid or flags. Also we specify NULL
7020 		 * rp since we're only interested in setting owner_group
7021 		 * attributes.
7022 		 */
7023 		nfs4args_setattr(&argop[9], &_v, NULL, 0, NULL, cr, supp_attrs,
7024 		    &e.error, 0);
7025 
7026 		if (e.error) {
7027 			nfs4_end_op(mi, dvp, *vpp, &recov_state, TRUE);
7028 			nfs_rw_exit(&drp->r_rwlock);
7029 			nfs4_fattr4_free(crattr);
7030 			nfs4args_verify_free(&argop[8]);
7031 			kmem_free(argop, argoplist_size);
7032 			return (e.error);
7033 		}
7034 	} else {
7035 		argop[1].argop = OP_SAVEFH;
7036 
7037 		argop[5].argop = OP_RESTOREFH;
7038 
7039 		argop[6].argop = OP_GETATTR;
7040 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7041 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
7042 	}
7043 
7044 	dnlc_remove(dvp, nm);
7045 
7046 	doqueue = 1;
7047 	t = gethrtime();
7048 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
7049 
7050 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
7051 	if (e.error) {
7052 		PURGE_ATTRCACHE4(dvp);
7053 		if (!needrecov)
7054 			goto out;
7055 	}
7056 
7057 	if (needrecov) {
7058 		if (nfs4_start_recovery(&e, mi, dvp, NULL, NULL, NULL,
7059 		    OP_CREATE, NULL, NULL, NULL) == FALSE) {
7060 			nfs4_end_op(mi, dvp, NULL, &recov_state,
7061 			    needrecov);
7062 			need_end_op = FALSE;
7063 			nfs4_fattr4_free(crattr);
7064 			if (setgid_flag) {
7065 				nfs4args_verify_free(&argop[8]);
7066 				nfs4args_setattr_free(&argop[9]);
7067 			}
7068 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
7069 			goto recov_retry;
7070 		}
7071 	}
7072 
7073 	resp = &res;
7074 
7075 	if (res.status != NFS4_OK && res.array_len <= idx_fattr + 1) {
7076 
7077 		if (res.status == NFS4ERR_BADOWNER)
7078 			nfs4_log_badowner(mi, OP_CREATE);
7079 
7080 		e.error = geterrno4(res.status);
7081 
7082 		/*
7083 		 * This check is left over from when create was implemented
7084 		 * using a setattr op (instead of createattrs).  If the
7085 		 * putfh/create/getfh failed, the error was returned.  If
7086 		 * setattr/getattr failed, we keep going.
7087 		 *
7088 		 * It might be better to get rid of the GETFH also, and just
7089 		 * do PUTFH/CREATE/GETATTR since the FH attr is mandatory.
7090 		 * Then if any of the operations failed, we could return the
7091 		 * error now, and remove much of the error code below.
7092 		 */
7093 		if (res.array_len <= idx_fattr) {
7094 			/*
7095 			 * Either Putfh, Create or Getfh failed.
7096 			 */
7097 			PURGE_ATTRCACHE4(dvp);
7098 			/*
7099 			 * nfs4_purge_stale_fh() may generate otw calls through
7100 			 * nfs4_invalidate_pages. Hence the need to call
7101 			 * nfs4_end_op() here to avoid nfs4_start_op() deadlock.
7102 			 */
7103 			nfs4_end_op(mi, dvp, NULL, &recov_state,
7104 			    needrecov);
7105 			need_end_op = FALSE;
7106 			nfs4_purge_stale_fh(e.error, dvp, cr);
7107 			goto out;
7108 		}
7109 	}
7110 
7111 	resop = &res.array[idx_create];	/* create res */
7112 	cinfo = &resop->nfs_resop4_u.opcreate.cinfo;
7113 
7114 	resop = &res.array[idx_create + 1]; /* getfh res */
7115 	gf_res = &resop->nfs_resop4_u.opgetfh;
7116 
7117 	sfhp = sfh4_get(&gf_res->object, mi);
7118 	if (e.error) {
7119 		*vpp = vp = makenfs4node(sfhp, NULL, dvp->v_vfsp, t, cr, dvp,
7120 		    fn_get(VTOSV(dvp)->sv_name, nm, sfhp));
7121 		if (vp->v_type == VNON) {
7122 			vattr.va_mask = AT_TYPE;
7123 			/*
7124 			 * Need to call nfs4_end_op before nfs4getattr to avoid
7125 			 * potential nfs4_start_op deadlock. See RFE 4777612.
7126 			 */
7127 			nfs4_end_op(mi, dvp, NULL, &recov_state,
7128 			    needrecov);
7129 			need_end_op = FALSE;
7130 			e.error = nfs4getattr(vp, &vattr, cr);
7131 			if (e.error) {
7132 				VN_RELE(vp);
7133 				*vpp = NULL;
7134 				goto out;
7135 			}
7136 			vp->v_type = vattr.va_type;
7137 		}
7138 		e.error = 0;
7139 	} else {
7140 		*vpp = vp = makenfs4node(sfhp,
7141 		    &res.array[idx_fattr].nfs_resop4_u.opgetattr.ga_res,
7142 		    dvp->v_vfsp, t, cr,
7143 		    dvp, fn_get(VTOSV(dvp)->sv_name, nm, sfhp));
7144 	}
7145 
7146 	/*
7147 	 * If compound succeeded, then update dir attrs
7148 	 */
7149 	if (res.status == NFS4_OK) {
7150 		dinfo.di_garp = &res.array[6].nfs_resop4_u.opgetattr.ga_res;
7151 		dinfo.di_cred = cr;
7152 		dinfo.di_time_call = t;
7153 		dinfop = &dinfo;
7154 	} else
7155 		dinfop = NULL;
7156 
7157 	/* Update directory cache attribute, readdir and dnlc caches */
7158 	nfs4_update_dircaches(cinfo, dvp, vp, nm, dinfop);
7159 
7160 out:
7161 	if (sfhp != NULL)
7162 		sfh4_rele(&sfhp);
7163 	nfs_rw_exit(&drp->r_rwlock);
7164 	nfs4_fattr4_free(crattr);
7165 	if (setgid_flag) {
7166 		nfs4args_verify_free(&argop[8]);
7167 		nfs4args_setattr_free(&argop[9]);
7168 	}
7169 	if (resp)
7170 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7171 	if (need_end_op)
7172 		nfs4_end_op(mi, dvp, NULL, &recov_state, needrecov);
7173 
7174 	kmem_free(argop, argoplist_size);
7175 	return (e.error);
7176 }
7177 
7178 /* ARGSUSED */
7179 static int
nfs4mknod(vnode_t * dvp,char * nm,struct vattr * va,enum vcexcl exclusive,int mode,vnode_t ** vpp,cred_t * cr)7180 nfs4mknod(vnode_t *dvp, char *nm, struct vattr *va, enum vcexcl exclusive,
7181     int mode, vnode_t **vpp, cred_t *cr)
7182 {
7183 	int error;
7184 	vnode_t *vp;
7185 	nfs_ftype4 type;
7186 	specdata4 spec, *specp = NULL;
7187 
7188 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
7189 
7190 	switch (va->va_type) {
7191 	case VCHR:
7192 	case VBLK:
7193 		type = (va->va_type == VCHR) ? NF4CHR : NF4BLK;
7194 		spec.specdata1 = getmajor(va->va_rdev);
7195 		spec.specdata2 = getminor(va->va_rdev);
7196 		specp = &spec;
7197 		break;
7198 
7199 	case VFIFO:
7200 		type = NF4FIFO;
7201 		break;
7202 	case VSOCK:
7203 		type = NF4SOCK;
7204 		break;
7205 
7206 	default:
7207 		return (EINVAL);
7208 	}
7209 
7210 	error = call_nfs4_create_req(dvp, nm, specp, va, &vp, cr, type);
7211 	if (error) {
7212 		return (error);
7213 	}
7214 
7215 	/*
7216 	 * This might not be needed any more; special case to deal
7217 	 * with problematic v2/v3 servers.  Since create was unable
7218 	 * to set group correctly, not sure what hope setattr has.
7219 	 */
7220 	if (va->va_gid != VTOR4(vp)->r_attr.va_gid) {
7221 		va->va_mask = AT_GID;
7222 		(void) nfs4setattr(vp, va, 0, cr, NULL);
7223 	}
7224 
7225 	/*
7226 	 * If vnode is a device create special vnode
7227 	 */
7228 	if (ISVDEV(vp->v_type)) {
7229 		*vpp = specvp(vp, vp->v_rdev, vp->v_type, cr);
7230 		VN_RELE(vp);
7231 	} else {
7232 		*vpp = vp;
7233 	}
7234 	return (error);
7235 }
7236 
7237 /*
7238  * Remove requires that the current fh be the target directory.
7239  * After the operation, the current fh is unchanged.
7240  * The compound op structure is:
7241  *      PUTFH(targetdir), REMOVE
7242  *
7243  * Weirdness: if the vnode to be removed is open
7244  * we rename it instead of removing it and nfs_inactive
7245  * will remove the new name.
7246  */
7247 /* ARGSUSED */
7248 static int
nfs4_remove(vnode_t * dvp,char * nm,cred_t * cr,caller_context_t * ct,int flags)7249 nfs4_remove(vnode_t *dvp, char *nm, cred_t *cr, caller_context_t *ct, int flags)
7250 {
7251 	COMPOUND4args_clnt args;
7252 	COMPOUND4res_clnt res, *resp = NULL;
7253 	REMOVE4res *rm_res;
7254 	nfs_argop4 argop[3];
7255 	nfs_resop4 *resop;
7256 	vnode_t *vp;
7257 	char *tmpname;
7258 	int doqueue;
7259 	mntinfo4_t *mi;
7260 	rnode4_t *rp;
7261 	rnode4_t *drp;
7262 	int needrecov = 0;
7263 	nfs4_recov_state_t recov_state;
7264 	int isopen;
7265 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7266 	dirattr_info_t dinfo;
7267 
7268 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
7269 		return (EPERM);
7270 	drp = VTOR4(dvp);
7271 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
7272 		return (EINTR);
7273 
7274 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
7275 	if (e.error) {
7276 		nfs_rw_exit(&drp->r_rwlock);
7277 		return (e.error);
7278 	}
7279 
7280 	if (vp->v_type == VDIR) {
7281 		VN_RELE(vp);
7282 		nfs_rw_exit(&drp->r_rwlock);
7283 		return (EISDIR);
7284 	}
7285 
7286 	/*
7287 	 * First just remove the entry from the name cache, as it
7288 	 * is most likely the only entry for this vp.
7289 	 */
7290 	dnlc_remove(dvp, nm);
7291 
7292 	rp = VTOR4(vp);
7293 
7294 	/*
7295 	 * For regular file types, check to see if the file is open by looking
7296 	 * at the open streams.
7297 	 * For all other types, check the reference count on the vnode.  Since
7298 	 * they are not opened OTW they never have an open stream.
7299 	 *
7300 	 * If the file is open, rename it to .nfsXXXX.
7301 	 */
7302 	if (vp->v_type != VREG) {
7303 		/*
7304 		 * If the file has a v_count > 1 then there may be more than one
7305 		 * entry in the name cache due multiple links or an open file,
7306 		 * but we don't have the real reference count so flush all
7307 		 * possible entries.
7308 		 */
7309 		if (vp->v_count > 1)
7310 			dnlc_purge_vp(vp);
7311 
7312 		/*
7313 		 * Now we have the real reference count.
7314 		 */
7315 		isopen = vp->v_count > 1;
7316 	} else {
7317 		mutex_enter(&rp->r_os_lock);
7318 		isopen = list_head(&rp->r_open_streams) != NULL;
7319 		mutex_exit(&rp->r_os_lock);
7320 	}
7321 
7322 	mutex_enter(&rp->r_statelock);
7323 	if (isopen &&
7324 	    (rp->r_unldvp == NULL || strcmp(nm, rp->r_unlname) == 0)) {
7325 		mutex_exit(&rp->r_statelock);
7326 		tmpname = newname();
7327 		e.error = nfs4rename(dvp, nm, dvp, tmpname, cr, ct);
7328 		if (e.error)
7329 			kmem_free(tmpname, MAXNAMELEN);
7330 		else {
7331 			mutex_enter(&rp->r_statelock);
7332 			if (rp->r_unldvp == NULL) {
7333 				VN_HOLD(dvp);
7334 				rp->r_unldvp = dvp;
7335 				if (rp->r_unlcred != NULL)
7336 					crfree(rp->r_unlcred);
7337 				crhold(cr);
7338 				rp->r_unlcred = cr;
7339 				rp->r_unlname = tmpname;
7340 			} else {
7341 				kmem_free(rp->r_unlname, MAXNAMELEN);
7342 				rp->r_unlname = tmpname;
7343 			}
7344 			mutex_exit(&rp->r_statelock);
7345 		}
7346 		VN_RELE(vp);
7347 		nfs_rw_exit(&drp->r_rwlock);
7348 		return (e.error);
7349 	}
7350 	/*
7351 	 * Actually remove the file/dir
7352 	 */
7353 	mutex_exit(&rp->r_statelock);
7354 
7355 	/*
7356 	 * We need to flush any dirty pages which happen to
7357 	 * be hanging around before removing the file.
7358 	 * This shouldn't happen very often since in NFSv4
7359 	 * we should be close to open consistent.
7360 	 */
7361 	if (nfs4_has_pages(vp) &&
7362 	    ((rp->r_flags & R4DIRTY) || rp->r_count > 0)) {
7363 		e.error = nfs4_putpage(vp, (u_offset_t)0, 0, 0, cr, ct);
7364 		if (e.error && (e.error == ENOSPC || e.error == EDQUOT)) {
7365 			mutex_enter(&rp->r_statelock);
7366 			if (!rp->r_error)
7367 				rp->r_error = e.error;
7368 			mutex_exit(&rp->r_statelock);
7369 		}
7370 	}
7371 
7372 	mi = VTOMI4(dvp);
7373 
7374 	(void) nfs4delegreturn(rp, NFS4_DR_REOPEN);
7375 	recov_state.rs_flags = 0;
7376 	recov_state.rs_num_retry_despite_err = 0;
7377 
7378 recov_retry:
7379 	/*
7380 	 * Remove ops: putfh dir; remove
7381 	 */
7382 	args.ctag = TAG_REMOVE;
7383 	args.array_len = 3;
7384 	args.array = argop;
7385 
7386 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
7387 	if (e.error) {
7388 		nfs_rw_exit(&drp->r_rwlock);
7389 		VN_RELE(vp);
7390 		return (e.error);
7391 	}
7392 
7393 	/* putfh directory */
7394 	argop[0].argop = OP_CPUTFH;
7395 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
7396 
7397 	/* remove */
7398 	argop[1].argop = OP_CREMOVE;
7399 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
7400 
7401 	/* getattr dir */
7402 	argop[2].argop = OP_GETATTR;
7403 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7404 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
7405 
7406 	doqueue = 1;
7407 	dinfo.di_time_call = gethrtime();
7408 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
7409 
7410 	PURGE_ATTRCACHE4(vp);
7411 
7412 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
7413 	if (e.error)
7414 		PURGE_ATTRCACHE4(dvp);
7415 
7416 	if (needrecov) {
7417 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp,
7418 		    NULL, NULL, NULL, OP_REMOVE, NULL, NULL, NULL) == FALSE) {
7419 			if (!e.error)
7420 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7421 				    (caddr_t)&res);
7422 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
7423 			    needrecov);
7424 			goto recov_retry;
7425 		}
7426 	}
7427 
7428 	/*
7429 	 * Matching nfs4_end_op() for start_op() above.
7430 	 * There is a path in the code below which calls
7431 	 * nfs4_purge_stale_fh(), which may generate otw calls through
7432 	 * nfs4_invalidate_pages. Hence we need to call nfs4_end_op()
7433 	 * here to avoid nfs4_start_op() deadlock.
7434 	 */
7435 	nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
7436 
7437 	if (!e.error) {
7438 		resp = &res;
7439 
7440 		if (res.status) {
7441 			e.error = geterrno4(res.status);
7442 			PURGE_ATTRCACHE4(dvp);
7443 			nfs4_purge_stale_fh(e.error, dvp, cr);
7444 		} else {
7445 			resop = &res.array[1];	/* remove res */
7446 			rm_res = &resop->nfs_resop4_u.opremove;
7447 
7448 			dinfo.di_garp =
7449 			    &res.array[2].nfs_resop4_u.opgetattr.ga_res;
7450 			dinfo.di_cred = cr;
7451 
7452 			/* Update directory attr, readdir and dnlc caches */
7453 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
7454 			    &dinfo);
7455 		}
7456 	}
7457 	nfs_rw_exit(&drp->r_rwlock);
7458 	if (resp)
7459 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7460 
7461 	if (e.error == 0) {
7462 		vnode_t *tvp;
7463 		rnode4_t *trp;
7464 		trp = VTOR4(vp);
7465 		tvp = vp;
7466 		if (IS_SHADOW(vp, trp))
7467 			tvp = RTOV4(trp);
7468 		vnevent_remove(tvp, dvp, nm, ct);
7469 	}
7470 	VN_RELE(vp);
7471 	return (e.error);
7472 }
7473 
7474 /*
7475  * Link requires that the current fh be the target directory and the
7476  * saved fh be the source fh. After the operation, the current fh is unchanged.
7477  * Thus the compound op structure is:
7478  *	PUTFH(file), SAVEFH, PUTFH(targetdir), LINK, RESTOREFH,
7479  *	GETATTR(file)
7480  */
7481 /* ARGSUSED */
7482 static int
nfs4_link(vnode_t * tdvp,vnode_t * svp,char * tnm,cred_t * cr,caller_context_t * ct,int flags)7483 nfs4_link(vnode_t *tdvp, vnode_t *svp, char *tnm, cred_t *cr,
7484     caller_context_t *ct, int flags)
7485 {
7486 	COMPOUND4args_clnt args;
7487 	COMPOUND4res_clnt res, *resp = NULL;
7488 	LINK4res *ln_res;
7489 	int argoplist_size  = 7 * sizeof (nfs_argop4);
7490 	nfs_argop4 *argop;
7491 	nfs_resop4 *resop;
7492 	vnode_t *realvp, *nvp;
7493 	int doqueue;
7494 	mntinfo4_t *mi;
7495 	rnode4_t *tdrp;
7496 	bool_t needrecov = FALSE;
7497 	nfs4_recov_state_t recov_state;
7498 	hrtime_t t;
7499 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
7500 	dirattr_info_t dinfo;
7501 
7502 	ASSERT(*tnm != '\0');
7503 	ASSERT(tdvp->v_type == VDIR);
7504 	ASSERT(nfs4_consistent_type(tdvp));
7505 	ASSERT(nfs4_consistent_type(svp));
7506 
7507 	if (nfs_zone() != VTOMI4(tdvp)->mi_zone)
7508 		return (EPERM);
7509 	if (VOP_REALVP(svp, &realvp, ct) == 0) {
7510 		svp = realvp;
7511 		ASSERT(nfs4_consistent_type(svp));
7512 	}
7513 
7514 	tdrp = VTOR4(tdvp);
7515 	mi = VTOMI4(svp);
7516 
7517 	if (!(mi->mi_flags & MI4_LINK)) {
7518 		return (EOPNOTSUPP);
7519 	}
7520 	recov_state.rs_flags = 0;
7521 	recov_state.rs_num_retry_despite_err = 0;
7522 
7523 	if (nfs_rw_enter_sig(&tdrp->r_rwlock, RW_WRITER, INTR4(tdvp)))
7524 		return (EINTR);
7525 
7526 recov_retry:
7527 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
7528 
7529 	args.ctag = TAG_LINK;
7530 
7531 	/*
7532 	 * Link ops: putfh fl; savefh; putfh tdir; link; getattr(dir);
7533 	 * restorefh; getattr(fl)
7534 	 */
7535 	args.array_len = 7;
7536 	args.array = argop;
7537 
7538 	e.error = nfs4_start_op(VTOMI4(svp), svp, tdvp, &recov_state);
7539 	if (e.error) {
7540 		kmem_free(argop, argoplist_size);
7541 		nfs_rw_exit(&tdrp->r_rwlock);
7542 		return (e.error);
7543 	}
7544 
7545 	/* 0. putfh file */
7546 	argop[0].argop = OP_CPUTFH;
7547 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(svp)->r_fh;
7548 
7549 	/* 1. save current fh to free up the space for the dir */
7550 	argop[1].argop = OP_SAVEFH;
7551 
7552 	/* 2. putfh targetdir */
7553 	argop[2].argop = OP_CPUTFH;
7554 	argop[2].nfs_argop4_u.opcputfh.sfh = tdrp->r_fh;
7555 
7556 	/* 3. link: current_fh is targetdir, saved_fh is source */
7557 	argop[3].argop = OP_CLINK;
7558 	argop[3].nfs_argop4_u.opclink.cnewname = tnm;
7559 
7560 	/* 4. Get attributes of dir */
7561 	argop[4].argop = OP_GETATTR;
7562 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7563 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
7564 
7565 	/* 5. If link was successful, restore current vp to file */
7566 	argop[5].argop = OP_RESTOREFH;
7567 
7568 	/* 6. Get attributes of linked object */
7569 	argop[6].argop = OP_GETATTR;
7570 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
7571 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
7572 
7573 	dnlc_remove(tdvp, tnm);
7574 
7575 	doqueue = 1;
7576 	t = gethrtime();
7577 
7578 	rfs4call(VTOMI4(svp), &args, &res, cr, &doqueue, 0, &e);
7579 
7580 	needrecov = nfs4_needs_recovery(&e, FALSE, svp->v_vfsp);
7581 	if (e.error != 0 && !needrecov) {
7582 		PURGE_ATTRCACHE4(tdvp);
7583 		PURGE_ATTRCACHE4(svp);
7584 		nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7585 		goto out;
7586 	}
7587 
7588 	if (needrecov) {
7589 		bool_t abort;
7590 
7591 		abort = nfs4_start_recovery(&e, VTOMI4(svp), svp, tdvp,
7592 		    NULL, NULL, OP_LINK, NULL, NULL, NULL);
7593 		if (abort == FALSE) {
7594 			nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state,
7595 			    needrecov);
7596 			kmem_free(argop, argoplist_size);
7597 			if (!e.error)
7598 				(void) xdr_free(xdr_COMPOUND4res_clnt,
7599 				    (caddr_t)&res);
7600 			goto recov_retry;
7601 		} else {
7602 			if (e.error != 0) {
7603 				PURGE_ATTRCACHE4(tdvp);
7604 				PURGE_ATTRCACHE4(svp);
7605 				nfs4_end_op(VTOMI4(svp), svp, tdvp,
7606 				    &recov_state, needrecov);
7607 				goto out;
7608 			}
7609 			/* fall through for res.status case */
7610 		}
7611 	}
7612 
7613 	nfs4_end_op(VTOMI4(svp), svp, tdvp, &recov_state, needrecov);
7614 
7615 	resp = &res;
7616 	if (res.status) {
7617 		/* If link succeeded, then don't return error */
7618 		e.error = geterrno4(res.status);
7619 		if (res.array_len <= 4) {
7620 			/*
7621 			 * Either Putfh, Savefh, Putfh dir, or Link failed
7622 			 */
7623 			PURGE_ATTRCACHE4(svp);
7624 			PURGE_ATTRCACHE4(tdvp);
7625 			if (e.error == EOPNOTSUPP) {
7626 				mutex_enter(&mi->mi_lock);
7627 				mi->mi_flags &= ~MI4_LINK;
7628 				mutex_exit(&mi->mi_lock);
7629 			}
7630 			/* Remap EISDIR to EPERM for non-root user for SVVS */
7631 			/* XXX-LP */
7632 			if (e.error == EISDIR && crgetuid(cr) != 0)
7633 				e.error = EPERM;
7634 			goto out;
7635 		}
7636 	}
7637 
7638 	/* either no error or one of the postop getattr failed */
7639 
7640 	/*
7641 	 * XXX - if LINK succeeded, but no attrs were returned for link
7642 	 * file, purge its cache.
7643 	 *
7644 	 * XXX Perform a simplified version of wcc checking. Instead of
7645 	 * have another getattr to get pre-op, just purge cache if
7646 	 * any of the ops prior to and including the getattr failed.
7647 	 * If the getattr succeeded then update the attrcache accordingly.
7648 	 */
7649 
7650 	/*
7651 	 * update cache with link file postattrs.
7652 	 * Note: at this point resop points to link res.
7653 	 */
7654 	resop = &res.array[3];	/* link res */
7655 	ln_res = &resop->nfs_resop4_u.oplink;
7656 	if (res.status == NFS4_OK)
7657 		e.error = nfs4_update_attrcache(res.status,
7658 		    &res.array[6].nfs_resop4_u.opgetattr.ga_res,
7659 		    t, svp, cr);
7660 
7661 	/*
7662 	 * Call makenfs4node to create the new shadow vp for tnm.
7663 	 * We pass NULL attrs because we just cached attrs for
7664 	 * the src object.  All we're trying to accomplish is to
7665 	 * to create the new shadow vnode.
7666 	 */
7667 	nvp = makenfs4node(VTOR4(svp)->r_fh, NULL, tdvp->v_vfsp, t, cr,
7668 	    tdvp, fn_get(VTOSV(tdvp)->sv_name, tnm, VTOR4(svp)->r_fh));
7669 
7670 	/* Update target cache attribute, readdir and dnlc caches */
7671 	dinfo.di_garp = &res.array[4].nfs_resop4_u.opgetattr.ga_res;
7672 	dinfo.di_time_call = t;
7673 	dinfo.di_cred = cr;
7674 
7675 	nfs4_update_dircaches(&ln_res->cinfo, tdvp, nvp, tnm, &dinfo);
7676 	ASSERT(nfs4_consistent_type(tdvp));
7677 	ASSERT(nfs4_consistent_type(svp));
7678 	ASSERT(nfs4_consistent_type(nvp));
7679 	VN_RELE(nvp);
7680 
7681 	if (!e.error) {
7682 		vnode_t *tvp;
7683 		rnode4_t *trp;
7684 		/*
7685 		 * Notify the source file of this link operation.
7686 		 */
7687 		trp = VTOR4(svp);
7688 		tvp = svp;
7689 		if (IS_SHADOW(svp, trp))
7690 			tvp = RTOV4(trp);
7691 		vnevent_link(tvp, ct);
7692 	}
7693 out:
7694 	kmem_free(argop, argoplist_size);
7695 	if (resp)
7696 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
7697 
7698 	nfs_rw_exit(&tdrp->r_rwlock);
7699 
7700 	return (e.error);
7701 }
7702 
7703 /* ARGSUSED */
7704 static int
nfs4_rename(vnode_t * odvp,char * onm,vnode_t * ndvp,char * nnm,cred_t * cr,caller_context_t * ct,int flags)7705 nfs4_rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr,
7706     caller_context_t *ct, int flags)
7707 {
7708 	vnode_t *realvp;
7709 
7710 	if (nfs_zone() != VTOMI4(odvp)->mi_zone)
7711 		return (EPERM);
7712 	if (VOP_REALVP(ndvp, &realvp, ct) == 0)
7713 		ndvp = realvp;
7714 
7715 	return (nfs4rename(odvp, onm, ndvp, nnm, cr, ct));
7716 }
7717 
7718 /*
7719  * nfs4rename does the real work of renaming in NFS Version 4.
7720  *
7721  * A file handle is considered volatile for renaming purposes if either
7722  * of the volatile bits are turned on. However, the compound may differ
7723  * based on the likelihood of the filehandle to change during rename.
7724  */
7725 static int
nfs4rename(vnode_t * odvp,char * onm,vnode_t * ndvp,char * nnm,cred_t * cr,caller_context_t * ct)7726 nfs4rename(vnode_t *odvp, char *onm, vnode_t *ndvp, char *nnm, cred_t *cr,
7727     caller_context_t *ct)
7728 {
7729 	int error;
7730 	mntinfo4_t *mi;
7731 	vnode_t *nvp = NULL;
7732 	vnode_t *ovp = NULL;
7733 	char *tmpname = NULL;
7734 	rnode4_t *rp;
7735 	rnode4_t *odrp;
7736 	rnode4_t *ndrp;
7737 	int did_link = 0;
7738 	int do_link = 1;
7739 	nfsstat4 stat = NFS4_OK;
7740 
7741 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
7742 	ASSERT(nfs4_consistent_type(odvp));
7743 	ASSERT(nfs4_consistent_type(ndvp));
7744 
7745 	if (onm[0] == '.' && (onm[1] == '\0' ||
7746 	    (onm[1] == '.' && onm[2] == '\0')))
7747 		return (EINVAL);
7748 
7749 	if (nnm[0] == '.' && (nnm[1] == '\0' ||
7750 	    (nnm[1] == '.' && nnm[2] == '\0')))
7751 		return (EINVAL);
7752 
7753 	odrp = VTOR4(odvp);
7754 	ndrp = VTOR4(ndvp);
7755 	if ((intptr_t)odrp < (intptr_t)ndrp) {
7756 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp)))
7757 			return (EINTR);
7758 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp))) {
7759 			nfs_rw_exit(&odrp->r_rwlock);
7760 			return (EINTR);
7761 		}
7762 	} else {
7763 		if (nfs_rw_enter_sig(&ndrp->r_rwlock, RW_WRITER, INTR4(ndvp)))
7764 			return (EINTR);
7765 		if (nfs_rw_enter_sig(&odrp->r_rwlock, RW_WRITER, INTR4(odvp))) {
7766 			nfs_rw_exit(&ndrp->r_rwlock);
7767 			return (EINTR);
7768 		}
7769 	}
7770 
7771 	/*
7772 	 * Lookup the target file.  If it exists, it needs to be
7773 	 * checked to see whether it is a mount point and whether
7774 	 * it is active (open).
7775 	 */
7776 	error = nfs4lookup(ndvp, nnm, &nvp, cr, 0);
7777 	if (!error) {
7778 		int	isactive;
7779 
7780 		ASSERT(nfs4_consistent_type(nvp));
7781 		/*
7782 		 * If this file has been mounted on, then just
7783 		 * return busy because renaming to it would remove
7784 		 * the mounted file system from the name space.
7785 		 */
7786 		if (vn_ismntpt(nvp)) {
7787 			VN_RELE(nvp);
7788 			nfs_rw_exit(&odrp->r_rwlock);
7789 			nfs_rw_exit(&ndrp->r_rwlock);
7790 			return (EBUSY);
7791 		}
7792 
7793 		/*
7794 		 * First just remove the entry from the name cache, as it
7795 		 * is most likely the only entry for this vp.
7796 		 */
7797 		dnlc_remove(ndvp, nnm);
7798 
7799 		rp = VTOR4(nvp);
7800 
7801 		if (nvp->v_type != VREG) {
7802 			/*
7803 			 * Purge the name cache of all references to this vnode
7804 			 * so that we can check the reference count to infer
7805 			 * whether it is active or not.
7806 			 */
7807 			if (nvp->v_count > 1)
7808 				dnlc_purge_vp(nvp);
7809 
7810 			isactive = nvp->v_count > 1;
7811 		} else {
7812 			mutex_enter(&rp->r_os_lock);
7813 			isactive = list_head(&rp->r_open_streams) != NULL;
7814 			mutex_exit(&rp->r_os_lock);
7815 		}
7816 
7817 		/*
7818 		 * If the vnode is active and is not a directory,
7819 		 * arrange to rename it to a
7820 		 * temporary file so that it will continue to be
7821 		 * accessible.  This implements the "unlink-open-file"
7822 		 * semantics for the target of a rename operation.
7823 		 * Before doing this though, make sure that the
7824 		 * source and target files are not already the same.
7825 		 */
7826 		if (isactive && nvp->v_type != VDIR) {
7827 			/*
7828 			 * Lookup the source name.
7829 			 */
7830 			error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7831 
7832 			/*
7833 			 * The source name *should* already exist.
7834 			 */
7835 			if (error) {
7836 				VN_RELE(nvp);
7837 				nfs_rw_exit(&odrp->r_rwlock);
7838 				nfs_rw_exit(&ndrp->r_rwlock);
7839 				return (error);
7840 			}
7841 
7842 			ASSERT(nfs4_consistent_type(ovp));
7843 
7844 			/*
7845 			 * Compare the two vnodes.  If they are the same,
7846 			 * just release all held vnodes and return success.
7847 			 */
7848 			if (VN_CMP(ovp, nvp)) {
7849 				VN_RELE(ovp);
7850 				VN_RELE(nvp);
7851 				nfs_rw_exit(&odrp->r_rwlock);
7852 				nfs_rw_exit(&ndrp->r_rwlock);
7853 				return (0);
7854 			}
7855 
7856 			/*
7857 			 * Can't mix and match directories and non-
7858 			 * directories in rename operations.  We already
7859 			 * know that the target is not a directory.  If
7860 			 * the source is a directory, return an error.
7861 			 */
7862 			if (ovp->v_type == VDIR) {
7863 				VN_RELE(ovp);
7864 				VN_RELE(nvp);
7865 				nfs_rw_exit(&odrp->r_rwlock);
7866 				nfs_rw_exit(&ndrp->r_rwlock);
7867 				return (ENOTDIR);
7868 			}
7869 link_call:
7870 			/*
7871 			 * The target file exists, is not the same as
7872 			 * the source file, and is active.  We first
7873 			 * try to Link it to a temporary filename to
7874 			 * avoid having the server removing the file
7875 			 * completely (which could cause data loss to
7876 			 * the user's POV in the event the Rename fails
7877 			 * -- see bug 1165874).
7878 			 */
7879 			/*
7880 			 * The do_link and did_link booleans are
7881 			 * introduced in the event we get NFS4ERR_FILE_OPEN
7882 			 * returned for the Rename.  Some servers can
7883 			 * not Rename over an Open file, so they return
7884 			 * this error.  The client needs to Remove the
7885 			 * newly created Link and do two Renames, just
7886 			 * as if the server didn't support LINK.
7887 			 */
7888 			tmpname = newname();
7889 			error = 0;
7890 
7891 			if (do_link) {
7892 				error = nfs4_link(ndvp, nvp, tmpname, cr,
7893 				    NULL, 0);
7894 			}
7895 			if (error == EOPNOTSUPP || !do_link) {
7896 				error = nfs4_rename(ndvp, nnm, ndvp, tmpname,
7897 				    cr, NULL, 0);
7898 				did_link = 0;
7899 			} else {
7900 				did_link = 1;
7901 			}
7902 			if (error) {
7903 				kmem_free(tmpname, MAXNAMELEN);
7904 				VN_RELE(ovp);
7905 				VN_RELE(nvp);
7906 				nfs_rw_exit(&odrp->r_rwlock);
7907 				nfs_rw_exit(&ndrp->r_rwlock);
7908 				return (error);
7909 			}
7910 
7911 			mutex_enter(&rp->r_statelock);
7912 			if (rp->r_unldvp == NULL) {
7913 				VN_HOLD(ndvp);
7914 				rp->r_unldvp = ndvp;
7915 				if (rp->r_unlcred != NULL)
7916 					crfree(rp->r_unlcred);
7917 				crhold(cr);
7918 				rp->r_unlcred = cr;
7919 				rp->r_unlname = tmpname;
7920 			} else {
7921 				if (rp->r_unlname)
7922 					kmem_free(rp->r_unlname, MAXNAMELEN);
7923 				rp->r_unlname = tmpname;
7924 			}
7925 			mutex_exit(&rp->r_statelock);
7926 		}
7927 
7928 		(void) nfs4delegreturn(VTOR4(nvp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7929 
7930 		ASSERT(nfs4_consistent_type(nvp));
7931 	}
7932 
7933 	if (ovp == NULL) {
7934 		/*
7935 		 * When renaming directories to be a subdirectory of a
7936 		 * different parent, the dnlc entry for ".." will no
7937 		 * longer be valid, so it must be removed.
7938 		 *
7939 		 * We do a lookup here to determine whether we are renaming
7940 		 * a directory and we need to check if we are renaming
7941 		 * an unlinked file.  This might have already been done
7942 		 * in previous code, so we check ovp == NULL to avoid
7943 		 * doing it twice.
7944 		 */
7945 		error = nfs4lookup(odvp, onm, &ovp, cr, 0);
7946 		/*
7947 		 * The source name *should* already exist.
7948 		 */
7949 		if (error) {
7950 			nfs_rw_exit(&odrp->r_rwlock);
7951 			nfs_rw_exit(&ndrp->r_rwlock);
7952 			if (nvp) {
7953 				VN_RELE(nvp);
7954 			}
7955 			return (error);
7956 		}
7957 		ASSERT(ovp != NULL);
7958 		ASSERT(nfs4_consistent_type(ovp));
7959 	}
7960 
7961 	/*
7962 	 * Is the object being renamed a dir, and if so, is
7963 	 * it being renamed to a child of itself?  The underlying
7964 	 * fs should ultimately return EINVAL for this case;
7965 	 * however, buggy beta non-Solaris NFSv4 servers at
7966 	 * interop testing events have allowed this behavior,
7967 	 * and it caused our client to panic due to a recursive
7968 	 * mutex_enter in fn_move.
7969 	 *
7970 	 * The tedious locking in fn_move could be changed to
7971 	 * deal with this case, and the client could avoid the
7972 	 * panic; however, the client would just confuse itself
7973 	 * later and misbehave.  A better way to handle the broken
7974 	 * server is to detect this condition and return EINVAL
7975 	 * without ever sending the the bogus rename to the server.
7976 	 * We know the rename is invalid -- just fail it now.
7977 	 */
7978 	if (ovp->v_type == VDIR && VN_CMP(ndvp, ovp)) {
7979 		VN_RELE(ovp);
7980 		nfs_rw_exit(&odrp->r_rwlock);
7981 		nfs_rw_exit(&ndrp->r_rwlock);
7982 		if (nvp) {
7983 			VN_RELE(nvp);
7984 		}
7985 		return (EINVAL);
7986 	}
7987 
7988 	(void) nfs4delegreturn(VTOR4(ovp), NFS4_DR_PUSH|NFS4_DR_REOPEN);
7989 
7990 	/*
7991 	 * If FH4_VOL_RENAME or FH4_VOLATILE_ANY bits are set, it is
7992 	 * possible for the filehandle to change due to the rename.
7993 	 * If neither of these bits is set, but FH4_VOL_MIGRATION is set,
7994 	 * the fh will not change because of the rename, but we still need
7995 	 * to update its rnode entry with the new name for
7996 	 * an eventual fh change due to migration. The FH4_NOEXPIRE_ON_OPEN
7997 	 * has no effect on these for now, but for future improvements,
7998 	 * we might want to use it too to simplify handling of files
7999 	 * that are open with that flag on. (XXX)
8000 	 */
8001 	mi = VTOMI4(odvp);
8002 	if (NFS4_VOLATILE_FH(mi))
8003 		error = nfs4rename_volatile_fh(odvp, onm, ovp, ndvp, nnm, cr,
8004 		    &stat);
8005 	else
8006 		error = nfs4rename_persistent_fh(odvp, onm, ovp, ndvp, nnm, cr,
8007 		    &stat);
8008 
8009 	ASSERT(nfs4_consistent_type(odvp));
8010 	ASSERT(nfs4_consistent_type(ndvp));
8011 	ASSERT(nfs4_consistent_type(ovp));
8012 
8013 	if (stat == NFS4ERR_FILE_OPEN && did_link) {
8014 		do_link = 0;
8015 		/*
8016 		 * Before the 'link_call' code, we did a nfs4_lookup
8017 		 * that puts a VN_HOLD on nvp.  After the nfs4_link
8018 		 * call we call VN_RELE to match that hold.  We need
8019 		 * to place an additional VN_HOLD here since we will
8020 		 * be hitting that VN_RELE again.
8021 		 */
8022 		VN_HOLD(nvp);
8023 
8024 		(void) nfs4_remove(ndvp, tmpname, cr, NULL, 0);
8025 
8026 		/* Undo the unlinked file naming stuff we just did */
8027 		mutex_enter(&rp->r_statelock);
8028 		if (rp->r_unldvp) {
8029 			VN_RELE(ndvp);
8030 			rp->r_unldvp = NULL;
8031 			if (rp->r_unlcred != NULL)
8032 				crfree(rp->r_unlcred);
8033 			rp->r_unlcred = NULL;
8034 			/* rp->r_unlanme points to tmpname */
8035 			if (rp->r_unlname)
8036 				kmem_free(rp->r_unlname, MAXNAMELEN);
8037 			rp->r_unlname = NULL;
8038 		}
8039 		mutex_exit(&rp->r_statelock);
8040 
8041 		if (nvp) {
8042 			VN_RELE(nvp);
8043 		}
8044 		goto link_call;
8045 	}
8046 
8047 	if (error) {
8048 		VN_RELE(ovp);
8049 		nfs_rw_exit(&odrp->r_rwlock);
8050 		nfs_rw_exit(&ndrp->r_rwlock);
8051 		if (nvp) {
8052 			VN_RELE(nvp);
8053 		}
8054 		return (error);
8055 	}
8056 
8057 	/*
8058 	 * when renaming directories to be a subdirectory of a
8059 	 * different parent, the dnlc entry for ".." will no
8060 	 * longer be valid, so it must be removed
8061 	 */
8062 	rp = VTOR4(ovp);
8063 	if (ndvp != odvp) {
8064 		if (ovp->v_type == VDIR) {
8065 			dnlc_remove(ovp, "..");
8066 			if (rp->r_dir != NULL)
8067 				nfs4_purge_rddir_cache(ovp);
8068 		}
8069 	}
8070 
8071 	/*
8072 	 * If we are renaming the unlinked file, update the
8073 	 * r_unldvp and r_unlname as needed.
8074 	 */
8075 	mutex_enter(&rp->r_statelock);
8076 	if (rp->r_unldvp != NULL) {
8077 		if (strcmp(rp->r_unlname, onm) == 0) {
8078 			(void) strncpy(rp->r_unlname, nnm, MAXNAMELEN);
8079 			rp->r_unlname[MAXNAMELEN - 1] = '\0';
8080 			if (ndvp != rp->r_unldvp) {
8081 				VN_RELE(rp->r_unldvp);
8082 				rp->r_unldvp = ndvp;
8083 				VN_HOLD(ndvp);
8084 			}
8085 		}
8086 	}
8087 	mutex_exit(&rp->r_statelock);
8088 
8089 	/*
8090 	 * Notify the rename vnevents to source vnode, and to the target
8091 	 * vnode if it already existed.
8092 	 */
8093 	if (error == 0) {
8094 		vnode_t *tvp;
8095 		rnode4_t *trp;
8096 		/*
8097 		 * Notify the vnode. Each links is represented by
8098 		 * a different vnode, in nfsv4.
8099 		 */
8100 		if (nvp) {
8101 			trp = VTOR4(nvp);
8102 			tvp = nvp;
8103 			if (IS_SHADOW(nvp, trp))
8104 				tvp = RTOV4(trp);
8105 			vnevent_rename_dest(tvp, ndvp, nnm, ct);
8106 		}
8107 
8108 		/*
8109 		 * if the source and destination directory are not the
8110 		 * same notify the destination directory.
8111 		 */
8112 		if (VTOR4(odvp) != VTOR4(ndvp)) {
8113 			trp = VTOR4(ndvp);
8114 			tvp = ndvp;
8115 			if (IS_SHADOW(ndvp, trp))
8116 				tvp = RTOV4(trp);
8117 			vnevent_rename_dest_dir(tvp, ct);
8118 		}
8119 
8120 		trp = VTOR4(ovp);
8121 		tvp = ovp;
8122 		if (IS_SHADOW(ovp, trp))
8123 			tvp = RTOV4(trp);
8124 		vnevent_rename_src(tvp, odvp, onm, ct);
8125 	}
8126 
8127 	if (nvp) {
8128 		VN_RELE(nvp);
8129 	}
8130 	VN_RELE(ovp);
8131 
8132 	nfs_rw_exit(&odrp->r_rwlock);
8133 	nfs_rw_exit(&ndrp->r_rwlock);
8134 
8135 	return (error);
8136 }
8137 
8138 /*
8139  * When the parent directory has changed, sv_dfh must be updated
8140  */
8141 static void
update_parentdir_sfh(vnode_t * vp,vnode_t * ndvp)8142 update_parentdir_sfh(vnode_t *vp, vnode_t *ndvp)
8143 {
8144 	svnode_t *sv = VTOSV(vp);
8145 	nfs4_sharedfh_t *old_dfh = sv->sv_dfh;
8146 	nfs4_sharedfh_t *new_dfh = VTOR4(ndvp)->r_fh;
8147 
8148 	sfh4_hold(new_dfh);
8149 	sv->sv_dfh = new_dfh;
8150 	sfh4_rele(&old_dfh);
8151 }
8152 
8153 /*
8154  * nfs4rename_persistent does the otw portion of renaming in NFS Version 4,
8155  * when it is known that the filehandle is persistent through rename.
8156  *
8157  * Rename requires that the current fh be the target directory and the
8158  * saved fh be the source directory. After the operation, the current fh
8159  * is unchanged.
8160  * The compound op structure for persistent fh rename is:
8161  *      PUTFH(sourcdir), SAVEFH, PUTFH(targetdir), RENAME
8162  * Rather than bother with the directory postop args, we'll simply
8163  * update that a change occurred in the cache, so no post-op getattrs.
8164  */
8165 static int
nfs4rename_persistent_fh(vnode_t * odvp,char * onm,vnode_t * renvp,vnode_t * ndvp,char * nnm,cred_t * cr,nfsstat4 * statp)8166 nfs4rename_persistent_fh(vnode_t *odvp, char *onm, vnode_t *renvp,
8167     vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
8168 {
8169 	COMPOUND4args_clnt args;
8170 	COMPOUND4res_clnt res, *resp = NULL;
8171 	nfs_argop4 *argop;
8172 	nfs_resop4 *resop;
8173 	int doqueue, argoplist_size;
8174 	mntinfo4_t *mi;
8175 	rnode4_t *odrp = VTOR4(odvp);
8176 	rnode4_t *ndrp = VTOR4(ndvp);
8177 	RENAME4res *rn_res;
8178 	bool_t needrecov;
8179 	nfs4_recov_state_t recov_state;
8180 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8181 	dirattr_info_t dinfo, *dinfop;
8182 
8183 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
8184 
8185 	recov_state.rs_flags = 0;
8186 	recov_state.rs_num_retry_despite_err = 0;
8187 
8188 	/*
8189 	 * Rename ops: putfh sdir; savefh; putfh tdir; rename; getattr tdir
8190 	 *
8191 	 * If source/target are different dirs, then append putfh(src); getattr
8192 	 */
8193 	args.array_len = (odvp == ndvp) ? 5 : 7;
8194 	argoplist_size = args.array_len * sizeof (nfs_argop4);
8195 	args.array = argop = kmem_alloc(argoplist_size, KM_SLEEP);
8196 
8197 recov_retry:
8198 	*statp = NFS4_OK;
8199 
8200 	/* No need to Lookup the file, persistent fh */
8201 	args.ctag = TAG_RENAME;
8202 
8203 	mi = VTOMI4(odvp);
8204 	e.error = nfs4_start_op(mi, odvp, ndvp, &recov_state);
8205 	if (e.error) {
8206 		kmem_free(argop, argoplist_size);
8207 		return (e.error);
8208 	}
8209 
8210 	/* 0: putfh source directory */
8211 	argop[0].argop = OP_CPUTFH;
8212 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8213 
8214 	/* 1: Save source fh to free up current for target */
8215 	argop[1].argop = OP_SAVEFH;
8216 
8217 	/* 2: putfh targetdir */
8218 	argop[2].argop = OP_CPUTFH;
8219 	argop[2].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8220 
8221 	/* 3: current_fh is targetdir, saved_fh is sourcedir */
8222 	argop[3].argop = OP_CRENAME;
8223 	argop[3].nfs_argop4_u.opcrename.coldname = onm;
8224 	argop[3].nfs_argop4_u.opcrename.cnewname = nnm;
8225 
8226 	/* 4: getattr (targetdir) */
8227 	argop[4].argop = OP_GETATTR;
8228 	argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8229 	argop[4].nfs_argop4_u.opgetattr.mi = mi;
8230 
8231 	if (ndvp != odvp) {
8232 
8233 		/* 5: putfh (sourcedir) */
8234 		argop[5].argop = OP_CPUTFH;
8235 		argop[5].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8236 
8237 		/* 6: getattr (sourcedir) */
8238 		argop[6].argop = OP_GETATTR;
8239 		argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8240 		argop[6].nfs_argop4_u.opgetattr.mi = mi;
8241 	}
8242 
8243 	dnlc_remove(odvp, onm);
8244 	dnlc_remove(ndvp, nnm);
8245 
8246 	doqueue = 1;
8247 	dinfo.di_time_call = gethrtime();
8248 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8249 
8250 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8251 	if (e.error) {
8252 		PURGE_ATTRCACHE4(odvp);
8253 		PURGE_ATTRCACHE4(ndvp);
8254 	} else {
8255 		*statp = res.status;
8256 	}
8257 
8258 	if (needrecov) {
8259 		if (nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8260 		    OP_RENAME, NULL, NULL, NULL) == FALSE) {
8261 			nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
8262 			if (!e.error)
8263 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8264 				    (caddr_t)&res);
8265 			goto recov_retry;
8266 		}
8267 	}
8268 
8269 	if (!e.error) {
8270 		resp = &res;
8271 		/*
8272 		 * as long as OP_RENAME
8273 		 */
8274 		if (res.status != NFS4_OK && res.array_len <= 4) {
8275 			e.error = geterrno4(res.status);
8276 			PURGE_ATTRCACHE4(odvp);
8277 			PURGE_ATTRCACHE4(ndvp);
8278 			/*
8279 			 * System V defines rename to return EEXIST, not
8280 			 * ENOTEMPTY if the target directory is not empty.
8281 			 * Over the wire, the error is NFSERR_ENOTEMPTY
8282 			 * which geterrno4 maps to ENOTEMPTY.
8283 			 */
8284 			if (e.error == ENOTEMPTY)
8285 				e.error = EEXIST;
8286 		} else {
8287 
8288 			resop = &res.array[3];	/* rename res */
8289 			rn_res = &resop->nfs_resop4_u.oprename;
8290 
8291 			if (res.status == NFS4_OK) {
8292 				/*
8293 				 * Update target attribute, readdir and dnlc
8294 				 * caches.
8295 				 */
8296 				dinfo.di_garp =
8297 				    &res.array[4].nfs_resop4_u.opgetattr.ga_res;
8298 				dinfo.di_cred = cr;
8299 				dinfop = &dinfo;
8300 			} else
8301 				dinfop = NULL;
8302 
8303 			nfs4_update_dircaches(&rn_res->target_cinfo,
8304 			    ndvp, NULL, NULL, dinfop);
8305 
8306 			/*
8307 			 * Update source attribute, readdir and dnlc caches
8308 			 *
8309 			 */
8310 			if (ndvp != odvp) {
8311 				update_parentdir_sfh(renvp, ndvp);
8312 
8313 				if (dinfop)
8314 					dinfo.di_garp =
8315 					    &(res.array[6].nfs_resop4_u.
8316 					    opgetattr.ga_res);
8317 
8318 				nfs4_update_dircaches(&rn_res->source_cinfo,
8319 				    odvp, NULL, NULL, dinfop);
8320 			}
8321 
8322 			fn_move(VTOSV(renvp)->sv_name, VTOSV(ndvp)->sv_name,
8323 			    nnm);
8324 		}
8325 	}
8326 
8327 	if (resp)
8328 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8329 	nfs4_end_op(mi, odvp, ndvp, &recov_state, needrecov);
8330 	kmem_free(argop, argoplist_size);
8331 
8332 	return (e.error);
8333 }
8334 
8335 /*
8336  * nfs4rename_volatile_fh does the otw part of renaming in NFS Version 4, when
8337  * it is possible for the filehandle to change due to the rename.
8338  *
8339  * The compound req in this case includes a post-rename lookup and getattr
8340  * to ensure that we have the correct fh and attributes for the object.
8341  *
8342  * Rename requires that the current fh be the target directory and the
8343  * saved fh be the source directory. After the operation, the current fh
8344  * is unchanged.
8345  *
8346  * We need the new filehandle (hence a LOOKUP and GETFH) so that we can
8347  * update the filehandle for the renamed object.  We also get the old
8348  * filehandle for historical reasons; this should be taken out sometime.
8349  * This results in a rather cumbersome compound...
8350  *
8351  *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8352  *    PUTFH(targetdir), RENAME, LOOKUP(trgt), GETFH(new), GETATTR
8353  *
8354  */
8355 static int
nfs4rename_volatile_fh(vnode_t * odvp,char * onm,vnode_t * ovp,vnode_t * ndvp,char * nnm,cred_t * cr,nfsstat4 * statp)8356 nfs4rename_volatile_fh(vnode_t *odvp, char *onm, vnode_t *ovp,
8357     vnode_t *ndvp, char *nnm, cred_t *cr, nfsstat4 *statp)
8358 {
8359 	COMPOUND4args_clnt args;
8360 	COMPOUND4res_clnt res, *resp = NULL;
8361 	int argoplist_size;
8362 	nfs_argop4 *argop;
8363 	nfs_resop4 *resop;
8364 	int doqueue;
8365 	mntinfo4_t *mi;
8366 	rnode4_t *odrp = VTOR4(odvp);	/* old directory */
8367 	rnode4_t *ndrp = VTOR4(ndvp);	/* new directory */
8368 	rnode4_t *orp = VTOR4(ovp);	/* object being renamed */
8369 	RENAME4res *rn_res;
8370 	GETFH4res *ngf_res;
8371 	bool_t needrecov;
8372 	nfs4_recov_state_t recov_state;
8373 	hrtime_t t;
8374 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8375 	dirattr_info_t dinfo, *dinfop = &dinfo;
8376 
8377 	ASSERT(nfs_zone() == VTOMI4(odvp)->mi_zone);
8378 
8379 	recov_state.rs_flags = 0;
8380 	recov_state.rs_num_retry_despite_err = 0;
8381 
8382 recov_retry:
8383 	*statp = NFS4_OK;
8384 
8385 	/*
8386 	 * There is a window between the RPC and updating the path and
8387 	 * filehandle stored in the rnode.  Lock out the FHEXPIRED recovery
8388 	 * code, so that it doesn't try to use the old path during that
8389 	 * window.
8390 	 */
8391 	mutex_enter(&orp->r_statelock);
8392 	while (orp->r_flags & R4RECEXPFH) {
8393 		klwp_t *lwp = ttolwp(curthread);
8394 
8395 		if (lwp != NULL)
8396 			lwp->lwp_nostop++;
8397 		if (cv_wait_sig(&orp->r_cv, &orp->r_statelock) == 0) {
8398 			mutex_exit(&orp->r_statelock);
8399 			if (lwp != NULL)
8400 				lwp->lwp_nostop--;
8401 			return (EINTR);
8402 		}
8403 		if (lwp != NULL)
8404 			lwp->lwp_nostop--;
8405 	}
8406 	orp->r_flags |= R4RECEXPFH;
8407 	mutex_exit(&orp->r_statelock);
8408 
8409 	mi = VTOMI4(odvp);
8410 
8411 	args.ctag = TAG_RENAME_VFH;
8412 	args.array_len = (odvp == ndvp) ? 10 : 12;
8413 	argoplist_size  = args.array_len * sizeof (nfs_argop4);
8414 	argop = kmem_alloc(argoplist_size, KM_SLEEP);
8415 
8416 	/*
8417 	 * Rename ops:
8418 	 *    PUTFH(sourcdir), SAVEFH, LOOKUP(src), GETFH(old),
8419 	 *    PUTFH(targetdir), RENAME, GETATTR(targetdir)
8420 	 *    LOOKUP(trgt), GETFH(new), GETATTR,
8421 	 *
8422 	 *    if (odvp != ndvp)
8423 	 *	add putfh(sourcedir), getattr(sourcedir) }
8424 	 */
8425 	args.array = argop;
8426 
8427 	e.error = nfs4_start_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8428 	    &recov_state, NULL);
8429 	if (e.error) {
8430 		kmem_free(argop, argoplist_size);
8431 		mutex_enter(&orp->r_statelock);
8432 		orp->r_flags &= ~R4RECEXPFH;
8433 		cv_broadcast(&orp->r_cv);
8434 		mutex_exit(&orp->r_statelock);
8435 		return (e.error);
8436 	}
8437 
8438 	/* 0: putfh source directory */
8439 	argop[0].argop = OP_CPUTFH;
8440 	argop[0].nfs_argop4_u.opcputfh.sfh = odrp->r_fh;
8441 
8442 	/* 1: Save source fh to free up current for target */
8443 	argop[1].argop = OP_SAVEFH;
8444 
8445 	/* 2: Lookup pre-rename fh of renamed object */
8446 	argop[2].argop = OP_CLOOKUP;
8447 	argop[2].nfs_argop4_u.opclookup.cname = onm;
8448 
8449 	/* 3: getfh fh of renamed object (before rename) */
8450 	argop[3].argop = OP_GETFH;
8451 
8452 	/* 4: putfh targetdir */
8453 	argop[4].argop = OP_CPUTFH;
8454 	argop[4].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8455 
8456 	/* 5: current_fh is targetdir, saved_fh is sourcedir */
8457 	argop[5].argop = OP_CRENAME;
8458 	argop[5].nfs_argop4_u.opcrename.coldname = onm;
8459 	argop[5].nfs_argop4_u.opcrename.cnewname = nnm;
8460 
8461 	/* 6: getattr of target dir (post op attrs) */
8462 	argop[6].argop = OP_GETATTR;
8463 	argop[6].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8464 	argop[6].nfs_argop4_u.opgetattr.mi = mi;
8465 
8466 	/* 7: Lookup post-rename fh of renamed object */
8467 	argop[7].argop = OP_CLOOKUP;
8468 	argop[7].nfs_argop4_u.opclookup.cname = nnm;
8469 
8470 	/* 8: getfh fh of renamed object (after rename) */
8471 	argop[8].argop = OP_GETFH;
8472 
8473 	/* 9: getattr of renamed object */
8474 	argop[9].argop = OP_GETATTR;
8475 	argop[9].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8476 	argop[9].nfs_argop4_u.opgetattr.mi = mi;
8477 
8478 	/*
8479 	 * If source/target dirs are different, then get new post-op
8480 	 * attrs for source dir also.
8481 	 */
8482 	if (ndvp != odvp) {
8483 		/* 10: putfh (sourcedir) */
8484 		argop[10].argop = OP_CPUTFH;
8485 		argop[10].nfs_argop4_u.opcputfh.sfh = ndrp->r_fh;
8486 
8487 		/* 11: getattr (sourcedir) */
8488 		argop[11].argop = OP_GETATTR;
8489 		argop[11].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8490 		argop[11].nfs_argop4_u.opgetattr.mi = mi;
8491 	}
8492 
8493 	dnlc_remove(odvp, onm);
8494 	dnlc_remove(ndvp, nnm);
8495 
8496 	doqueue = 1;
8497 	t = gethrtime();
8498 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8499 
8500 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8501 	if (e.error) {
8502 		PURGE_ATTRCACHE4(odvp);
8503 		PURGE_ATTRCACHE4(ndvp);
8504 		if (!needrecov) {
8505 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8506 			    &recov_state, needrecov);
8507 			goto out;
8508 		}
8509 	} else {
8510 		*statp = res.status;
8511 	}
8512 
8513 	if (needrecov) {
8514 		bool_t abort;
8515 
8516 		abort = nfs4_start_recovery(&e, mi, odvp, ndvp, NULL, NULL,
8517 		    OP_RENAME, NULL, NULL, NULL);
8518 		if (abort == FALSE) {
8519 			nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8520 			    &recov_state, needrecov);
8521 			kmem_free(argop, argoplist_size);
8522 			if (!e.error)
8523 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8524 				    (caddr_t)&res);
8525 			mutex_enter(&orp->r_statelock);
8526 			orp->r_flags &= ~R4RECEXPFH;
8527 			cv_broadcast(&orp->r_cv);
8528 			mutex_exit(&orp->r_statelock);
8529 			goto recov_retry;
8530 		} else {
8531 			if (e.error != 0) {
8532 				nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME,
8533 				    &recov_state, needrecov);
8534 				goto out;
8535 			}
8536 			/* fall through for res.status case */
8537 		}
8538 	}
8539 
8540 	resp = &res;
8541 	/*
8542 	 * If OP_RENAME (or any prev op) failed, then return an error.
8543 	 * OP_RENAME is index 5, so if array len <= 6 we return an error.
8544 	 */
8545 	if ((res.status != NFS4_OK) && (res.array_len <= 6)) {
8546 		/*
8547 		 * Error in an op other than last Getattr
8548 		 */
8549 		e.error = geterrno4(res.status);
8550 		PURGE_ATTRCACHE4(odvp);
8551 		PURGE_ATTRCACHE4(ndvp);
8552 		/*
8553 		 * System V defines rename to return EEXIST, not
8554 		 * ENOTEMPTY if the target directory is not empty.
8555 		 * Over the wire, the error is NFSERR_ENOTEMPTY
8556 		 * which geterrno4 maps to ENOTEMPTY.
8557 		 */
8558 		if (e.error == ENOTEMPTY)
8559 			e.error = EEXIST;
8560 		nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state,
8561 		    needrecov);
8562 		goto out;
8563 	}
8564 
8565 	/* rename results */
8566 	rn_res = &res.array[5].nfs_resop4_u.oprename;
8567 
8568 	if (res.status == NFS4_OK) {
8569 		/* Update target attribute, readdir and dnlc caches */
8570 		dinfo.di_garp =
8571 		    &res.array[6].nfs_resop4_u.opgetattr.ga_res;
8572 		dinfo.di_cred = cr;
8573 		dinfo.di_time_call = t;
8574 	} else
8575 		dinfop = NULL;
8576 
8577 	/* Update source cache attribute, readdir and dnlc caches */
8578 	nfs4_update_dircaches(&rn_res->target_cinfo, ndvp, NULL, NULL, dinfop);
8579 
8580 	/* Update source cache attribute, readdir and dnlc caches */
8581 	if (ndvp != odvp) {
8582 		update_parentdir_sfh(ovp, ndvp);
8583 
8584 		/*
8585 		 * If dinfop is non-NULL, then compound succeded, so
8586 		 * set di_garp to attrs for source dir.  dinfop is only
8587 		 * set to NULL when compound fails.
8588 		 */
8589 		if (dinfop)
8590 			dinfo.di_garp =
8591 			    &res.array[11].nfs_resop4_u.opgetattr.ga_res;
8592 		nfs4_update_dircaches(&rn_res->source_cinfo, odvp, NULL, NULL,
8593 		    dinfop);
8594 	}
8595 
8596 	/*
8597 	 * Update the rnode with the new component name and args,
8598 	 * and if the file handle changed, also update it with the new fh.
8599 	 * This is only necessary if the target object has an rnode
8600 	 * entry and there is no need to create one for it.
8601 	 */
8602 	resop = &res.array[8];	/* getfh new res */
8603 	ngf_res = &resop->nfs_resop4_u.opgetfh;
8604 
8605 	/*
8606 	 * Update the path and filehandle for the renamed object.
8607 	 */
8608 	nfs4rename_update(ovp, ndvp, &ngf_res->object, nnm);
8609 
8610 	nfs4_end_fop(mi, odvp, ndvp, OH_VFH_RENAME, &recov_state, needrecov);
8611 
8612 	if (res.status == NFS4_OK) {
8613 		resop++;	/* getattr res */
8614 		e.error = nfs4_update_attrcache(res.status,
8615 		    &resop->nfs_resop4_u.opgetattr.ga_res,
8616 		    t, ovp, cr);
8617 	}
8618 
8619 out:
8620 	kmem_free(argop, argoplist_size);
8621 	if (resp)
8622 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8623 	mutex_enter(&orp->r_statelock);
8624 	orp->r_flags &= ~R4RECEXPFH;
8625 	cv_broadcast(&orp->r_cv);
8626 	mutex_exit(&orp->r_statelock);
8627 
8628 	return (e.error);
8629 }
8630 
8631 /* ARGSUSED */
8632 static int
nfs4_mkdir(vnode_t * dvp,char * nm,struct vattr * va,vnode_t ** vpp,cred_t * cr,caller_context_t * ct,int flags,vsecattr_t * vsecp)8633 nfs4_mkdir(vnode_t *dvp, char *nm, struct vattr *va, vnode_t **vpp, cred_t *cr,
8634     caller_context_t *ct, int flags, vsecattr_t *vsecp)
8635 {
8636 	int error;
8637 	vnode_t *vp;
8638 
8639 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8640 		return (EPERM);
8641 	/*
8642 	 * As ".." has special meaning and rather than send a mkdir
8643 	 * over the wire to just let the server freak out, we just
8644 	 * short circuit it here and return EEXIST
8645 	 */
8646 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8647 		return (EEXIST);
8648 
8649 	/*
8650 	 * Decision to get the right gid and setgid bit of the
8651 	 * new directory is now made in call_nfs4_create_req.
8652 	 */
8653 	va->va_mask |= AT_MODE;
8654 	error = call_nfs4_create_req(dvp, nm, NULL, va, &vp, cr, NF4DIR);
8655 	if (error)
8656 		return (error);
8657 
8658 	*vpp = vp;
8659 	return (0);
8660 }
8661 
8662 
8663 /*
8664  * rmdir is using the same remove v4 op as does remove.
8665  * Remove requires that the current fh be the target directory.
8666  * After the operation, the current fh is unchanged.
8667  * The compound op structure is:
8668  *      PUTFH(targetdir), REMOVE
8669  */
8670 /*ARGSUSED4*/
8671 static int
nfs4_rmdir(vnode_t * dvp,char * nm,vnode_t * cdir,cred_t * cr,caller_context_t * ct,int flags)8672 nfs4_rmdir(vnode_t *dvp, char *nm, vnode_t *cdir, cred_t *cr,
8673     caller_context_t *ct, int flags)
8674 {
8675 	int need_end_op = FALSE;
8676 	COMPOUND4args_clnt args;
8677 	COMPOUND4res_clnt res, *resp = NULL;
8678 	REMOVE4res *rm_res;
8679 	nfs_argop4 argop[3];
8680 	nfs_resop4 *resop;
8681 	vnode_t *vp;
8682 	int doqueue;
8683 	mntinfo4_t *mi;
8684 	rnode4_t *drp;
8685 	bool_t needrecov = FALSE;
8686 	nfs4_recov_state_t recov_state;
8687 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
8688 	dirattr_info_t dinfo, *dinfop;
8689 
8690 	if (nfs_zone() != VTOMI4(dvp)->mi_zone)
8691 		return (EPERM);
8692 	/*
8693 	 * As ".." has special meaning and rather than send a rmdir
8694 	 * over the wire to just let the server freak out, we just
8695 	 * short circuit it here and return EEXIST
8696 	 */
8697 	if (nm[0] == '.' && nm[1] == '.' && nm[2] == '\0')
8698 		return (EEXIST);
8699 
8700 	drp = VTOR4(dvp);
8701 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_WRITER, INTR4(dvp)))
8702 		return (EINTR);
8703 
8704 	/*
8705 	 * Attempt to prevent a rmdir(".") from succeeding.
8706 	 */
8707 	e.error = nfs4lookup(dvp, nm, &vp, cr, 0);
8708 	if (e.error) {
8709 		nfs_rw_exit(&drp->r_rwlock);
8710 		return (e.error);
8711 	}
8712 	if (vp == cdir) {
8713 		VN_RELE(vp);
8714 		nfs_rw_exit(&drp->r_rwlock);
8715 		return (EINVAL);
8716 	}
8717 
8718 	/*
8719 	 * Since nfsv4 remove op works on both files and directories,
8720 	 * check that the removed object is indeed a directory.
8721 	 */
8722 	if (vp->v_type != VDIR) {
8723 		VN_RELE(vp);
8724 		nfs_rw_exit(&drp->r_rwlock);
8725 		return (ENOTDIR);
8726 	}
8727 
8728 	/*
8729 	 * First just remove the entry from the name cache, as it
8730 	 * is most likely an entry for this vp.
8731 	 */
8732 	dnlc_remove(dvp, nm);
8733 
8734 	/*
8735 	 * If there vnode reference count is greater than one, then
8736 	 * there may be additional references in the DNLC which will
8737 	 * need to be purged.  First, trying removing the entry for
8738 	 * the parent directory and see if that removes the additional
8739 	 * reference(s).  If that doesn't do it, then use dnlc_purge_vp
8740 	 * to completely remove any references to the directory which
8741 	 * might still exist in the DNLC.
8742 	 */
8743 	if (vp->v_count > 1) {
8744 		dnlc_remove(vp, "..");
8745 		if (vp->v_count > 1)
8746 			dnlc_purge_vp(vp);
8747 	}
8748 
8749 	mi = VTOMI4(dvp);
8750 	recov_state.rs_flags = 0;
8751 	recov_state.rs_num_retry_despite_err = 0;
8752 
8753 recov_retry:
8754 	args.ctag = TAG_RMDIR;
8755 
8756 	/*
8757 	 * Rmdir ops: putfh dir; remove
8758 	 */
8759 	args.array_len = 3;
8760 	args.array = argop;
8761 
8762 	e.error = nfs4_start_op(VTOMI4(dvp), dvp, NULL, &recov_state);
8763 	if (e.error) {
8764 		nfs_rw_exit(&drp->r_rwlock);
8765 		return (e.error);
8766 	}
8767 	need_end_op = TRUE;
8768 
8769 	/* putfh directory */
8770 	argop[0].argop = OP_CPUTFH;
8771 	argop[0].nfs_argop4_u.opcputfh.sfh = drp->r_fh;
8772 
8773 	/* remove */
8774 	argop[1].argop = OP_CREMOVE;
8775 	argop[1].nfs_argop4_u.opcremove.ctarget = nm;
8776 
8777 	/* getattr (postop attrs for dir that contained removed dir) */
8778 	argop[2].argop = OP_GETATTR;
8779 	argop[2].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
8780 	argop[2].nfs_argop4_u.opgetattr.mi = mi;
8781 
8782 	dinfo.di_time_call = gethrtime();
8783 	doqueue = 1;
8784 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
8785 
8786 	PURGE_ATTRCACHE4(vp);
8787 
8788 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
8789 	if (e.error) {
8790 		PURGE_ATTRCACHE4(dvp);
8791 	}
8792 
8793 	if (needrecov) {
8794 		if (nfs4_start_recovery(&e, VTOMI4(dvp), dvp, NULL, NULL,
8795 		    NULL, OP_REMOVE, NULL, NULL, NULL) == FALSE) {
8796 			if (!e.error)
8797 				(void) xdr_free(xdr_COMPOUND4res_clnt,
8798 				    (caddr_t)&res);
8799 
8800 			nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state,
8801 			    needrecov);
8802 			need_end_op = FALSE;
8803 			goto recov_retry;
8804 		}
8805 	}
8806 
8807 	if (!e.error) {
8808 		resp = &res;
8809 
8810 		/*
8811 		 * Only return error if first 2 ops (OP_REMOVE or earlier)
8812 		 * failed.
8813 		 */
8814 		if (res.status != NFS4_OK && res.array_len <= 2) {
8815 			e.error = geterrno4(res.status);
8816 			PURGE_ATTRCACHE4(dvp);
8817 			nfs4_end_op(VTOMI4(dvp), dvp, NULL,
8818 			    &recov_state, needrecov);
8819 			need_end_op = FALSE;
8820 			nfs4_purge_stale_fh(e.error, dvp, cr);
8821 			/*
8822 			 * System V defines rmdir to return EEXIST, not
8823 			 * ENOTEMPTY if the directory is not empty.  Over
8824 			 * the wire, the error is NFSERR_ENOTEMPTY which
8825 			 * geterrno4 maps to ENOTEMPTY.
8826 			 */
8827 			if (e.error == ENOTEMPTY)
8828 				e.error = EEXIST;
8829 		} else {
8830 			resop = &res.array[1];	/* remove res */
8831 			rm_res = &resop->nfs_resop4_u.opremove;
8832 
8833 			if (res.status == NFS4_OK) {
8834 				resop = &res.array[2];	/* dir attrs */
8835 				dinfo.di_garp =
8836 				    &resop->nfs_resop4_u.opgetattr.ga_res;
8837 				dinfo.di_cred = cr;
8838 				dinfop = &dinfo;
8839 			} else
8840 				dinfop = NULL;
8841 
8842 			/* Update dir attribute, readdir and dnlc caches */
8843 			nfs4_update_dircaches(&rm_res->cinfo, dvp, NULL, NULL,
8844 			    dinfop);
8845 
8846 			/* destroy rddir cache for dir that was removed */
8847 			if (VTOR4(vp)->r_dir != NULL)
8848 				nfs4_purge_rddir_cache(vp);
8849 		}
8850 	}
8851 
8852 	if (need_end_op)
8853 		nfs4_end_op(VTOMI4(dvp), dvp, NULL, &recov_state, needrecov);
8854 
8855 	nfs_rw_exit(&drp->r_rwlock);
8856 
8857 	if (resp)
8858 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
8859 
8860 	if (e.error == 0) {
8861 		vnode_t *tvp;
8862 		rnode4_t *trp;
8863 		trp = VTOR4(vp);
8864 		tvp = vp;
8865 		if (IS_SHADOW(vp, trp))
8866 			tvp = RTOV4(trp);
8867 		vnevent_rmdir(tvp, dvp, nm, ct);
8868 	}
8869 
8870 	VN_RELE(vp);
8871 
8872 	return (e.error);
8873 }
8874 
8875 /* ARGSUSED */
8876 static int
nfs4_symlink(vnode_t * dvp,char * lnm,struct vattr * tva,char * tnm,cred_t * cr,caller_context_t * ct,int flags)8877 nfs4_symlink(vnode_t *dvp, char *lnm, struct vattr *tva, char *tnm, cred_t *cr,
8878     caller_context_t *ct, int flags)
8879 {
8880 	int error;
8881 	vnode_t *vp;
8882 	rnode4_t *rp;
8883 	char *contents;
8884 	mntinfo4_t *mi = VTOMI4(dvp);
8885 
8886 	if (nfs_zone() != mi->mi_zone)
8887 		return (EPERM);
8888 	if (!(mi->mi_flags & MI4_SYMLINK))
8889 		return (EOPNOTSUPP);
8890 
8891 	error = call_nfs4_create_req(dvp, lnm, tnm, tva, &vp, cr, NF4LNK);
8892 	if (error)
8893 		return (error);
8894 
8895 	ASSERT(nfs4_consistent_type(vp));
8896 	rp = VTOR4(vp);
8897 	if (nfs4_do_symlink_cache && rp->r_symlink.contents == NULL) {
8898 
8899 		contents = kmem_alloc(MAXPATHLEN, KM_SLEEP);
8900 
8901 		if (contents != NULL) {
8902 			mutex_enter(&rp->r_statelock);
8903 			if (rp->r_symlink.contents == NULL) {
8904 				rp->r_symlink.len = strlen(tnm);
8905 				bcopy(tnm, contents, rp->r_symlink.len);
8906 				rp->r_symlink.contents = contents;
8907 				rp->r_symlink.size = MAXPATHLEN;
8908 				mutex_exit(&rp->r_statelock);
8909 			} else {
8910 				mutex_exit(&rp->r_statelock);
8911 				kmem_free((void *)contents, MAXPATHLEN);
8912 			}
8913 		}
8914 	}
8915 	VN_RELE(vp);
8916 
8917 	return (error);
8918 }
8919 
8920 
8921 /*
8922  * Read directory entries.
8923  * There are some weird things to look out for here.  The uio_loffset
8924  * field is either 0 or it is the offset returned from a previous
8925  * readdir.  It is an opaque value used by the server to find the
8926  * correct directory block to read. The count field is the number
8927  * of blocks to read on the server.  This is advisory only, the server
8928  * may return only one block's worth of entries.  Entries may be compressed
8929  * on the server.
8930  */
8931 /* ARGSUSED */
8932 static int
nfs4_readdir(vnode_t * vp,struct uio * uiop,cred_t * cr,int * eofp,caller_context_t * ct,int flags)8933 nfs4_readdir(vnode_t *vp, struct uio *uiop, cred_t *cr, int *eofp,
8934     caller_context_t *ct, int flags)
8935 {
8936 	int error;
8937 	uint_t count;
8938 	rnode4_t *rp;
8939 	rddir4_cache *rdc;
8940 	rddir4_cache *rrdc;
8941 
8942 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
8943 		return (EIO);
8944 	rp = VTOR4(vp);
8945 
8946 	ASSERT(nfs_rw_lock_held(&rp->r_rwlock, RW_READER));
8947 
8948 	/*
8949 	 * Make sure that the directory cache is valid.
8950 	 */
8951 	if (rp->r_dir != NULL) {
8952 		if (nfs_disable_rddir_cache != 0) {
8953 			/*
8954 			 * Setting nfs_disable_rddir_cache in /etc/system
8955 			 * allows interoperability with servers that do not
8956 			 * properly update the attributes of directories.
8957 			 * Any cached information gets purged before an
8958 			 * access is made to it.
8959 			 */
8960 			nfs4_purge_rddir_cache(vp);
8961 		}
8962 
8963 		error = nfs4_validate_caches(vp, cr);
8964 		if (error)
8965 			return (error);
8966 	}
8967 
8968 	count = MIN(uiop->uio_iov->iov_len, MAXBSIZE);
8969 
8970 	/*
8971 	 * Short circuit last readdir which always returns 0 bytes.
8972 	 * This can be done after the directory has been read through
8973 	 * completely at least once.  This will set r_direof which
8974 	 * can be used to find the value of the last cookie.
8975 	 */
8976 	mutex_enter(&rp->r_statelock);
8977 	if (rp->r_direof != NULL &&
8978 	    uiop->uio_loffset == rp->r_direof->nfs4_ncookie) {
8979 		mutex_exit(&rp->r_statelock);
8980 #ifdef DEBUG
8981 		nfs4_readdir_cache_shorts++;
8982 #endif
8983 		if (eofp)
8984 			*eofp = 1;
8985 		return (0);
8986 	}
8987 
8988 	/*
8989 	 * Look for a cache entry.  Cache entries are identified
8990 	 * by the NFS cookie value and the byte count requested.
8991 	 */
8992 	rdc = rddir4_cache_lookup(rp, uiop->uio_loffset, count);
8993 
8994 	/*
8995 	 * If rdc is NULL then the lookup resulted in an unrecoverable error.
8996 	 */
8997 	if (rdc == NULL) {
8998 		mutex_exit(&rp->r_statelock);
8999 		return (EINTR);
9000 	}
9001 
9002 	/*
9003 	 * Check to see if we need to fill this entry in.
9004 	 */
9005 	if (rdc->flags & RDDIRREQ) {
9006 		rdc->flags &= ~RDDIRREQ;
9007 		rdc->flags |= RDDIR;
9008 		mutex_exit(&rp->r_statelock);
9009 
9010 		/*
9011 		 * Do the readdir.
9012 		 */
9013 		nfs4readdir(vp, rdc, cr);
9014 
9015 		/*
9016 		 * Reacquire the lock, so that we can continue
9017 		 */
9018 		mutex_enter(&rp->r_statelock);
9019 		/*
9020 		 * The entry is now complete
9021 		 */
9022 		rdc->flags &= ~RDDIR;
9023 	}
9024 
9025 	ASSERT(!(rdc->flags & RDDIR));
9026 
9027 	/*
9028 	 * If an error occurred while attempting
9029 	 * to fill the cache entry, mark the entry invalid and
9030 	 * just return the error.
9031 	 */
9032 	if (rdc->error) {
9033 		error = rdc->error;
9034 		rdc->flags |= RDDIRREQ;
9035 		rddir4_cache_rele(rp, rdc);
9036 		mutex_exit(&rp->r_statelock);
9037 		return (error);
9038 	}
9039 
9040 	/*
9041 	 * The cache entry is complete and good,
9042 	 * copyout the dirent structs to the calling
9043 	 * thread.
9044 	 */
9045 	error = uiomove(rdc->entries, rdc->actlen, UIO_READ, uiop);
9046 
9047 	/*
9048 	 * If no error occurred during the copyout,
9049 	 * update the offset in the uio struct to
9050 	 * contain the value of the next NFS 4 cookie
9051 	 * and set the eof value appropriately.
9052 	 */
9053 	if (!error) {
9054 		uiop->uio_loffset = rdc->nfs4_ncookie;
9055 		if (eofp)
9056 			*eofp = rdc->eof;
9057 	}
9058 
9059 	/*
9060 	 * Decide whether to do readahead.  Don't if we
9061 	 * have already read to the end of directory.
9062 	 */
9063 	if (rdc->eof) {
9064 		/*
9065 		 * Make the entry the direof only if it is cached
9066 		 */
9067 		if (rdc->flags & RDDIRCACHED)
9068 			rp->r_direof = rdc;
9069 		rddir4_cache_rele(rp, rdc);
9070 		mutex_exit(&rp->r_statelock);
9071 		return (error);
9072 	}
9073 
9074 	/* Determine if a readdir readahead should be done */
9075 	if (!(rp->r_flags & R4LOOKUP)) {
9076 		rddir4_cache_rele(rp, rdc);
9077 		mutex_exit(&rp->r_statelock);
9078 		return (error);
9079 	}
9080 
9081 	/*
9082 	 * Now look for a readahead entry.
9083 	 *
9084 	 * Check to see whether we found an entry for the readahead.
9085 	 * If so, we don't need to do anything further, so free the new
9086 	 * entry if one was allocated.  Otherwise, allocate a new entry, add
9087 	 * it to the cache, and then initiate an asynchronous readdir
9088 	 * operation to fill it.
9089 	 */
9090 	rrdc = rddir4_cache_lookup(rp, rdc->nfs4_ncookie, count);
9091 
9092 	/*
9093 	 * A readdir cache entry could not be obtained for the readahead.  In
9094 	 * this case we skip the readahead and return.
9095 	 */
9096 	if (rrdc == NULL) {
9097 		rddir4_cache_rele(rp, rdc);
9098 		mutex_exit(&rp->r_statelock);
9099 		return (error);
9100 	}
9101 
9102 	/*
9103 	 * Check to see if we need to fill this entry in.
9104 	 */
9105 	if (rrdc->flags & RDDIRREQ) {
9106 		rrdc->flags &= ~RDDIRREQ;
9107 		rrdc->flags |= RDDIR;
9108 		rddir4_cache_rele(rp, rdc);
9109 		mutex_exit(&rp->r_statelock);
9110 #ifdef DEBUG
9111 		nfs4_readdir_readahead++;
9112 #endif
9113 		/*
9114 		 * Do the readdir.
9115 		 */
9116 		nfs4_async_readdir(vp, rrdc, cr, do_nfs4readdir);
9117 		return (error);
9118 	}
9119 
9120 	rddir4_cache_rele(rp, rrdc);
9121 	rddir4_cache_rele(rp, rdc);
9122 	mutex_exit(&rp->r_statelock);
9123 	return (error);
9124 }
9125 
9126 static int
do_nfs4readdir(vnode_t * vp,rddir4_cache * rdc,cred_t * cr)9127 do_nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
9128 {
9129 	int error;
9130 	rnode4_t *rp;
9131 
9132 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
9133 
9134 	rp = VTOR4(vp);
9135 
9136 	/*
9137 	 * Obtain the readdir results for the caller.
9138 	 */
9139 	nfs4readdir(vp, rdc, cr);
9140 
9141 	mutex_enter(&rp->r_statelock);
9142 	/*
9143 	 * The entry is now complete
9144 	 */
9145 	rdc->flags &= ~RDDIR;
9146 
9147 	error = rdc->error;
9148 	if (error)
9149 		rdc->flags |= RDDIRREQ;
9150 	rddir4_cache_rele(rp, rdc);
9151 	mutex_exit(&rp->r_statelock);
9152 
9153 	return (error);
9154 }
9155 
9156 /*
9157  * Read directory entries.
9158  * There are some weird things to look out for here.  The uio_loffset
9159  * field is either 0 or it is the offset returned from a previous
9160  * readdir.  It is an opaque value used by the server to find the
9161  * correct directory block to read. The count field is the number
9162  * of blocks to read on the server.  This is advisory only, the server
9163  * may return only one block's worth of entries.  Entries may be compressed
9164  * on the server.
9165  *
9166  * Generates the following compound request:
9167  * 1. If readdir offset is zero and no dnlc entry for parent exists,
9168  *    must include a Lookupp as well. In this case, send:
9169  *    { Putfh <fh>; Readdir; Lookupp; Getfh; Getattr }
9170  * 2. Otherwise just do: { Putfh <fh>; Readdir }
9171  *
9172  * Get complete attributes and filehandles for entries if this is the
9173  * first read of the directory. Otherwise, just get fileid's.
9174  */
9175 static void
nfs4readdir(vnode_t * vp,rddir4_cache * rdc,cred_t * cr)9176 nfs4readdir(vnode_t *vp, rddir4_cache *rdc, cred_t *cr)
9177 {
9178 	COMPOUND4args_clnt args;
9179 	COMPOUND4res_clnt res;
9180 	READDIR4args *rargs;
9181 	READDIR4res_clnt *rd_res;
9182 	bitmap4 rd_bitsval;
9183 	nfs_argop4 argop[5];
9184 	nfs_resop4 *resop;
9185 	rnode4_t *rp = VTOR4(vp);
9186 	mntinfo4_t *mi = VTOMI4(vp);
9187 	int doqueue;
9188 	u_longlong_t nodeid, pnodeid;	/* id's of dir and its parents */
9189 	vnode_t *dvp;
9190 	nfs_cookie4 cookie = (nfs_cookie4)rdc->nfs4_cookie;
9191 	int num_ops, res_opcnt;
9192 	bool_t needrecov = FALSE;
9193 	nfs4_recov_state_t recov_state;
9194 	hrtime_t t;
9195 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
9196 
9197 	ASSERT(nfs_zone() == mi->mi_zone);
9198 	ASSERT(rdc->flags & RDDIR);
9199 	ASSERT(rdc->entries == NULL);
9200 
9201 	/*
9202 	 * If rp were a stub, it should have triggered and caused
9203 	 * a mount for us to get this far.
9204 	 */
9205 	ASSERT(!RP_ISSTUB(rp));
9206 
9207 	num_ops = 2;
9208 	if (cookie == (nfs_cookie4)0 || cookie == (nfs_cookie4)1) {
9209 		/*
9210 		 * Since nfsv4 readdir may not return entries for "." and "..",
9211 		 * the client must recreate them:
9212 		 * To find the correct nodeid, do the following:
9213 		 * For current node, get nodeid from dnlc.
9214 		 * - if current node is rootvp, set pnodeid to nodeid.
9215 		 * - else if parent is in the dnlc, get its nodeid from there.
9216 		 * - else add LOOKUPP+GETATTR to compound.
9217 		 */
9218 		nodeid = rp->r_attr.va_nodeid;
9219 		if (vp->v_flag & VROOT) {
9220 			pnodeid = nodeid;	/* root of mount point */
9221 		} else {
9222 			dvp = dnlc_lookup(vp, "..");
9223 			if (dvp != NULL && dvp != DNLC_NO_VNODE) {
9224 				/* parent in dnlc cache - no need for otw */
9225 				pnodeid = VTOR4(dvp)->r_attr.va_nodeid;
9226 			} else {
9227 				/*
9228 				 * parent not in dnlc cache,
9229 				 * do lookupp to get its id
9230 				 */
9231 				num_ops = 5;
9232 				pnodeid = 0; /* set later by getattr parent */
9233 			}
9234 			if (dvp)
9235 				VN_RELE(dvp);
9236 		}
9237 	}
9238 	recov_state.rs_flags = 0;
9239 	recov_state.rs_num_retry_despite_err = 0;
9240 
9241 	/* Save the original mount point security flavor */
9242 	(void) save_mnt_secinfo(mi->mi_curr_serv);
9243 
9244 recov_retry:
9245 	args.ctag = TAG_READDIR;
9246 
9247 	args.array = argop;
9248 	args.array_len = num_ops;
9249 
9250 	if (e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9251 	    &recov_state, NULL)) {
9252 		/*
9253 		 * If readdir a node that is a stub for a crossed mount point,
9254 		 * keep the original secinfo flavor for the current file
9255 		 * system, not the crossed one.
9256 		 */
9257 		(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9258 		rdc->error = e.error;
9259 		return;
9260 	}
9261 
9262 	/*
9263 	 * Determine which attrs to request for dirents.  This code
9264 	 * must be protected by nfs4_start/end_fop because of r_server
9265 	 * (which will change during failover recovery).
9266 	 *
9267 	 */
9268 	if (rp->r_flags & (R4LOOKUP | R4READDIRWATTR)) {
9269 		/*
9270 		 * Get all vattr attrs plus filehandle and rdattr_error
9271 		 */
9272 		rd_bitsval = NFS4_VATTR_MASK |
9273 		    FATTR4_RDATTR_ERROR_MASK |
9274 		    FATTR4_FILEHANDLE_MASK;
9275 
9276 		if (rp->r_flags & R4READDIRWATTR) {
9277 			mutex_enter(&rp->r_statelock);
9278 			rp->r_flags &= ~R4READDIRWATTR;
9279 			mutex_exit(&rp->r_statelock);
9280 		}
9281 	} else {
9282 		servinfo4_t *svp = rp->r_server;
9283 
9284 		/*
9285 		 * Already read directory. Use readdir with
9286 		 * no attrs (except for mounted_on_fileid) for updates.
9287 		 */
9288 		rd_bitsval = FATTR4_RDATTR_ERROR_MASK;
9289 
9290 		/*
9291 		 * request mounted on fileid if supported, else request
9292 		 * fileid.  maybe we should verify that fileid is supported
9293 		 * and request something else if not.
9294 		 */
9295 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
9296 		if (svp->sv_supp_attrs & FATTR4_MOUNTED_ON_FILEID_MASK)
9297 			rd_bitsval |= FATTR4_MOUNTED_ON_FILEID_MASK;
9298 		nfs_rw_exit(&svp->sv_lock);
9299 	}
9300 
9301 	/* putfh directory fh */
9302 	argop[0].argop = OP_CPUTFH;
9303 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
9304 
9305 	argop[1].argop = OP_READDIR;
9306 	rargs = &argop[1].nfs_argop4_u.opreaddir;
9307 	/*
9308 	 * 1 and 2 are reserved for client "." and ".." entry offset.
9309 	 * cookie 0 should be used over-the-wire to start reading at
9310 	 * the beginning of the directory excluding "." and "..".
9311 	 */
9312 	if (rdc->nfs4_cookie == 0 ||
9313 	    rdc->nfs4_cookie == 1 ||
9314 	    rdc->nfs4_cookie == 2) {
9315 		rargs->cookie = (nfs_cookie4)0;
9316 		rargs->cookieverf = 0;
9317 	} else {
9318 		rargs->cookie = (nfs_cookie4)rdc->nfs4_cookie;
9319 		mutex_enter(&rp->r_statelock);
9320 		rargs->cookieverf = rp->r_cookieverf4;
9321 		mutex_exit(&rp->r_statelock);
9322 	}
9323 	rargs->dircount = MIN(rdc->buflen, mi->mi_tsize);
9324 	rargs->maxcount = mi->mi_tsize;
9325 	rargs->attr_request = rd_bitsval;
9326 	rargs->rdc = rdc;
9327 	rargs->dvp = vp;
9328 	rargs->mi = mi;
9329 	rargs->cr = cr;
9330 
9331 
9332 	/*
9333 	 * If count < than the minimum required, we return no entries
9334 	 * and fail with EINVAL
9335 	 */
9336 	if (rargs->dircount < (DIRENT64_RECLEN(1) + DIRENT64_RECLEN(2))) {
9337 		rdc->error = EINVAL;
9338 		goto out;
9339 	}
9340 
9341 	if (args.array_len == 5) {
9342 		/*
9343 		 * Add lookupp and getattr for parent nodeid.
9344 		 */
9345 		argop[2].argop = OP_LOOKUPP;
9346 
9347 		argop[3].argop = OP_GETFH;
9348 
9349 		/* getattr parent */
9350 		argop[4].argop = OP_GETATTR;
9351 		argop[4].nfs_argop4_u.opgetattr.attr_request = NFS4_VATTR_MASK;
9352 		argop[4].nfs_argop4_u.opgetattr.mi = mi;
9353 	}
9354 
9355 	doqueue = 1;
9356 
9357 	if (mi->mi_io_kstats) {
9358 		mutex_enter(&mi->mi_lock);
9359 		kstat_runq_enter(KSTAT_IO_PTR(mi->mi_io_kstats));
9360 		mutex_exit(&mi->mi_lock);
9361 	}
9362 
9363 	/* capture the time of this call */
9364 	rargs->t = t = gethrtime();
9365 
9366 	rfs4call(mi, &args, &res, cr, &doqueue, 0, &e);
9367 
9368 	if (mi->mi_io_kstats) {
9369 		mutex_enter(&mi->mi_lock);
9370 		kstat_runq_exit(KSTAT_IO_PTR(mi->mi_io_kstats));
9371 		mutex_exit(&mi->mi_lock);
9372 	}
9373 
9374 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
9375 
9376 	/*
9377 	 * If RPC error occurred and it isn't an error that
9378 	 * triggers recovery, then go ahead and fail now.
9379 	 */
9380 	if (e.error != 0 && !needrecov) {
9381 		rdc->error = e.error;
9382 		goto out;
9383 	}
9384 
9385 	if (needrecov) {
9386 		bool_t abort;
9387 
9388 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
9389 		    "nfs4readdir: initiating recovery.\n"));
9390 
9391 		abort = nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
9392 		    NULL, OP_READDIR, NULL, NULL, NULL);
9393 		if (abort == FALSE) {
9394 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9395 			    &recov_state, needrecov);
9396 			if (!e.error)
9397 				(void) xdr_free(xdr_COMPOUND4res_clnt,
9398 				    (caddr_t)&res);
9399 			if (rdc->entries != NULL) {
9400 				kmem_free(rdc->entries, rdc->entlen);
9401 				rdc->entries = NULL;
9402 			}
9403 			goto recov_retry;
9404 		}
9405 
9406 		if (e.error != 0) {
9407 			rdc->error = e.error;
9408 			goto out;
9409 		}
9410 
9411 		/* fall through for res.status case */
9412 	}
9413 
9414 	res_opcnt = res.array_len;
9415 
9416 	/*
9417 	 * If compound failed first 2 ops (PUTFH+READDIR), then return
9418 	 * failure here.  Subsequent ops are for filling out dot-dot
9419 	 * dirent, and if they fail, we still want to give the caller
9420 	 * the dirents returned by (the successful) READDIR op, so we need
9421 	 * to silently ignore failure for subsequent ops (LOOKUPP+GETATTR).
9422 	 *
9423 	 * One example where PUTFH+READDIR ops would succeed but
9424 	 * LOOKUPP+GETATTR would fail would be a dir that has r perm
9425 	 * but lacks x.  In this case, a POSIX server's VOP_READDIR
9426 	 * would succeed; however, VOP_LOOKUP(..) would fail since no
9427 	 * x perm.  We need to come up with a non-vendor-specific way
9428 	 * for a POSIX server to return d_ino from dotdot's dirent if
9429 	 * client only requests mounted_on_fileid, and just say the
9430 	 * LOOKUPP succeeded and fill out the GETATTR.  However, if
9431 	 * client requested any mandatory attrs, server would be required
9432 	 * to fail the GETATTR op because it can't call VOP_LOOKUP+VOP_GETATTR
9433 	 * for dotdot.
9434 	 */
9435 
9436 	if (res.status) {
9437 		if (res_opcnt <= 2) {
9438 			e.error = geterrno4(res.status);
9439 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_READDIR,
9440 			    &recov_state, needrecov);
9441 			nfs4_purge_stale_fh(e.error, vp, cr);
9442 			rdc->error = e.error;
9443 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9444 			if (rdc->entries != NULL) {
9445 				kmem_free(rdc->entries, rdc->entlen);
9446 				rdc->entries = NULL;
9447 			}
9448 			/*
9449 			 * If readdir a node that is a stub for a
9450 			 * crossed mount point, keep the original
9451 			 * secinfo flavor for the current file system,
9452 			 * not the crossed one.
9453 			 */
9454 			(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9455 			return;
9456 		}
9457 	}
9458 
9459 	resop = &res.array[1];	/* readdir res */
9460 	rd_res = &resop->nfs_resop4_u.opreaddirclnt;
9461 
9462 	mutex_enter(&rp->r_statelock);
9463 	rp->r_cookieverf4 = rd_res->cookieverf;
9464 	mutex_exit(&rp->r_statelock);
9465 
9466 	/*
9467 	 * For "." and ".." entries
9468 	 * e.g.
9469 	 *	seek(cookie=0) -> "." entry with d_off = 1
9470 	 *	seek(cookie=1) -> ".." entry with d_off = 2
9471 	 */
9472 	if (cookie == (nfs_cookie4) 0) {
9473 		if (rd_res->dotp)
9474 			rd_res->dotp->d_ino = nodeid;
9475 		if (rd_res->dotdotp)
9476 			rd_res->dotdotp->d_ino = pnodeid;
9477 	}
9478 	if (cookie == (nfs_cookie4) 1) {
9479 		if (rd_res->dotdotp)
9480 			rd_res->dotdotp->d_ino = pnodeid;
9481 	}
9482 
9483 
9484 	/* LOOKUPP+GETATTR attemped */
9485 	if (args.array_len == 5 && rd_res->dotdotp) {
9486 		if (res.status == NFS4_OK && res_opcnt == 5) {
9487 			nfs_fh4 *fhp;
9488 			nfs4_sharedfh_t *sfhp;
9489 			vnode_t *pvp;
9490 			nfs4_ga_res_t *garp;
9491 
9492 			resop++;	/* lookupp */
9493 			resop++;	/* getfh   */
9494 			fhp = &resop->nfs_resop4_u.opgetfh.object;
9495 
9496 			resop++;	/* getattr of parent */
9497 
9498 			/*
9499 			 * First, take care of finishing the
9500 			 * readdir results.
9501 			 */
9502 			garp = &resop->nfs_resop4_u.opgetattr.ga_res;
9503 			/*
9504 			 * The d_ino of .. must be the inode number
9505 			 * of the mounted filesystem.
9506 			 */
9507 			if (garp->n4g_va.va_mask & AT_NODEID)
9508 				rd_res->dotdotp->d_ino =
9509 				    garp->n4g_va.va_nodeid;
9510 
9511 
9512 			/*
9513 			 * Next, create the ".." dnlc entry
9514 			 */
9515 			sfhp = sfh4_get(fhp, mi);
9516 			if (!nfs4_make_dotdot(sfhp, t, vp, cr, &pvp, 0)) {
9517 				dnlc_update(vp, "..", pvp);
9518 				VN_RELE(pvp);
9519 			}
9520 			sfh4_rele(&sfhp);
9521 		}
9522 	}
9523 
9524 	if (mi->mi_io_kstats) {
9525 		mutex_enter(&mi->mi_lock);
9526 		KSTAT_IO_PTR(mi->mi_io_kstats)->reads++;
9527 		KSTAT_IO_PTR(mi->mi_io_kstats)->nread += rdc->actlen;
9528 		mutex_exit(&mi->mi_lock);
9529 	}
9530 
9531 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
9532 
9533 out:
9534 	/*
9535 	 * If readdir a node that is a stub for a crossed mount point,
9536 	 * keep the original secinfo flavor for the current file system,
9537 	 * not the crossed one.
9538 	 */
9539 	(void) check_mnt_secinfo(mi->mi_curr_serv, vp);
9540 
9541 	nfs4_end_fop(mi, vp, NULL, OH_READDIR, &recov_state, needrecov);
9542 }
9543 
9544 
9545 static int
nfs4_bio(struct buf * bp,stable_how4 * stab_comm,cred_t * cr,bool_t readahead)9546 nfs4_bio(struct buf *bp, stable_how4 *stab_comm, cred_t *cr, bool_t readahead)
9547 {
9548 	rnode4_t *rp = VTOR4(bp->b_vp);
9549 	int count;
9550 	int error;
9551 	cred_t *cred_otw = NULL;
9552 	offset_t offset;
9553 	nfs4_open_stream_t *osp = NULL;
9554 	bool_t first_time = TRUE;	/* first time getting otw cred */
9555 	bool_t last_time = FALSE;	/* last time getting otw cred */
9556 
9557 	ASSERT(nfs_zone() == VTOMI4(bp->b_vp)->mi_zone);
9558 
9559 	DTRACE_IO1(start, struct buf *, bp);
9560 	offset = ldbtob(bp->b_lblkno);
9561 
9562 	if (bp->b_flags & B_READ) {
9563 	read_again:
9564 		/*
9565 		 * Releases the osp, if it is provided.
9566 		 * Puts a hold on the cred_otw and the new osp (if found).
9567 		 */
9568 		cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9569 		    &first_time, &last_time);
9570 		error = bp->b_error = nfs4read(bp->b_vp, bp->b_un.b_addr,
9571 		    offset, bp->b_bcount, &bp->b_resid, cred_otw,
9572 		    readahead, NULL);
9573 		crfree(cred_otw);
9574 		if (!error) {
9575 			if (bp->b_resid) {
9576 				/*
9577 				 * Didn't get it all because we hit EOF,
9578 				 * zero all the memory beyond the EOF.
9579 				 */
9580 				/* bzero(rdaddr + */
9581 				bzero(bp->b_un.b_addr +
9582 				    bp->b_bcount - bp->b_resid, bp->b_resid);
9583 			}
9584 			mutex_enter(&rp->r_statelock);
9585 			if (bp->b_resid == bp->b_bcount &&
9586 			    offset >= rp->r_size) {
9587 				/*
9588 				 * We didn't read anything at all as we are
9589 				 * past EOF.  Return an error indicator back
9590 				 * but don't destroy the pages (yet).
9591 				 */
9592 				error = NFS_EOF;
9593 			}
9594 			mutex_exit(&rp->r_statelock);
9595 		} else if (error == EACCES && last_time == FALSE) {
9596 				goto read_again;
9597 		}
9598 	} else {
9599 		if (!(rp->r_flags & R4STALE)) {
9600 write_again:
9601 			/*
9602 			 * Releases the osp, if it is provided.
9603 			 * Puts a hold on the cred_otw and the new
9604 			 * osp (if found).
9605 			 */
9606 			cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
9607 			    &first_time, &last_time);
9608 			mutex_enter(&rp->r_statelock);
9609 			count = MIN(bp->b_bcount, rp->r_size - offset);
9610 			mutex_exit(&rp->r_statelock);
9611 			if (count < 0)
9612 				cmn_err(CE_PANIC, "nfs4_bio: write count < 0");
9613 #ifdef DEBUG
9614 			if (count == 0) {
9615 				zoneid_t zoneid = getzoneid();
9616 
9617 				zcmn_err(zoneid, CE_WARN,
9618 				    "nfs4_bio: zero length write at %lld",
9619 				    offset);
9620 				zcmn_err(zoneid, CE_CONT, "flags=0x%x, "
9621 				    "b_bcount=%ld, file size=%lld",
9622 				    rp->r_flags, (long)bp->b_bcount,
9623 				    rp->r_size);
9624 				sfh4_printfhandle(VTOR4(bp->b_vp)->r_fh);
9625 				if (nfs4_bio_do_stop)
9626 					debug_enter("nfs4_bio");
9627 			}
9628 #endif
9629 			error = nfs4write(bp->b_vp, bp->b_un.b_addr, offset,
9630 			    count, cred_otw, stab_comm);
9631 			if (error == EACCES && last_time == FALSE) {
9632 				crfree(cred_otw);
9633 				goto write_again;
9634 			}
9635 			bp->b_error = error;
9636 			if (error && error != EINTR &&
9637 			    !(bp->b_vp->v_vfsp->vfs_flag & VFS_UNMOUNTED)) {
9638 				/*
9639 				 * Don't print EDQUOT errors on the console.
9640 				 * Don't print asynchronous EACCES errors.
9641 				 * Don't print EFBIG errors.
9642 				 * Print all other write errors.
9643 				 */
9644 				if (error != EDQUOT && error != EFBIG &&
9645 				    (error != EACCES ||
9646 				    !(bp->b_flags & B_ASYNC)))
9647 					nfs4_write_error(bp->b_vp,
9648 					    error, cred_otw);
9649 				/*
9650 				 * Update r_error and r_flags as appropriate.
9651 				 * If the error was ESTALE, then mark the
9652 				 * rnode as not being writeable and save
9653 				 * the error status.  Otherwise, save any
9654 				 * errors which occur from asynchronous
9655 				 * page invalidations.  Any errors occurring
9656 				 * from other operations should be saved
9657 				 * by the caller.
9658 				 */
9659 				mutex_enter(&rp->r_statelock);
9660 				if (error == ESTALE) {
9661 					rp->r_flags |= R4STALE;
9662 					if (!rp->r_error)
9663 						rp->r_error = error;
9664 				} else if (!rp->r_error &&
9665 				    (bp->b_flags &
9666 				    (B_INVAL|B_FORCE|B_ASYNC)) ==
9667 				    (B_INVAL|B_FORCE|B_ASYNC)) {
9668 					rp->r_error = error;
9669 				}
9670 				mutex_exit(&rp->r_statelock);
9671 			}
9672 			crfree(cred_otw);
9673 		} else {
9674 			error = rp->r_error;
9675 			/*
9676 			 * A close may have cleared r_error, if so,
9677 			 * propagate ESTALE error return properly
9678 			 */
9679 			if (error == 0)
9680 				error = ESTALE;
9681 		}
9682 	}
9683 
9684 	if (error != 0 && error != NFS_EOF)
9685 		bp->b_flags |= B_ERROR;
9686 
9687 	if (osp)
9688 		open_stream_rele(osp, rp);
9689 
9690 	DTRACE_IO1(done, struct buf *, bp);
9691 
9692 	return (error);
9693 }
9694 
9695 /* ARGSUSED */
9696 int
nfs4_fid(vnode_t * vp,fid_t * fidp,caller_context_t * ct)9697 nfs4_fid(vnode_t *vp, fid_t *fidp, caller_context_t *ct)
9698 {
9699 	return (EREMOTE);
9700 }
9701 
9702 /* ARGSUSED2 */
9703 int
nfs4_rwlock(vnode_t * vp,int write_lock,caller_context_t * ctp)9704 nfs4_rwlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9705 {
9706 	rnode4_t *rp = VTOR4(vp);
9707 
9708 	if (!write_lock) {
9709 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9710 		return (V_WRITELOCK_FALSE);
9711 	}
9712 
9713 	if ((rp->r_flags & R4DIRECTIO) ||
9714 	    (VTOMI4(vp)->mi_flags & MI4_DIRECTIO)) {
9715 		(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_READER, FALSE);
9716 		if (rp->r_mapcnt == 0 && !nfs4_has_pages(vp))
9717 			return (V_WRITELOCK_FALSE);
9718 		nfs_rw_exit(&rp->r_rwlock);
9719 	}
9720 
9721 	(void) nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, FALSE);
9722 	return (V_WRITELOCK_TRUE);
9723 }
9724 
9725 /* ARGSUSED */
9726 void
nfs4_rwunlock(vnode_t * vp,int write_lock,caller_context_t * ctp)9727 nfs4_rwunlock(vnode_t *vp, int write_lock, caller_context_t *ctp)
9728 {
9729 	rnode4_t *rp = VTOR4(vp);
9730 
9731 	nfs_rw_exit(&rp->r_rwlock);
9732 }
9733 
9734 /* ARGSUSED */
9735 static int
nfs4_seek(vnode_t * vp,offset_t ooff,offset_t * noffp,caller_context_t * ct)9736 nfs4_seek(vnode_t *vp, offset_t ooff, offset_t *noffp, caller_context_t *ct)
9737 {
9738 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9739 		return (EIO);
9740 
9741 	/*
9742 	 * Because we stuff the readdir cookie into the offset field
9743 	 * someone may attempt to do an lseek with the cookie which
9744 	 * we want to succeed.
9745 	 */
9746 	if (vp->v_type == VDIR)
9747 		return (0);
9748 	if (*noffp < 0)
9749 		return (EINVAL);
9750 	return (0);
9751 }
9752 
9753 
9754 /*
9755  * Return all the pages from [off..off+len) in file
9756  */
9757 /* ARGSUSED */
9758 static int
nfs4_getpage(vnode_t * vp,offset_t off,size_t len,uint_t * protp,page_t * pl[],size_t plsz,struct seg * seg,caddr_t addr,enum seg_rw rw,cred_t * cr,caller_context_t * ct)9759 nfs4_getpage(vnode_t *vp, offset_t off, size_t len, uint_t *protp,
9760     page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9761     enum seg_rw rw, cred_t *cr, caller_context_t *ct)
9762 {
9763 	rnode4_t *rp;
9764 	int error;
9765 	mntinfo4_t *mi;
9766 
9767 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9768 		return (EIO);
9769 	rp = VTOR4(vp);
9770 	if (IS_SHADOW(vp, rp))
9771 		vp = RTOV4(rp);
9772 
9773 	if (vp->v_flag & VNOMAP)
9774 		return (ENOSYS);
9775 
9776 	if (protp != NULL)
9777 		*protp = PROT_ALL;
9778 
9779 	/*
9780 	 * Now validate that the caches are up to date.
9781 	 */
9782 	if (error = nfs4_validate_caches(vp, cr))
9783 		return (error);
9784 
9785 	mi = VTOMI4(vp);
9786 retry:
9787 	mutex_enter(&rp->r_statelock);
9788 
9789 	/*
9790 	 * Don't create dirty pages faster than they
9791 	 * can be cleaned so that the system doesn't
9792 	 * get imbalanced.  If the async queue is
9793 	 * maxed out, then wait for it to drain before
9794 	 * creating more dirty pages.  Also, wait for
9795 	 * any threads doing pagewalks in the vop_getattr
9796 	 * entry points so that they don't block for
9797 	 * long periods.
9798 	 */
9799 	if (rw == S_CREATE) {
9800 		while ((mi->mi_max_threads != 0 &&
9801 		    rp->r_awcount > 2 * mi->mi_max_threads) ||
9802 		    rp->r_gcount > 0)
9803 			cv_wait(&rp->r_cv, &rp->r_statelock);
9804 	}
9805 
9806 	/*
9807 	 * If we are getting called as a side effect of an nfs_write()
9808 	 * operation the local file size might not be extended yet.
9809 	 * In this case we want to be able to return pages of zeroes.
9810 	 */
9811 	if (off + len > rp->r_size + PAGEOFFSET && seg != segkmap) {
9812 		NFS4_DEBUG(nfs4_pageio_debug,
9813 		    (CE_NOTE, "getpage beyond EOF: off=%lld, "
9814 		    "len=%llu, size=%llu, attrsize =%llu", off,
9815 		    (u_longlong_t)len, rp->r_size, rp->r_attr.va_size));
9816 		mutex_exit(&rp->r_statelock);
9817 		return (EFAULT);		/* beyond EOF */
9818 	}
9819 
9820 	mutex_exit(&rp->r_statelock);
9821 
9822 	error = pvn_getpages(nfs4_getapage, vp, off, len, protp,
9823 	    pl, plsz, seg, addr, rw, cr);
9824 	NFS4_DEBUG(nfs4_pageio_debug && error,
9825 	    (CE_NOTE, "getpages error %d; off=%lld, len=%lld",
9826 	    error, off, (u_longlong_t)len));
9827 
9828 	switch (error) {
9829 	case NFS_EOF:
9830 		nfs4_purge_caches(vp, NFS4_NOPURGE_DNLC, cr, FALSE);
9831 		goto retry;
9832 	case ESTALE:
9833 		nfs4_purge_stale_fh(error, vp, cr);
9834 	}
9835 
9836 	return (error);
9837 }
9838 
9839 /*
9840  * Called from pvn_getpages to get a particular page.
9841  */
9842 /* ARGSUSED */
9843 static int
nfs4_getapage(vnode_t * vp,u_offset_t off,size_t len,uint_t * protp,page_t * pl[],size_t plsz,struct seg * seg,caddr_t addr,enum seg_rw rw,cred_t * cr)9844 nfs4_getapage(vnode_t *vp, u_offset_t off, size_t len, uint_t *protp,
9845     page_t *pl[], size_t plsz, struct seg *seg, caddr_t addr,
9846     enum seg_rw rw, cred_t *cr)
9847 {
9848 	rnode4_t *rp;
9849 	uint_t bsize;
9850 	struct buf *bp;
9851 	page_t *pp;
9852 	u_offset_t lbn;
9853 	u_offset_t io_off;
9854 	u_offset_t blkoff;
9855 	u_offset_t rablkoff;
9856 	size_t io_len;
9857 	uint_t blksize;
9858 	int error;
9859 	int readahead;
9860 	int readahead_issued = 0;
9861 	int ra_window; /* readahead window */
9862 	page_t *pagefound;
9863 	page_t *savepp;
9864 
9865 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
9866 		return (EIO);
9867 
9868 	rp = VTOR4(vp);
9869 	ASSERT(!IS_SHADOW(vp, rp));
9870 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
9871 
9872 reread:
9873 	bp = NULL;
9874 	pp = NULL;
9875 	pagefound = NULL;
9876 
9877 	if (pl != NULL)
9878 		pl[0] = NULL;
9879 
9880 	error = 0;
9881 	lbn = off / bsize;
9882 	blkoff = lbn * bsize;
9883 
9884 	/*
9885 	 * Queueing up the readahead before doing the synchronous read
9886 	 * results in a significant increase in read throughput because
9887 	 * of the increased parallelism between the async threads and
9888 	 * the process context.
9889 	 */
9890 	if ((off & ((vp->v_vfsp->vfs_bsize) - 1)) == 0 &&
9891 	    rw != S_CREATE &&
9892 	    !(vp->v_flag & VNOCACHE)) {
9893 		mutex_enter(&rp->r_statelock);
9894 
9895 		/*
9896 		 * Calculate the number of readaheads to do.
9897 		 * a) No readaheads at offset = 0.
9898 		 * b) Do maximum(nfs4_nra) readaheads when the readahead
9899 		 *    window is closed.
9900 		 * c) Do readaheads between 1 to (nfs4_nra - 1) depending
9901 		 *    upon how far the readahead window is open or close.
9902 		 * d) No readaheads if rp->r_nextr is not within the scope
9903 		 *    of the readahead window (random i/o).
9904 		 */
9905 
9906 		if (off == 0)
9907 			readahead = 0;
9908 		else if (blkoff == rp->r_nextr)
9909 			readahead = nfs4_nra;
9910 		else if (rp->r_nextr > blkoff &&
9911 		    ((ra_window = (rp->r_nextr - blkoff) / bsize)
9912 		    <= (nfs4_nra - 1)))
9913 			readahead = nfs4_nra - ra_window;
9914 		else
9915 			readahead = 0;
9916 
9917 		rablkoff = rp->r_nextr;
9918 		while (readahead > 0 && rablkoff + bsize < rp->r_size) {
9919 			mutex_exit(&rp->r_statelock);
9920 			if (nfs4_async_readahead(vp, rablkoff + bsize,
9921 			    addr + (rablkoff + bsize - off),
9922 			    seg, cr, nfs4_readahead) < 0) {
9923 				mutex_enter(&rp->r_statelock);
9924 				break;
9925 			}
9926 			readahead--;
9927 			rablkoff += bsize;
9928 			/*
9929 			 * Indicate that we did a readahead so
9930 			 * readahead offset is not updated
9931 			 * by the synchronous read below.
9932 			 */
9933 			readahead_issued = 1;
9934 			mutex_enter(&rp->r_statelock);
9935 			/*
9936 			 * set readahead offset to
9937 			 * offset of last async readahead
9938 			 * request.
9939 			 */
9940 			rp->r_nextr = rablkoff;
9941 		}
9942 		mutex_exit(&rp->r_statelock);
9943 	}
9944 
9945 again:
9946 	if ((pagefound = page_exists(vp, off)) == NULL) {
9947 		if (pl == NULL) {
9948 			(void) nfs4_async_readahead(vp, blkoff, addr, seg, cr,
9949 			    nfs4_readahead);
9950 		} else if (rw == S_CREATE) {
9951 			/*
9952 			 * Block for this page is not allocated, or the offset
9953 			 * is beyond the current allocation size, or we're
9954 			 * allocating a swap slot and the page was not found,
9955 			 * so allocate it and return a zero page.
9956 			 */
9957 			if ((pp = page_create_va(vp, off,
9958 			    PAGESIZE, PG_WAIT, seg, addr)) == NULL)
9959 				cmn_err(CE_PANIC, "nfs4_getapage: page_create");
9960 			io_len = PAGESIZE;
9961 			mutex_enter(&rp->r_statelock);
9962 			rp->r_nextr = off + PAGESIZE;
9963 			mutex_exit(&rp->r_statelock);
9964 		} else {
9965 			/*
9966 			 * Need to go to server to get a block
9967 			 */
9968 			mutex_enter(&rp->r_statelock);
9969 			if (blkoff < rp->r_size &&
9970 			    blkoff + bsize > rp->r_size) {
9971 				/*
9972 				 * If less than a block left in
9973 				 * file read less than a block.
9974 				 */
9975 				if (rp->r_size <= off) {
9976 					/*
9977 					 * Trying to access beyond EOF,
9978 					 * set up to get at least one page.
9979 					 */
9980 					blksize = off + PAGESIZE - blkoff;
9981 				} else
9982 					blksize = rp->r_size - blkoff;
9983 			} else if ((off == 0) ||
9984 			    (off != rp->r_nextr && !readahead_issued)) {
9985 				blksize = PAGESIZE;
9986 				blkoff = off; /* block = page here */
9987 			} else
9988 				blksize = bsize;
9989 			mutex_exit(&rp->r_statelock);
9990 
9991 			pp = pvn_read_kluster(vp, off, seg, addr, &io_off,
9992 			    &io_len, blkoff, blksize, 0);
9993 
9994 			/*
9995 			 * Some other thread has entered the page,
9996 			 * so just use it.
9997 			 */
9998 			if (pp == NULL)
9999 				goto again;
10000 
10001 			/*
10002 			 * Now round the request size up to page boundaries.
10003 			 * This ensures that the entire page will be
10004 			 * initialized to zeroes if EOF is encountered.
10005 			 */
10006 			io_len = ptob(btopr(io_len));
10007 
10008 			bp = pageio_setup(pp, io_len, vp, B_READ);
10009 			ASSERT(bp != NULL);
10010 
10011 			/*
10012 			 * pageio_setup should have set b_addr to 0.  This
10013 			 * is correct since we want to do I/O on a page
10014 			 * boundary.  bp_mapin will use this addr to calculate
10015 			 * an offset, and then set b_addr to the kernel virtual
10016 			 * address it allocated for us.
10017 			 */
10018 			ASSERT(bp->b_un.b_addr == 0);
10019 
10020 			bp->b_edev = 0;
10021 			bp->b_dev = 0;
10022 			bp->b_lblkno = lbtodb(io_off);
10023 			bp->b_file = vp;
10024 			bp->b_offset = (offset_t)off;
10025 			bp_mapin(bp);
10026 
10027 			/*
10028 			 * If doing a write beyond what we believe is EOF,
10029 			 * don't bother trying to read the pages from the
10030 			 * server, we'll just zero the pages here.  We
10031 			 * don't check that the rw flag is S_WRITE here
10032 			 * because some implementations may attempt a
10033 			 * read access to the buffer before copying data.
10034 			 */
10035 			mutex_enter(&rp->r_statelock);
10036 			if (io_off >= rp->r_size && seg == segkmap) {
10037 				mutex_exit(&rp->r_statelock);
10038 				bzero(bp->b_un.b_addr, io_len);
10039 			} else {
10040 				mutex_exit(&rp->r_statelock);
10041 				error = nfs4_bio(bp, NULL, cr, FALSE);
10042 			}
10043 
10044 			/*
10045 			 * Unmap the buffer before freeing it.
10046 			 */
10047 			bp_mapout(bp);
10048 			pageio_done(bp);
10049 
10050 			savepp = pp;
10051 			do {
10052 				pp->p_fsdata = C_NOCOMMIT;
10053 			} while ((pp = pp->p_next) != savepp);
10054 
10055 			if (error == NFS_EOF) {
10056 				/*
10057 				 * If doing a write system call just return
10058 				 * zeroed pages, else user tried to get pages
10059 				 * beyond EOF, return error.  We don't check
10060 				 * that the rw flag is S_WRITE here because
10061 				 * some implementations may attempt a read
10062 				 * access to the buffer before copying data.
10063 				 */
10064 				if (seg == segkmap)
10065 					error = 0;
10066 				else
10067 					error = EFAULT;
10068 			}
10069 
10070 			if (!readahead_issued && !error) {
10071 				mutex_enter(&rp->r_statelock);
10072 				rp->r_nextr = io_off + io_len;
10073 				mutex_exit(&rp->r_statelock);
10074 			}
10075 		}
10076 	}
10077 
10078 out:
10079 	if (pl == NULL)
10080 		return (error);
10081 
10082 	if (error) {
10083 		if (pp != NULL)
10084 			pvn_read_done(pp, B_ERROR);
10085 		return (error);
10086 	}
10087 
10088 	if (pagefound) {
10089 		se_t se = (rw == S_CREATE ? SE_EXCL : SE_SHARED);
10090 
10091 		/*
10092 		 * Page exists in the cache, acquire the appropriate lock.
10093 		 * If this fails, start all over again.
10094 		 */
10095 		if ((pp = page_lookup(vp, off, se)) == NULL) {
10096 #ifdef DEBUG
10097 			nfs4_lostpage++;
10098 #endif
10099 			goto reread;
10100 		}
10101 		pl[0] = pp;
10102 		pl[1] = NULL;
10103 		return (0);
10104 	}
10105 
10106 	if (pp != NULL)
10107 		pvn_plist_init(pp, pl, plsz, off, io_len, rw);
10108 
10109 	return (error);
10110 }
10111 
10112 static void
nfs4_readahead(vnode_t * vp,u_offset_t blkoff,caddr_t addr,struct seg * seg,cred_t * cr)10113 nfs4_readahead(vnode_t *vp, u_offset_t blkoff, caddr_t addr, struct seg *seg,
10114     cred_t *cr)
10115 {
10116 	int error;
10117 	page_t *pp;
10118 	u_offset_t io_off;
10119 	size_t io_len;
10120 	struct buf *bp;
10121 	uint_t bsize, blksize;
10122 	rnode4_t *rp = VTOR4(vp);
10123 	page_t *savepp;
10124 
10125 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10126 
10127 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
10128 
10129 	mutex_enter(&rp->r_statelock);
10130 	if (blkoff < rp->r_size && blkoff + bsize > rp->r_size) {
10131 		/*
10132 		 * If less than a block left in file read less
10133 		 * than a block.
10134 		 */
10135 		blksize = rp->r_size - blkoff;
10136 	} else
10137 		blksize = bsize;
10138 	mutex_exit(&rp->r_statelock);
10139 
10140 	pp = pvn_read_kluster(vp, blkoff, segkmap, addr,
10141 	    &io_off, &io_len, blkoff, blksize, 1);
10142 	/*
10143 	 * The isra flag passed to the kluster function is 1, we may have
10144 	 * gotten a return value of NULL for a variety of reasons (# of free
10145 	 * pages < minfree, someone entered the page on the vnode etc). In all
10146 	 * cases, we want to punt on the readahead.
10147 	 */
10148 	if (pp == NULL)
10149 		return;
10150 
10151 	/*
10152 	 * Now round the request size up to page boundaries.
10153 	 * This ensures that the entire page will be
10154 	 * initialized to zeroes if EOF is encountered.
10155 	 */
10156 	io_len = ptob(btopr(io_len));
10157 
10158 	bp = pageio_setup(pp, io_len, vp, B_READ);
10159 	ASSERT(bp != NULL);
10160 
10161 	/*
10162 	 * pageio_setup should have set b_addr to 0.  This is correct since
10163 	 * we want to do I/O on a page boundary. bp_mapin() will use this addr
10164 	 * to calculate an offset, and then set b_addr to the kernel virtual
10165 	 * address it allocated for us.
10166 	 */
10167 	ASSERT(bp->b_un.b_addr == 0);
10168 
10169 	bp->b_edev = 0;
10170 	bp->b_dev = 0;
10171 	bp->b_lblkno = lbtodb(io_off);
10172 	bp->b_file = vp;
10173 	bp->b_offset = (offset_t)blkoff;
10174 	bp_mapin(bp);
10175 
10176 	/*
10177 	 * If doing a write beyond what we believe is EOF, don't bother trying
10178 	 * to read the pages from the server, we'll just zero the pages here.
10179 	 * We don't check that the rw flag is S_WRITE here because some
10180 	 * implementations may attempt a read access to the buffer before
10181 	 * copying data.
10182 	 */
10183 	mutex_enter(&rp->r_statelock);
10184 	if (io_off >= rp->r_size && seg == segkmap) {
10185 		mutex_exit(&rp->r_statelock);
10186 		bzero(bp->b_un.b_addr, io_len);
10187 		error = 0;
10188 	} else {
10189 		mutex_exit(&rp->r_statelock);
10190 		error = nfs4_bio(bp, NULL, cr, TRUE);
10191 		if (error == NFS_EOF)
10192 			error = 0;
10193 	}
10194 
10195 	/*
10196 	 * Unmap the buffer before freeing it.
10197 	 */
10198 	bp_mapout(bp);
10199 	pageio_done(bp);
10200 
10201 	savepp = pp;
10202 	do {
10203 		pp->p_fsdata = C_NOCOMMIT;
10204 	} while ((pp = pp->p_next) != savepp);
10205 
10206 	pvn_read_done(pp, error ? B_READ | B_ERROR : B_READ);
10207 
10208 	/*
10209 	 * In case of error set readahead offset
10210 	 * to the lowest offset.
10211 	 * pvn_read_done() calls VN_DISPOSE to destroy the pages
10212 	 */
10213 	if (error && rp->r_nextr > io_off) {
10214 		mutex_enter(&rp->r_statelock);
10215 		if (rp->r_nextr > io_off)
10216 			rp->r_nextr = io_off;
10217 		mutex_exit(&rp->r_statelock);
10218 	}
10219 }
10220 
10221 /*
10222  * Flags are composed of {B_INVAL, B_FREE, B_DONTNEED, B_FORCE}
10223  * If len == 0, do from off to EOF.
10224  *
10225  * The normal cases should be len == 0 && off == 0 (entire vp list) or
10226  * len == MAXBSIZE (from segmap_release actions), and len == PAGESIZE
10227  * (from pageout).
10228  */
10229 /* ARGSUSED */
10230 static int
nfs4_putpage(vnode_t * vp,offset_t off,size_t len,int flags,cred_t * cr,caller_context_t * ct)10231 nfs4_putpage(vnode_t *vp, offset_t off, size_t len, int flags, cred_t *cr,
10232     caller_context_t *ct)
10233 {
10234 	int error;
10235 	rnode4_t *rp;
10236 
10237 	ASSERT(cr != NULL);
10238 
10239 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
10240 		return (EIO);
10241 
10242 	rp = VTOR4(vp);
10243 	if (IS_SHADOW(vp, rp))
10244 		vp = RTOV4(rp);
10245 
10246 	/*
10247 	 * XXX - Why should this check be made here?
10248 	 */
10249 	if (vp->v_flag & VNOMAP)
10250 		return (ENOSYS);
10251 
10252 	if (len == 0 && !(flags & B_INVAL) &&
10253 	    (vp->v_vfsp->vfs_flag & VFS_RDONLY))
10254 		return (0);
10255 
10256 	mutex_enter(&rp->r_statelock);
10257 	rp->r_count++;
10258 	mutex_exit(&rp->r_statelock);
10259 	error = nfs4_putpages(vp, off, len, flags, cr);
10260 	mutex_enter(&rp->r_statelock);
10261 	rp->r_count--;
10262 	cv_broadcast(&rp->r_cv);
10263 	mutex_exit(&rp->r_statelock);
10264 
10265 	return (error);
10266 }
10267 
10268 /*
10269  * Write out a single page, possibly klustering adjacent dirty pages.
10270  */
10271 int
nfs4_putapage(vnode_t * vp,page_t * pp,u_offset_t * offp,size_t * lenp,int flags,cred_t * cr)10272 nfs4_putapage(vnode_t *vp, page_t *pp, u_offset_t *offp, size_t *lenp,
10273     int flags, cred_t *cr)
10274 {
10275 	u_offset_t io_off;
10276 	u_offset_t lbn_off;
10277 	u_offset_t lbn;
10278 	size_t io_len;
10279 	uint_t bsize;
10280 	int error;
10281 	rnode4_t *rp;
10282 
10283 	ASSERT(!(vp->v_vfsp->vfs_flag & VFS_RDONLY));
10284 	ASSERT(pp != NULL);
10285 	ASSERT(cr != NULL);
10286 	ASSERT((flags & B_ASYNC) || nfs_zone() == VTOMI4(vp)->mi_zone);
10287 
10288 	rp = VTOR4(vp);
10289 	ASSERT(rp->r_count > 0);
10290 	ASSERT(!IS_SHADOW(vp, rp));
10291 
10292 	bsize = MAX(vp->v_vfsp->vfs_bsize, PAGESIZE);
10293 	lbn = pp->p_offset / bsize;
10294 	lbn_off = lbn * bsize;
10295 
10296 	/*
10297 	 * Find a kluster that fits in one block, or in
10298 	 * one page if pages are bigger than blocks.  If
10299 	 * there is less file space allocated than a whole
10300 	 * page, we'll shorten the i/o request below.
10301 	 */
10302 	pp = pvn_write_kluster(vp, pp, &io_off, &io_len, lbn_off,
10303 	    roundup(bsize, PAGESIZE), flags);
10304 
10305 	/*
10306 	 * pvn_write_kluster shouldn't have returned a page with offset
10307 	 * behind the original page we were given.  Verify that.
10308 	 */
10309 	ASSERT((pp->p_offset / bsize) >= lbn);
10310 
10311 	/*
10312 	 * Now pp will have the list of kept dirty pages marked for
10313 	 * write back.  It will also handle invalidation and freeing
10314 	 * of pages that are not dirty.  Check for page length rounding
10315 	 * problems.
10316 	 */
10317 	if (io_off + io_len > lbn_off + bsize) {
10318 		ASSERT((io_off + io_len) - (lbn_off + bsize) < PAGESIZE);
10319 		io_len = lbn_off + bsize - io_off;
10320 	}
10321 	/*
10322 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10323 	 * consistent value of r_size. R4MODINPROGRESS is set in writerp4().
10324 	 * When R4MODINPROGRESS is set it indicates that a uiomove() is in
10325 	 * progress and the r_size has not been made consistent with the
10326 	 * new size of the file. When the uiomove() completes the r_size is
10327 	 * updated and the R4MODINPROGRESS flag is cleared.
10328 	 *
10329 	 * The R4MODINPROGRESS flag makes sure that nfs4_bio() sees a
10330 	 * consistent value of r_size. Without this handshaking, it is
10331 	 * possible that nfs4_bio() picks  up the old value of r_size
10332 	 * before the uiomove() in writerp4() completes. This will result
10333 	 * in the write through nfs4_bio() being dropped.
10334 	 *
10335 	 * More precisely, there is a window between the time the uiomove()
10336 	 * completes and the time the r_size is updated. If a VOP_PUTPAGE()
10337 	 * operation intervenes in this window, the page will be picked up,
10338 	 * because it is dirty (it will be unlocked, unless it was
10339 	 * pagecreate'd). When the page is picked up as dirty, the dirty
10340 	 * bit is reset (pvn_getdirty()). In nfs4write(), r_size is
10341 	 * checked. This will still be the old size. Therefore the page will
10342 	 * not be written out. When segmap_release() calls VOP_PUTPAGE(),
10343 	 * the page will be found to be clean and the write will be dropped.
10344 	 */
10345 	if (rp->r_flags & R4MODINPROGRESS) {
10346 		mutex_enter(&rp->r_statelock);
10347 		if ((rp->r_flags & R4MODINPROGRESS) &&
10348 		    rp->r_modaddr + MAXBSIZE > io_off &&
10349 		    rp->r_modaddr < io_off + io_len) {
10350 			page_t *plist;
10351 			/*
10352 			 * A write is in progress for this region of the file.
10353 			 * If we did not detect R4MODINPROGRESS here then this
10354 			 * path through nfs_putapage() would eventually go to
10355 			 * nfs4_bio() and may not write out all of the data
10356 			 * in the pages. We end up losing data. So we decide
10357 			 * to set the modified bit on each page in the page
10358 			 * list and mark the rnode with R4DIRTY. This write
10359 			 * will be restarted at some later time.
10360 			 */
10361 			plist = pp;
10362 			while (plist != NULL) {
10363 				pp = plist;
10364 				page_sub(&plist, pp);
10365 				hat_setmod(pp);
10366 				page_io_unlock(pp);
10367 				page_unlock(pp);
10368 			}
10369 			rp->r_flags |= R4DIRTY;
10370 			mutex_exit(&rp->r_statelock);
10371 			if (offp)
10372 				*offp = io_off;
10373 			if (lenp)
10374 				*lenp = io_len;
10375 			return (0);
10376 		}
10377 		mutex_exit(&rp->r_statelock);
10378 	}
10379 
10380 	if (flags & B_ASYNC) {
10381 		error = nfs4_async_putapage(vp, pp, io_off, io_len, flags, cr,
10382 		    nfs4_sync_putapage);
10383 	} else
10384 		error = nfs4_sync_putapage(vp, pp, io_off, io_len, flags, cr);
10385 
10386 	if (offp)
10387 		*offp = io_off;
10388 	if (lenp)
10389 		*lenp = io_len;
10390 	return (error);
10391 }
10392 
10393 static int
nfs4_sync_putapage(vnode_t * vp,page_t * pp,u_offset_t io_off,size_t io_len,int flags,cred_t * cr)10394 nfs4_sync_putapage(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
10395     int flags, cred_t *cr)
10396 {
10397 	int error;
10398 	rnode4_t *rp;
10399 
10400 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
10401 
10402 	flags |= B_WRITE;
10403 
10404 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
10405 
10406 	rp = VTOR4(vp);
10407 
10408 	if ((error == ENOSPC || error == EDQUOT || error == EFBIG ||
10409 	    error == EACCES) &&
10410 	    (flags & (B_INVAL|B_FORCE)) != (B_INVAL|B_FORCE)) {
10411 		if (!(rp->r_flags & R4OUTOFSPACE)) {
10412 			mutex_enter(&rp->r_statelock);
10413 			rp->r_flags |= R4OUTOFSPACE;
10414 			mutex_exit(&rp->r_statelock);
10415 		}
10416 		flags |= B_ERROR;
10417 		pvn_write_done(pp, flags);
10418 		/*
10419 		 * If this was not an async thread, then try again to
10420 		 * write out the pages, but this time, also destroy
10421 		 * them whether or not the write is successful.  This
10422 		 * will prevent memory from filling up with these
10423 		 * pages and destroying them is the only alternative
10424 		 * if they can't be written out.
10425 		 *
10426 		 * Don't do this if this is an async thread because
10427 		 * when the pages are unlocked in pvn_write_done,
10428 		 * some other thread could have come along, locked
10429 		 * them, and queued for an async thread.  It would be
10430 		 * possible for all of the async threads to be tied
10431 		 * up waiting to lock the pages again and they would
10432 		 * all already be locked and waiting for an async
10433 		 * thread to handle them.  Deadlock.
10434 		 */
10435 		if (!(flags & B_ASYNC)) {
10436 			error = nfs4_putpage(vp, io_off, io_len,
10437 			    B_INVAL | B_FORCE, cr, NULL);
10438 		}
10439 	} else {
10440 		if (error)
10441 			flags |= B_ERROR;
10442 		else if (rp->r_flags & R4OUTOFSPACE) {
10443 			mutex_enter(&rp->r_statelock);
10444 			rp->r_flags &= ~R4OUTOFSPACE;
10445 			mutex_exit(&rp->r_statelock);
10446 		}
10447 		pvn_write_done(pp, flags);
10448 		if (freemem < desfree)
10449 			(void) nfs4_commit_vp(vp, (u_offset_t)0, 0, cr,
10450 			    NFS4_WRITE_NOWAIT);
10451 	}
10452 
10453 	return (error);
10454 }
10455 
10456 #ifdef DEBUG
10457 int nfs4_force_open_before_mmap = 0;
10458 #endif
10459 
10460 /* ARGSUSED */
10461 static int
nfs4_map(vnode_t * vp,offset_t off,struct as * as,caddr_t * addrp,size_t len,uchar_t prot,uchar_t maxprot,uint_t flags,cred_t * cr,caller_context_t * ct)10462 nfs4_map(vnode_t *vp, offset_t off, struct as *as, caddr_t *addrp,
10463     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
10464     caller_context_t *ct)
10465 {
10466 	struct segvn_crargs vn_a;
10467 	int error = 0;
10468 	rnode4_t *rp = VTOR4(vp);
10469 	mntinfo4_t *mi = VTOMI4(vp);
10470 
10471 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10472 		return (EIO);
10473 
10474 	if (vp->v_flag & VNOMAP)
10475 		return (ENOSYS);
10476 
10477 	if (off < 0 || (off + len) < 0)
10478 		return (ENXIO);
10479 
10480 	if (vp->v_type != VREG)
10481 		return (ENODEV);
10482 
10483 	/*
10484 	 * If the file is delegated to the client don't do anything.
10485 	 * If the file is not delegated, then validate the data cache.
10486 	 */
10487 	mutex_enter(&rp->r_statev4_lock);
10488 	if (rp->r_deleg_type == OPEN_DELEGATE_NONE) {
10489 		mutex_exit(&rp->r_statev4_lock);
10490 		error = nfs4_validate_caches(vp, cr);
10491 		if (error)
10492 			return (error);
10493 	} else {
10494 		mutex_exit(&rp->r_statev4_lock);
10495 	}
10496 
10497 	/*
10498 	 * Check to see if the vnode is currently marked as not cachable.
10499 	 * This means portions of the file are locked (through VOP_FRLOCK).
10500 	 * In this case the map request must be refused.  We use
10501 	 * rp->r_lkserlock to avoid a race with concurrent lock requests.
10502 	 *
10503 	 * Atomically increment r_inmap after acquiring r_rwlock. The
10504 	 * idea here is to acquire r_rwlock to block read/write and
10505 	 * not to protect r_inmap. r_inmap will inform nfs4_read/write()
10506 	 * that we are in nfs4_map(). Now, r_rwlock is acquired in order
10507 	 * and we can prevent the deadlock that would have occurred
10508 	 * when nfs4_addmap() would have acquired it out of order.
10509 	 *
10510 	 * Since we are not protecting r_inmap by any lock, we do not
10511 	 * hold any lock when we decrement it. We atomically decrement
10512 	 * r_inmap after we release r_lkserlock.
10513 	 */
10514 
10515 	if (nfs_rw_enter_sig(&rp->r_rwlock, RW_WRITER, INTR4(vp)))
10516 		return (EINTR);
10517 	atomic_inc_uint(&rp->r_inmap);
10518 	nfs_rw_exit(&rp->r_rwlock);
10519 
10520 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_READER, INTR4(vp))) {
10521 		atomic_dec_uint(&rp->r_inmap);
10522 		return (EINTR);
10523 	}
10524 
10525 
10526 	if (vp->v_flag & VNOCACHE) {
10527 		error = EAGAIN;
10528 		goto done;
10529 	}
10530 
10531 	/*
10532 	 * Don't allow concurrent locks and mapping if mandatory locking is
10533 	 * enabled.
10534 	 */
10535 	if (flk_has_remote_locks(vp)) {
10536 		struct vattr va;
10537 		va.va_mask = AT_MODE;
10538 		error = nfs4getattr(vp, &va, cr);
10539 		if (error != 0)
10540 			goto done;
10541 		if (MANDLOCK(vp, va.va_mode)) {
10542 			error = EAGAIN;
10543 			goto done;
10544 		}
10545 	}
10546 
10547 	/*
10548 	 * It is possible that the rnode has a lost lock request that we
10549 	 * are still trying to recover, and that the request conflicts with
10550 	 * this map request.
10551 	 *
10552 	 * An alternative approach would be for nfs4_safemap() to consider
10553 	 * queued lock requests when deciding whether to set or clear
10554 	 * VNOCACHE.  This would require the frlock code path to call
10555 	 * nfs4_safemap() after enqueing a lost request.
10556 	 */
10557 	if (nfs4_map_lost_lock_conflict(vp)) {
10558 		error = EAGAIN;
10559 		goto done;
10560 	}
10561 
10562 	as_rangelock(as);
10563 	error = choose_addr(as, addrp, len, off, ADDR_VACALIGN, flags);
10564 	if (error != 0) {
10565 		as_rangeunlock(as);
10566 		goto done;
10567 	}
10568 
10569 	if (vp->v_type == VREG) {
10570 		/*
10571 		 * We need to retrieve the open stream
10572 		 */
10573 		nfs4_open_stream_t	*osp = NULL;
10574 		nfs4_open_owner_t	*oop = NULL;
10575 
10576 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10577 		if (oop != NULL) {
10578 			/* returns with 'os_sync_lock' held */
10579 			osp = find_open_stream(oop, rp);
10580 			open_owner_rele(oop);
10581 		}
10582 		if (osp == NULL) {
10583 #ifdef DEBUG
10584 			if (nfs4_force_open_before_mmap) {
10585 				error = EIO;
10586 				goto done;
10587 			}
10588 #endif
10589 			/* returns with 'os_sync_lock' held */
10590 			error = open_and_get_osp(vp, cr, &osp);
10591 			if (osp == NULL) {
10592 				NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10593 				    "nfs4_map: we tried to OPEN the file "
10594 				    "but again no osp, so fail with EIO"));
10595 				goto done;
10596 			}
10597 		}
10598 
10599 		if (osp->os_failed_reopen) {
10600 			mutex_exit(&osp->os_sync_lock);
10601 			open_stream_rele(osp, rp);
10602 			NFS4_DEBUG(nfs4_open_stream_debug, (CE_NOTE,
10603 			    "nfs4_map: os_failed_reopen set on "
10604 			    "osp %p, cr %p, rp %s", (void *)osp,
10605 			    (void *)cr, rnode4info(rp)));
10606 			error = EIO;
10607 			goto done;
10608 		}
10609 		mutex_exit(&osp->os_sync_lock);
10610 		open_stream_rele(osp, rp);
10611 	}
10612 
10613 	vn_a.vp = vp;
10614 	vn_a.offset = off;
10615 	vn_a.type = (flags & MAP_TYPE);
10616 	vn_a.prot = (uchar_t)prot;
10617 	vn_a.maxprot = (uchar_t)maxprot;
10618 	vn_a.flags = (flags & ~MAP_TYPE);
10619 	vn_a.cred = cr;
10620 	vn_a.amp = NULL;
10621 	vn_a.szc = 0;
10622 	vn_a.lgrp_mem_policy_flags = 0;
10623 
10624 	error = as_map(as, *addrp, len, segvn_create, &vn_a);
10625 	as_rangeunlock(as);
10626 
10627 done:
10628 	nfs_rw_exit(&rp->r_lkserlock);
10629 	atomic_dec_uint(&rp->r_inmap);
10630 	return (error);
10631 }
10632 
10633 /*
10634  * We're most likely dealing with a kernel module that likes to READ
10635  * and mmap without OPENing the file (ie: lookup/read/mmap), so lets
10636  * officially OPEN the file to create the necessary client state
10637  * for bookkeeping of os_mmap_read/write counts.
10638  *
10639  * Since VOP_MAP only passes in a pointer to the vnode rather than
10640  * a double pointer, we can't handle the case where nfs4open_otw()
10641  * returns a different vnode than the one passed into VOP_MAP (since
10642  * VOP_DELMAP will not see the vnode nfs4open_otw used).  In this case,
10643  * we return NULL and let nfs4_map() fail.  Note: the only case where
10644  * this should happen is if the file got removed and replaced with the
10645  * same name on the server (in addition to the fact that we're trying
10646  * to VOP_MAP withouth VOP_OPENing the file in the first place).
10647  */
10648 static int
open_and_get_osp(vnode_t * map_vp,cred_t * cr,nfs4_open_stream_t ** ospp)10649 open_and_get_osp(vnode_t *map_vp, cred_t *cr, nfs4_open_stream_t **ospp)
10650 {
10651 	rnode4_t		*rp, *drp;
10652 	vnode_t			*dvp, *open_vp;
10653 	char			file_name[MAXNAMELEN];
10654 	int			just_created;
10655 	nfs4_open_stream_t	*osp;
10656 	nfs4_open_owner_t	*oop;
10657 	int			error;
10658 
10659 	*ospp = NULL;
10660 	open_vp = map_vp;
10661 
10662 	rp = VTOR4(open_vp);
10663 	if ((error = vtodv(open_vp, &dvp, cr, TRUE)) != 0)
10664 		return (error);
10665 	drp = VTOR4(dvp);
10666 
10667 	if (nfs_rw_enter_sig(&drp->r_rwlock, RW_READER, INTR4(dvp))) {
10668 		VN_RELE(dvp);
10669 		return (EINTR);
10670 	}
10671 
10672 	if ((error = vtoname(open_vp, file_name, MAXNAMELEN)) != 0) {
10673 		nfs_rw_exit(&drp->r_rwlock);
10674 		VN_RELE(dvp);
10675 		return (error);
10676 	}
10677 
10678 	mutex_enter(&rp->r_statev4_lock);
10679 	if (rp->created_v4) {
10680 		rp->created_v4 = 0;
10681 		mutex_exit(&rp->r_statev4_lock);
10682 
10683 		dnlc_update(dvp, file_name, open_vp);
10684 		/* This is needed so we don't bump the open ref count */
10685 		just_created = 1;
10686 	} else {
10687 		mutex_exit(&rp->r_statev4_lock);
10688 		just_created = 0;
10689 	}
10690 
10691 	VN_HOLD(map_vp);
10692 
10693 	error = nfs4open_otw(dvp, file_name, NULL, &open_vp, cr, 0, FREAD, 0,
10694 	    just_created);
10695 	if (error) {
10696 		nfs_rw_exit(&drp->r_rwlock);
10697 		VN_RELE(dvp);
10698 		VN_RELE(map_vp);
10699 		return (error);
10700 	}
10701 
10702 	nfs_rw_exit(&drp->r_rwlock);
10703 	VN_RELE(dvp);
10704 
10705 	/*
10706 	 * If nfs4open_otw() returned a different vnode then "undo"
10707 	 * the open and return failure to the caller.
10708 	 */
10709 	if (!VN_CMP(open_vp, map_vp)) {
10710 		nfs4_error_t e;
10711 
10712 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10713 		    "open returned a different vnode"));
10714 		/*
10715 		 * If there's an error, ignore it,
10716 		 * and let VOP_INACTIVE handle it.
10717 		 */
10718 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10719 		    CLOSE_NORM, 0, 0, 0);
10720 		VN_RELE(map_vp);
10721 		return (EIO);
10722 	}
10723 
10724 	VN_RELE(map_vp);
10725 
10726 	oop = find_open_owner(cr, NFS4_PERM_CREATED, VTOMI4(open_vp));
10727 	if (!oop) {
10728 		nfs4_error_t e;
10729 
10730 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "open_and_get_osp: "
10731 		    "no open owner"));
10732 		/*
10733 		 * If there's an error, ignore it,
10734 		 * and let VOP_INACTIVE handle it.
10735 		 */
10736 		(void) nfs4close_one(open_vp, NULL, cr, FREAD, NULL, &e,
10737 		    CLOSE_NORM, 0, 0, 0);
10738 		return (EIO);
10739 	}
10740 	osp = find_open_stream(oop, rp);
10741 	open_owner_rele(oop);
10742 	*ospp = osp;
10743 	return (0);
10744 }
10745 
10746 /*
10747  * Please be aware that when this function is called, the address space write
10748  * a_lock is held.  Do not put over the wire calls in this function.
10749  */
10750 /* ARGSUSED */
10751 static int
nfs4_addmap(vnode_t * vp,offset_t off,struct as * as,caddr_t addr,size_t len,uchar_t prot,uchar_t maxprot,uint_t flags,cred_t * cr,caller_context_t * ct)10752 nfs4_addmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
10753     size_t len, uchar_t prot, uchar_t maxprot, uint_t flags, cred_t *cr,
10754     caller_context_t *ct)
10755 {
10756 	rnode4_t		*rp;
10757 	int			error = 0;
10758 	mntinfo4_t		*mi;
10759 
10760 	mi = VTOMI4(vp);
10761 	rp = VTOR4(vp);
10762 
10763 	if (nfs_zone() != mi->mi_zone)
10764 		return (EIO);
10765 	if (vp->v_flag & VNOMAP)
10766 		return (ENOSYS);
10767 
10768 	/*
10769 	 * Don't need to update the open stream first, since this
10770 	 * mmap can't add any additional share access that isn't
10771 	 * already contained in the open stream (for the case where we
10772 	 * open/mmap/only update rp->r_mapcnt/server reboots/reopen doesn't
10773 	 * take into account os_mmap_read[write] counts).
10774 	 */
10775 	atomic_add_long((ulong_t *)&rp->r_mapcnt, btopr(len));
10776 
10777 	if (vp->v_type == VREG) {
10778 		/*
10779 		 * We need to retrieve the open stream and update the counts.
10780 		 * If there is no open stream here, something is wrong.
10781 		 */
10782 		nfs4_open_stream_t	*osp = NULL;
10783 		nfs4_open_owner_t	*oop = NULL;
10784 
10785 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
10786 		if (oop != NULL) {
10787 			/* returns with 'os_sync_lock' held */
10788 			osp = find_open_stream(oop, rp);
10789 			open_owner_rele(oop);
10790 		}
10791 		if (osp == NULL) {
10792 			NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE,
10793 			    "nfs4_addmap: we should have an osp"
10794 			    "but we don't, so fail with EIO"));
10795 			error = EIO;
10796 			goto out;
10797 		}
10798 
10799 		NFS4_DEBUG(nfs4_mmap_debug, (CE_NOTE, "nfs4_addmap: osp %p,"
10800 		    " pages %ld, prot 0x%x", (void *)osp, btopr(len), prot));
10801 
10802 		/*
10803 		 * Update the map count in the open stream.
10804 		 * This is necessary in the case where we
10805 		 * open/mmap/close/, then the server reboots, and we
10806 		 * attempt to reopen.  If the mmap doesn't add share
10807 		 * access then we send an invalid reopen with
10808 		 * access = NONE.
10809 		 *
10810 		 * We need to specifically check each PROT_* so a mmap
10811 		 * call of (PROT_WRITE | PROT_EXEC) will ensure us both
10812 		 * read and write access.  A simple comparison of prot
10813 		 * to ~PROT_WRITE to determine read access is insufficient
10814 		 * since prot can be |= with PROT_USER, etc.
10815 		 */
10816 
10817 		/*
10818 		 * Unless we're MAP_SHARED, no sense in adding os_mmap_write
10819 		 */
10820 		if ((flags & MAP_SHARED) && (maxprot & PROT_WRITE))
10821 			osp->os_mmap_write += btopr(len);
10822 		if (maxprot & PROT_READ)
10823 			osp->os_mmap_read += btopr(len);
10824 		if (maxprot & PROT_EXEC)
10825 			osp->os_mmap_read += btopr(len);
10826 		/*
10827 		 * Ensure that os_mmap_read gets incremented, even if
10828 		 * maxprot were to look like PROT_NONE.
10829 		 */
10830 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
10831 		    !(maxprot & PROT_EXEC))
10832 			osp->os_mmap_read += btopr(len);
10833 		osp->os_mapcnt += btopr(len);
10834 		mutex_exit(&osp->os_sync_lock);
10835 		open_stream_rele(osp, rp);
10836 	}
10837 
10838 out:
10839 	/*
10840 	 * If we got an error, then undo our
10841 	 * incrementing of 'r_mapcnt'.
10842 	 */
10843 
10844 	if (error) {
10845 		atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(len));
10846 		ASSERT(rp->r_mapcnt >= 0);
10847 	}
10848 	return (error);
10849 }
10850 
10851 /* ARGSUSED */
10852 static int
nfs4_cmp(vnode_t * vp1,vnode_t * vp2,caller_context_t * ct)10853 nfs4_cmp(vnode_t *vp1, vnode_t *vp2, caller_context_t *ct)
10854 {
10855 
10856 	return (VTOR4(vp1) == VTOR4(vp2));
10857 }
10858 
10859 /*
10860  * Data structure for nfs4_lkserlock_callback() function.
10861  */
10862 struct nfs4_lkserlock_callback_data {
10863 	vnode_t *vp;
10864 	int rc;
10865 };
10866 
10867 /*
10868  * Callback function for reclock().
10869  */
10870 static callb_cpr_t *
nfs4_lkserlock_callback(flk_cb_when_t when,void * infop)10871 nfs4_lkserlock_callback(flk_cb_when_t when, void *infop)
10872 {
10873 	struct nfs4_lkserlock_callback_data *dp =
10874 	    (struct nfs4_lkserlock_callback_data *)infop;
10875 	rnode4_t *rp = VTOR4(dp->vp);
10876 
10877 	if (when == FLK_BEFORE_SLEEP)
10878 		nfs_rw_exit(&rp->r_lkserlock);
10879 	else
10880 		dp->rc = nfs_rw_enter_sig(&rp->r_lkserlock, RW_WRITER,
10881 		    INTR4(dp->vp));
10882 
10883 	return (NULL);
10884 }
10885 
10886 /* ARGSUSED */
10887 static int
nfs4_frlock(vnode_t * vp,int cmd,struct flock64 * bfp,int flag,offset_t offset,struct flk_callback * flk_cbp,cred_t * cr,caller_context_t * ct)10888 nfs4_frlock(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
10889     offset_t offset, struct flk_callback *flk_cbp, cred_t *cr,
10890     caller_context_t *ct)
10891 {
10892 	int rc = 0;
10893 	rnode4_t *rp;
10894 	int intr = INTR4(vp);
10895 	nfs4_error_t e;
10896 	int frcmd;
10897 	struct lm_sysid	*ls = NULL;
10898 
10899 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
10900 		return (EIO);
10901 
10902 	/* check for valid cmd parameter and set frcmd appropriately */
10903 	switch (cmd) {
10904 	case F_GETLK:
10905 		frcmd = 0;
10906 		break;
10907 	case F_SETLK:
10908 		frcmd = SETFLCK;
10909 		break;
10910 	case F_SETLKW:
10911 		frcmd = SETFLCK | SLPFLCK;
10912 		break;
10913 	default:
10914 		return (EINVAL);
10915 	}
10916 
10917 	/*
10918 	 * If lock is relative to EOF, we need the newest length of the file.
10919 	 * Therefore invalidate the ATTR_CACHE.
10920 	 */
10921 	if (bfp->l_whence == 2)		/* SEEK_END */
10922 		PURGE_ATTRCACHE4(vp);
10923 
10924 	/*
10925 	 * If the filesystem is mounted using local locking, pass the
10926 	 * request off to the local locking code.
10927 	 */
10928 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK || vp->v_type != VREG) {
10929 		if (cmd == F_SETLK || cmd == F_SETLKW) {
10930 			/*
10931 			 * For complete safety, we should be holding
10932 			 * r_lkserlock.  However, we can't call
10933 			 * nfs4_safelock and then fs_frlock while
10934 			 * holding r_lkserlock, so just invoke
10935 			 * nfs4_safelock and expect that this will
10936 			 * catch enough of the cases.
10937 			 */
10938 			if (!nfs4_safelock(vp, bfp, cr))
10939 				return (EAGAIN);
10940 		}
10941 		return (fs_frlock(vp, cmd, bfp, flag, offset, flk_cbp, cr, ct));
10942 	}
10943 
10944 	/*
10945 	 * Convert the offset.  We need to do this to make sure our view of the
10946 	 * locking range is always the same through the rest of this function.
10947 	 * This is especially needed for bfp->l_whence == SEEK_END, because the
10948 	 * length of the file could change anytime and thus the locking range
10949 	 * would be a moving target for us.
10950 	 *
10951 	 * For the bfp->l_whence == SEEK_CUR case this is just a convenient
10952 	 * conversion to make the life easier for nfs4frlock().
10953 	 */
10954 	rc = convoff(vp, bfp, 0, offset);
10955 	if (rc != 0)
10956 		return (rc);
10957 
10958 	if (bfp->l_type == F_UNLCK) {
10959 		u_offset_t start, end;
10960 
10961 		/*
10962 		 * Shortcut for trivial case.
10963 		 */
10964 		if (cmd == F_GETLK)
10965 			return (rc);
10966 
10967 		/*
10968 		 * For every lock or unlock request we need to do two steps:
10969 		 * (un)register the local lock, and (un)register the lock at
10970 		 * the NFSv4 server.  It is essential to make sure the lock
10971 		 * status registered at the server and registered locally is
10972 		 * same and never goes out of sync.  This means that if one
10973 		 * step fails, the other one needs to be either skipped, or
10974 		 * reverted.
10975 		 *
10976 		 * For lock requests the situation is easy since a lock
10977 		 * registration can be reverted without any risk of data
10978 		 * corruption.
10979 		 *
10980 		 * The unlock requests cannot be reverted because once a lock
10981 		 * is unregistered the race window is open and some other
10982 		 * process could grab a conflicting lock.  This means that once
10983 		 * the first step (the first lock unregistration) succeeded,
10984 		 * the second step cannot fail.  The second step for the unlock
10985 		 * request is the local lock unregistration by the reclock()
10986 		 * call.
10987 		 *
10988 		 * The only way how the reclock() call for an unlock request
10989 		 * could fail is the invalid unlock range so we check it here,
10990 		 * before the lock is unregistered at NFSv4 server.  This
10991 		 * duplicates the check done in the reclock() function.
10992 		 */
10993 		rc = flk_convert_lock_data(vp, bfp, &start, &end, offset);
10994 		if (rc != 0)
10995 			return (rc);
10996 		rc = flk_check_lock_data(start, end, MAXEND);
10997 		if (rc != 0)
10998 			return (rc);
10999 
11000 		intr = 0;
11001 	}
11002 
11003 	/*
11004 	 * For F_SETLK and F_SETLKW we need to set sysid.
11005 	 */
11006 	if (cmd == F_SETLK || cmd == F_SETLKW) {
11007 		rc = nfs4frlock_get_sysid(&ls, vp, bfp);
11008 		if (rc != 0)
11009 			return (rc);
11010 
11011 		/*
11012 		 * Client locks are registerred locally by oring the sysid with
11013 		 * LM_SYSID_CLIENT.  The server registers locks locally using
11014 		 * just the sysid.  We need to distinguish between the two to
11015 		 * avoid collision in a case one machine is used as both client
11016 		 * and server.
11017 		 */
11018 		bfp->l_sysid |= LM_SYSID_CLIENT;
11019 	}
11020 
11021 	bfp->l_pid = curproc->p_pid;
11022 
11023 	rp = VTOR4(vp);
11024 
11025 	/*
11026 	 * Check whether the given lock request can proceed, given the
11027 	 * current file mappings.
11028 	 */
11029 	if (nfs_rw_enter_sig(&rp->r_lkserlock, RW_WRITER, intr)) {
11030 		if (ls != NULL)
11031 			lm_rel_sysid(ls);
11032 		return (EINTR);
11033 	}
11034 	if (cmd == F_SETLK || cmd == F_SETLKW) {
11035 		if (!nfs4_safelock(vp, bfp, cr)) {
11036 			rc = EAGAIN;
11037 			goto done;
11038 		}
11039 	}
11040 
11041 	/*
11042 	 * For query we will try to find a conflicting local lock first by
11043 	 * calling reclock().
11044 	 *
11045 	 * In a case this is a lock request we need to register it locally
11046 	 * first before we consult the NFSv4 server.
11047 	 */
11048 	if (cmd == F_GETLK || bfp->l_type != F_UNLCK) {
11049 		/*
11050 		 * If we might sleep in reclock() we need to register a
11051 		 * callback to release the r_lkserlock during the sleep.
11052 		 */
11053 		if ((frcmd & SLPFLCK) == 0) {
11054 			rc = reclock(vp, bfp, frcmd, flag, 0, flk_cbp);
11055 		} else {
11056 			flk_callback_t callback;
11057 			struct nfs4_lkserlock_callback_data callback_data =
11058 			    {vp, 0};
11059 
11060 			flk_add_callback(&callback, nfs4_lkserlock_callback,
11061 			    &callback_data, flk_cbp);
11062 			rc = reclock(vp, bfp, frcmd, flag, 0, &callback);
11063 			flk_del_callback(&callback);
11064 
11065 			if (callback_data.rc != 0) {
11066 				/*
11067 				 * The nfs_rw_enter_sig() call in
11068 				 * nfs4_lkserlock_callback() failed.
11069 				 */
11070 
11071 				if (rc == 0) {
11072 					/*
11073 					 * The reclock() call above succeeded
11074 					 * so we need to revert it.
11075 					 */
11076 					bfp->l_type = F_UNLCK;
11077 					rc = reclock(vp, bfp, frcmd, flag, 0,
11078 					    flk_cbp);
11079 					/* The unlock cannot fail */
11080 					ASSERT(rc == 0);
11081 
11082 					/*
11083 					 * We are here because we failed to
11084 					 * acquire r_lkserlock in
11085 					 * nfs4_lkserlock_callback() due to a
11086 					 * signal.  Return the appropriate
11087 					 * error.
11088 					 */
11089 					rc = EINTR;
11090 				}
11091 
11092 				ASSERT(ls != NULL);
11093 				lm_rel_sysid(ls);
11094 
11095 				return (rc);
11096 			}
11097 
11098 			/*
11099 			 * We possibly released r_lkserlock in reclock() so
11100 			 * make sure it is still safe to lock the file.
11101 			 */
11102 			if (!nfs4_safelock(vp, bfp, cr)) {
11103 				rc = EAGAIN;
11104 				goto revert;
11105 			}
11106 
11107 		}
11108 
11109 		/*
11110 		 * If the reclock() call failed we are done and we will return
11111 		 * an error to the caller.  Similarly, if we found a
11112 		 * conflicting lock registered locally we are done too.  We do
11113 		 * not need to consult the server.
11114 		 */
11115 		if ((rc != 0) || (cmd == F_GETLK && bfp->l_type != F_UNLCK))
11116 			goto done;
11117 	}
11118 
11119 	/*
11120 	 * Flush the cache after waiting for async I/O to finish.  For new
11121 	 * locks, this is so that the process gets the latest bits from the
11122 	 * server.  For unlocks, this is so that other clients see the
11123 	 * latest bits once the file has been unlocked.  If currently dirty
11124 	 * pages can't be flushed, then don't allow a lock to be set.  But
11125 	 * allow unlocks to succeed, to avoid having orphan locks on the
11126 	 * server.
11127 	 */
11128 	if (cmd != F_GETLK) {
11129 		mutex_enter(&rp->r_statelock);
11130 		while (rp->r_count > 0) {
11131 			if (intr) {
11132 				klwp_t *lwp = ttolwp(curthread);
11133 
11134 				if (lwp != NULL)
11135 					lwp->lwp_nostop++;
11136 				if (cv_wait_sig(&rp->r_cv,
11137 				    &rp->r_statelock) == 0) {
11138 					if (lwp != NULL)
11139 						lwp->lwp_nostop--;
11140 					rc = EINTR;
11141 					break;
11142 				}
11143 				if (lwp != NULL)
11144 					lwp->lwp_nostop--;
11145 				} else
11146 					cv_wait(&rp->r_cv, &rp->r_statelock);
11147 		}
11148 		mutex_exit(&rp->r_statelock);
11149 		if (rc != 0) {
11150 			ASSERT(bfp->l_type != F_UNLCK);
11151 
11152 			goto revert;
11153 		}
11154 
11155 		rc = nfs4_putpage(vp, (offset_t)0, 0, B_INVAL, cr, ct);
11156 		if (rc != 0) {
11157 			if (rc == ENOSPC || rc == EDQUOT) {
11158 				mutex_enter(&rp->r_statelock);
11159 				if (!rp->r_error)
11160 					rp->r_error = rc;
11161 				mutex_exit(&rp->r_statelock);
11162 			}
11163 
11164 			/*
11165 			 * If this was a lock request, make sure it is
11166 			 * reverted.
11167 			 */
11168 			if (bfp->l_type != F_UNLCK) {
11169 				rc = ENOLCK;
11170 				goto revert;
11171 			}
11172 		}
11173 	}
11174 
11175 	/*
11176 	 * Call the lock manager to do the real work of contacting
11177 	 * the server and obtaining the lock.
11178 	 */
11179 	nfs4frlock(NFS4_LCK_CTYPE_NORM, vp, cmd, bfp, cr, &e, NULL, NULL);
11180 	rc = e.error;
11181 
11182 	if (rc == 0)
11183 		nfs4_lockcompletion(vp, cmd);
11184 
11185 revert:
11186 	/*
11187 	 * If this is either successful unlock request or a lock request that
11188 	 * failed we should unregister/revert the local lock now.
11189 	 */
11190 	if ((rc == 0 && cmd != F_GETLK && bfp->l_type == F_UNLCK) ||
11191 	    (rc != 0 && cmd != F_GETLK && bfp->l_type != F_UNLCK)) {
11192 		int r;
11193 
11194 		bfp->l_type = F_UNLCK;
11195 		r = reclock(vp, bfp, frcmd, flag, 0, flk_cbp);
11196 		/* The unlock cannot fail */
11197 		ASSERT(r == 0);
11198 	}
11199 
11200 done:
11201 	nfs_rw_exit(&rp->r_lkserlock);
11202 	if (ls != NULL)
11203 		lm_rel_sysid(ls);
11204 
11205 	return (rc);
11206 }
11207 
11208 /*
11209  * Free storage space associated with the specified vnode.  The portion
11210  * to be freed is specified by bfp->l_start and bfp->l_len (already
11211  * normalized to a "whence" of 0).
11212  *
11213  * This is an experimental facility whose continued existence is not
11214  * guaranteed.  Currently, we only support the special case
11215  * of l_len == 0, meaning free to end of file.
11216  */
11217 /* ARGSUSED */
11218 static int
nfs4_space(vnode_t * vp,int cmd,struct flock64 * bfp,int flag,offset_t offset,cred_t * cr,caller_context_t * ct)11219 nfs4_space(vnode_t *vp, int cmd, struct flock64 *bfp, int flag,
11220     offset_t offset, cred_t *cr, caller_context_t *ct)
11221 {
11222 	int error;
11223 
11224 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
11225 		return (EIO);
11226 	ASSERT(vp->v_type == VREG);
11227 	if (cmd != F_FREESP)
11228 		return (EINVAL);
11229 
11230 	error = convoff(vp, bfp, 0, offset);
11231 	if (!error) {
11232 		ASSERT(bfp->l_start >= 0);
11233 		if (bfp->l_len == 0) {
11234 			struct vattr va;
11235 
11236 			va.va_mask = AT_SIZE;
11237 			va.va_size = bfp->l_start;
11238 			error = nfs4setattr(vp, &va, 0, cr, NULL);
11239 
11240 			if (error == 0 && bfp->l_start == 0)
11241 				vnevent_truncate(vp, ct);
11242 		} else
11243 			error = EINVAL;
11244 	}
11245 
11246 	return (error);
11247 }
11248 
11249 /* ARGSUSED */
11250 int
nfs4_realvp(vnode_t * vp,vnode_t ** vpp,caller_context_t * ct)11251 nfs4_realvp(vnode_t *vp, vnode_t **vpp, caller_context_t *ct)
11252 {
11253 	rnode4_t *rp;
11254 	rp = VTOR4(vp);
11255 
11256 	if (vp->v_type == VREG && IS_SHADOW(vp, rp)) {
11257 		vp = RTOV4(rp);
11258 	}
11259 	*vpp = vp;
11260 	return (0);
11261 }
11262 
11263 /*
11264  * Setup and add an address space callback to do the work of the delmap call.
11265  * The callback will (and must be) deleted in the actual callback function.
11266  *
11267  * This is done in order to take care of the problem that we have with holding
11268  * the address space's a_lock for a long period of time (e.g. if the NFS server
11269  * is down).  Callbacks will be executed in the address space code while the
11270  * a_lock is not held.  Holding the address space's a_lock causes things such
11271  * as ps and fork to hang because they are trying to acquire this lock as well.
11272  */
11273 /* ARGSUSED */
11274 static int
nfs4_delmap(vnode_t * vp,offset_t off,struct as * as,caddr_t addr,size_t len,uint_t prot,uint_t maxprot,uint_t flags,cred_t * cr,caller_context_t * ct)11275 nfs4_delmap(vnode_t *vp, offset_t off, struct as *as, caddr_t addr,
11276     size_t len, uint_t prot, uint_t maxprot, uint_t flags, cred_t *cr,
11277     caller_context_t *ct)
11278 {
11279 	int			caller_found;
11280 	int			error;
11281 	rnode4_t		*rp;
11282 	nfs4_delmap_args_t	*dmapp;
11283 	nfs4_delmapcall_t	*delmap_call;
11284 
11285 	if (vp->v_flag & VNOMAP)
11286 		return (ENOSYS);
11287 
11288 	/*
11289 	 * A process may not change zones if it has NFS pages mmap'ed
11290 	 * in, so we can't legitimately get here from the wrong zone.
11291 	 */
11292 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11293 
11294 	rp = VTOR4(vp);
11295 
11296 	/*
11297 	 * The way that the address space of this process deletes its mapping
11298 	 * of this file is via the following call chains:
11299 	 * - as_free()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
11300 	 * - as_unmap()->SEGOP_UNMAP()/segvn_unmap()->VOP_DELMAP()/nfs4_delmap()
11301 	 *
11302 	 * With the use of address space callbacks we are allowed to drop the
11303 	 * address space lock, a_lock, while executing the NFS operations that
11304 	 * need to go over the wire.  Returning EAGAIN to the caller of this
11305 	 * function is what drives the execution of the callback that we add
11306 	 * below.  The callback will be executed by the address space code
11307 	 * after dropping the a_lock.  When the callback is finished, since
11308 	 * we dropped the a_lock, it must be re-acquired and segvn_unmap()
11309 	 * is called again on the same segment to finish the rest of the work
11310 	 * that needs to happen during unmapping.
11311 	 *
11312 	 * This action of calling back into the segment driver causes
11313 	 * nfs4_delmap() to get called again, but since the callback was
11314 	 * already executed at this point, it already did the work and there
11315 	 * is nothing left for us to do.
11316 	 *
11317 	 * To Summarize:
11318 	 * - The first time nfs4_delmap is called by the current thread is when
11319 	 * we add the caller associated with this delmap to the delmap caller
11320 	 * list, add the callback, and return EAGAIN.
11321 	 * - The second time in this call chain when nfs4_delmap is called we
11322 	 * will find this caller in the delmap caller list and realize there
11323 	 * is no more work to do thus removing this caller from the list and
11324 	 * returning the error that was set in the callback execution.
11325 	 */
11326 	caller_found = nfs4_find_and_delete_delmapcall(rp, &error);
11327 	if (caller_found) {
11328 		/*
11329 		 * 'error' is from the actual delmap operations.  To avoid
11330 		 * hangs, we need to handle the return of EAGAIN differently
11331 		 * since this is what drives the callback execution.
11332 		 * In this case, we don't want to return EAGAIN and do the
11333 		 * callback execution because there are none to execute.
11334 		 */
11335 		if (error == EAGAIN)
11336 			return (0);
11337 		else
11338 			return (error);
11339 	}
11340 
11341 	/* current caller was not in the list */
11342 	delmap_call = nfs4_init_delmapcall();
11343 
11344 	mutex_enter(&rp->r_statelock);
11345 	list_insert_tail(&rp->r_indelmap, delmap_call);
11346 	mutex_exit(&rp->r_statelock);
11347 
11348 	dmapp = kmem_alloc(sizeof (nfs4_delmap_args_t), KM_SLEEP);
11349 
11350 	dmapp->vp = vp;
11351 	dmapp->off = off;
11352 	dmapp->addr = addr;
11353 	dmapp->len = len;
11354 	dmapp->prot = prot;
11355 	dmapp->maxprot = maxprot;
11356 	dmapp->flags = flags;
11357 	dmapp->cr = cr;
11358 	dmapp->caller = delmap_call;
11359 
11360 	error = as_add_callback(as, nfs4_delmap_callback, dmapp,
11361 	    AS_UNMAP_EVENT, addr, len, KM_SLEEP);
11362 
11363 	return (error ? error : EAGAIN);
11364 }
11365 
11366 static nfs4_delmapcall_t *
nfs4_init_delmapcall()11367 nfs4_init_delmapcall()
11368 {
11369 	nfs4_delmapcall_t	*delmap_call;
11370 
11371 	delmap_call = kmem_alloc(sizeof (nfs4_delmapcall_t), KM_SLEEP);
11372 	delmap_call->call_id = curthread;
11373 	delmap_call->error = 0;
11374 
11375 	return (delmap_call);
11376 }
11377 
11378 static void
nfs4_free_delmapcall(nfs4_delmapcall_t * delmap_call)11379 nfs4_free_delmapcall(nfs4_delmapcall_t *delmap_call)
11380 {
11381 	kmem_free(delmap_call, sizeof (nfs4_delmapcall_t));
11382 }
11383 
11384 /*
11385  * Searches for the current delmap caller (based on curthread) in the list of
11386  * callers.  If it is found, we remove it and free the delmap caller.
11387  * Returns:
11388  *      0 if the caller wasn't found
11389  *      1 if the caller was found, removed and freed.  *errp will be set
11390  *	to what the result of the delmap was.
11391  */
11392 static int
nfs4_find_and_delete_delmapcall(rnode4_t * rp,int * errp)11393 nfs4_find_and_delete_delmapcall(rnode4_t *rp, int *errp)
11394 {
11395 	nfs4_delmapcall_t	*delmap_call;
11396 
11397 	/*
11398 	 * If the list doesn't exist yet, we create it and return
11399 	 * that the caller wasn't found.  No list = no callers.
11400 	 */
11401 	mutex_enter(&rp->r_statelock);
11402 	if (!(rp->r_flags & R4DELMAPLIST)) {
11403 		/* The list does not exist */
11404 		list_create(&rp->r_indelmap, sizeof (nfs4_delmapcall_t),
11405 		    offsetof(nfs4_delmapcall_t, call_node));
11406 		rp->r_flags |= R4DELMAPLIST;
11407 		mutex_exit(&rp->r_statelock);
11408 		return (0);
11409 	} else {
11410 		/* The list exists so search it */
11411 		for (delmap_call = list_head(&rp->r_indelmap);
11412 		    delmap_call != NULL;
11413 		    delmap_call = list_next(&rp->r_indelmap, delmap_call)) {
11414 			if (delmap_call->call_id == curthread) {
11415 				/* current caller is in the list */
11416 				*errp = delmap_call->error;
11417 				list_remove(&rp->r_indelmap, delmap_call);
11418 				mutex_exit(&rp->r_statelock);
11419 				nfs4_free_delmapcall(delmap_call);
11420 				return (1);
11421 			}
11422 		}
11423 	}
11424 	mutex_exit(&rp->r_statelock);
11425 	return (0);
11426 }
11427 
11428 /*
11429  * Remove some pages from an mmap'd vnode.  Just update the
11430  * count of pages.  If doing close-to-open, then flush and
11431  * commit all of the pages associated with this file.
11432  * Otherwise, start an asynchronous page flush to write out
11433  * any dirty pages.  This will also associate a credential
11434  * with the rnode which can be used to write the pages.
11435  */
11436 /* ARGSUSED */
11437 static void
nfs4_delmap_callback(struct as * as,void * arg,uint_t event)11438 nfs4_delmap_callback(struct as *as, void *arg, uint_t event)
11439 {
11440 	nfs4_error_t		e = { 0, NFS4_OK, RPC_SUCCESS };
11441 	rnode4_t		*rp;
11442 	mntinfo4_t		*mi;
11443 	nfs4_delmap_args_t	*dmapp = (nfs4_delmap_args_t *)arg;
11444 
11445 	rp = VTOR4(dmapp->vp);
11446 	mi = VTOMI4(dmapp->vp);
11447 
11448 	atomic_add_long((ulong_t *)&rp->r_mapcnt, -btopr(dmapp->len));
11449 	ASSERT(rp->r_mapcnt >= 0);
11450 
11451 	/*
11452 	 * Initiate a page flush and potential commit if there are
11453 	 * pages, the file system was not mounted readonly, the segment
11454 	 * was mapped shared, and the pages themselves were writeable.
11455 	 */
11456 	if (nfs4_has_pages(dmapp->vp) &&
11457 	    !(dmapp->vp->v_vfsp->vfs_flag & VFS_RDONLY) &&
11458 	    dmapp->flags == MAP_SHARED && (dmapp->maxprot & PROT_WRITE)) {
11459 		mutex_enter(&rp->r_statelock);
11460 		rp->r_flags |= R4DIRTY;
11461 		mutex_exit(&rp->r_statelock);
11462 		e.error = nfs4_putpage_commit(dmapp->vp, dmapp->off,
11463 		    dmapp->len, dmapp->cr);
11464 		if (!e.error) {
11465 			mutex_enter(&rp->r_statelock);
11466 			e.error = rp->r_error;
11467 			rp->r_error = 0;
11468 			mutex_exit(&rp->r_statelock);
11469 		}
11470 	} else
11471 		e.error = 0;
11472 
11473 	if ((rp->r_flags & R4DIRECTIO) || (mi->mi_flags & MI4_DIRECTIO))
11474 		(void) nfs4_putpage(dmapp->vp, dmapp->off, dmapp->len,
11475 		    B_INVAL, dmapp->cr, NULL);
11476 
11477 	if (e.error) {
11478 		e.stat = puterrno4(e.error);
11479 		nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
11480 		    OP_COMMIT, FALSE, NULL, 0, dmapp->vp);
11481 		dmapp->caller->error = e.error;
11482 	}
11483 
11484 	/* Check to see if we need to close the file */
11485 
11486 	if (dmapp->vp->v_type == VREG) {
11487 		nfs4close_one(dmapp->vp, NULL, dmapp->cr, 0, NULL, &e,
11488 		    CLOSE_DELMAP, dmapp->len, dmapp->maxprot, dmapp->flags);
11489 
11490 		if (e.error != 0 || e.stat != NFS4_OK) {
11491 			/*
11492 			 * Since it is possible that e.error == 0 and
11493 			 * e.stat != NFS4_OK (and vice versa),
11494 			 * we do the proper checking in order to get both
11495 			 * e.error and e.stat reporting the correct info.
11496 			 */
11497 			if (e.stat == NFS4_OK)
11498 				e.stat = puterrno4(e.error);
11499 			if (e.error == 0)
11500 				e.error = geterrno4(e.stat);
11501 
11502 			nfs4_queue_fact(RF_DELMAP_CB_ERR, mi, e.stat, 0,
11503 			    OP_CLOSE, FALSE, NULL, 0, dmapp->vp);
11504 			dmapp->caller->error = e.error;
11505 		}
11506 	}
11507 
11508 	(void) as_delete_callback(as, arg);
11509 	kmem_free(dmapp, sizeof (nfs4_delmap_args_t));
11510 }
11511 
11512 
11513 static uint_t
fattr4_maxfilesize_to_bits(uint64_t ll)11514 fattr4_maxfilesize_to_bits(uint64_t ll)
11515 {
11516 	uint_t l = 1;
11517 
11518 	if (ll == 0) {
11519 		return (0);
11520 	}
11521 
11522 	if (ll & 0xffffffff00000000) {
11523 		l += 32; ll >>= 32;
11524 	}
11525 	if (ll & 0xffff0000) {
11526 		l += 16; ll >>= 16;
11527 	}
11528 	if (ll & 0xff00) {
11529 		l += 8; ll >>= 8;
11530 	}
11531 	if (ll & 0xf0) {
11532 		l += 4; ll >>= 4;
11533 	}
11534 	if (ll & 0xc) {
11535 		l += 2; ll >>= 2;
11536 	}
11537 	if (ll & 0x2) {
11538 		l += 1;
11539 	}
11540 	return (l);
11541 }
11542 
11543 static int
nfs4_have_xattrs(vnode_t * vp,ulong_t * valp,cred_t * cr)11544 nfs4_have_xattrs(vnode_t *vp, ulong_t *valp, cred_t *cr)
11545 {
11546 	vnode_t *avp = NULL;
11547 	int error;
11548 
11549 	if ((error = nfs4lookup_xattr(vp, "", &avp,
11550 	    LOOKUP_XATTR, cr)) == 0)
11551 		error = do_xattr_exists_check(avp, valp, cr);
11552 	if (avp)
11553 		VN_RELE(avp);
11554 
11555 	return (error);
11556 }
11557 
11558 /* ARGSUSED */
11559 int
nfs4_pathconf(vnode_t * vp,int cmd,ulong_t * valp,cred_t * cr,caller_context_t * ct)11560 nfs4_pathconf(vnode_t *vp, int cmd, ulong_t *valp, cred_t *cr,
11561     caller_context_t *ct)
11562 {
11563 	int error;
11564 	hrtime_t t;
11565 	rnode4_t *rp;
11566 	nfs4_ga_res_t gar;
11567 	nfs4_ga_ext_res_t ger;
11568 
11569 	gar.n4g_ext_res = &ger;
11570 
11571 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
11572 		return (EIO);
11573 	if (cmd == _PC_PATH_MAX || cmd == _PC_SYMLINK_MAX) {
11574 		*valp = MAXPATHLEN;
11575 		return (0);
11576 	}
11577 	if (cmd == _PC_ACL_ENABLED) {
11578 		*valp = _ACL_ACE_ENABLED;
11579 		return (0);
11580 	}
11581 
11582 	rp = VTOR4(vp);
11583 	if (cmd == _PC_XATTR_EXISTS) {
11584 		/*
11585 		 * The existence of the xattr directory is not sufficient
11586 		 * for determining whether generic user attributes exists.
11587 		 * The attribute directory could only be a transient directory
11588 		 * used for Solaris sysattr support.  Do a small readdir
11589 		 * to verify if the only entries are sysattrs or not.
11590 		 *
11591 		 * pc4_xattr_valid can be only be trusted when r_xattr_dir
11592 		 * is NULL.  Once the xadir vp exists, we can create xattrs,
11593 		 * and we don't have any way to update the "base" object's
11594 		 * pc4_xattr_exists from the xattr or xadir.  Maybe FEM
11595 		 * could help out.
11596 		 */
11597 		if (ATTRCACHE4_VALID(vp) && rp->r_pathconf.pc4_xattr_valid &&
11598 		    rp->r_xattr_dir == NULL) {
11599 			return (nfs4_have_xattrs(vp, valp, cr));
11600 		}
11601 	} else {  /* OLD CODE */
11602 		if (ATTRCACHE4_VALID(vp)) {
11603 			mutex_enter(&rp->r_statelock);
11604 			if (rp->r_pathconf.pc4_cache_valid) {
11605 				error = 0;
11606 				switch (cmd) {
11607 				case _PC_FILESIZEBITS:
11608 					*valp =
11609 					    rp->r_pathconf.pc4_filesizebits;
11610 					break;
11611 				case _PC_LINK_MAX:
11612 					*valp =
11613 					    rp->r_pathconf.pc4_link_max;
11614 					break;
11615 				case _PC_NAME_MAX:
11616 					*valp =
11617 					    rp->r_pathconf.pc4_name_max;
11618 					break;
11619 				case _PC_CHOWN_RESTRICTED:
11620 					*valp =
11621 					    rp->r_pathconf.pc4_chown_restricted;
11622 					break;
11623 				case _PC_NO_TRUNC:
11624 					*valp =
11625 					    rp->r_pathconf.pc4_no_trunc;
11626 					break;
11627 				default:
11628 					error = EINVAL;
11629 					break;
11630 				}
11631 				mutex_exit(&rp->r_statelock);
11632 #ifdef DEBUG
11633 				nfs4_pathconf_cache_hits++;
11634 #endif
11635 				return (error);
11636 			}
11637 			mutex_exit(&rp->r_statelock);
11638 		}
11639 	}
11640 #ifdef DEBUG
11641 	nfs4_pathconf_cache_misses++;
11642 #endif
11643 
11644 	t = gethrtime();
11645 
11646 	error = nfs4_attr_otw(vp, TAG_PATHCONF, &gar, NFS4_PATHCONF_MASK, cr);
11647 
11648 	if (error) {
11649 		mutex_enter(&rp->r_statelock);
11650 		rp->r_pathconf.pc4_cache_valid = FALSE;
11651 		rp->r_pathconf.pc4_xattr_valid = FALSE;
11652 		mutex_exit(&rp->r_statelock);
11653 		return (error);
11654 	}
11655 
11656 	/* interpret the max filesize */
11657 	gar.n4g_ext_res->n4g_pc4.pc4_filesizebits =
11658 	    fattr4_maxfilesize_to_bits(gar.n4g_ext_res->n4g_maxfilesize);
11659 
11660 	/* Store the attributes we just received */
11661 	nfs4_attr_cache(vp, &gar, t, cr, TRUE, NULL);
11662 
11663 	switch (cmd) {
11664 	case _PC_FILESIZEBITS:
11665 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_filesizebits;
11666 		break;
11667 	case _PC_LINK_MAX:
11668 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_link_max;
11669 		break;
11670 	case _PC_NAME_MAX:
11671 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_name_max;
11672 		break;
11673 	case _PC_CHOWN_RESTRICTED:
11674 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_chown_restricted;
11675 		break;
11676 	case _PC_NO_TRUNC:
11677 		*valp = gar.n4g_ext_res->n4g_pc4.pc4_no_trunc;
11678 		break;
11679 	case _PC_XATTR_EXISTS:
11680 		if (gar.n4g_ext_res->n4g_pc4.pc4_xattr_exists) {
11681 			if (error = nfs4_have_xattrs(vp, valp, cr))
11682 				return (error);
11683 		}
11684 		break;
11685 	default:
11686 		return (EINVAL);
11687 	}
11688 
11689 	return (0);
11690 }
11691 
11692 /*
11693  * Called by async thread to do synchronous pageio. Do the i/o, wait
11694  * for it to complete, and cleanup the page list when done.
11695  */
11696 static int
nfs4_sync_pageio(vnode_t * vp,page_t * pp,u_offset_t io_off,size_t io_len,int flags,cred_t * cr)11697 nfs4_sync_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11698     int flags, cred_t *cr)
11699 {
11700 	int error;
11701 
11702 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11703 
11704 	error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11705 	if (flags & B_READ)
11706 		pvn_read_done(pp, (error ? B_ERROR : 0) | flags);
11707 	else
11708 		pvn_write_done(pp, (error ? B_ERROR : 0) | flags);
11709 	return (error);
11710 }
11711 
11712 /* ARGSUSED */
11713 static int
nfs4_pageio(vnode_t * vp,page_t * pp,u_offset_t io_off,size_t io_len,int flags,cred_t * cr,caller_context_t * ct)11714 nfs4_pageio(vnode_t *vp, page_t *pp, u_offset_t io_off, size_t io_len,
11715     int flags, cred_t *cr, caller_context_t *ct)
11716 {
11717 	int error;
11718 	rnode4_t *rp;
11719 
11720 	if (!(flags & B_ASYNC) && nfs_zone() != VTOMI4(vp)->mi_zone)
11721 		return (EIO);
11722 
11723 	if (pp == NULL)
11724 		return (EINVAL);
11725 
11726 	rp = VTOR4(vp);
11727 	mutex_enter(&rp->r_statelock);
11728 	rp->r_count++;
11729 	mutex_exit(&rp->r_statelock);
11730 
11731 	if (flags & B_ASYNC) {
11732 		error = nfs4_async_pageio(vp, pp, io_off, io_len, flags, cr,
11733 		    nfs4_sync_pageio);
11734 	} else
11735 		error = nfs4_rdwrlbn(vp, pp, io_off, io_len, flags, cr);
11736 	mutex_enter(&rp->r_statelock);
11737 	rp->r_count--;
11738 	cv_broadcast(&rp->r_cv);
11739 	mutex_exit(&rp->r_statelock);
11740 	return (error);
11741 }
11742 
11743 /* ARGSUSED */
11744 static void
nfs4_dispose(vnode_t * vp,page_t * pp,int fl,int dn,cred_t * cr,caller_context_t * ct)11745 nfs4_dispose(vnode_t *vp, page_t *pp, int fl, int dn, cred_t *cr,
11746     caller_context_t *ct)
11747 {
11748 	int error;
11749 	rnode4_t *rp;
11750 	page_t *plist;
11751 	page_t *pptr;
11752 	offset3 offset;
11753 	count3 len;
11754 	k_sigset_t smask;
11755 
11756 	/*
11757 	 * We should get called with fl equal to either B_FREE or
11758 	 * B_INVAL.  Any other value is illegal.
11759 	 *
11760 	 * The page that we are either supposed to free or destroy
11761 	 * should be exclusive locked and its io lock should not
11762 	 * be held.
11763 	 */
11764 	ASSERT(fl == B_FREE || fl == B_INVAL);
11765 	ASSERT((PAGE_EXCL(pp) && !page_iolock_assert(pp)) || panicstr);
11766 
11767 	rp = VTOR4(vp);
11768 
11769 	/*
11770 	 * If the page doesn't need to be committed or we shouldn't
11771 	 * even bother attempting to commit it, then just make sure
11772 	 * that the p_fsdata byte is clear and then either free or
11773 	 * destroy the page as appropriate.
11774 	 */
11775 	if (pp->p_fsdata == C_NOCOMMIT || (rp->r_flags & R4STALE)) {
11776 		pp->p_fsdata = C_NOCOMMIT;
11777 		if (fl == B_FREE)
11778 			page_free(pp, dn);
11779 		else
11780 			page_destroy(pp, dn);
11781 		return;
11782 	}
11783 
11784 	/*
11785 	 * If there is a page invalidation operation going on, then
11786 	 * if this is one of the pages being destroyed, then just
11787 	 * clear the p_fsdata byte and then either free or destroy
11788 	 * the page as appropriate.
11789 	 */
11790 	mutex_enter(&rp->r_statelock);
11791 	if ((rp->r_flags & R4TRUNCATE) && pp->p_offset >= rp->r_truncaddr) {
11792 		mutex_exit(&rp->r_statelock);
11793 		pp->p_fsdata = C_NOCOMMIT;
11794 		if (fl == B_FREE)
11795 			page_free(pp, dn);
11796 		else
11797 			page_destroy(pp, dn);
11798 		return;
11799 	}
11800 
11801 	/*
11802 	 * If we are freeing this page and someone else is already
11803 	 * waiting to do a commit, then just unlock the page and
11804 	 * return.  That other thread will take care of commiting
11805 	 * this page.  The page can be freed sometime after the
11806 	 * commit has finished.  Otherwise, if the page is marked
11807 	 * as delay commit, then we may be getting called from
11808 	 * pvn_write_done, one page at a time.   This could result
11809 	 * in one commit per page, so we end up doing lots of small
11810 	 * commits instead of fewer larger commits.  This is bad,
11811 	 * we want do as few commits as possible.
11812 	 */
11813 	if (fl == B_FREE) {
11814 		if (rp->r_flags & R4COMMITWAIT) {
11815 			page_unlock(pp);
11816 			mutex_exit(&rp->r_statelock);
11817 			return;
11818 		}
11819 		if (pp->p_fsdata == C_DELAYCOMMIT) {
11820 			pp->p_fsdata = C_COMMIT;
11821 			page_unlock(pp);
11822 			mutex_exit(&rp->r_statelock);
11823 			return;
11824 		}
11825 	}
11826 
11827 	/*
11828 	 * Check to see if there is a signal which would prevent an
11829 	 * attempt to commit the pages from being successful.  If so,
11830 	 * then don't bother with all of the work to gather pages and
11831 	 * generate the unsuccessful RPC.  Just return from here and
11832 	 * let the page be committed at some later time.
11833 	 */
11834 	sigintr(&smask, VTOMI4(vp)->mi_flags & MI4_INT);
11835 	if (ttolwp(curthread) != NULL && ISSIG(curthread, JUSTLOOKING)) {
11836 		sigunintr(&smask);
11837 		page_unlock(pp);
11838 		mutex_exit(&rp->r_statelock);
11839 		return;
11840 	}
11841 	sigunintr(&smask);
11842 
11843 	/*
11844 	 * We are starting to need to commit pages, so let's try
11845 	 * to commit as many as possible at once to reduce the
11846 	 * overhead.
11847 	 *
11848 	 * Set the `commit inprogress' state bit.  We must
11849 	 * first wait until any current one finishes.  Then
11850 	 * we initialize the c_pages list with this page.
11851 	 */
11852 	while (rp->r_flags & R4COMMIT) {
11853 		rp->r_flags |= R4COMMITWAIT;
11854 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
11855 		rp->r_flags &= ~R4COMMITWAIT;
11856 	}
11857 	rp->r_flags |= R4COMMIT;
11858 	mutex_exit(&rp->r_statelock);
11859 	ASSERT(rp->r_commit.c_pages == NULL);
11860 	rp->r_commit.c_pages = pp;
11861 	rp->r_commit.c_commbase = (offset3)pp->p_offset;
11862 	rp->r_commit.c_commlen = PAGESIZE;
11863 
11864 	/*
11865 	 * Gather together all other pages which can be committed.
11866 	 * They will all be chained off r_commit.c_pages.
11867 	 */
11868 	nfs4_get_commit(vp);
11869 
11870 	/*
11871 	 * Clear the `commit inprogress' status and disconnect
11872 	 * the list of pages to be committed from the rnode.
11873 	 * At this same time, we also save the starting offset
11874 	 * and length of data to be committed on the server.
11875 	 */
11876 	plist = rp->r_commit.c_pages;
11877 	rp->r_commit.c_pages = NULL;
11878 	offset = rp->r_commit.c_commbase;
11879 	len = rp->r_commit.c_commlen;
11880 	mutex_enter(&rp->r_statelock);
11881 	rp->r_flags &= ~R4COMMIT;
11882 	cv_broadcast(&rp->r_commit.c_cv);
11883 	mutex_exit(&rp->r_statelock);
11884 
11885 	if (curproc == proc_pageout || curproc == proc_fsflush ||
11886 	    nfs_zone() != VTOMI4(vp)->mi_zone) {
11887 		nfs4_async_commit(vp, plist, offset, len,
11888 		    cr, do_nfs4_async_commit);
11889 		return;
11890 	}
11891 
11892 	/*
11893 	 * Actually generate the COMMIT op over the wire operation.
11894 	 */
11895 	error = nfs4_commit(vp, (offset4)offset, (count4)len, cr);
11896 
11897 	/*
11898 	 * If we got an error during the commit, just unlock all
11899 	 * of the pages.  The pages will get retransmitted to the
11900 	 * server during a putpage operation.
11901 	 */
11902 	if (error) {
11903 		while (plist != NULL) {
11904 			pptr = plist;
11905 			page_sub(&plist, pptr);
11906 			page_unlock(pptr);
11907 		}
11908 		return;
11909 	}
11910 
11911 	/*
11912 	 * We've tried as hard as we can to commit the data to stable
11913 	 * storage on the server.  We just unlock the rest of the pages
11914 	 * and clear the commit required state.  They will be put
11915 	 * onto the tail of the cachelist if they are nolonger
11916 	 * mapped.
11917 	 */
11918 	while (plist != pp) {
11919 		pptr = plist;
11920 		page_sub(&plist, pptr);
11921 		pptr->p_fsdata = C_NOCOMMIT;
11922 		page_unlock(pptr);
11923 	}
11924 
11925 	/*
11926 	 * It is possible that nfs4_commit didn't return error but
11927 	 * some other thread has modified the page we are going
11928 	 * to free/destroy.
11929 	 *    In this case we need to rewrite the page. Do an explicit check
11930 	 * before attempting to free/destroy the page. If modified, needs to
11931 	 * be rewritten so unlock the page and return.
11932 	 */
11933 	if (hat_ismod(pp)) {
11934 		pp->p_fsdata = C_NOCOMMIT;
11935 		page_unlock(pp);
11936 		return;
11937 	}
11938 
11939 	/*
11940 	 * Now, as appropriate, either free or destroy the page
11941 	 * that we were called with.
11942 	 */
11943 	pp->p_fsdata = C_NOCOMMIT;
11944 	if (fl == B_FREE)
11945 		page_free(pp, dn);
11946 	else
11947 		page_destroy(pp, dn);
11948 }
11949 
11950 /*
11951  * Commit requires that the current fh be the file written to.
11952  * The compound op structure is:
11953  *      PUTFH(file), COMMIT
11954  */
11955 static int
nfs4_commit(vnode_t * vp,offset4 offset,count4 count,cred_t * cr)11956 nfs4_commit(vnode_t *vp, offset4 offset, count4 count, cred_t *cr)
11957 {
11958 	COMPOUND4args_clnt args;
11959 	COMPOUND4res_clnt res;
11960 	COMMIT4res *cm_res;
11961 	nfs_argop4 argop[2];
11962 	nfs_resop4 *resop;
11963 	int doqueue;
11964 	mntinfo4_t *mi;
11965 	rnode4_t *rp;
11966 	cred_t *cred_otw = NULL;
11967 	bool_t needrecov = FALSE;
11968 	nfs4_recov_state_t recov_state;
11969 	nfs4_open_stream_t *osp = NULL;
11970 	bool_t first_time = TRUE;	/* first time getting OTW cred */
11971 	bool_t last_time = FALSE;	/* last time getting OTW cred */
11972 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
11973 
11974 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
11975 
11976 	rp = VTOR4(vp);
11977 
11978 	mi = VTOMI4(vp);
11979 	recov_state.rs_flags = 0;
11980 	recov_state.rs_num_retry_despite_err = 0;
11981 get_commit_cred:
11982 	/*
11983 	 * Releases the osp, if a valid open stream is provided.
11984 	 * Puts a hold on the cred_otw and the new osp (if found).
11985 	 */
11986 	cred_otw = nfs4_get_otw_cred_by_osp(rp, cr, &osp,
11987 	    &first_time, &last_time);
11988 	args.ctag = TAG_COMMIT;
11989 recov_retry:
11990 	/*
11991 	 * Commit ops: putfh file; commit
11992 	 */
11993 	args.array_len = 2;
11994 	args.array = argop;
11995 
11996 	e.error = nfs4_start_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
11997 	    &recov_state, NULL);
11998 	if (e.error) {
11999 		crfree(cred_otw);
12000 		if (osp != NULL)
12001 			open_stream_rele(osp, rp);
12002 		return (e.error);
12003 	}
12004 
12005 	/* putfh directory */
12006 	argop[0].argop = OP_CPUTFH;
12007 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
12008 
12009 	/* commit */
12010 	argop[1].argop = OP_COMMIT;
12011 	argop[1].nfs_argop4_u.opcommit.offset = offset;
12012 	argop[1].nfs_argop4_u.opcommit.count = count;
12013 
12014 	doqueue = 1;
12015 	rfs4call(mi, &args, &res, cred_otw, &doqueue, 0, &e);
12016 
12017 	needrecov = nfs4_needs_recovery(&e, FALSE, mi->mi_vfsp);
12018 	if (!needrecov && e.error) {
12019 		nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state,
12020 		    needrecov);
12021 		crfree(cred_otw);
12022 		if (e.error == EACCES && last_time == FALSE)
12023 			goto get_commit_cred;
12024 		if (osp != NULL)
12025 			open_stream_rele(osp, rp);
12026 		return (e.error);
12027 	}
12028 
12029 	if (needrecov) {
12030 		if (nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
12031 		    NULL, OP_COMMIT, NULL, NULL, NULL) == FALSE) {
12032 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
12033 			    &recov_state, needrecov);
12034 			if (!e.error)
12035 				(void) xdr_free(xdr_COMPOUND4res_clnt,
12036 				    (caddr_t)&res);
12037 			goto recov_retry;
12038 		}
12039 		if (e.error) {
12040 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
12041 			    &recov_state, needrecov);
12042 			crfree(cred_otw);
12043 			if (osp != NULL)
12044 				open_stream_rele(osp, rp);
12045 			return (e.error);
12046 		}
12047 		/* fall through for res.status case */
12048 	}
12049 
12050 	if (res.status) {
12051 		e.error = geterrno4(res.status);
12052 		if (e.error == EACCES && last_time == FALSE) {
12053 			crfree(cred_otw);
12054 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
12055 			    &recov_state, needrecov);
12056 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12057 			goto get_commit_cred;
12058 		}
12059 		/*
12060 		 * Can't do a nfs4_purge_stale_fh here because this
12061 		 * can cause a deadlock.  nfs4_commit can
12062 		 * be called from nfs4_dispose which can be called
12063 		 * indirectly via pvn_vplist_dirty.  nfs4_purge_stale_fh
12064 		 * can call back to pvn_vplist_dirty.
12065 		 */
12066 		if (e.error == ESTALE) {
12067 			mutex_enter(&rp->r_statelock);
12068 			rp->r_flags |= R4STALE;
12069 			if (!rp->r_error)
12070 				rp->r_error = e.error;
12071 			mutex_exit(&rp->r_statelock);
12072 			PURGE_ATTRCACHE4(vp);
12073 		} else {
12074 			mutex_enter(&rp->r_statelock);
12075 			if (!rp->r_error)
12076 				rp->r_error = e.error;
12077 			mutex_exit(&rp->r_statelock);
12078 		}
12079 	} else {
12080 		ASSERT(rp->r_flags & R4HAVEVERF);
12081 		resop = &res.array[1];	/* commit res */
12082 		cm_res = &resop->nfs_resop4_u.opcommit;
12083 		mutex_enter(&rp->r_statelock);
12084 		if (cm_res->writeverf == rp->r_writeverf) {
12085 			mutex_exit(&rp->r_statelock);
12086 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12087 			nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT,
12088 			    &recov_state, needrecov);
12089 			crfree(cred_otw);
12090 			if (osp != NULL)
12091 				open_stream_rele(osp, rp);
12092 			return (0);
12093 		}
12094 		nfs4_set_mod(vp);
12095 		rp->r_writeverf = cm_res->writeverf;
12096 		mutex_exit(&rp->r_statelock);
12097 		e.error = NFS_VERF_MISMATCH;
12098 	}
12099 
12100 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
12101 	nfs4_end_fop(VTOMI4(vp), vp, NULL, OH_COMMIT, &recov_state, needrecov);
12102 	crfree(cred_otw);
12103 	if (osp != NULL)
12104 		open_stream_rele(osp, rp);
12105 
12106 	return (e.error);
12107 }
12108 
12109 static void
nfs4_set_mod(vnode_t * vp)12110 nfs4_set_mod(vnode_t *vp)
12111 {
12112 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12113 
12114 	/* make sure we're looking at the master vnode, not a shadow */
12115 	pvn_vplist_setdirty(RTOV4(VTOR4(vp)), nfs_setmod_check);
12116 }
12117 
12118 /*
12119  * This function is used to gather a page list of the pages which
12120  * can be committed on the server.
12121  *
12122  * The calling thread must have set R4COMMIT.  This bit is used to
12123  * serialize access to the commit structure in the rnode.  As long
12124  * as the thread has set R4COMMIT, then it can manipulate the commit
12125  * structure without requiring any other locks.
12126  *
12127  * When this function is called from nfs4_dispose() the page passed
12128  * into nfs4_dispose() will be SE_EXCL locked, and so this function
12129  * will skip it. This is not a problem since we initially add the
12130  * page to the r_commit page list.
12131  *
12132  */
12133 static void
nfs4_get_commit(vnode_t * vp)12134 nfs4_get_commit(vnode_t *vp)
12135 {
12136 	rnode4_t *rp;
12137 	page_t *pp;
12138 	kmutex_t *vphm;
12139 
12140 	rp = VTOR4(vp);
12141 
12142 	ASSERT(rp->r_flags & R4COMMIT);
12143 
12144 	/* make sure we're looking at the master vnode, not a shadow */
12145 
12146 	if (IS_SHADOW(vp, rp))
12147 		vp = RTOV4(rp);
12148 
12149 	vphm = page_vnode_mutex(vp);
12150 	mutex_enter(vphm);
12151 
12152 	/*
12153 	 * If there are no pages associated with this vnode, then
12154 	 * just return.
12155 	 */
12156 	if ((pp = vp->v_pages) == NULL) {
12157 		mutex_exit(vphm);
12158 		return;
12159 	}
12160 
12161 	/*
12162 	 * Step through all of the pages associated with this vnode
12163 	 * looking for pages which need to be committed.
12164 	 */
12165 	do {
12166 		/* Skip marker pages. */
12167 		if (pp->p_hash == PVN_VPLIST_HASH_TAG)
12168 			continue;
12169 
12170 		/*
12171 		 * First short-cut everything (without the page_lock)
12172 		 * and see if this page does not need to be committed
12173 		 * or is modified if so then we'll just skip it.
12174 		 */
12175 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp))
12176 			continue;
12177 
12178 		/*
12179 		 * Attempt to lock the page.  If we can't, then
12180 		 * someone else is messing with it or we have been
12181 		 * called from nfs4_dispose and this is the page that
12182 		 * nfs4_dispose was called with.. anyway just skip it.
12183 		 */
12184 		if (!page_trylock(pp, SE_EXCL))
12185 			continue;
12186 
12187 		/*
12188 		 * Lets check again now that we have the page lock.
12189 		 */
12190 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
12191 			page_unlock(pp);
12192 			continue;
12193 		}
12194 
12195 		/* this had better not be a free page */
12196 		ASSERT(PP_ISFREE(pp) == 0);
12197 
12198 		/*
12199 		 * The page needs to be committed and we locked it.
12200 		 * Update the base and length parameters and add it
12201 		 * to r_pages.
12202 		 */
12203 		if (rp->r_commit.c_pages == NULL) {
12204 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
12205 			rp->r_commit.c_commlen = PAGESIZE;
12206 		} else if (pp->p_offset < rp->r_commit.c_commbase) {
12207 			rp->r_commit.c_commlen = rp->r_commit.c_commbase -
12208 			    (offset3)pp->p_offset + rp->r_commit.c_commlen;
12209 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
12210 		} else if ((rp->r_commit.c_commbase + rp->r_commit.c_commlen)
12211 		    <= pp->p_offset) {
12212 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
12213 			    rp->r_commit.c_commbase + PAGESIZE;
12214 		}
12215 		page_add(&rp->r_commit.c_pages, pp);
12216 	} while ((pp = pp->p_vpnext) != vp->v_pages);
12217 
12218 	mutex_exit(vphm);
12219 }
12220 
12221 /*
12222  * This routine is used to gather together a page list of the pages
12223  * which are to be committed on the server.  This routine must not
12224  * be called if the calling thread holds any locked pages.
12225  *
12226  * The calling thread must have set R4COMMIT.  This bit is used to
12227  * serialize access to the commit structure in the rnode.  As long
12228  * as the thread has set R4COMMIT, then it can manipulate the commit
12229  * structure without requiring any other locks.
12230  */
12231 static void
nfs4_get_commit_range(vnode_t * vp,u_offset_t soff,size_t len)12232 nfs4_get_commit_range(vnode_t *vp, u_offset_t soff, size_t len)
12233 {
12234 
12235 	rnode4_t *rp;
12236 	page_t *pp;
12237 	u_offset_t end;
12238 	u_offset_t off;
12239 	ASSERT(len != 0);
12240 	rp = VTOR4(vp);
12241 	ASSERT(rp->r_flags & R4COMMIT);
12242 
12243 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12244 
12245 	/* make sure we're looking at the master vnode, not a shadow */
12246 
12247 	if (IS_SHADOW(vp, rp))
12248 		vp = RTOV4(rp);
12249 
12250 	/*
12251 	 * If there are no pages associated with this vnode, then
12252 	 * just return.
12253 	 */
12254 	if ((pp = vp->v_pages) == NULL)
12255 		return;
12256 	/*
12257 	 * Calculate the ending offset.
12258 	 */
12259 	end = soff + len;
12260 	for (off = soff; off < end; off += PAGESIZE) {
12261 		/*
12262 		 * Lookup each page by vp, offset.
12263 		 */
12264 		if ((pp = page_lookup_nowait(vp, off, SE_EXCL)) == NULL)
12265 			continue;
12266 		/*
12267 		 * If this page does not need to be committed or is
12268 		 * modified, then just skip it.
12269 		 */
12270 		if (pp->p_fsdata == C_NOCOMMIT || hat_ismod(pp)) {
12271 			page_unlock(pp);
12272 			continue;
12273 		}
12274 
12275 		ASSERT(PP_ISFREE(pp) == 0);
12276 		/*
12277 		 * The page needs to be committed and we locked it.
12278 		 * Update the base and length parameters and add it
12279 		 * to r_pages.
12280 		 */
12281 		if (rp->r_commit.c_pages == NULL) {
12282 			rp->r_commit.c_commbase = (offset3)pp->p_offset;
12283 			rp->r_commit.c_commlen = PAGESIZE;
12284 		} else {
12285 			rp->r_commit.c_commlen = (offset3)pp->p_offset -
12286 			    rp->r_commit.c_commbase + PAGESIZE;
12287 		}
12288 		page_add(&rp->r_commit.c_pages, pp);
12289 	}
12290 }
12291 
12292 /*
12293  * Called from nfs4_close(), nfs4_fsync() and nfs4_delmap().
12294  * Flushes and commits data to the server.
12295  */
12296 static int
nfs4_putpage_commit(vnode_t * vp,offset_t poff,size_t plen,cred_t * cr)12297 nfs4_putpage_commit(vnode_t *vp, offset_t poff, size_t plen, cred_t *cr)
12298 {
12299 	int error;
12300 	verifier4 write_verf;
12301 	rnode4_t *rp = VTOR4(vp);
12302 
12303 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12304 
12305 	/*
12306 	 * Flush the data portion of the file and then commit any
12307 	 * portions which need to be committed.  This may need to
12308 	 * be done twice if the server has changed state since
12309 	 * data was last written.  The data will need to be
12310 	 * rewritten to the server and then a new commit done.
12311 	 *
12312 	 * In fact, this may need to be done several times if the
12313 	 * server is having problems and crashing while we are
12314 	 * attempting to do this.
12315 	 */
12316 
12317 top:
12318 	/*
12319 	 * Do a flush based on the poff and plen arguments.  This
12320 	 * will synchronously write out any modified pages in the
12321 	 * range specified by (poff, plen). This starts all of the
12322 	 * i/o operations which will be waited for in the next
12323 	 * call to nfs4_putpage
12324 	 */
12325 
12326 	mutex_enter(&rp->r_statelock);
12327 	write_verf = rp->r_writeverf;
12328 	mutex_exit(&rp->r_statelock);
12329 
12330 	error = nfs4_putpage(vp, poff, plen, B_ASYNC, cr, NULL);
12331 	if (error == EAGAIN)
12332 		error = 0;
12333 
12334 	/*
12335 	 * Do a flush based on the poff and plen arguments.  This
12336 	 * will synchronously write out any modified pages in the
12337 	 * range specified by (poff, plen) and wait until all of
12338 	 * the asynchronous i/o's in that range are done as well.
12339 	 */
12340 	if (!error)
12341 		error = nfs4_putpage(vp, poff, plen, 0, cr, NULL);
12342 
12343 	if (error)
12344 		return (error);
12345 
12346 	mutex_enter(&rp->r_statelock);
12347 	if (rp->r_writeverf != write_verf) {
12348 		mutex_exit(&rp->r_statelock);
12349 		goto top;
12350 	}
12351 	mutex_exit(&rp->r_statelock);
12352 
12353 	/*
12354 	 * Now commit any pages which might need to be committed.
12355 	 * If the error, NFS_VERF_MISMATCH, is returned, then
12356 	 * start over with the flush operation.
12357 	 */
12358 	error = nfs4_commit_vp(vp, poff, plen, cr, NFS4_WRITE_WAIT);
12359 
12360 	if (error == NFS_VERF_MISMATCH)
12361 		goto top;
12362 
12363 	return (error);
12364 }
12365 
12366 /*
12367  * nfs4_commit_vp()  will wait for other pending commits and
12368  * will either commit the whole file or a range, plen dictates
12369  * if we commit whole file. a value of zero indicates the whole
12370  * file. Called from nfs4_putpage_commit() or nfs4_sync_putapage()
12371  */
12372 static int
nfs4_commit_vp(vnode_t * vp,u_offset_t poff,size_t plen,cred_t * cr,int wait_on_writes)12373 nfs4_commit_vp(vnode_t *vp, u_offset_t poff, size_t plen,
12374     cred_t *cr, int wait_on_writes)
12375 {
12376 	rnode4_t *rp;
12377 	page_t *plist;
12378 	offset3 offset;
12379 	count3 len;
12380 
12381 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12382 
12383 	rp = VTOR4(vp);
12384 
12385 	/*
12386 	 *  before we gather commitable pages make
12387 	 *  sure there are no outstanding async writes
12388 	 */
12389 	if (rp->r_count && wait_on_writes == NFS4_WRITE_WAIT) {
12390 		mutex_enter(&rp->r_statelock);
12391 		while (rp->r_count > 0) {
12392 			cv_wait(&rp->r_cv, &rp->r_statelock);
12393 		}
12394 		mutex_exit(&rp->r_statelock);
12395 	}
12396 
12397 	/*
12398 	 * Set the `commit inprogress' state bit.  We must
12399 	 * first wait until any current one finishes.
12400 	 */
12401 	mutex_enter(&rp->r_statelock);
12402 	while (rp->r_flags & R4COMMIT) {
12403 		rp->r_flags |= R4COMMITWAIT;
12404 		cv_wait(&rp->r_commit.c_cv, &rp->r_statelock);
12405 		rp->r_flags &= ~R4COMMITWAIT;
12406 	}
12407 	rp->r_flags |= R4COMMIT;
12408 	mutex_exit(&rp->r_statelock);
12409 
12410 	/*
12411 	 * Gather all of the pages which need to be
12412 	 * committed.
12413 	 */
12414 	if (plen == 0)
12415 		nfs4_get_commit(vp);
12416 	else
12417 		nfs4_get_commit_range(vp, poff, plen);
12418 
12419 	/*
12420 	 * Clear the `commit inprogress' bit and disconnect the
12421 	 * page list which was gathered by nfs4_get_commit.
12422 	 */
12423 	plist = rp->r_commit.c_pages;
12424 	rp->r_commit.c_pages = NULL;
12425 	offset = rp->r_commit.c_commbase;
12426 	len = rp->r_commit.c_commlen;
12427 	mutex_enter(&rp->r_statelock);
12428 	rp->r_flags &= ~R4COMMIT;
12429 	cv_broadcast(&rp->r_commit.c_cv);
12430 	mutex_exit(&rp->r_statelock);
12431 
12432 	/*
12433 	 * If any pages need to be committed, commit them and
12434 	 * then unlock them so that they can be freed some
12435 	 * time later.
12436 	 */
12437 	if (plist == NULL)
12438 		return (0);
12439 
12440 	/*
12441 	 * No error occurred during the flush portion
12442 	 * of this operation, so now attempt to commit
12443 	 * the data to stable storage on the server.
12444 	 *
12445 	 * This will unlock all of the pages on the list.
12446 	 */
12447 	return (nfs4_sync_commit(vp, plist, offset, len, cr));
12448 }
12449 
12450 static int
nfs4_sync_commit(vnode_t * vp,page_t * plist,offset3 offset,count3 count,cred_t * cr)12451 nfs4_sync_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
12452     cred_t *cr)
12453 {
12454 	int error;
12455 	page_t *pp;
12456 
12457 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12458 
12459 	error = nfs4_commit(vp, (offset4)offset, (count3)count, cr);
12460 
12461 	/*
12462 	 * If we got an error, then just unlock all of the pages
12463 	 * on the list.
12464 	 */
12465 	if (error) {
12466 		while (plist != NULL) {
12467 			pp = plist;
12468 			page_sub(&plist, pp);
12469 			page_unlock(pp);
12470 		}
12471 		return (error);
12472 	}
12473 	/*
12474 	 * We've tried as hard as we can to commit the data to stable
12475 	 * storage on the server.  We just unlock the pages and clear
12476 	 * the commit required state.  They will get freed later.
12477 	 */
12478 	while (plist != NULL) {
12479 		pp = plist;
12480 		page_sub(&plist, pp);
12481 		pp->p_fsdata = C_NOCOMMIT;
12482 		page_unlock(pp);
12483 	}
12484 
12485 	return (error);
12486 }
12487 
12488 static void
do_nfs4_async_commit(vnode_t * vp,page_t * plist,offset3 offset,count3 count,cred_t * cr)12489 do_nfs4_async_commit(vnode_t *vp, page_t *plist, offset3 offset, count3 count,
12490     cred_t *cr)
12491 {
12492 
12493 	(void) nfs4_sync_commit(vp, plist, offset, count, cr);
12494 }
12495 
12496 /*ARGSUSED*/
12497 static int
nfs4_setsecattr(vnode_t * vp,vsecattr_t * vsecattr,int flag,cred_t * cr,caller_context_t * ct)12498 nfs4_setsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr,
12499     caller_context_t *ct)
12500 {
12501 	int		error = 0;
12502 	mntinfo4_t	*mi;
12503 	vattr_t		va;
12504 	vsecattr_t	nfsace4_vsap;
12505 
12506 	mi = VTOMI4(vp);
12507 	if (nfs_zone() != mi->mi_zone)
12508 		return (EIO);
12509 	if (mi->mi_flags & MI4_ACL) {
12510 		/* if we have a delegation, return it */
12511 		if (VTOR4(vp)->r_deleg_type != OPEN_DELEGATE_NONE)
12512 			(void) nfs4delegreturn(VTOR4(vp),
12513 			    NFS4_DR_REOPEN|NFS4_DR_PUSH);
12514 
12515 		error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask,
12516 		    NFS4_ACL_SET);
12517 		if (error) /* EINVAL */
12518 			return (error);
12519 
12520 		if (vsecattr->vsa_mask & (VSA_ACL | VSA_DFACL)) {
12521 			/*
12522 			 * These are aclent_t type entries.
12523 			 */
12524 			error = vs_aent_to_ace4(vsecattr, &nfsace4_vsap,
12525 			    vp->v_type == VDIR, FALSE);
12526 			if (error)
12527 				return (error);
12528 		} else {
12529 			/*
12530 			 * These are ace_t type entries.
12531 			 */
12532 			error = vs_acet_to_ace4(vsecattr, &nfsace4_vsap,
12533 			    FALSE);
12534 			if (error)
12535 				return (error);
12536 		}
12537 		bzero(&va, sizeof (va));
12538 		error = nfs4setattr(vp, &va, flag, cr, &nfsace4_vsap);
12539 		vs_ace4_destroy(&nfsace4_vsap);
12540 		return (error);
12541 	}
12542 	return (ENOSYS);
12543 }
12544 
12545 /* ARGSUSED */
12546 int
nfs4_getsecattr(vnode_t * vp,vsecattr_t * vsecattr,int flag,cred_t * cr,caller_context_t * ct)12547 nfs4_getsecattr(vnode_t *vp, vsecattr_t *vsecattr, int flag, cred_t *cr,
12548     caller_context_t *ct)
12549 {
12550 	int		error;
12551 	mntinfo4_t	*mi;
12552 	nfs4_ga_res_t	gar;
12553 	rnode4_t	*rp = VTOR4(vp);
12554 
12555 	mi = VTOMI4(vp);
12556 	if (nfs_zone() != mi->mi_zone)
12557 		return (EIO);
12558 
12559 	bzero(&gar, sizeof (gar));
12560 	gar.n4g_vsa.vsa_mask = vsecattr->vsa_mask;
12561 
12562 	/*
12563 	 * vsecattr->vsa_mask holds the original acl request mask.
12564 	 * This is needed when determining what to return.
12565 	 * (See: nfs4_create_getsecattr_return())
12566 	 */
12567 	error = nfs4_is_acl_mask_valid(vsecattr->vsa_mask, NFS4_ACL_GET);
12568 	if (error) /* EINVAL */
12569 		return (error);
12570 
12571 	/*
12572 	 * If this is a referral stub, don't try to go OTW for an ACL
12573 	 */
12574 	if (RP_ISSTUB_REFERRAL(VTOR4(vp)))
12575 		return (fs_fab_acl(vp, vsecattr, flag, cr, ct));
12576 
12577 	if (mi->mi_flags & MI4_ACL) {
12578 		/*
12579 		 * Check if the data is cached and the cache is valid.  If it
12580 		 * is we don't go over the wire.
12581 		 */
12582 		if (rp->r_secattr != NULL && ATTRCACHE4_VALID(vp)) {
12583 			mutex_enter(&rp->r_statelock);
12584 			if (rp->r_secattr != NULL) {
12585 				error = nfs4_create_getsecattr_return(
12586 				    rp->r_secattr, vsecattr, rp->r_attr.va_uid,
12587 				    rp->r_attr.va_gid,
12588 				    vp->v_type == VDIR);
12589 				if (!error) { /* error == 0 - Success! */
12590 					mutex_exit(&rp->r_statelock);
12591 					return (error);
12592 				}
12593 			}
12594 			mutex_exit(&rp->r_statelock);
12595 		}
12596 
12597 		/*
12598 		 * The getattr otw call will always get both the acl, in
12599 		 * the form of a list of nfsace4's, and the number of acl
12600 		 * entries; independent of the value of gar.n4g_va.va_mask.
12601 		 */
12602 		error =  nfs4_getattr_otw(vp, &gar, cr, 1);
12603 		if (error) {
12604 			vs_ace4_destroy(&gar.n4g_vsa);
12605 			if (error == ENOTSUP || error == EOPNOTSUPP)
12606 				error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12607 			return (error);
12608 		}
12609 
12610 		if (!(gar.n4g_resbmap & FATTR4_ACL_MASK)) {
12611 			/*
12612 			 * No error was returned, but according to the response
12613 			 * bitmap, neither was an acl.
12614 			 */
12615 			vs_ace4_destroy(&gar.n4g_vsa);
12616 			error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12617 			return (error);
12618 		}
12619 
12620 		/*
12621 		 * Update the cache with the ACL.
12622 		 */
12623 		nfs4_acl_fill_cache(rp, &gar.n4g_vsa);
12624 
12625 		error = nfs4_create_getsecattr_return(&gar.n4g_vsa,
12626 		    vsecattr, gar.n4g_va.va_uid, gar.n4g_va.va_gid,
12627 		    vp->v_type == VDIR);
12628 		vs_ace4_destroy(&gar.n4g_vsa);
12629 		if ((error) && (vsecattr->vsa_mask &
12630 		    (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) &&
12631 		    (error != EACCES)) {
12632 			error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12633 		}
12634 		return (error);
12635 	}
12636 	error = fs_fab_acl(vp, vsecattr, flag, cr, ct);
12637 	return (error);
12638 }
12639 
12640 /*
12641  * The function returns:
12642  *	- 0 (zero) if the passed in "acl_mask" is a valid request.
12643  *	- EINVAL if the passed in "acl_mask" is an invalid request.
12644  *
12645  * In the case of getting an acl (op == NFS4_ACL_GET) the mask is invalid if:
12646  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12647  *
12648  * In the case of setting an acl (op == NFS4_ACL_SET) the mask is invalid if:
12649  * - We have a mixture of ACE and ACL requests (e.g. VSA_ACL | VSA_ACE)
12650  * - We have a count field set without the corresponding acl field set. (e.g. -
12651  * VSA_ACECNT is set, but VSA_ACE is not)
12652  */
12653 static int
nfs4_is_acl_mask_valid(uint_t acl_mask,nfs4_acl_op_t op)12654 nfs4_is_acl_mask_valid(uint_t acl_mask, nfs4_acl_op_t op)
12655 {
12656 	/* Shortcut the masks that are always valid. */
12657 	if (acl_mask == (VSA_ACE | VSA_ACECNT))
12658 		return (0);
12659 	if (acl_mask == (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT))
12660 		return (0);
12661 
12662 	if (acl_mask & (VSA_ACE | VSA_ACECNT)) {
12663 		/*
12664 		 * We can't have any VSA_ACL type stuff in the mask now.
12665 		 */
12666 		if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12667 		    VSA_DFACLCNT))
12668 			return (EINVAL);
12669 
12670 		if (op == NFS4_ACL_SET) {
12671 			if ((acl_mask & VSA_ACECNT) && !(acl_mask & VSA_ACE))
12672 				return (EINVAL);
12673 		}
12674 	}
12675 
12676 	if (acl_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL | VSA_DFACLCNT)) {
12677 		/*
12678 		 * We can't have any VSA_ACE type stuff in the mask now.
12679 		 */
12680 		if (acl_mask & (VSA_ACE | VSA_ACECNT))
12681 			return (EINVAL);
12682 
12683 		if (op == NFS4_ACL_SET) {
12684 			if ((acl_mask & VSA_ACLCNT) && !(acl_mask & VSA_ACL))
12685 				return (EINVAL);
12686 
12687 			if ((acl_mask & VSA_DFACLCNT) &&
12688 			    !(acl_mask & VSA_DFACL))
12689 				return (EINVAL);
12690 		}
12691 	}
12692 	return (0);
12693 }
12694 
12695 /*
12696  * The theory behind creating the correct getsecattr return is simply this:
12697  * "Don't return anything that the caller is not expecting to have to free."
12698  */
12699 static int
nfs4_create_getsecattr_return(vsecattr_t * filled_vsap,vsecattr_t * vsap,uid_t uid,gid_t gid,int isdir)12700 nfs4_create_getsecattr_return(vsecattr_t *filled_vsap, vsecattr_t *vsap,
12701     uid_t uid, gid_t gid, int isdir)
12702 {
12703 	int error = 0;
12704 	/* Save the mask since the translators modify it. */
12705 	uint_t	orig_mask = vsap->vsa_mask;
12706 
12707 	if (orig_mask & (VSA_ACE | VSA_ACECNT)) {
12708 		error = vs_ace4_to_acet(filled_vsap, vsap, uid, gid, FALSE);
12709 
12710 		if (error)
12711 			return (error);
12712 
12713 		/*
12714 		 * If the caller only asked for the ace count (VSA_ACECNT)
12715 		 * don't give them the full acl (VSA_ACE), free it.
12716 		 */
12717 		if (!orig_mask & VSA_ACE) {
12718 			if (vsap->vsa_aclentp != NULL) {
12719 				kmem_free(vsap->vsa_aclentp,
12720 				    vsap->vsa_aclcnt * sizeof (ace_t));
12721 				vsap->vsa_aclentp = NULL;
12722 			}
12723 		}
12724 		vsap->vsa_mask = orig_mask;
12725 
12726 	} else if (orig_mask & (VSA_ACL | VSA_ACLCNT | VSA_DFACL |
12727 	    VSA_DFACLCNT)) {
12728 		error = vs_ace4_to_aent(filled_vsap, vsap, uid, gid,
12729 		    isdir, FALSE);
12730 
12731 		if (error)
12732 			return (error);
12733 
12734 		/*
12735 		 * If the caller only asked for the acl count (VSA_ACLCNT)
12736 		 * and/or the default acl count (VSA_DFACLCNT) don't give them
12737 		 * the acl (VSA_ACL) or default acl (VSA_DFACL), free it.
12738 		 */
12739 		if (!orig_mask & VSA_ACL) {
12740 			if (vsap->vsa_aclentp != NULL) {
12741 				kmem_free(vsap->vsa_aclentp,
12742 				    vsap->vsa_aclcnt * sizeof (aclent_t));
12743 				vsap->vsa_aclentp = NULL;
12744 			}
12745 		}
12746 
12747 		if (!orig_mask & VSA_DFACL) {
12748 			if (vsap->vsa_dfaclentp != NULL) {
12749 				kmem_free(vsap->vsa_dfaclentp,
12750 				    vsap->vsa_dfaclcnt * sizeof (aclent_t));
12751 				vsap->vsa_dfaclentp = NULL;
12752 			}
12753 		}
12754 		vsap->vsa_mask = orig_mask;
12755 	}
12756 	return (0);
12757 }
12758 
12759 /* ARGSUSED */
12760 int
nfs4_shrlock(vnode_t * vp,int cmd,struct shrlock * shr,int flag,cred_t * cr,caller_context_t * ct)12761 nfs4_shrlock(vnode_t *vp, int cmd, struct shrlock *shr, int flag, cred_t *cr,
12762     caller_context_t *ct)
12763 {
12764 	int error;
12765 
12766 	if (nfs_zone() != VTOMI4(vp)->mi_zone)
12767 		return (EIO);
12768 	/*
12769 	 * check for valid cmd parameter
12770 	 */
12771 	if (cmd != F_SHARE && cmd != F_UNSHARE && cmd != F_HASREMOTELOCKS)
12772 		return (EINVAL);
12773 
12774 	/*
12775 	 * Check access permissions
12776 	 */
12777 	if ((cmd & F_SHARE) &&
12778 	    (((shr->s_access & F_RDACC) && (flag & FREAD) == 0) ||
12779 	    (shr->s_access == F_WRACC && (flag & FWRITE) == 0)))
12780 		return (EBADF);
12781 
12782 	/*
12783 	 * If the filesystem is mounted using local locking, pass the
12784 	 * request off to the local share code.
12785 	 */
12786 	if (VTOMI4(vp)->mi_flags & MI4_LLOCK)
12787 		return (fs_shrlock(vp, cmd, shr, flag, cr, ct));
12788 
12789 	switch (cmd) {
12790 	case F_SHARE:
12791 	case F_UNSHARE:
12792 		/*
12793 		 * This will be properly implemented later,
12794 		 * see RFE: 4823948 .
12795 		 */
12796 		error = EAGAIN;
12797 		break;
12798 
12799 	case F_HASREMOTELOCKS:
12800 		/*
12801 		 * NFS client can't store remote locks itself
12802 		 */
12803 		shr->s_access = 0;
12804 		error = 0;
12805 		break;
12806 
12807 	default:
12808 		error = EINVAL;
12809 		break;
12810 	}
12811 
12812 	return (error);
12813 }
12814 
12815 /*
12816  * Common code called by directory ops to update the attrcache
12817  */
12818 static int
nfs4_update_attrcache(nfsstat4 status,nfs4_ga_res_t * garp,hrtime_t t,vnode_t * vp,cred_t * cr)12819 nfs4_update_attrcache(nfsstat4 status, nfs4_ga_res_t *garp,
12820     hrtime_t t, vnode_t *vp, cred_t *cr)
12821 {
12822 	int error = 0;
12823 
12824 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12825 
12826 	if (status != NFS4_OK) {
12827 		/* getattr not done or failed */
12828 		PURGE_ATTRCACHE4(vp);
12829 		return (error);
12830 	}
12831 
12832 	if (garp) {
12833 		nfs4_attr_cache(vp, garp, t, cr, FALSE, NULL);
12834 	} else {
12835 		PURGE_ATTRCACHE4(vp);
12836 	}
12837 	return (error);
12838 }
12839 
12840 /*
12841  * Update directory caches for directory modification ops (link, rename, etc.)
12842  * When dinfo is NULL, manage dircaches in the old way.
12843  */
12844 static void
nfs4_update_dircaches(change_info4 * cinfo,vnode_t * dvp,vnode_t * vp,char * nm,dirattr_info_t * dinfo)12845 nfs4_update_dircaches(change_info4 *cinfo, vnode_t *dvp, vnode_t *vp, char *nm,
12846     dirattr_info_t *dinfo)
12847 {
12848 	rnode4_t	*drp = VTOR4(dvp);
12849 
12850 	ASSERT(nfs_zone() == VTOMI4(dvp)->mi_zone);
12851 
12852 	/* Purge rddir cache for dir since it changed */
12853 	if (drp->r_dir != NULL)
12854 		nfs4_purge_rddir_cache(dvp);
12855 
12856 	/*
12857 	 * If caller provided dinfo, then use it to manage dir caches.
12858 	 */
12859 	if (dinfo != NULL) {
12860 		if (vp != NULL) {
12861 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12862 			if (!VTOR4(vp)->created_v4) {
12863 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12864 				dnlc_update(dvp, nm, vp);
12865 			} else {
12866 				/*
12867 				 * XXX don't update if the created_v4 flag is
12868 				 * set
12869 				 */
12870 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12871 				NFS4_DEBUG(nfs4_client_state_debug,
12872 				    (CE_NOTE, "nfs4_update_dircaches: "
12873 				    "don't update dnlc: created_v4 flag"));
12874 			}
12875 		}
12876 
12877 		nfs4_attr_cache(dvp, dinfo->di_garp, dinfo->di_time_call,
12878 		    dinfo->di_cred, FALSE, cinfo);
12879 
12880 		return;
12881 	}
12882 
12883 	/*
12884 	 * Caller didn't provide dinfo, then check change_info4 to update DNLC.
12885 	 * Since caller modified dir but didn't receive post-dirmod-op dir
12886 	 * attrs, the dir's attrs must be purged.
12887 	 *
12888 	 * XXX this check and dnlc update/purge should really be atomic,
12889 	 * XXX but can't use rnode statelock because it'll deadlock in
12890 	 * XXX dnlc_purge_vp, however, the risk is minimal even if a race
12891 	 * XXX does occur.
12892 	 *
12893 	 * XXX We also may want to check that atomic is true in the
12894 	 * XXX change_info struct. If it is not, the change_info may
12895 	 * XXX reflect changes by more than one clients which means that
12896 	 * XXX our cache may not be valid.
12897 	 */
12898 	PURGE_ATTRCACHE4(dvp);
12899 	if (drp->r_change == cinfo->before) {
12900 		/* no changes took place in the directory prior to our link */
12901 		if (vp != NULL) {
12902 			mutex_enter(&VTOR4(vp)->r_statev4_lock);
12903 			if (!VTOR4(vp)->created_v4) {
12904 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12905 				dnlc_update(dvp, nm, vp);
12906 			} else {
12907 				/*
12908 				 * XXX dont' update if the created_v4 flag
12909 				 * is set
12910 				 */
12911 				mutex_exit(&VTOR4(vp)->r_statev4_lock);
12912 				NFS4_DEBUG(nfs4_client_state_debug, (CE_NOTE,
12913 				    "nfs4_update_dircaches: don't"
12914 				    " update dnlc: created_v4 flag"));
12915 			}
12916 		}
12917 	} else {
12918 		/* Another client modified directory - purge its dnlc cache */
12919 		dnlc_purge_vp(dvp);
12920 	}
12921 }
12922 
12923 /*
12924  * The OPEN_CONFIRM operation confirms the sequence number used in OPENing a
12925  * file.
12926  *
12927  * The 'reopening_file' boolean should be set to TRUE if we are reopening this
12928  * file (ie: client recovery) and otherwise set to FALSE.
12929  *
12930  * 'nfs4_start/end_op' should have been called by the proper (ie: not recovery
12931  * initiated) calling functions.
12932  *
12933  * 'resend' is set to TRUE if this is a OPEN_CONFIRM issued as a result
12934  * of resending a 'lost' open request.
12935  *
12936  * 'num_bseqid_retryp' makes sure we don't loop forever on a broken
12937  * server that hands out BAD_SEQID on open confirm.
12938  *
12939  * Errors are returned via the nfs4_error_t parameter.
12940  */
12941 void
nfs4open_confirm(vnode_t * vp,seqid4 * seqid,stateid4 * stateid,cred_t * cr,bool_t reopening_file,bool_t * retry_open,nfs4_open_owner_t * oop,bool_t resend,nfs4_error_t * ep,int * num_bseqid_retryp)12942 nfs4open_confirm(vnode_t *vp, seqid4 *seqid, stateid4 *stateid, cred_t *cr,
12943     bool_t reopening_file, bool_t *retry_open, nfs4_open_owner_t *oop,
12944     bool_t resend, nfs4_error_t *ep, int *num_bseqid_retryp)
12945 {
12946 	COMPOUND4args_clnt args;
12947 	COMPOUND4res_clnt res;
12948 	nfs_argop4 argop[2];
12949 	nfs_resop4 *resop;
12950 	int doqueue = 1;
12951 	mntinfo4_t *mi;
12952 	OPEN_CONFIRM4args *open_confirm_args;
12953 	int needrecov;
12954 
12955 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
12956 #if DEBUG
12957 	mutex_enter(&oop->oo_lock);
12958 	ASSERT(oop->oo_seqid_inuse);
12959 	mutex_exit(&oop->oo_lock);
12960 #endif
12961 
12962 recov_retry_confirm:
12963 	nfs4_error_zinit(ep);
12964 	*retry_open = FALSE;
12965 
12966 	if (resend)
12967 		args.ctag = TAG_OPEN_CONFIRM_LOST;
12968 	else
12969 		args.ctag = TAG_OPEN_CONFIRM;
12970 
12971 	args.array_len = 2;
12972 	args.array = argop;
12973 
12974 	/* putfh target fh */
12975 	argop[0].argop = OP_CPUTFH;
12976 	argop[0].nfs_argop4_u.opcputfh.sfh = VTOR4(vp)->r_fh;
12977 
12978 	argop[1].argop = OP_OPEN_CONFIRM;
12979 	open_confirm_args = &argop[1].nfs_argop4_u.opopen_confirm;
12980 
12981 	(*seqid) += 1;
12982 	open_confirm_args->seqid = *seqid;
12983 	open_confirm_args->open_stateid = *stateid;
12984 
12985 	mi = VTOMI4(vp);
12986 
12987 	rfs4call(mi, &args, &res, cr, &doqueue, 0, ep);
12988 
12989 	if (!ep->error && nfs4_need_to_bump_seqid(&res)) {
12990 		nfs4_set_open_seqid((*seqid), oop, args.ctag);
12991 	}
12992 
12993 	needrecov = nfs4_needs_recovery(ep, FALSE, mi->mi_vfsp);
12994 	if (!needrecov && ep->error)
12995 		return;
12996 
12997 	if (needrecov) {
12998 		bool_t abort = FALSE;
12999 
13000 		if (reopening_file == FALSE) {
13001 			nfs4_bseqid_entry_t *bsep = NULL;
13002 
13003 			if (!ep->error && res.status == NFS4ERR_BAD_SEQID)
13004 				bsep = nfs4_create_bseqid_entry(oop, NULL,
13005 				    vp, 0, args.ctag,
13006 				    open_confirm_args->seqid);
13007 
13008 			abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL,
13009 			    NULL, NULL, OP_OPEN_CONFIRM, bsep, NULL, NULL);
13010 			if (bsep) {
13011 				kmem_free(bsep, sizeof (*bsep));
13012 				if (num_bseqid_retryp &&
13013 				    --(*num_bseqid_retryp) == 0)
13014 					abort = TRUE;
13015 			}
13016 		}
13017 		if ((ep->error == ETIMEDOUT ||
13018 		    res.status == NFS4ERR_RESOURCE) &&
13019 		    abort == FALSE && resend == FALSE) {
13020 			if (!ep->error)
13021 				(void) xdr_free(xdr_COMPOUND4res_clnt,
13022 				    (caddr_t)&res);
13023 
13024 			delay(SEC_TO_TICK(confirm_retry_sec));
13025 			goto recov_retry_confirm;
13026 		}
13027 		/* State may have changed so retry the entire OPEN op */
13028 		if (abort == FALSE)
13029 			*retry_open = TRUE;
13030 		else
13031 			*retry_open = FALSE;
13032 		if (!ep->error)
13033 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
13034 		return;
13035 	}
13036 
13037 	if (res.status) {
13038 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
13039 		return;
13040 	}
13041 
13042 	resop = &res.array[1];  /* open confirm res */
13043 	bcopy(&resop->nfs_resop4_u.opopen_confirm.open_stateid,
13044 	    stateid, sizeof (*stateid));
13045 
13046 	(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)&res);
13047 }
13048 
13049 /*
13050  * Return the credentials associated with a client state object.  The
13051  * caller is responsible for freeing the credentials.
13052  */
13053 
13054 static cred_t *
state_to_cred(nfs4_open_stream_t * osp)13055 state_to_cred(nfs4_open_stream_t *osp)
13056 {
13057 	cred_t *cr;
13058 
13059 	/*
13060 	 * It's ok to not lock the open stream and open owner to get
13061 	 * the oo_cred since this is only written once (upon creation)
13062 	 * and will not change.
13063 	 */
13064 	cr = osp->os_open_owner->oo_cred;
13065 	crhold(cr);
13066 
13067 	return (cr);
13068 }
13069 
13070 /*
13071  * nfs4_find_sysid
13072  *
13073  * Find the sysid for the knetconfig associated with the given mi.
13074  */
13075 static struct lm_sysid *
nfs4_find_sysid(mntinfo4_t * mi)13076 nfs4_find_sysid(mntinfo4_t *mi)
13077 {
13078 	ASSERT(nfs_zone() == mi->mi_zone);
13079 
13080 	/*
13081 	 * Switch from RDMA knconf to original mount knconf
13082 	 */
13083 	return (lm_get_sysid(ORIG_KNCONF(mi), &mi->mi_curr_serv->sv_addr,
13084 	    mi->mi_curr_serv->sv_hostname, NULL));
13085 }
13086 
13087 #ifdef DEBUG
13088 /*
13089  * Return a string version of the call type for easy reading.
13090  */
13091 static char *
nfs4frlock_get_call_type(nfs4_lock_call_type_t ctype)13092 nfs4frlock_get_call_type(nfs4_lock_call_type_t ctype)
13093 {
13094 	switch (ctype) {
13095 	case NFS4_LCK_CTYPE_NORM:
13096 		return ("NORMAL");
13097 	case NFS4_LCK_CTYPE_RECLAIM:
13098 		return ("RECLAIM");
13099 	case NFS4_LCK_CTYPE_RESEND:
13100 		return ("RESEND");
13101 	case NFS4_LCK_CTYPE_REINSTATE:
13102 		return ("REINSTATE");
13103 	default:
13104 		cmn_err(CE_PANIC, "nfs4frlock_get_call_type: got illegal "
13105 		    "type %d", ctype);
13106 		return ("");
13107 	}
13108 }
13109 #endif
13110 
13111 /*
13112  * Map the frlock cmd and lock type to the NFSv4 over-the-wire lock type
13113  * Unlock requests don't have an over-the-wire locktype, so we just return
13114  * something non-threatening.
13115  */
13116 
13117 static nfs_lock_type4
flk_to_locktype(int cmd,int l_type)13118 flk_to_locktype(int cmd, int l_type)
13119 {
13120 	ASSERT(l_type == F_RDLCK || l_type == F_WRLCK || l_type == F_UNLCK);
13121 
13122 	switch (l_type) {
13123 	case F_UNLCK:
13124 		return (READ_LT);
13125 	case F_RDLCK:
13126 		if (cmd == F_SETLK)
13127 			return (READ_LT);
13128 		else
13129 			return (READW_LT);
13130 	case F_WRLCK:
13131 		if (cmd == F_SETLK)
13132 			return (WRITE_LT);
13133 		else
13134 			return (WRITEW_LT);
13135 	}
13136 	panic("flk_to_locktype");
13137 	/*NOTREACHED*/
13138 }
13139 
13140 /*
13141  * Set the flock64's lm_sysid for nfs4frlock.
13142  */
13143 static int
nfs4frlock_get_sysid(struct lm_sysid ** lspp,vnode_t * vp,flock64_t * flk)13144 nfs4frlock_get_sysid(struct lm_sysid **lspp, vnode_t *vp, flock64_t *flk)
13145 {
13146 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13147 
13148 	/* Find the lm_sysid */
13149 	*lspp = nfs4_find_sysid(VTOMI4(vp));
13150 
13151 	if (*lspp == NULL) {
13152 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13153 		    "nfs4frlock_get_sysid: no sysid, return ENOLCK"));
13154 		return (ENOLCK);
13155 	}
13156 
13157 	flk->l_sysid = lm_sysidt(*lspp);
13158 
13159 	return (0);
13160 }
13161 
13162 /*
13163  * Do the remaining preliminary setup for nfs4frlock.
13164  */
13165 static void
nfs4frlock_pre_setup(clock_t * tick_delayp,nfs4_recov_state_t * recov_statep,vnode_t * vp,cred_t * search_cr,cred_t ** cred_otw)13166 nfs4frlock_pre_setup(clock_t *tick_delayp, nfs4_recov_state_t *recov_statep,
13167     vnode_t *vp, cred_t *search_cr, cred_t **cred_otw)
13168 {
13169 	/*
13170 	 * set tick_delay to the base delay time.
13171 	 * (nfs4_base_wait_time is in msecs)
13172 	 */
13173 
13174 	*tick_delayp = drv_usectohz(nfs4_base_wait_time * 1000);
13175 
13176 	recov_statep->rs_flags = 0;
13177 	recov_statep->rs_num_retry_despite_err = 0;
13178 	*cred_otw = nfs4_get_otw_cred(search_cr, VTOMI4(vp), NULL);
13179 }
13180 
13181 /*
13182  * Initialize and allocate the data structures necessary for
13183  * the nfs4frlock call.
13184  * Allocates argsp's op array, frees up the saved_rqstpp if there is one.
13185  */
13186 static void
nfs4frlock_call_init(COMPOUND4args_clnt * argsp,COMPOUND4args_clnt ** argspp,nfs_argop4 ** argopp,nfs4_op_hint_t * op_hintp,flock64_t * flk,int cmd,bool_t * retry,bool_t * did_start_fop,COMPOUND4res_clnt ** respp,bool_t * skip_get_err,nfs4_lost_rqst_t * lost_rqstp)13187 nfs4frlock_call_init(COMPOUND4args_clnt *argsp, COMPOUND4args_clnt **argspp,
13188     nfs_argop4 **argopp, nfs4_op_hint_t *op_hintp, flock64_t *flk, int cmd,
13189     bool_t *retry, bool_t *did_start_fop, COMPOUND4res_clnt **respp,
13190     bool_t *skip_get_err, nfs4_lost_rqst_t *lost_rqstp)
13191 {
13192 	int		argoplist_size;
13193 	int		num_ops = 2;
13194 
13195 	*retry = FALSE;
13196 	*did_start_fop = FALSE;
13197 	*skip_get_err = FALSE;
13198 	lost_rqstp->lr_op = 0;
13199 	argoplist_size  = num_ops * sizeof (nfs_argop4);
13200 	/* fill array with zero */
13201 	*argopp = kmem_zalloc(argoplist_size, KM_SLEEP);
13202 
13203 	*argspp = argsp;
13204 	*respp = NULL;
13205 
13206 	argsp->array_len = num_ops;
13207 	argsp->array = *argopp;
13208 
13209 	/* initialize in case of error; will get real value down below */
13210 	argsp->ctag = TAG_NONE;
13211 
13212 	if ((cmd == F_SETLK || cmd == F_SETLKW) && flk->l_type == F_UNLCK)
13213 		*op_hintp = OH_LOCKU;
13214 	else
13215 		*op_hintp = OH_OTHER;
13216 }
13217 
13218 /*
13219  * Call the nfs4_start_fop() for nfs4frlock, if necessary.  Assign
13220  * the proper nfs4_server_t for this instance of nfs4frlock.
13221  * Returns 0 (success) or an errno value.
13222  */
13223 static int
nfs4frlock_start_call(nfs4_lock_call_type_t ctype,vnode_t * vp,nfs4_op_hint_t op_hint,nfs4_recov_state_t * recov_statep,bool_t * did_start_fop,bool_t * startrecovp)13224 nfs4frlock_start_call(nfs4_lock_call_type_t ctype, vnode_t *vp,
13225     nfs4_op_hint_t op_hint, nfs4_recov_state_t *recov_statep,
13226     bool_t *did_start_fop, bool_t *startrecovp)
13227 {
13228 	int error = 0;
13229 	rnode4_t *rp;
13230 
13231 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13232 
13233 	if (ctype == NFS4_LCK_CTYPE_NORM) {
13234 		error = nfs4_start_fop(VTOMI4(vp), vp, NULL, op_hint,
13235 		    recov_statep, startrecovp);
13236 		if (error)
13237 			return (error);
13238 		*did_start_fop = TRUE;
13239 	} else {
13240 		*did_start_fop = FALSE;
13241 		*startrecovp = FALSE;
13242 	}
13243 
13244 	if (!error) {
13245 		rp = VTOR4(vp);
13246 
13247 		/* If the file failed recovery, just quit. */
13248 		mutex_enter(&rp->r_statelock);
13249 		if (rp->r_flags & R4RECOVERR) {
13250 			error = EIO;
13251 		}
13252 		mutex_exit(&rp->r_statelock);
13253 	}
13254 
13255 	return (error);
13256 }
13257 
13258 /*
13259  * Setup the LOCK4/LOCKU4 arguments for resending a lost lock request.  A
13260  * resend nfs4frlock call is initiated by the recovery framework.
13261  * Acquires the lop and oop seqid synchronization.
13262  */
13263 static void
nfs4frlock_setup_resend_lock_args(nfs4_lost_rqst_t * resend_rqstp,COMPOUND4args_clnt * argsp,nfs_argop4 * argop,nfs4_lock_owner_t ** lopp,nfs4_open_owner_t ** oopp,nfs4_open_stream_t ** ospp,LOCK4args ** lock_argsp,LOCKU4args ** locku_argsp)13264 nfs4frlock_setup_resend_lock_args(nfs4_lost_rqst_t *resend_rqstp,
13265     COMPOUND4args_clnt *argsp, nfs_argop4 *argop, nfs4_lock_owner_t **lopp,
13266     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13267     LOCK4args **lock_argsp, LOCKU4args **locku_argsp)
13268 {
13269 	mntinfo4_t *mi = VTOMI4(resend_rqstp->lr_vp);
13270 	int error;
13271 
13272 	NFS4_DEBUG((nfs4_lost_rqst_debug || nfs4_client_lock_debug),
13273 	    (CE_NOTE,
13274 	    "nfs4frlock_setup_resend_lock_args: have lost lock to resend"));
13275 	ASSERT(resend_rqstp != NULL);
13276 	ASSERT(resend_rqstp->lr_op == OP_LOCK ||
13277 	    resend_rqstp->lr_op == OP_LOCKU);
13278 
13279 	*oopp = resend_rqstp->lr_oop;
13280 	if (resend_rqstp->lr_oop) {
13281 		open_owner_hold(resend_rqstp->lr_oop);
13282 		error = nfs4_start_open_seqid_sync(resend_rqstp->lr_oop, mi);
13283 		ASSERT(error == 0);	/* recov thread always succeeds */
13284 	}
13285 
13286 	/* Must resend this lost lock/locku request. */
13287 	ASSERT(resend_rqstp->lr_lop != NULL);
13288 	*lopp = resend_rqstp->lr_lop;
13289 	lock_owner_hold(resend_rqstp->lr_lop);
13290 	error = nfs4_start_lock_seqid_sync(resend_rqstp->lr_lop, mi);
13291 	ASSERT(error == 0);	/* recov thread always succeeds */
13292 
13293 	*ospp = resend_rqstp->lr_osp;
13294 	if (*ospp)
13295 		open_stream_hold(resend_rqstp->lr_osp);
13296 
13297 	if (resend_rqstp->lr_op == OP_LOCK) {
13298 		LOCK4args *lock_args;
13299 
13300 		argop->argop = OP_LOCK;
13301 		*lock_argsp = lock_args = &argop->nfs_argop4_u.oplock;
13302 		lock_args->locktype = resend_rqstp->lr_locktype;
13303 		lock_args->reclaim =
13304 		    (resend_rqstp->lr_ctype == NFS4_LCK_CTYPE_RECLAIM);
13305 		lock_args->offset = resend_rqstp->lr_flk->l_start;
13306 		lock_args->length = resend_rqstp->lr_flk->l_len;
13307 		if (lock_args->length == 0)
13308 			lock_args->length = ~lock_args->length;
13309 		nfs4_setup_lock_args(*lopp, *oopp, *ospp,
13310 		    mi2clientid(mi), &lock_args->locker);
13311 
13312 		switch (resend_rqstp->lr_ctype) {
13313 		case NFS4_LCK_CTYPE_RESEND:
13314 			argsp->ctag = TAG_LOCK_RESEND;
13315 			break;
13316 		case NFS4_LCK_CTYPE_REINSTATE:
13317 			argsp->ctag = TAG_LOCK_REINSTATE;
13318 			break;
13319 		case NFS4_LCK_CTYPE_RECLAIM:
13320 			argsp->ctag = TAG_LOCK_RECLAIM;
13321 			break;
13322 		default:
13323 			argsp->ctag = TAG_LOCK_UNKNOWN;
13324 			break;
13325 		}
13326 	} else {
13327 		LOCKU4args *locku_args;
13328 		nfs4_lock_owner_t *lop = resend_rqstp->lr_lop;
13329 
13330 		argop->argop = OP_LOCKU;
13331 		*locku_argsp = locku_args = &argop->nfs_argop4_u.oplocku;
13332 		locku_args->locktype = READ_LT;
13333 		locku_args->seqid = lop->lock_seqid + 1;
13334 		mutex_enter(&lop->lo_lock);
13335 		locku_args->lock_stateid = lop->lock_stateid;
13336 		mutex_exit(&lop->lo_lock);
13337 		locku_args->offset = resend_rqstp->lr_flk->l_start;
13338 		locku_args->length = resend_rqstp->lr_flk->l_len;
13339 		if (locku_args->length == 0)
13340 			locku_args->length = ~locku_args->length;
13341 
13342 		switch (resend_rqstp->lr_ctype) {
13343 		case NFS4_LCK_CTYPE_RESEND:
13344 			argsp->ctag = TAG_LOCKU_RESEND;
13345 			break;
13346 		case NFS4_LCK_CTYPE_REINSTATE:
13347 			argsp->ctag = TAG_LOCKU_REINSTATE;
13348 			break;
13349 		default:
13350 			argsp->ctag = TAG_LOCK_UNKNOWN;
13351 			break;
13352 		}
13353 	}
13354 }
13355 
13356 /*
13357  * Setup the LOCKT4 arguments.
13358  */
13359 static void
nfs4frlock_setup_lockt_args(nfs_argop4 * argop,LOCKT4args ** lockt_argsp,COMPOUND4args_clnt * argsp,flock64_t * flk,rnode4_t * rp)13360 nfs4frlock_setup_lockt_args(nfs_argop4 *argop, LOCKT4args **lockt_argsp,
13361     COMPOUND4args_clnt *argsp, flock64_t *flk, rnode4_t *rp)
13362 {
13363 	LOCKT4args *lockt_args;
13364 
13365 	ASSERT(nfs_zone() == VTOMI4(RTOV4(rp))->mi_zone);
13366 	argop->argop = OP_LOCKT;
13367 	argsp->ctag = TAG_LOCKT;
13368 	lockt_args = &argop->nfs_argop4_u.oplockt;
13369 
13370 	/*
13371 	 * The locktype will be READ_LT unless it's
13372 	 * a write lock. We do this because the Solaris
13373 	 * system call allows the combination of
13374 	 * F_UNLCK and F_GETLK* and so in that case the
13375 	 * unlock is mapped to a read.
13376 	 */
13377 	if (flk->l_type == F_WRLCK)
13378 		lockt_args->locktype = WRITE_LT;
13379 	else
13380 		lockt_args->locktype = READ_LT;
13381 
13382 	lockt_args->owner.clientid = mi2clientid(VTOMI4(RTOV4(rp)));
13383 	/* set the lock owner4 args */
13384 	nfs4_setlockowner_args(&lockt_args->owner, rp, flk->l_pid);
13385 	lockt_args->offset = flk->l_start;
13386 	lockt_args->length = flk->l_len;
13387 	if (flk->l_len == 0)
13388 		lockt_args->length = ~lockt_args->length;
13389 
13390 	*lockt_argsp = lockt_args;
13391 }
13392 
13393 /*
13394  * If the client is holding a delegation, and the open stream to be used
13395  * with this lock request is a delegation open stream, then re-open the stream.
13396  * Sets the nfs4_error_t to all zeros unless the open stream has already
13397  * failed a reopen or we couldn't find the open stream.  NFS4ERR_DELAY
13398  * means the caller should retry (like a recovery retry).
13399  */
13400 static void
nfs4frlock_check_deleg(vnode_t * vp,nfs4_error_t * ep,cred_t * cr,int lt)13401 nfs4frlock_check_deleg(vnode_t *vp, nfs4_error_t *ep, cred_t *cr, int lt)
13402 {
13403 	open_delegation_type4	dt;
13404 	bool_t			reopen_needed, force;
13405 	nfs4_open_stream_t	*osp;
13406 	open_claim_type4	oclaim;
13407 	rnode4_t		*rp = VTOR4(vp);
13408 	mntinfo4_t		*mi = VTOMI4(vp);
13409 
13410 	ASSERT(nfs_zone() == mi->mi_zone);
13411 
13412 	nfs4_error_zinit(ep);
13413 
13414 	mutex_enter(&rp->r_statev4_lock);
13415 	dt = rp->r_deleg_type;
13416 	mutex_exit(&rp->r_statev4_lock);
13417 
13418 	if (dt != OPEN_DELEGATE_NONE) {
13419 		nfs4_open_owner_t	*oop;
13420 
13421 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
13422 		if (!oop) {
13423 			ep->stat = NFS4ERR_IO;
13424 			return;
13425 		}
13426 		/* returns with 'os_sync_lock' held */
13427 		osp = find_open_stream(oop, rp);
13428 		if (!osp) {
13429 			open_owner_rele(oop);
13430 			ep->stat = NFS4ERR_IO;
13431 			return;
13432 		}
13433 
13434 		if (osp->os_failed_reopen) {
13435 			NFS4_DEBUG((nfs4_open_stream_debug ||
13436 			    nfs4_client_lock_debug), (CE_NOTE,
13437 			    "nfs4frlock_check_deleg: os_failed_reopen set "
13438 			    "for osp %p, cr %p, rp %s", (void *)osp,
13439 			    (void *)cr, rnode4info(rp)));
13440 			mutex_exit(&osp->os_sync_lock);
13441 			open_stream_rele(osp, rp);
13442 			open_owner_rele(oop);
13443 			ep->stat = NFS4ERR_IO;
13444 			return;
13445 		}
13446 
13447 		/*
13448 		 * Determine whether a reopen is needed.  If this
13449 		 * is a delegation open stream, then send the open
13450 		 * to the server to give visibility to the open owner.
13451 		 * Even if it isn't a delegation open stream, we need
13452 		 * to check if the previous open CLAIM_DELEGATE_CUR
13453 		 * was sufficient.
13454 		 */
13455 
13456 		reopen_needed = osp->os_delegation ||
13457 		    ((lt == F_RDLCK &&
13458 		    !(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_READ)) ||
13459 		    (lt == F_WRLCK &&
13460 		    !(osp->os_dc_openacc & OPEN4_SHARE_ACCESS_WRITE)));
13461 
13462 		mutex_exit(&osp->os_sync_lock);
13463 		open_owner_rele(oop);
13464 
13465 		if (reopen_needed) {
13466 			/*
13467 			 * Always use CLAIM_PREVIOUS after server reboot.
13468 			 * The server will reject CLAIM_DELEGATE_CUR if
13469 			 * it is used during the grace period.
13470 			 */
13471 			mutex_enter(&mi->mi_lock);
13472 			if (mi->mi_recovflags & MI4R_SRV_REBOOT) {
13473 				oclaim = CLAIM_PREVIOUS;
13474 				force = TRUE;
13475 			} else {
13476 				oclaim = CLAIM_DELEGATE_CUR;
13477 				force = FALSE;
13478 			}
13479 			mutex_exit(&mi->mi_lock);
13480 
13481 			nfs4_reopen(vp, osp, ep, oclaim, force, FALSE);
13482 			if (ep->error == EAGAIN) {
13483 				nfs4_error_zinit(ep);
13484 				ep->stat = NFS4ERR_DELAY;
13485 			}
13486 		}
13487 		open_stream_rele(osp, rp);
13488 		osp = NULL;
13489 	}
13490 }
13491 
13492 /*
13493  * Setup the LOCKU4 arguments.
13494  * Returns errors via the nfs4_error_t.
13495  * NFS4_OK		no problems.  *go_otwp is TRUE if call should go
13496  *			over-the-wire.  The caller must release the
13497  *			reference on *lopp.
13498  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13499  * (other)		unrecoverable error.
13500  */
13501 static void
nfs4frlock_setup_locku_args(nfs4_lock_call_type_t ctype,nfs_argop4 * argop,LOCKU4args ** locku_argsp,flock64_t * flk,nfs4_lock_owner_t ** lopp,nfs4_error_t * ep,COMPOUND4args_clnt * argsp,vnode_t * vp,cred_t * cr,bool_t * skip_get_err,bool_t * go_otwp)13502 nfs4frlock_setup_locku_args(nfs4_lock_call_type_t ctype, nfs_argop4 *argop,
13503     LOCKU4args **locku_argsp, flock64_t *flk,
13504     nfs4_lock_owner_t **lopp, nfs4_error_t *ep, COMPOUND4args_clnt *argsp,
13505     vnode_t *vp, cred_t *cr, bool_t *skip_get_err, bool_t *go_otwp)
13506 {
13507 	nfs4_lock_owner_t	*lop = NULL;
13508 	LOCKU4args		*locku_args;
13509 	pid_t			pid = flk->l_pid;
13510 	bool_t			is_spec = FALSE;
13511 	rnode4_t		*rp = VTOR4(vp);
13512 
13513 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13514 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13515 
13516 	nfs4frlock_check_deleg(vp, ep, cr, F_UNLCK);
13517 	if (ep->error || ep->stat)
13518 		return;
13519 
13520 	argop->argop = OP_LOCKU;
13521 	if (ctype == NFS4_LCK_CTYPE_REINSTATE)
13522 		argsp->ctag = TAG_LOCKU_REINSTATE;
13523 	else
13524 		argsp->ctag = TAG_LOCKU;
13525 	locku_args = &argop->nfs_argop4_u.oplocku;
13526 	*locku_argsp = locku_args;
13527 
13528 	/*
13529 	 * XXX what should locku_args->locktype be?
13530 	 * setting to ALWAYS be READ_LT so at least
13531 	 * it is a valid locktype.
13532 	 */
13533 
13534 	locku_args->locktype = READ_LT;
13535 
13536 	/*
13537 	 * Get the lock owner stateid.  If no lock owner
13538 	 * exists, return success.
13539 	 */
13540 	lop = find_lock_owner(rp, pid, LOWN_ANY);
13541 	*lopp = lop;
13542 	if (lop && CLNT_ISSPECIAL(&lop->lock_stateid))
13543 		is_spec = TRUE;
13544 	if (!lop || is_spec) {
13545 		/*
13546 		 * No lock owner so no locks to unlock.
13547 		 * Return success.
13548 		 *
13549 		 * If the lockowner is using a special stateid,
13550 		 * then the original lock request (that created
13551 		 * this lockowner) was never successful, so we
13552 		 * have no lock to undo OTW.
13553 		 */
13554 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
13555 		    "nfs4frlock_setup_locku_args: LOCKU: no lock owner "
13556 		    "(%ld) so return success", (long)pid));
13557 
13558 		/*
13559 		 * Release our hold and NULL out so final_cleanup
13560 		 * doesn't try to end a lock seqid sync we
13561 		 * never started.
13562 		 */
13563 		if (is_spec) {
13564 			lock_owner_rele(lop);
13565 			*lopp = NULL;
13566 		}
13567 		*skip_get_err = TRUE;
13568 		*go_otwp = FALSE;
13569 		return;
13570 	}
13571 
13572 	ep->error = nfs4_start_lock_seqid_sync(lop, VTOMI4(vp));
13573 	if (ep->error == EAGAIN) {
13574 		lock_owner_rele(lop);
13575 		*lopp = NULL;
13576 		return;
13577 	}
13578 
13579 	mutex_enter(&lop->lo_lock);
13580 	locku_args->lock_stateid = lop->lock_stateid;
13581 	mutex_exit(&lop->lo_lock);
13582 	locku_args->seqid = lop->lock_seqid + 1;
13583 
13584 	/* leave the ref count on lop, rele after RPC call */
13585 
13586 	locku_args->offset = flk->l_start;
13587 	locku_args->length = flk->l_len;
13588 	if (flk->l_len == 0)
13589 		locku_args->length = ~locku_args->length;
13590 
13591 	*go_otwp = TRUE;
13592 }
13593 
13594 /*
13595  * Setup the LOCK4 arguments.
13596  *
13597  * Returns errors via the nfs4_error_t.
13598  * NFS4_OK		no problems
13599  * NFS4ERR_DELAY	caller should retry (like recovery retry)
13600  * (other)		unrecoverable error
13601  */
13602 static void
nfs4frlock_setup_lock_args(nfs4_lock_call_type_t ctype,LOCK4args ** lock_argsp,nfs4_open_owner_t ** oopp,nfs4_open_stream_t ** ospp,nfs4_lock_owner_t ** lopp,nfs_argop4 * argop,COMPOUND4args_clnt * argsp,flock64_t * flk,int cmd,vnode_t * vp,cred_t * cr,nfs4_error_t * ep)13603 nfs4frlock_setup_lock_args(nfs4_lock_call_type_t ctype, LOCK4args **lock_argsp,
13604     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13605     nfs4_lock_owner_t **lopp, nfs_argop4 *argop, COMPOUND4args_clnt *argsp,
13606     flock64_t *flk, int cmd, vnode_t *vp, cred_t *cr, nfs4_error_t *ep)
13607 {
13608 	LOCK4args		*lock_args;
13609 	nfs4_open_owner_t	*oop = NULL;
13610 	nfs4_open_stream_t	*osp = NULL;
13611 	nfs4_lock_owner_t	*lop = NULL;
13612 	pid_t			pid = flk->l_pid;
13613 	rnode4_t		*rp = VTOR4(vp);
13614 
13615 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13616 
13617 	nfs4frlock_check_deleg(vp, ep, cr, flk->l_type);
13618 	if (ep->error || ep->stat != NFS4_OK)
13619 		return;
13620 
13621 	argop->argop = OP_LOCK;
13622 	if (ctype == NFS4_LCK_CTYPE_NORM)
13623 		argsp->ctag = TAG_LOCK;
13624 	else if (ctype == NFS4_LCK_CTYPE_RECLAIM)
13625 		argsp->ctag = TAG_RELOCK;
13626 	else
13627 		argsp->ctag = TAG_LOCK_REINSTATE;
13628 	lock_args = &argop->nfs_argop4_u.oplock;
13629 	lock_args->locktype = flk_to_locktype(cmd, flk->l_type);
13630 	lock_args->reclaim = ctype == NFS4_LCK_CTYPE_RECLAIM ? 1 : 0;
13631 	/*
13632 	 * Get the lock owner.  If no lock owner exists,
13633 	 * create a 'temporary' one and grab the open seqid
13634 	 * synchronization (which puts a hold on the open
13635 	 * owner and open stream).
13636 	 * This also grabs the lock seqid synchronization.
13637 	 */
13638 	ep->stat =
13639 	    nfs4_find_or_create_lock_owner(pid, rp, cr, &oop, &osp, &lop);
13640 
13641 	if (ep->stat != NFS4_OK)
13642 		goto out;
13643 
13644 	nfs4_setup_lock_args(lop, oop, osp, mi2clientid(VTOMI4(vp)),
13645 	    &lock_args->locker);
13646 
13647 	lock_args->offset = flk->l_start;
13648 	lock_args->length = flk->l_len;
13649 	if (flk->l_len == 0)
13650 		lock_args->length = ~lock_args->length;
13651 	*lock_argsp = lock_args;
13652 out:
13653 	*oopp = oop;
13654 	*ospp = osp;
13655 	*lopp = lop;
13656 }
13657 
13658 /*
13659  * After we get the reply from the server, record the proper information
13660  * for possible resend lock requests.
13661  *
13662  * Allocates memory for the saved_rqstp if we have a lost lock to save.
13663  */
13664 static void
nfs4frlock_save_lost_rqst(nfs4_lock_call_type_t ctype,int error,nfs_lock_type4 locktype,nfs4_open_owner_t * oop,nfs4_open_stream_t * osp,nfs4_lock_owner_t * lop,flock64_t * flk,nfs4_lost_rqst_t * lost_rqstp,cred_t * cr,vnode_t * vp)13665 nfs4frlock_save_lost_rqst(nfs4_lock_call_type_t ctype, int error,
13666     nfs_lock_type4 locktype, nfs4_open_owner_t *oop,
13667     nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop, flock64_t *flk,
13668     nfs4_lost_rqst_t *lost_rqstp, cred_t *cr, vnode_t *vp)
13669 {
13670 	bool_t unlock = (flk->l_type == F_UNLCK);
13671 
13672 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13673 	ASSERT(ctype == NFS4_LCK_CTYPE_NORM ||
13674 	    ctype == NFS4_LCK_CTYPE_REINSTATE);
13675 
13676 	if (error != 0 && !unlock) {
13677 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13678 		    nfs4_client_lock_debug), (CE_NOTE,
13679 		    "nfs4frlock_save_lost_rqst: set lo_pending_rqsts to 1 "
13680 		    " for lop %p", (void *)lop));
13681 		ASSERT(lop != NULL);
13682 		mutex_enter(&lop->lo_lock);
13683 		lop->lo_pending_rqsts = 1;
13684 		mutex_exit(&lop->lo_lock);
13685 	}
13686 
13687 	lost_rqstp->lr_putfirst = FALSE;
13688 	lost_rqstp->lr_op = 0;
13689 
13690 	/*
13691 	 * For lock/locku requests, we treat EINTR as ETIMEDOUT for
13692 	 * recovery purposes so that the lock request that was sent
13693 	 * can be saved and re-issued later.  Ditto for EIO from a forced
13694 	 * unmount.  This is done to have the client's local locking state
13695 	 * match the v4 server's state; that is, the request was
13696 	 * potentially received and accepted by the server but the client
13697 	 * thinks it was not.
13698 	 */
13699 	if (error == ETIMEDOUT || error == EINTR ||
13700 	    NFS4_FRC_UNMT_ERR(error, vp->v_vfsp)) {
13701 		NFS4_DEBUG((nfs4_lost_rqst_debug ||
13702 		    nfs4_client_lock_debug), (CE_NOTE,
13703 		    "nfs4frlock_save_lost_rqst: got a lost %s lock for "
13704 		    "lop %p oop %p osp %p", unlock ? "LOCKU" : "LOCK",
13705 		    (void *)lop, (void *)oop, (void *)osp));
13706 		if (unlock)
13707 			lost_rqstp->lr_op = OP_LOCKU;
13708 		else {
13709 			lost_rqstp->lr_op = OP_LOCK;
13710 			lost_rqstp->lr_locktype = locktype;
13711 		}
13712 		/*
13713 		 * Objects are held and rele'd via the recovery code.
13714 		 * See nfs4_save_lost_rqst.
13715 		 */
13716 		lost_rqstp->lr_vp = vp;
13717 		lost_rqstp->lr_dvp = NULL;
13718 		lost_rqstp->lr_oop = oop;
13719 		lost_rqstp->lr_osp = osp;
13720 		lost_rqstp->lr_lop = lop;
13721 		lost_rqstp->lr_cr = cr;
13722 		switch (ctype) {
13723 		case NFS4_LCK_CTYPE_NORM:
13724 			lost_rqstp->lr_ctype = NFS4_LCK_CTYPE_RESEND;
13725 			break;
13726 		case NFS4_LCK_CTYPE_REINSTATE:
13727 			lost_rqstp->lr_putfirst = TRUE;
13728 			lost_rqstp->lr_ctype = ctype;
13729 			break;
13730 		default:
13731 			break;
13732 		}
13733 		lost_rqstp->lr_flk = flk;
13734 	}
13735 }
13736 
13737 /*
13738  * Update lop's seqid.  Also update the seqid stored in a resend request,
13739  * if any.  (Some recovery errors increment the seqid, and we may have to
13740  * send the resend request again.)
13741  */
13742 
13743 static void
nfs4frlock_bump_seqid(LOCK4args * lock_args,LOCKU4args * locku_args,nfs4_open_owner_t * oop,nfs4_lock_owner_t * lop,nfs4_tag_type_t tag_type)13744 nfs4frlock_bump_seqid(LOCK4args *lock_args, LOCKU4args *locku_args,
13745     nfs4_open_owner_t *oop, nfs4_lock_owner_t *lop, nfs4_tag_type_t tag_type)
13746 {
13747 	if (lock_args) {
13748 		if (lock_args->locker.new_lock_owner == TRUE)
13749 			nfs4_get_and_set_next_open_seqid(oop, tag_type);
13750 		else {
13751 			ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13752 			nfs4_set_lock_seqid(lop->lock_seqid + 1, lop);
13753 		}
13754 	} else if (locku_args) {
13755 		ASSERT(lop->lo_flags & NFS4_LOCK_SEQID_INUSE);
13756 		nfs4_set_lock_seqid(lop->lock_seqid +1, lop);
13757 	}
13758 }
13759 
13760 /*
13761  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13762  * COMPOUND4 args/res for calls that need to retry.
13763  * Switches the *cred_otwp to base_cr.
13764  */
13765 static void
nfs4frlock_check_access(vnode_t * vp,nfs4_op_hint_t op_hint,nfs4_recov_state_t * recov_statep,int needrecov,bool_t * did_start_fop,COMPOUND4args_clnt ** argspp,COMPOUND4res_clnt ** respp,int error,nfs4_lock_owner_t ** lopp,nfs4_open_owner_t ** oopp,nfs4_open_stream_t ** ospp,cred_t * base_cr,cred_t ** cred_otwp)13766 nfs4frlock_check_access(vnode_t *vp, nfs4_op_hint_t op_hint,
13767     nfs4_recov_state_t *recov_statep, int needrecov, bool_t *did_start_fop,
13768     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp, int error,
13769     nfs4_lock_owner_t **lopp, nfs4_open_owner_t **oopp,
13770     nfs4_open_stream_t **ospp, cred_t *base_cr, cred_t **cred_otwp)
13771 {
13772 	nfs4_open_owner_t	*oop = *oopp;
13773 	nfs4_open_stream_t	*osp = *ospp;
13774 	nfs4_lock_owner_t	*lop = *lopp;
13775 	nfs_argop4		*argop = (*argspp)->array;
13776 
13777 	if (*did_start_fop) {
13778 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13779 		    needrecov);
13780 		*did_start_fop = FALSE;
13781 	}
13782 	ASSERT((*argspp)->array_len == 2);
13783 	if (argop[1].argop == OP_LOCK)
13784 		nfs4args_lock_free(&argop[1]);
13785 	else if (argop[1].argop == OP_LOCKT)
13786 		nfs4args_lockt_free(&argop[1]);
13787 	kmem_free(argop, 2 * sizeof (nfs_argop4));
13788 	if (!error)
13789 		(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13790 	*argspp = NULL;
13791 	*respp = NULL;
13792 
13793 	if (lop) {
13794 		nfs4_end_lock_seqid_sync(lop);
13795 		lock_owner_rele(lop);
13796 		*lopp = NULL;
13797 	}
13798 
13799 	/* need to free up the reference on osp for lock args */
13800 	if (osp != NULL) {
13801 		open_stream_rele(osp, VTOR4(vp));
13802 		*ospp = NULL;
13803 	}
13804 
13805 	/* need to free up the reference on oop for lock args */
13806 	if (oop != NULL) {
13807 		nfs4_end_open_seqid_sync(oop);
13808 		open_owner_rele(oop);
13809 		*oopp = NULL;
13810 	}
13811 
13812 	crfree(*cred_otwp);
13813 	*cred_otwp = base_cr;
13814 	crhold(*cred_otwp);
13815 }
13816 
13817 /*
13818  * Function to process the client's recovery for nfs4frlock.
13819  * Returns TRUE if we should retry the lock request; FALSE otherwise.
13820  *
13821  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13822  * COMPOUND4 args/res for calls that need to retry.
13823  *
13824  * Note: the rp's r_lkserlock is *not* dropped during this path.
13825  */
13826 static bool_t
nfs4frlock_recovery(int needrecov,nfs4_error_t * ep,COMPOUND4args_clnt ** argspp,COMPOUND4res_clnt ** respp,LOCK4args * lock_args,LOCKU4args * locku_args,nfs4_open_owner_t ** oopp,nfs4_open_stream_t ** ospp,nfs4_lock_owner_t ** lopp,rnode4_t * rp,vnode_t * vp,nfs4_recov_state_t * recov_statep,nfs4_op_hint_t op_hint,bool_t * did_start_fop,nfs4_lost_rqst_t * lost_rqstp,flock64_t * flk)13827 nfs4frlock_recovery(int needrecov, nfs4_error_t *ep,
13828     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13829     LOCK4args *lock_args, LOCKU4args *locku_args,
13830     nfs4_open_owner_t **oopp, nfs4_open_stream_t **ospp,
13831     nfs4_lock_owner_t **lopp, rnode4_t *rp, vnode_t *vp,
13832     nfs4_recov_state_t *recov_statep, nfs4_op_hint_t op_hint,
13833     bool_t *did_start_fop, nfs4_lost_rqst_t *lost_rqstp, flock64_t *flk)
13834 {
13835 	nfs4_open_owner_t	*oop = *oopp;
13836 	nfs4_open_stream_t	*osp = *ospp;
13837 	nfs4_lock_owner_t	*lop = *lopp;
13838 
13839 	bool_t abort, retry;
13840 
13841 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13842 	ASSERT((*argspp) != NULL);
13843 	ASSERT((*respp) != NULL);
13844 	if (lock_args || locku_args)
13845 		ASSERT(lop != NULL);
13846 
13847 	NFS4_DEBUG((nfs4_client_lock_debug || nfs4_client_recov_debug),
13848 	    (CE_NOTE, "nfs4frlock_recovery: initiating recovery\n"));
13849 
13850 	retry = TRUE;
13851 	abort = FALSE;
13852 	if (needrecov) {
13853 		nfs4_bseqid_entry_t *bsep = NULL;
13854 		nfs_opnum4 op;
13855 
13856 		op = lock_args ? OP_LOCK : locku_args ? OP_LOCKU : OP_LOCKT;
13857 
13858 		if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID) {
13859 			seqid4 seqid;
13860 
13861 			if (lock_args) {
13862 				if (lock_args->locker.new_lock_owner == TRUE)
13863 					seqid = lock_args->locker.locker4_u.
13864 					    open_owner.open_seqid;
13865 				else
13866 					seqid = lock_args->locker.locker4_u.
13867 					    lock_owner.lock_seqid;
13868 			} else if (locku_args) {
13869 				seqid = locku_args->seqid;
13870 			} else {
13871 				seqid = 0;
13872 			}
13873 
13874 			bsep = nfs4_create_bseqid_entry(oop, lop, vp,
13875 			    flk->l_pid, (*argspp)->ctag, seqid);
13876 		}
13877 
13878 		abort = nfs4_start_recovery(ep, VTOMI4(vp), vp, NULL, NULL,
13879 		    (lost_rqstp && (lost_rqstp->lr_op == OP_LOCK ||
13880 		    lost_rqstp->lr_op == OP_LOCKU)) ? lost_rqstp :
13881 		    NULL, op, bsep, NULL, NULL);
13882 
13883 		if (bsep)
13884 			kmem_free(bsep, sizeof (*bsep));
13885 	}
13886 
13887 	/*
13888 	 * Return that we do not want to retry the request for 3 cases:
13889 	 * 1. If we received EINTR or are bailing out because of a forced
13890 	 *    unmount, we came into this code path just for the sake of
13891 	 *    initiating recovery, we now need to return the error.
13892 	 * 2. If we have aborted recovery.
13893 	 * 3. We received NFS4ERR_BAD_SEQID.
13894 	 */
13895 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp) ||
13896 	    abort == TRUE || (ep->error == 0 && ep->stat == NFS4ERR_BAD_SEQID))
13897 		retry = FALSE;
13898 
13899 	if (*did_start_fop == TRUE) {
13900 		nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint, recov_statep,
13901 		    needrecov);
13902 		*did_start_fop = FALSE;
13903 	}
13904 
13905 	if (retry == TRUE) {
13906 		nfs_argop4	*argop;
13907 
13908 		argop = (*argspp)->array;
13909 		ASSERT((*argspp)->array_len == 2);
13910 
13911 		if (argop[1].argop == OP_LOCK)
13912 			nfs4args_lock_free(&argop[1]);
13913 		else if (argop[1].argop == OP_LOCKT)
13914 			nfs4args_lockt_free(&argop[1]);
13915 		kmem_free(argop, 2 * sizeof (nfs_argop4));
13916 		if (!ep->error)
13917 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)*respp);
13918 		*respp = NULL;
13919 		*argspp = NULL;
13920 	}
13921 
13922 	if (lop != NULL) {
13923 		nfs4_end_lock_seqid_sync(lop);
13924 		lock_owner_rele(lop);
13925 	}
13926 
13927 	*lopp = NULL;
13928 
13929 	/* need to free up the reference on osp for lock args */
13930 	if (osp != NULL) {
13931 		open_stream_rele(osp, rp);
13932 		*ospp = NULL;
13933 	}
13934 
13935 	/* need to free up the reference on oop for lock args */
13936 	if (oop != NULL) {
13937 		nfs4_end_open_seqid_sync(oop);
13938 		open_owner_rele(oop);
13939 		*oopp = NULL;
13940 	}
13941 
13942 	return (retry);
13943 }
13944 
13945 /*
13946  * Handle the DENIED reply from the server for nfs4frlock.
13947  * Returns TRUE if we should retry the request; FALSE otherwise.
13948  *
13949  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
13950  * COMPOUND4 args/res for calls that need to retry.  Can also
13951  * drop and regrab the r_lkserlock.
13952  */
13953 static bool_t
nfs4frlock_results_denied(nfs4_lock_call_type_t ctype,LOCK4args * lock_args,LOCKT4args * lockt_args,nfs4_open_owner_t ** oopp,nfs4_open_stream_t ** ospp,nfs4_lock_owner_t ** lopp,int cmd,vnode_t * vp,flock64_t * flk,nfs4_op_hint_t op_hint,nfs4_recov_state_t * recov_statep,int needrecov,COMPOUND4args_clnt ** argspp,COMPOUND4res_clnt ** respp,clock_t * tick_delayp,int * errorp,nfs_resop4 * resop,cred_t * cr,bool_t * did_start_fop,bool_t * skip_get_err)13954 nfs4frlock_results_denied(nfs4_lock_call_type_t ctype, LOCK4args *lock_args,
13955     LOCKT4args *lockt_args, nfs4_open_owner_t **oopp,
13956     nfs4_open_stream_t **ospp, nfs4_lock_owner_t **lopp, int cmd,
13957     vnode_t *vp, flock64_t *flk, nfs4_op_hint_t op_hint,
13958     nfs4_recov_state_t *recov_statep, int needrecov,
13959     COMPOUND4args_clnt **argspp, COMPOUND4res_clnt **respp,
13960     clock_t *tick_delayp, int *errorp,
13961     nfs_resop4 *resop, cred_t *cr, bool_t *did_start_fop,
13962     bool_t *skip_get_err)
13963 {
13964 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
13965 
13966 	if (lock_args) {
13967 		nfs4_open_owner_t	*oop = *oopp;
13968 		nfs4_open_stream_t	*osp = *ospp;
13969 		nfs4_lock_owner_t	*lop = *lopp;
13970 		int			intr;
13971 
13972 		/*
13973 		 * Blocking lock needs to sleep and retry from the request.
13974 		 *
13975 		 * Do not block and wait for 'resend' or 'reinstate'
13976 		 * lock requests, just return the error.
13977 		 *
13978 		 * Note: reclaim requests have cmd == F_SETLK, not F_SETLKW.
13979 		 */
13980 		if (cmd == F_SETLKW) {
13981 			rnode4_t *rp = VTOR4(vp);
13982 			nfs_argop4 *argop = (*argspp)->array;
13983 
13984 			ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
13985 
13986 			nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
13987 			    recov_statep, needrecov);
13988 			*did_start_fop = FALSE;
13989 			ASSERT((*argspp)->array_len == 2);
13990 			if (argop[1].argop == OP_LOCK)
13991 				nfs4args_lock_free(&argop[1]);
13992 			else if (argop[1].argop == OP_LOCKT)
13993 				nfs4args_lockt_free(&argop[1]);
13994 			kmem_free(argop, 2 * sizeof (nfs_argop4));
13995 			if (*respp)
13996 				(void) xdr_free(xdr_COMPOUND4res_clnt,
13997 				    (caddr_t)*respp);
13998 			*argspp = NULL;
13999 			*respp = NULL;
14000 			nfs4_end_lock_seqid_sync(lop);
14001 			lock_owner_rele(lop);
14002 			*lopp = NULL;
14003 			if (osp != NULL) {
14004 				open_stream_rele(osp, rp);
14005 				*ospp = NULL;
14006 			}
14007 			if (oop != NULL) {
14008 				nfs4_end_open_seqid_sync(oop);
14009 				open_owner_rele(oop);
14010 				*oopp = NULL;
14011 			}
14012 
14013 			nfs_rw_exit(&rp->r_lkserlock);
14014 
14015 			intr = nfs4_block_and_wait(tick_delayp);
14016 
14017 			(void) nfs_rw_enter_sig(&rp->r_lkserlock, RW_WRITER,
14018 			    FALSE);
14019 
14020 			if (intr) {
14021 				*errorp = EINTR;
14022 				return (FALSE);
14023 			}
14024 
14025 			/*
14026 			 * Make sure we are still safe to lock with
14027 			 * regards to mmapping.
14028 			 */
14029 			if (!nfs4_safelock(vp, flk, cr)) {
14030 				*errorp = EAGAIN;
14031 				return (FALSE);
14032 			}
14033 
14034 			return (TRUE);
14035 		}
14036 		if (ctype == NFS4_LCK_CTYPE_NORM)
14037 			*errorp = EAGAIN;
14038 		*skip_get_err = TRUE;
14039 		flk->l_whence = 0;
14040 		return (FALSE);
14041 	} else if (lockt_args) {
14042 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14043 		    "nfs4frlock_results_denied: OP_LOCKT DENIED"));
14044 
14045 		denied_to_flk(&resop->nfs_resop4_u.oplockt.denied,
14046 		    flk, lockt_args);
14047 
14048 		/* according to NLM code */
14049 		*errorp = 0;
14050 		*skip_get_err = TRUE;
14051 		return (FALSE);
14052 	}
14053 	return (FALSE);
14054 }
14055 
14056 /*
14057  * Handles all NFS4 errors besides NFS4_OK and NFS4ERR_DENIED for nfs4frlock.
14058  */
14059 static void
nfs4frlock_results_default(COMPOUND4res_clnt * resp,int * errorp)14060 nfs4frlock_results_default(COMPOUND4res_clnt *resp, int *errorp)
14061 {
14062 	switch (resp->status) {
14063 	case NFS4ERR_ACCESS:
14064 	case NFS4ERR_ADMIN_REVOKED:
14065 	case NFS4ERR_BADHANDLE:
14066 	case NFS4ERR_BAD_RANGE:
14067 	case NFS4ERR_BAD_SEQID:
14068 	case NFS4ERR_BAD_STATEID:
14069 	case NFS4ERR_BADXDR:
14070 	case NFS4ERR_DEADLOCK:
14071 	case NFS4ERR_DELAY:
14072 	case NFS4ERR_EXPIRED:
14073 	case NFS4ERR_FHEXPIRED:
14074 	case NFS4ERR_GRACE:
14075 	case NFS4ERR_INVAL:
14076 	case NFS4ERR_ISDIR:
14077 	case NFS4ERR_LEASE_MOVED:
14078 	case NFS4ERR_LOCK_NOTSUPP:
14079 	case NFS4ERR_LOCK_RANGE:
14080 	case NFS4ERR_MOVED:
14081 	case NFS4ERR_NOFILEHANDLE:
14082 	case NFS4ERR_NO_GRACE:
14083 	case NFS4ERR_OLD_STATEID:
14084 	case NFS4ERR_OPENMODE:
14085 	case NFS4ERR_RECLAIM_BAD:
14086 	case NFS4ERR_RECLAIM_CONFLICT:
14087 	case NFS4ERR_RESOURCE:
14088 	case NFS4ERR_SERVERFAULT:
14089 	case NFS4ERR_STALE:
14090 	case NFS4ERR_STALE_CLIENTID:
14091 	case NFS4ERR_STALE_STATEID:
14092 		return;
14093 	default:
14094 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14095 		    "nfs4frlock_results_default: got unrecognizable "
14096 		    "res.status %d", resp->status));
14097 		*errorp = NFS4ERR_INVAL;
14098 	}
14099 }
14100 
14101 /*
14102  * The lock request was successful, so update the client's state.
14103  */
14104 static void
nfs4frlock_update_state(LOCK4args * lock_args,LOCKU4args * locku_args,LOCKT4args * lockt_args,nfs_resop4 * resop,nfs4_lock_owner_t * lop,vnode_t * vp,flock64_t * flk,cred_t * cr,nfs4_lost_rqst_t * resend_rqstp)14105 nfs4frlock_update_state(LOCK4args *lock_args, LOCKU4args *locku_args,
14106     LOCKT4args *lockt_args, nfs_resop4 *resop, nfs4_lock_owner_t *lop,
14107     vnode_t *vp, flock64_t *flk, cred_t *cr,
14108     nfs4_lost_rqst_t *resend_rqstp)
14109 {
14110 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14111 
14112 	if (lock_args) {
14113 		LOCK4res *lock_res;
14114 
14115 		lock_res = &resop->nfs_resop4_u.oplock;
14116 		/* update the stateid with server's response */
14117 
14118 		if (lock_args->locker.new_lock_owner == TRUE) {
14119 			mutex_enter(&lop->lo_lock);
14120 			lop->lo_just_created = NFS4_PERM_CREATED;
14121 			mutex_exit(&lop->lo_lock);
14122 		}
14123 
14124 		nfs4_set_lock_stateid(lop, lock_res->LOCK4res_u.lock_stateid);
14125 
14126 		/*
14127 		 * If the lock was the result of a resending a lost
14128 		 * request, we've synched up the stateid and seqid
14129 		 * with the server, but now the server might be out of sync
14130 		 * with what the application thinks it has for locks.
14131 		 * Clean that up here.  It's unclear whether we should do
14132 		 * this even if the filesystem has been forcibly unmounted.
14133 		 * For most servers, it's probably wasted effort, but
14134 		 * RFC3530 lets servers require that unlocks exactly match
14135 		 * the locks that are held.
14136 		 */
14137 		if (resend_rqstp != NULL &&
14138 		    resend_rqstp->lr_ctype != NFS4_LCK_CTYPE_REINSTATE) {
14139 			nfs4_reinstitute_local_lock_state(vp, flk, cr, lop);
14140 		} else {
14141 			flk->l_whence = 0;
14142 		}
14143 	} else if (locku_args) {
14144 		LOCKU4res *locku_res;
14145 
14146 		locku_res = &resop->nfs_resop4_u.oplocku;
14147 
14148 		/* Update the stateid with the server's response */
14149 		nfs4_set_lock_stateid(lop, locku_res->lock_stateid);
14150 	} else if (lockt_args) {
14151 		/* Switch the lock type to express success, see fcntl */
14152 		flk->l_type = F_UNLCK;
14153 		flk->l_whence = 0;
14154 	}
14155 }
14156 
14157 /*
14158  * Do final cleanup before exiting nfs4frlock.
14159  * Calls nfs4_end_fop, drops the seqid syncs, and frees up the
14160  * COMPOUND4 args/res for calls that haven't already.
14161  */
14162 static void
nfs4frlock_final_cleanup(nfs4_lock_call_type_t ctype,COMPOUND4args_clnt * argsp,COMPOUND4res_clnt * resp,vnode_t * vp,nfs4_op_hint_t op_hint,nfs4_recov_state_t * recov_statep,int needrecov,nfs4_open_owner_t * oop,nfs4_open_stream_t * osp,nfs4_lock_owner_t * lop,int * errorp,LOCK4args * lock_args,LOCKU4args * locku_args,bool_t did_start_fop,bool_t skip_get_err,cred_t * cred_otw,cred_t * cred)14163 nfs4frlock_final_cleanup(nfs4_lock_call_type_t ctype, COMPOUND4args_clnt *argsp,
14164     COMPOUND4res_clnt *resp, vnode_t *vp, nfs4_op_hint_t op_hint,
14165     nfs4_recov_state_t *recov_statep, int needrecov, nfs4_open_owner_t *oop,
14166     nfs4_open_stream_t *osp, nfs4_lock_owner_t *lop,
14167     int *errorp, LOCK4args *lock_args, LOCKU4args *locku_args,
14168     bool_t did_start_fop, bool_t skip_get_err,
14169     cred_t *cred_otw, cred_t *cred)
14170 {
14171 	mntinfo4_t	*mi = VTOMI4(vp);
14172 	rnode4_t	*rp = VTOR4(vp);
14173 	int		error = *errorp;
14174 	nfs_argop4	*argop;
14175 	int	do_flush_pages = 0;
14176 
14177 	ASSERT(nfs_zone() == mi->mi_zone);
14178 	/*
14179 	 * The client recovery code wants the raw status information,
14180 	 * so don't map the NFS status code to an errno value for
14181 	 * non-normal call types.
14182 	 */
14183 	if (ctype == NFS4_LCK_CTYPE_NORM) {
14184 		if (*errorp == 0 && resp != NULL && skip_get_err == FALSE)
14185 			*errorp = geterrno4(resp->status);
14186 		if (did_start_fop == TRUE)
14187 			nfs4_end_fop(mi, vp, NULL, op_hint, recov_statep,
14188 			    needrecov);
14189 
14190 		/*
14191 		 * We've established a new lock on the server, so invalidate
14192 		 * the pages associated with the vnode to get the most up to
14193 		 * date pages from the server after acquiring the lock. We
14194 		 * want to be sure that the read operation gets the newest data.
14195 		 *
14196 		 * We flush the pages below after calling nfs4_end_fop above.
14197 		 *
14198 		 * The flush of the page cache must be done after
14199 		 * nfs4_end_open_seqid_sync() to avoid a 4-way hang.
14200 		 */
14201 		if (!error && resp && resp->status == NFS4_OK)
14202 			do_flush_pages = 1;
14203 	}
14204 	if (argsp) {
14205 		ASSERT(argsp->array_len == 2);
14206 		argop = argsp->array;
14207 		if (argop[1].argop == OP_LOCK)
14208 			nfs4args_lock_free(&argop[1]);
14209 		else if (argop[1].argop == OP_LOCKT)
14210 			nfs4args_lockt_free(&argop[1]);
14211 		kmem_free(argop, 2 * sizeof (nfs_argop4));
14212 		if (resp)
14213 			(void) xdr_free(xdr_COMPOUND4res_clnt, (caddr_t)resp);
14214 	}
14215 
14216 	/* free the reference on the lock owner */
14217 	if (lop != NULL) {
14218 		nfs4_end_lock_seqid_sync(lop);
14219 		lock_owner_rele(lop);
14220 	}
14221 
14222 	/* need to free up the reference on osp for lock args */
14223 	if (osp != NULL)
14224 		open_stream_rele(osp, rp);
14225 
14226 	/* need to free up the reference on oop for lock args */
14227 	if (oop != NULL) {
14228 		nfs4_end_open_seqid_sync(oop);
14229 		open_owner_rele(oop);
14230 	}
14231 
14232 	if (do_flush_pages)
14233 		nfs4_flush_pages(vp, cred);
14234 
14235 	/*
14236 	 * Record debug information in the event we get EINVAL.
14237 	 */
14238 	mutex_enter(&mi->mi_lock);
14239 	if (*errorp == EINVAL && (lock_args || locku_args) &&
14240 	    (!(mi->mi_flags & MI4_POSIX_LOCK))) {
14241 		if (!(mi->mi_flags & MI4_LOCK_DEBUG)) {
14242 			zcmn_err(getzoneid(), CE_NOTE,
14243 			    "%s operation failed with "
14244 			    "EINVAL probably since the server, %s,"
14245 			    " doesn't support POSIX style locking",
14246 			    lock_args ? "LOCK" : "LOCKU",
14247 			    mi->mi_curr_serv->sv_hostname);
14248 			mi->mi_flags |= MI4_LOCK_DEBUG;
14249 		}
14250 	}
14251 	mutex_exit(&mi->mi_lock);
14252 
14253 	if (cred_otw)
14254 		crfree(cred_otw);
14255 }
14256 
14257 /*
14258  * This calls the server.
14259  *
14260  * Blocking lock requests will continually retry to acquire the lock
14261  * forever.
14262  *
14263  * The ctype is defined as follows:
14264  * NFS4_LCK_CTYPE_NORM: normal lock request.
14265  *
14266  * NFS4_LCK_CTYPE_RECLAIM:  bypass the usual calls for synchronizing with client
14267  * recovery.
14268  *
14269  * NFS4_LCK_CTYPE_RESEND: same as NFS4_LCK_CTYPE_RECLAIM, with the addition
14270  * that we will use the information passed in via resend_rqstp to setup the
14271  * lock/locku request.  This resend is the exact same request as the 'lost
14272  * lock', and is initiated by the recovery framework. A successful resend
14273  * request can initiate one or more reinstate requests.
14274  *
14275  * NFS4_LCK_CTYPE_REINSTATE: same as NFS4_LCK_CTYPE_RESEND, except that it
14276  * does not trigger additional reinstate requests.  This lock call type is
14277  * set for setting the v4 server's locking state back to match what the
14278  * client's local locking state is in the event of a received 'lost lock'.
14279  *
14280  * Errors are returned via the nfs4_error_t parameter.
14281  */
14282 void
nfs4frlock(nfs4_lock_call_type_t ctype,vnode_t * vp,int cmd,flock64_t * flk,cred_t * cr,nfs4_error_t * ep,nfs4_lost_rqst_t * resend_rqstp,int * did_reclaimp)14283 nfs4frlock(nfs4_lock_call_type_t ctype, vnode_t *vp, int cmd, flock64_t *flk,
14284     cred_t *cr, nfs4_error_t *ep, nfs4_lost_rqst_t *resend_rqstp,
14285     int *did_reclaimp)
14286 {
14287 	COMPOUND4args_clnt	args, *argsp = NULL;
14288 	COMPOUND4res_clnt	res, *resp = NULL;
14289 	nfs_argop4	*argop;
14290 	nfs_resop4	*resop;
14291 	rnode4_t	*rp;
14292 	int		doqueue = 1;
14293 	clock_t		tick_delay;  /* delay in clock ticks */
14294 	LOCK4args	*lock_args = NULL;
14295 	LOCKU4args	*locku_args = NULL;
14296 	LOCKT4args	*lockt_args = NULL;
14297 	nfs4_open_owner_t *oop = NULL;
14298 	nfs4_open_stream_t *osp = NULL;
14299 	nfs4_lock_owner_t *lop = NULL;
14300 	bool_t		needrecov = FALSE;
14301 	nfs4_recov_state_t recov_state;
14302 	nfs4_op_hint_t	op_hint;
14303 	nfs4_lost_rqst_t lost_rqst;
14304 	bool_t		retry = FALSE;
14305 	bool_t		did_start_fop = FALSE;
14306 	bool_t		skip_get_err = FALSE;
14307 	cred_t		*cred_otw = NULL;
14308 	bool_t		recovonly;	/* just queue request */
14309 	int		frc_no_reclaim = 0;
14310 #ifdef DEBUG
14311 	char *name;
14312 #endif
14313 
14314 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14315 
14316 #ifdef DEBUG
14317 	name = fn_name(VTOSV(vp)->sv_name);
14318 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4frlock: "
14319 	    "%s: cmd %d, type %d, start %"PRIx64", "
14320 	    "length %"PRIu64", pid %d, sysid %d, call type %s, "
14321 	    "resend request %s", name, cmd, flk->l_type, flk->l_start,
14322 	    flk->l_len, flk->l_pid, flk->l_sysid,
14323 	    nfs4frlock_get_call_type(ctype),
14324 	    resend_rqstp ? "TRUE" : "FALSE"));
14325 	kmem_free(name, MAXNAMELEN);
14326 #endif
14327 
14328 	nfs4_error_zinit(ep);
14329 
14330 	nfs4frlock_pre_setup(&tick_delay, &recov_state, vp, cr, &cred_otw);
14331 
14332 	rp = VTOR4(vp);
14333 
14334 recov_retry:
14335 	nfs4frlock_call_init(&args, &argsp, &argop, &op_hint, flk, cmd,
14336 	    &retry, &did_start_fop, &resp, &skip_get_err, &lost_rqst);
14337 
14338 	ep->error = nfs4frlock_start_call(ctype, vp, op_hint, &recov_state,
14339 	    &did_start_fop, &recovonly);
14340 
14341 	if (ep->error)
14342 		goto out;
14343 
14344 	if (recovonly) {
14345 		/*
14346 		 * Leave the request for the recovery system to deal with.
14347 		 */
14348 		ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
14349 		ASSERT(cmd != F_GETLK);
14350 		ASSERT(flk->l_type == F_UNLCK);
14351 
14352 		nfs4_error_init(ep, EINTR);
14353 		needrecov = TRUE;
14354 		lop = find_lock_owner(rp, flk->l_pid, LOWN_ANY);
14355 		if (lop != NULL) {
14356 			nfs4frlock_save_lost_rqst(ctype, ep->error, READ_LT,
14357 			    NULL, NULL, lop, flk, &lost_rqst, cr, vp);
14358 			(void) nfs4_start_recovery(ep,
14359 			    VTOMI4(vp), vp, NULL, NULL,
14360 			    (lost_rqst.lr_op == OP_LOCK ||
14361 			    lost_rqst.lr_op == OP_LOCKU) ?
14362 			    &lost_rqst : NULL, OP_LOCKU, NULL, NULL, NULL);
14363 			lock_owner_rele(lop);
14364 			lop = NULL;
14365 		}
14366 		goto out;
14367 	}
14368 
14369 	/* putfh directory fh */
14370 	argop[0].argop = OP_CPUTFH;
14371 	argop[0].nfs_argop4_u.opcputfh.sfh = rp->r_fh;
14372 
14373 	/*
14374 	 * Set up the over-the-wire arguments and get references to the
14375 	 * open owner, etc.
14376 	 */
14377 
14378 	if (ctype == NFS4_LCK_CTYPE_RESEND ||
14379 	    ctype == NFS4_LCK_CTYPE_REINSTATE) {
14380 		nfs4frlock_setup_resend_lock_args(resend_rqstp, argsp,
14381 		    &argop[1], &lop, &oop, &osp, &lock_args, &locku_args);
14382 	} else {
14383 		bool_t go_otw = TRUE;
14384 
14385 		ASSERT(resend_rqstp == NULL);
14386 
14387 		switch (cmd) {
14388 		case F_GETLK:
14389 		case F_O_GETLK:
14390 			ASSERT(ctype == NFS4_LCK_CTYPE_NORM);
14391 			nfs4frlock_setup_lockt_args(&argop[1], &lockt_args,
14392 			    argsp, flk, rp);
14393 			break;
14394 		case F_SETLKW:
14395 		case F_SETLK:
14396 			if (flk->l_type == F_UNLCK)
14397 				nfs4frlock_setup_locku_args(ctype,
14398 				    &argop[1], &locku_args, flk,
14399 				    &lop, ep, argsp, vp, cr,
14400 				    &skip_get_err, &go_otw);
14401 			else
14402 				nfs4frlock_setup_lock_args(ctype,
14403 				    &lock_args, &oop, &osp, &lop, &argop[1],
14404 				    argsp, flk, cmd, vp, cr, ep);
14405 
14406 			if (ep->error)
14407 				goto out;
14408 
14409 			switch (ep->stat) {
14410 			case NFS4_OK:
14411 				break;
14412 			case NFS4ERR_DELAY:
14413 				/* recov thread never gets this error */
14414 				ASSERT(resend_rqstp == NULL);
14415 				ASSERT(did_start_fop);
14416 
14417 				nfs4_end_fop(VTOMI4(vp), vp, NULL, op_hint,
14418 				    &recov_state, TRUE);
14419 				did_start_fop = FALSE;
14420 				if (argop[1].argop == OP_LOCK)
14421 					nfs4args_lock_free(&argop[1]);
14422 				else if (argop[1].argop == OP_LOCKT)
14423 					nfs4args_lockt_free(&argop[1]);
14424 				kmem_free(argop, 2 * sizeof (nfs_argop4));
14425 				argsp = NULL;
14426 				goto recov_retry;
14427 			default:
14428 				ep->error = EIO;
14429 				goto out;
14430 			}
14431 			break;
14432 		default:
14433 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14434 			    "nfs4_frlock: invalid cmd %d", cmd));
14435 			ep->error = EINVAL;
14436 			goto out;
14437 		}
14438 
14439 		if (!go_otw)
14440 			goto out;
14441 	}
14442 
14443 	/*
14444 	 * Send the server the lock request.  Continually loop with a delay
14445 	 * if get error NFS4ERR_DENIED (for blocking locks) or NFS4ERR_GRACE.
14446 	 */
14447 	resp = &res;
14448 
14449 	NFS4_DEBUG((nfs4_client_call_debug || nfs4_client_lock_debug),
14450 	    (CE_NOTE,
14451 	    "nfs4frlock: %s call, rp %s", needrecov ? "recov" : "first",
14452 	    rnode4info(rp)));
14453 
14454 	if (lock_args && frc_no_reclaim) {
14455 		ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14456 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14457 		    "nfs4frlock: frc_no_reclaim: clearing reclaim"));
14458 		lock_args->reclaim = FALSE;
14459 		if (did_reclaimp)
14460 			*did_reclaimp = 0;
14461 	}
14462 
14463 	/*
14464 	 * Do the OTW call.
14465 	 */
14466 	rfs4call(VTOMI4(vp), argsp, resp, cred_otw, &doqueue, 0, ep);
14467 
14468 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14469 	    "nfs4frlock: error %d, status %d", ep->error, resp->status));
14470 
14471 	needrecov = nfs4_needs_recovery(ep, TRUE, vp->v_vfsp);
14472 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14473 	    "nfs4frlock: needrecov %d", needrecov));
14474 
14475 	if (ep->error == 0 && nfs4_need_to_bump_seqid(resp))
14476 		nfs4frlock_bump_seqid(lock_args, locku_args, oop, lop,
14477 		    args.ctag);
14478 
14479 	/*
14480 	 * Check if one of these mutually exclusive error cases has
14481 	 * happened:
14482 	 *   need to swap credentials due to access error
14483 	 *   recovery is needed
14484 	 *   different error (only known case is missing Kerberos ticket)
14485 	 */
14486 
14487 	if ((ep->error == EACCES ||
14488 	    (ep->error == 0 && resp->status == NFS4ERR_ACCESS)) &&
14489 	    cred_otw != cr) {
14490 		nfs4frlock_check_access(vp, op_hint, &recov_state, needrecov,
14491 		    &did_start_fop, &argsp, &resp, ep->error, &lop, &oop, &osp,
14492 		    cr, &cred_otw);
14493 		goto recov_retry;
14494 	}
14495 
14496 	if (needrecov) {
14497 		/*
14498 		 * LOCKT requests don't need to recover from lost
14499 		 * requests since they don't create/modify state.
14500 		 */
14501 		if ((ep->error == EINTR ||
14502 		    NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) &&
14503 		    lockt_args)
14504 			goto out;
14505 		/*
14506 		 * Do not attempt recovery for requests initiated by
14507 		 * the recovery framework.  Let the framework redrive them.
14508 		 */
14509 		if (ctype != NFS4_LCK_CTYPE_NORM)
14510 			goto out;
14511 		else {
14512 			ASSERT(resend_rqstp == NULL);
14513 		}
14514 
14515 		nfs4frlock_save_lost_rqst(ctype, ep->error,
14516 		    flk_to_locktype(cmd, flk->l_type),
14517 		    oop, osp, lop, flk, &lost_rqst, cred_otw, vp);
14518 
14519 		retry = nfs4frlock_recovery(needrecov, ep, &argsp,
14520 		    &resp, lock_args, locku_args, &oop, &osp, &lop,
14521 		    rp, vp, &recov_state, op_hint, &did_start_fop,
14522 		    cmd != F_GETLK ? &lost_rqst : NULL, flk);
14523 
14524 		if (retry) {
14525 			ASSERT(oop == NULL);
14526 			ASSERT(osp == NULL);
14527 			ASSERT(lop == NULL);
14528 			goto recov_retry;
14529 		}
14530 		goto out;
14531 	}
14532 
14533 	/*
14534 	 * Bail out if have reached this point with ep->error set. Can
14535 	 * happen if (ep->error == EACCES && !needrecov && cred_otw == cr).
14536 	 * This happens if Kerberos ticket has expired or has been
14537 	 * destroyed.
14538 	 */
14539 	if (ep->error != 0)
14540 		goto out;
14541 
14542 	/*
14543 	 * Process the reply.
14544 	 */
14545 	switch (resp->status) {
14546 	case NFS4_OK:
14547 		resop = &resp->array[1];
14548 		/*
14549 		 * Have a successful lock operation, now update state.
14550 		 */
14551 		nfs4frlock_update_state(lock_args, locku_args, lockt_args,
14552 		    resop, lop, vp, flk, cr, resend_rqstp);
14553 		break;
14554 
14555 	case NFS4ERR_DENIED:
14556 		resop = &resp->array[1];
14557 		retry = nfs4frlock_results_denied(ctype, lock_args, lockt_args,
14558 		    &oop, &osp, &lop, cmd, vp, flk, op_hint,
14559 		    &recov_state, needrecov, &argsp, &resp,
14560 		    &tick_delay, &ep->error, resop, cr,
14561 		    &did_start_fop, &skip_get_err);
14562 
14563 		if (retry) {
14564 			ASSERT(oop == NULL);
14565 			ASSERT(osp == NULL);
14566 			ASSERT(lop == NULL);
14567 			goto recov_retry;
14568 		}
14569 		break;
14570 	/*
14571 	 * If the server won't let us reclaim, fall-back to trying to lock
14572 	 * the file from scratch. Code elsewhere will check the changeinfo
14573 	 * to ensure the file hasn't been changed.
14574 	 */
14575 	case NFS4ERR_NO_GRACE:
14576 		if (lock_args && lock_args->reclaim == TRUE) {
14577 			ASSERT(ctype == NFS4_LCK_CTYPE_RECLAIM);
14578 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14579 			    "nfs4frlock: reclaim: NFS4ERR_NO_GRACE"));
14580 			frc_no_reclaim = 1;
14581 			/* clean up before retrying */
14582 			needrecov = 0;
14583 			(void) nfs4frlock_recovery(needrecov, ep, &argsp, &resp,
14584 			    lock_args, locku_args, &oop, &osp, &lop, rp, vp,
14585 			    &recov_state, op_hint, &did_start_fop, NULL, flk);
14586 			goto recov_retry;
14587 		}
14588 		/* FALLTHROUGH */
14589 
14590 	default:
14591 		nfs4frlock_results_default(resp, &ep->error);
14592 		break;
14593 	}
14594 out:
14595 	/*
14596 	 * Process and cleanup from error.  Make interrupted unlock
14597 	 * requests look successful, since they will be handled by the
14598 	 * client recovery code.
14599 	 */
14600 	nfs4frlock_final_cleanup(ctype, argsp, resp, vp, op_hint, &recov_state,
14601 	    needrecov, oop, osp, lop, &ep->error,
14602 	    lock_args, locku_args, did_start_fop,
14603 	    skip_get_err, cred_otw, cr);
14604 
14605 	if (ep->error == EINTR && flk->l_type == F_UNLCK &&
14606 	    (cmd == F_SETLK || cmd == F_SETLKW))
14607 		ep->error = 0;
14608 }
14609 
14610 /*
14611  * nfs4_safelock:
14612  *
14613  * Return non-zero if the given lock request can be handled without
14614  * violating the constraints on concurrent mapping and locking.
14615  */
14616 
14617 static int
nfs4_safelock(vnode_t * vp,const struct flock64 * bfp,cred_t * cr)14618 nfs4_safelock(vnode_t *vp, const struct flock64 *bfp, cred_t *cr)
14619 {
14620 	rnode4_t *rp = VTOR4(vp);
14621 	struct vattr va;
14622 	int error;
14623 
14624 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14625 	ASSERT(rp->r_mapcnt >= 0);
14626 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock %s: "
14627 	    "(%"PRIx64", %"PRIx64"); mapcnt = %ld", bfp->l_type == F_WRLCK ?
14628 	    "write" : bfp->l_type == F_RDLCK ? "read" : "unlock",
14629 	    bfp->l_start, bfp->l_len, rp->r_mapcnt));
14630 
14631 	if (rp->r_mapcnt == 0)
14632 		return (1);		/* always safe if not mapped */
14633 
14634 	/*
14635 	 * If the file is already mapped and there are locks, then they
14636 	 * should be all safe locks.  So adding or removing a lock is safe
14637 	 * as long as the new request is safe (i.e., whole-file, meaning
14638 	 * length and starting offset are both zero).
14639 	 */
14640 
14641 	if (bfp->l_start != 0 || bfp->l_len != 0) {
14642 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14643 		    "cannot lock a memory mapped file unless locking the "
14644 		    "entire file: start %"PRIx64", len %"PRIx64,
14645 		    bfp->l_start, bfp->l_len));
14646 		return (0);
14647 	}
14648 
14649 	/* mandatory locking and mapping don't mix */
14650 	va.va_mask = AT_MODE;
14651 	error = VOP_GETATTR(vp, &va, 0, cr, NULL);
14652 	if (error != 0) {
14653 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14654 		    "getattr error %d", error));
14655 		return (0);		/* treat errors conservatively */
14656 	}
14657 	if (MANDLOCK(vp, va.va_mode)) {
14658 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_safelock: "
14659 		    "cannot mandatory lock and mmap a file"));
14660 		return (0);
14661 	}
14662 
14663 	return (1);
14664 }
14665 
14666 /*
14667  * nfs4_lockrelease:
14668  *
14669  * Release any locks on the given vnode that are held by the current
14670  * process.  Also removes the lock owner (if one exists) from the rnode's
14671  * list.
14672  */
14673 static int
nfs4_lockrelease(vnode_t * vp,int flag,offset_t offset,cred_t * cr)14674 nfs4_lockrelease(vnode_t *vp, int flag, offset_t offset, cred_t *cr)
14675 {
14676 	flock64_t ld;
14677 	int ret, error;
14678 	rnode4_t *rp;
14679 	nfs4_lock_owner_t *lop;
14680 	nfs4_recov_state_t recov_state;
14681 	mntinfo4_t *mi;
14682 	bool_t possible_orphan = FALSE;
14683 	bool_t recovonly;
14684 
14685 	ASSERT((uintptr_t)vp > KERNELBASE);
14686 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14687 
14688 	rp = VTOR4(vp);
14689 	mi = VTOMI4(vp);
14690 
14691 	/*
14692 	 * If we have not locked anything then we can
14693 	 * just return since we have no work to do.
14694 	 */
14695 	if (rp->r_lo_head.lo_next_rnode == &rp->r_lo_head) {
14696 		return (0);
14697 	}
14698 
14699 	/*
14700 	 * We need to comprehend that another thread may
14701 	 * kick off recovery and the lock_owner we have stashed
14702 	 * in lop might be invalid so we should NOT cache it
14703 	 * locally!
14704 	 */
14705 	recov_state.rs_flags = 0;
14706 	recov_state.rs_num_retry_despite_err = 0;
14707 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14708 	    &recovonly);
14709 	if (error) {
14710 		mutex_enter(&rp->r_statelock);
14711 		rp->r_flags |= R4LODANGLERS;
14712 		mutex_exit(&rp->r_statelock);
14713 		return (error);
14714 	}
14715 
14716 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14717 
14718 	/*
14719 	 * Check if the lock owner might have a lock (request was sent but
14720 	 * no response was received).  Also check if there are any remote
14721 	 * locks on the file.  (In theory we shouldn't have to make this
14722 	 * second check if there's no lock owner, but for now we'll be
14723 	 * conservative and do it anyway.)  If either condition is true,
14724 	 * send an unlock for the entire file to the server.
14725 	 *
14726 	 * Note that no explicit synchronization is needed here.  At worst,
14727 	 * flk_has_remote_locks() will return a false positive, in which case
14728 	 * the unlock call wastes time but doesn't harm correctness.
14729 	 */
14730 
14731 	if (lop) {
14732 		mutex_enter(&lop->lo_lock);
14733 		possible_orphan = lop->lo_pending_rqsts;
14734 		mutex_exit(&lop->lo_lock);
14735 		lock_owner_rele(lop);
14736 	}
14737 
14738 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14739 
14740 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14741 	    "nfs4_lockrelease: possible orphan %d, remote locks %d, for "
14742 	    "lop %p.", possible_orphan, flk_has_remote_locks(vp),
14743 	    (void *)lop));
14744 
14745 	if (possible_orphan || flk_has_remote_locks(vp)) {
14746 		ld.l_type = F_UNLCK;    /* set to unlock entire file */
14747 		ld.l_whence = 0;	/* unlock from start of file */
14748 		ld.l_start = 0;
14749 		ld.l_len = 0;		/* do entire file */
14750 
14751 		ret = VOP_FRLOCK(vp, F_SETLK, &ld, flag, offset, NULL,
14752 		    cr, NULL);
14753 
14754 		if (ret != 0) {
14755 			/*
14756 			 * If VOP_FRLOCK fails, make sure we unregister
14757 			 * local locks before we continue.
14758 			 */
14759 			struct lm_sysid *lmsid = nfs4_find_sysid(VTOMI4(vp));
14760 
14761 			if (lmsid != NULL) {
14762 				cleanlocks(vp, curproc->p_pid,
14763 				    lm_sysidt(lmsid) | LM_SYSID_CLIENT);
14764 				lm_rel_sysid(lmsid);
14765 			}
14766 
14767 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
14768 			    "nfs4_lockrelease: lock release error on vp"
14769 			    " %p: error %d.\n", (void *)vp, ret));
14770 		}
14771 	}
14772 
14773 	recov_state.rs_flags = 0;
14774 	recov_state.rs_num_retry_despite_err = 0;
14775 	error = nfs4_start_fop(mi, vp, NULL, OH_LOCKU, &recov_state,
14776 	    &recovonly);
14777 	if (error) {
14778 		mutex_enter(&rp->r_statelock);
14779 		rp->r_flags |= R4LODANGLERS;
14780 		mutex_exit(&rp->r_statelock);
14781 		return (error);
14782 	}
14783 
14784 	/*
14785 	 * So, here we're going to need to retrieve the lock-owner
14786 	 * again (in case recovery has done a switch-a-roo) and
14787 	 * remove it because we can.
14788 	 */
14789 	lop = find_lock_owner(rp, curproc->p_pid, LOWN_ANY);
14790 
14791 	if (lop) {
14792 		nfs4_rnode_remove_lock_owner(rp, lop);
14793 		lock_owner_rele(lop);
14794 	}
14795 
14796 	nfs4_end_fop(mi, vp, NULL, OH_LOCKU, &recov_state, 0);
14797 	return (0);
14798 }
14799 
14800 /*
14801  * Wait for 'tick_delay' clock ticks.
14802  * Implement exponential backoff until hit the lease_time of this nfs4_server.
14803  *
14804  * The client should retry to acquire the lock faster than the lease period.
14805  * We use roughly half of the lease time to use a similar calculation as it is
14806  * used in nfs4_renew_lease_thread().
14807  *
14808  * XXX For future improvements, should implement a waiting queue scheme.
14809  */
14810 static int
nfs4_block_and_wait(clock_t * tick_delay)14811 nfs4_block_and_wait(clock_t *tick_delay)
14812 {
14813 	/* wait tick_delay clock ticks or siginteruptus */
14814 	if (delay_sig(*tick_delay)) {
14815 		return (EINTR);
14816 	}
14817 
14818 	NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE, "nfs4_block_and_wait: "
14819 	    "reissue the lock request: blocked for %ld clock ticks: %ld "
14820 	    "milliseconds", *tick_delay, drv_hztousec(*tick_delay) / 1000));
14821 
14822 	*tick_delay = MIN(drv_usectohz(nfs4_max_base_wait_time * 1000),
14823 			  *tick_delay * 1.5);
14824 	return (0);
14825 }
14826 
14827 void
nfs4_vnops_init(void)14828 nfs4_vnops_init(void)
14829 {
14830 }
14831 
14832 void
nfs4_vnops_fini(void)14833 nfs4_vnops_fini(void)
14834 {
14835 }
14836 
14837 /*
14838  * Return a reference to the directory (parent) vnode for a given vnode,
14839  * using the saved pathname information and the directory file handle.  The
14840  * caller is responsible for disposing of the reference.
14841  * Returns zero or an errno value.
14842  *
14843  * Caller should set need_start_op to FALSE if it is the recovery
14844  * thread, or if a start_fop has already been done.  Otherwise, TRUE.
14845  */
14846 int
vtodv(vnode_t * vp,vnode_t ** dvpp,cred_t * cr,bool_t need_start_op)14847 vtodv(vnode_t *vp, vnode_t **dvpp, cred_t *cr, bool_t need_start_op)
14848 {
14849 	svnode_t *svnp;
14850 	vnode_t *dvp = NULL;
14851 	servinfo4_t *svp;
14852 	nfs4_fname_t *mfname;
14853 	int error;
14854 
14855 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
14856 
14857 	if (vp->v_flag & VROOT) {
14858 		nfs4_sharedfh_t *sfh;
14859 		nfs_fh4 fh;
14860 		mntinfo4_t *mi;
14861 
14862 		ASSERT(vp->v_type == VREG);
14863 
14864 		mi = VTOMI4(vp);
14865 		svp = mi->mi_curr_serv;
14866 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14867 		fh.nfs_fh4_len = svp->sv_pfhandle.fh_len;
14868 		fh.nfs_fh4_val = svp->sv_pfhandle.fh_buf;
14869 		sfh = sfh4_get(&fh, VTOMI4(vp));
14870 		nfs_rw_exit(&svp->sv_lock);
14871 		mfname = mi->mi_fname;
14872 		fn_hold(mfname);
14873 		dvp = makenfs4node_by_fh(sfh, NULL, &mfname, NULL, mi, cr, 0);
14874 		sfh4_rele(&sfh);
14875 
14876 		if (dvp->v_type == VNON)
14877 			dvp->v_type = VDIR;
14878 		*dvpp = dvp;
14879 		return (0);
14880 	}
14881 
14882 	svnp = VTOSV(vp);
14883 
14884 	if (svnp == NULL) {
14885 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14886 		    "shadow node is NULL"));
14887 		return (EINVAL);
14888 	}
14889 
14890 	if (svnp->sv_name == NULL || svnp->sv_dfh == NULL) {
14891 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14892 		    "shadow node name or dfh val == NULL"));
14893 		return (EINVAL);
14894 	}
14895 
14896 	error = nfs4_make_dotdot(svnp->sv_dfh, 0, vp, cr, &dvp,
14897 	    (int)need_start_op);
14898 	if (error != 0) {
14899 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14900 		    "nfs4_make_dotdot returned %d", error));
14901 		return (error);
14902 	}
14903 	if (!dvp) {
14904 		NFS4_DEBUG(nfs4_client_shadow_debug, (CE_NOTE, "vtodv: "
14905 		    "nfs4_make_dotdot returned a NULL dvp"));
14906 		return (EIO);
14907 	}
14908 	if (dvp->v_type == VNON)
14909 		dvp->v_type = VDIR;
14910 	ASSERT(dvp->v_type == VDIR);
14911 	if (VTOR4(vp)->r_flags & R4ISXATTR) {
14912 		mutex_enter(&dvp->v_lock);
14913 		dvp->v_flag |= V_XATTRDIR;
14914 		mutex_exit(&dvp->v_lock);
14915 	}
14916 	*dvpp = dvp;
14917 	return (0);
14918 }
14919 
14920 /*
14921  * Copy the (final) component name of vp to fnamep.  maxlen is the maximum
14922  * length that fnamep can accept, including the trailing null.
14923  * Returns 0 if okay, returns an errno value if there was a problem.
14924  */
14925 
14926 int
vtoname(vnode_t * vp,char * fnamep,ssize_t maxlen)14927 vtoname(vnode_t *vp, char *fnamep, ssize_t maxlen)
14928 {
14929 	char *fn;
14930 	int err = 0;
14931 	servinfo4_t *svp;
14932 	svnode_t *shvp;
14933 
14934 	/*
14935 	 * If the file being opened has VROOT set, then this is
14936 	 * a "file" mount.  sv_name will not be interesting, so
14937 	 * go back to the servinfo4 to get the original mount
14938 	 * path and strip off all but the final edge.  Otherwise
14939 	 * just return the name from the shadow vnode.
14940 	 */
14941 
14942 	if (vp->v_flag & VROOT) {
14943 
14944 		svp = VTOMI4(vp)->mi_curr_serv;
14945 		(void) nfs_rw_enter_sig(&svp->sv_lock, RW_READER, 0);
14946 
14947 		fn = strrchr(svp->sv_path, '/');
14948 		if (fn == NULL)
14949 			err = EINVAL;
14950 		else
14951 			fn++;
14952 	} else {
14953 		shvp = VTOSV(vp);
14954 		fn = fn_name(shvp->sv_name);
14955 	}
14956 
14957 	if (err == 0)
14958 		if (strlen(fn) < maxlen)
14959 			(void) strcpy(fnamep, fn);
14960 		else
14961 			err = ENAMETOOLONG;
14962 
14963 	if (vp->v_flag & VROOT)
14964 		nfs_rw_exit(&svp->sv_lock);
14965 	else
14966 		kmem_free(fn, MAXNAMELEN);
14967 
14968 	return (err);
14969 }
14970 
14971 /*
14972  * Bookkeeping for a close that doesn't need to go over the wire.
14973  * *have_lockp is set to 0 if 'os_sync_lock' is released; otherwise
14974  * it is left at 1.
14975  */
14976 void
nfs4close_notw(vnode_t * vp,nfs4_open_stream_t * osp,int * have_lockp)14977 nfs4close_notw(vnode_t *vp, nfs4_open_stream_t *osp, int *have_lockp)
14978 {
14979 	rnode4_t		*rp;
14980 	mntinfo4_t		*mi;
14981 
14982 	mi = VTOMI4(vp);
14983 	rp = VTOR4(vp);
14984 
14985 	NFS4_DEBUG(nfs4close_notw_debug, (CE_NOTE, "nfs4close_notw: "
14986 	    "rp=%p osp=%p", (void *)rp, (void *)osp));
14987 	ASSERT(nfs_zone() == mi->mi_zone);
14988 	ASSERT(mutex_owned(&osp->os_sync_lock));
14989 	ASSERT(*have_lockp);
14990 
14991 	if (!osp->os_valid ||
14992 	    osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
14993 		return;
14994 	}
14995 
14996 	/*
14997 	 * This removes the reference obtained at OPEN; ie,
14998 	 * when the open stream structure was created.
14999 	 *
15000 	 * We don't have to worry about calling 'open_stream_rele'
15001 	 * since we our currently holding a reference to this
15002 	 * open stream which means the count can not go to 0 with
15003 	 * this decrement.
15004 	 */
15005 	ASSERT(osp->os_ref_count >= 2);
15006 	osp->os_ref_count--;
15007 	osp->os_valid = 0;
15008 	mutex_exit(&osp->os_sync_lock);
15009 	*have_lockp = 0;
15010 
15011 	nfs4_dec_state_ref_count(mi);
15012 }
15013 
15014 /*
15015  * Close all remaining open streams on the rnode.  These open streams
15016  * could be here because:
15017  * - The close attempted at either close or delmap failed
15018  * - Some kernel entity did VOP_OPEN but never did VOP_CLOSE
15019  * - Someone did mknod on a regular file but never opened it
15020  */
15021 int
nfs4close_all(vnode_t * vp,cred_t * cr)15022 nfs4close_all(vnode_t *vp, cred_t *cr)
15023 {
15024 	nfs4_open_stream_t *osp;
15025 	int error;
15026 	nfs4_error_t e = { 0, NFS4_OK, RPC_SUCCESS };
15027 	rnode4_t *rp;
15028 
15029 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
15030 
15031 	error = 0;
15032 	rp = VTOR4(vp);
15033 
15034 	/*
15035 	 * At this point, all we know is that the last time
15036 	 * someone called vn_rele, the count was 1.  Since then,
15037 	 * the vnode could have been re-activated.  We want to
15038 	 * loop through the open streams and close each one, but
15039 	 * we have to be careful since once we release the rnode
15040 	 * hash bucket lock, someone else is free to come in and
15041 	 * re-activate the rnode and add new open streams.  The
15042 	 * strategy is take the rnode hash bucket lock, verify that
15043 	 * the count is still 1, grab the open stream off the
15044 	 * head of the list and mark it invalid, then release the
15045 	 * rnode hash bucket lock and proceed with that open stream.
15046 	 * This is ok because nfs4close_one() will acquire the proper
15047 	 * open/create to close/destroy synchronization for open
15048 	 * streams, and will ensure that if someone has reopened
15049 	 * the open stream after we've dropped the hash bucket lock
15050 	 * then we'll just simply return without destroying the
15051 	 * open stream.
15052 	 * Repeat until the list is empty.
15053 	 */
15054 
15055 	for (;;) {
15056 
15057 		/* make sure vnode hasn't been reactivated */
15058 		rw_enter(&rp->r_hashq->r_lock, RW_READER);
15059 		mutex_enter(&vp->v_lock);
15060 		if (vp->v_count > 1) {
15061 			mutex_exit(&vp->v_lock);
15062 			rw_exit(&rp->r_hashq->r_lock);
15063 			break;
15064 		}
15065 		/*
15066 		 * Grabbing r_os_lock before releasing v_lock prevents
15067 		 * a window where the rnode/open stream could get
15068 		 * reactivated (and os_force_close set to 0) before we
15069 		 * had a chance to set os_force_close to 1.
15070 		 */
15071 		mutex_enter(&rp->r_os_lock);
15072 		mutex_exit(&vp->v_lock);
15073 
15074 		osp = list_head(&rp->r_open_streams);
15075 		if (!osp) {
15076 			/* nothing left to CLOSE OTW, so return */
15077 			mutex_exit(&rp->r_os_lock);
15078 			rw_exit(&rp->r_hashq->r_lock);
15079 			break;
15080 		}
15081 
15082 		mutex_enter(&rp->r_statev4_lock);
15083 		/* the file can't still be mem mapped */
15084 		ASSERT(rp->r_mapcnt == 0);
15085 		if (rp->created_v4)
15086 			rp->created_v4 = 0;
15087 		mutex_exit(&rp->r_statev4_lock);
15088 
15089 		/*
15090 		 * Grab a ref on this open stream; nfs4close_one
15091 		 * will mark it as invalid
15092 		 */
15093 		mutex_enter(&osp->os_sync_lock);
15094 		osp->os_ref_count++;
15095 		osp->os_force_close = 1;
15096 		mutex_exit(&osp->os_sync_lock);
15097 		mutex_exit(&rp->r_os_lock);
15098 		rw_exit(&rp->r_hashq->r_lock);
15099 
15100 		nfs4close_one(vp, osp, cr, 0, NULL, &e, CLOSE_FORCE, 0, 0, 0);
15101 
15102 		/* Update error if it isn't already non-zero */
15103 		if (error == 0) {
15104 			if (e.error)
15105 				error = e.error;
15106 			else if (e.stat)
15107 				error = geterrno4(e.stat);
15108 		}
15109 
15110 #ifdef	DEBUG
15111 		nfs4close_all_cnt++;
15112 #endif
15113 		/* Release the ref on osp acquired above. */
15114 		open_stream_rele(osp, rp);
15115 
15116 		/* Proceed to the next open stream, if any */
15117 	}
15118 	return (error);
15119 }
15120 
15121 /*
15122  * nfs4close_one - close one open stream for a file if needed.
15123  *
15124  * "close_type" indicates which close path this is:
15125  * CLOSE_NORM: close initiated via VOP_CLOSE.
15126  * CLOSE_DELMAP: close initiated via VOP_DELMAP.
15127  * CLOSE_FORCE: close initiated via VOP_INACTIVE.  This path forces
15128  *	the close and release of client state for this open stream
15129  *	(unless someone else has the open stream open).
15130  * CLOSE_RESEND: indicates the request is a replay of an earlier request
15131  *	(e.g., due to abort because of a signal).
15132  * CLOSE_AFTER_RESEND: close initiated to "undo" a successful resent OPEN.
15133  *
15134  * CLOSE_RESEND and CLOSE_AFTER_RESEND will not attempt to retry after client
15135  * recovery.  Instead, the caller is expected to deal with retries.
15136  *
15137  * The caller can either pass in the osp ('provided_osp') or not.
15138  *
15139  * 'access_bits' represents the access we are closing/downgrading.
15140  *
15141  * 'len', 'prot', and 'mmap_flags' are used for CLOSE_DELMAP.  'len' is the
15142  * number of bytes we are unmapping, 'maxprot' is the mmap protection, and
15143  * 'mmap_flags' tells us the type of sharing (MAP_PRIVATE or MAP_SHARED).
15144  *
15145  * Errors are returned via the nfs4_error_t.
15146  */
15147 void
nfs4close_one(vnode_t * vp,nfs4_open_stream_t * provided_osp,cred_t * cr,int access_bits,nfs4_lost_rqst_t * lrp,nfs4_error_t * ep,nfs4_close_type_t close_type,size_t len,uint_t maxprot,uint_t mmap_flags)15148 nfs4close_one(vnode_t *vp, nfs4_open_stream_t *provided_osp, cred_t *cr,
15149     int access_bits, nfs4_lost_rqst_t *lrp, nfs4_error_t *ep,
15150     nfs4_close_type_t close_type, size_t len, uint_t maxprot,
15151     uint_t mmap_flags)
15152 {
15153 	nfs4_open_owner_t *oop;
15154 	nfs4_open_stream_t *osp = NULL;
15155 	int retry = 0;
15156 	int num_retries = NFS4_NUM_RECOV_RETRIES;
15157 	rnode4_t *rp;
15158 	mntinfo4_t *mi;
15159 	nfs4_recov_state_t recov_state;
15160 	cred_t *cred_otw = NULL;
15161 	bool_t recovonly = FALSE;
15162 	int isrecov;
15163 	int force_close;
15164 	int close_failed = 0;
15165 	int did_dec_count = 0;
15166 	int did_start_op = 0;
15167 	int did_force_recovlock = 0;
15168 	int did_start_seqid_sync = 0;
15169 	int have_sync_lock = 0;
15170 
15171 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
15172 
15173 	NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE, "closing vp %p osp %p, "
15174 	    "lrp %p, close type %d len %ld prot %x mmap flags %x bits %x",
15175 	    (void *)vp, (void *)provided_osp, (void *)lrp, close_type,
15176 	    len, maxprot, mmap_flags, access_bits));
15177 
15178 	nfs4_error_zinit(ep);
15179 	rp = VTOR4(vp);
15180 	mi = VTOMI4(vp);
15181 	isrecov = (close_type == CLOSE_RESEND ||
15182 	    close_type == CLOSE_AFTER_RESEND);
15183 
15184 	/*
15185 	 * First get the open owner.
15186 	 */
15187 	if (!provided_osp) {
15188 		oop = find_open_owner(cr, NFS4_PERM_CREATED, mi);
15189 	} else {
15190 		oop = provided_osp->os_open_owner;
15191 		ASSERT(oop != NULL);
15192 		open_owner_hold(oop);
15193 	}
15194 
15195 	if (!oop) {
15196 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15197 		    "nfs4close_one: no oop, rp %p, mi %p, cr %p, osp %p, "
15198 		    "close type %d", (void *)rp, (void *)mi, (void *)cr,
15199 		    (void *)provided_osp, close_type));
15200 		ep->error = EIO;
15201 		goto out;
15202 	}
15203 
15204 	cred_otw = nfs4_get_otw_cred(cr, mi, oop);
15205 recov_retry:
15206 	osp = NULL;
15207 	close_failed = 0;
15208 	force_close = (close_type == CLOSE_FORCE);
15209 	retry = 0;
15210 	did_start_op = 0;
15211 	did_force_recovlock = 0;
15212 	did_start_seqid_sync = 0;
15213 	have_sync_lock = 0;
15214 	recovonly = FALSE;
15215 	recov_state.rs_flags = 0;
15216 	recov_state.rs_num_retry_despite_err = 0;
15217 
15218 	/*
15219 	 * Second synchronize with recovery.
15220 	 */
15221 	if (!isrecov) {
15222 		ep->error = nfs4_start_fop(mi, vp, NULL, OH_CLOSE,
15223 		    &recov_state, &recovonly);
15224 		if (!ep->error) {
15225 			did_start_op = 1;
15226 		} else {
15227 			close_failed = 1;
15228 			/*
15229 			 * If we couldn't get start_fop, but have to
15230 			 * cleanup state, then at least acquire the
15231 			 * mi_recovlock so we can synchronize with
15232 			 * recovery.
15233 			 */
15234 			if (close_type == CLOSE_FORCE) {
15235 				(void) nfs_rw_enter_sig(&mi->mi_recovlock,
15236 				    RW_READER, FALSE);
15237 				did_force_recovlock = 1;
15238 			} else
15239 				goto out;
15240 		}
15241 	}
15242 
15243 	/*
15244 	 * We cannot attempt to get the open seqid sync if nfs4_start_fop
15245 	 * set 'recovonly' to TRUE since most likely this is due to
15246 	 * reovery being active (MI4_RECOV_ACTIV).  If recovery is active,
15247 	 * nfs4_start_open_seqid_sync() will fail with EAGAIN asking us
15248 	 * to retry, causing us to loop until recovery finishes.  Plus we
15249 	 * don't need protection over the open seqid since we're not going
15250 	 * OTW, hence don't need to use the seqid.
15251 	 */
15252 	if (recovonly == FALSE) {
15253 		/* need to grab the open owner sync before 'os_sync_lock' */
15254 		ep->error = nfs4_start_open_seqid_sync(oop, mi);
15255 		if (ep->error == EAGAIN) {
15256 			ASSERT(!isrecov);
15257 			if (did_start_op)
15258 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15259 				    &recov_state, TRUE);
15260 			if (did_force_recovlock)
15261 				nfs_rw_exit(&mi->mi_recovlock);
15262 			goto recov_retry;
15263 		}
15264 		did_start_seqid_sync = 1;
15265 	}
15266 
15267 	/*
15268 	 * Third get an open stream and acquire 'os_sync_lock' to
15269 	 * sychronize the opening/creating of an open stream with the
15270 	 * closing/destroying of an open stream.
15271 	 */
15272 	if (!provided_osp) {
15273 		/* returns with 'os_sync_lock' held */
15274 		osp = find_open_stream(oop, rp);
15275 		if (!osp) {
15276 			ep->error = EIO;
15277 			goto out;
15278 		}
15279 	} else {
15280 		osp = provided_osp;
15281 		open_stream_hold(osp);
15282 		mutex_enter(&osp->os_sync_lock);
15283 	}
15284 	have_sync_lock = 1;
15285 
15286 	ASSERT(oop == osp->os_open_owner);
15287 
15288 	/*
15289 	 * Fourth, do any special pre-OTW CLOSE processing
15290 	 * based on the specific close type.
15291 	 */
15292 	if ((close_type == CLOSE_NORM || close_type == CLOSE_AFTER_RESEND) &&
15293 	    !did_dec_count) {
15294 		ASSERT(osp->os_open_ref_count > 0);
15295 		osp->os_open_ref_count--;
15296 		did_dec_count = 1;
15297 		if (osp->os_open_ref_count == 0)
15298 			osp->os_final_close = 1;
15299 	}
15300 
15301 	if (close_type == CLOSE_FORCE) {
15302 		/* see if somebody reopened the open stream. */
15303 		if (!osp->os_force_close) {
15304 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
15305 			    "nfs4close_one: skip CLOSE_FORCE as osp %p "
15306 			    "was reopened, vp %p", (void *)osp, (void *)vp));
15307 			ep->error = 0;
15308 			ep->stat = NFS4_OK;
15309 			goto out;
15310 		}
15311 
15312 		if (!osp->os_final_close && !did_dec_count) {
15313 			osp->os_open_ref_count--;
15314 			did_dec_count = 1;
15315 		}
15316 
15317 		/*
15318 		 * We can't depend on os_open_ref_count being 0 due to the
15319 		 * way executables are opened (VN_RELE to match a VOP_OPEN).
15320 		 */
15321 #ifdef	NOTYET
15322 		ASSERT(osp->os_open_ref_count == 0);
15323 #endif
15324 		if (osp->os_open_ref_count != 0) {
15325 			NFS4_DEBUG(nfs4close_one_debug, (CE_NOTE,
15326 			    "nfs4close_one: should panic here on an "
15327 			    "ASSERT(osp->os_open_ref_count == 0). Ignoring "
15328 			    "since this is probably the exec problem."));
15329 
15330 			osp->os_open_ref_count = 0;
15331 		}
15332 
15333 		/*
15334 		 * There is the possibility that nfs4close_one()
15335 		 * for close_type == CLOSE_DELMAP couldn't find the
15336 		 * open stream, thus couldn't decrement its os_mapcnt;
15337 		 * therefore we can't use this ASSERT yet.
15338 		 */
15339 #ifdef	NOTYET
15340 		ASSERT(osp->os_mapcnt == 0);
15341 #endif
15342 		osp->os_mapcnt = 0;
15343 	}
15344 
15345 	if (close_type == CLOSE_DELMAP && !did_dec_count) {
15346 		ASSERT(osp->os_mapcnt >= btopr(len));
15347 
15348 		if ((mmap_flags & MAP_SHARED) && (maxprot & PROT_WRITE))
15349 			osp->os_mmap_write -= btopr(len);
15350 		if (maxprot & PROT_READ)
15351 			osp->os_mmap_read -= btopr(len);
15352 		if (maxprot & PROT_EXEC)
15353 			osp->os_mmap_read -= btopr(len);
15354 		/* mirror the PROT_NONE check in nfs4_addmap() */
15355 		if (!(maxprot & PROT_READ) && !(maxprot & PROT_WRITE) &&
15356 		    !(maxprot & PROT_EXEC))
15357 			osp->os_mmap_read -= btopr(len);
15358 		osp->os_mapcnt -= btopr(len);
15359 		did_dec_count = 1;
15360 	}
15361 
15362 	if (recovonly) {
15363 		nfs4_lost_rqst_t lost_rqst;
15364 
15365 		/* request should not already be in recovery queue */
15366 		ASSERT(lrp == NULL);
15367 		nfs4_error_init(ep, EINTR);
15368 		nfs4close_save_lost_rqst(ep->error, &lost_rqst, oop,
15369 		    osp, cred_otw, vp);
15370 		mutex_exit(&osp->os_sync_lock);
15371 		have_sync_lock = 0;
15372 		(void) nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15373 		    lost_rqst.lr_op == OP_CLOSE ?
15374 		    &lost_rqst : NULL, OP_CLOSE, NULL, NULL, NULL);
15375 		close_failed = 1;
15376 		force_close = 0;
15377 		goto close_cleanup;
15378 	}
15379 
15380 	/*
15381 	 * If a previous OTW call got NFS4ERR_BAD_SEQID, then
15382 	 * we stopped operating on the open owner's <old oo_name, old seqid>
15383 	 * space, which means we stopped operating on the open stream
15384 	 * too.  So don't go OTW (as the seqid is likely bad, and the
15385 	 * stateid could be stale, potentially triggering a false
15386 	 * setclientid), and just clean up the client's internal state.
15387 	 */
15388 	if (osp->os_orig_oo_name != oop->oo_name) {
15389 		NFS4_DEBUG(nfs4close_one_debug || nfs4_client_recov_debug,
15390 		    (CE_NOTE, "nfs4close_one: skip OTW close for osp %p "
15391 		    "oop %p due to bad seqid (orig oo_name %" PRIx64 " current "
15392 		    "oo_name %" PRIx64")",
15393 		    (void *)osp, (void *)oop, osp->os_orig_oo_name,
15394 		    oop->oo_name));
15395 		close_failed = 1;
15396 	}
15397 
15398 	/* If the file failed recovery, just quit. */
15399 	mutex_enter(&rp->r_statelock);
15400 	if (rp->r_flags & R4RECOVERR) {
15401 		close_failed = 1;
15402 	}
15403 	mutex_exit(&rp->r_statelock);
15404 
15405 	/*
15406 	 * If the force close path failed to obtain start_fop
15407 	 * then skip the OTW close and just remove the state.
15408 	 */
15409 	if (close_failed)
15410 		goto close_cleanup;
15411 
15412 	/*
15413 	 * Fifth, check to see if there are still mapped pages or other
15414 	 * opens using this open stream.  If there are then we can't
15415 	 * close yet but we can see if an OPEN_DOWNGRADE is necessary.
15416 	 */
15417 	if (osp->os_open_ref_count > 0 || osp->os_mapcnt > 0) {
15418 		nfs4_lost_rqst_t	new_lost_rqst;
15419 		bool_t			needrecov = FALSE;
15420 		cred_t			*odg_cred_otw = NULL;
15421 		seqid4			open_dg_seqid = 0;
15422 
15423 		if (osp->os_delegation) {
15424 			/*
15425 			 * If this open stream was never OPENed OTW then we
15426 			 * surely can't DOWNGRADE it (especially since the
15427 			 * osp->open_stateid is really a delegation stateid
15428 			 * when os_delegation is 1).
15429 			 */
15430 			if (access_bits & FREAD)
15431 				osp->os_share_acc_read--;
15432 			if (access_bits & FWRITE)
15433 				osp->os_share_acc_write--;
15434 			osp->os_share_deny_none--;
15435 			nfs4_error_zinit(ep);
15436 			goto out;
15437 		}
15438 		nfs4_open_downgrade(access_bits, 0, oop, osp, vp, cr,
15439 		    lrp, ep, &odg_cred_otw, &open_dg_seqid);
15440 		needrecov = nfs4_needs_recovery(ep, TRUE, mi->mi_vfsp);
15441 		if (needrecov && !isrecov) {
15442 			bool_t abort;
15443 			nfs4_bseqid_entry_t *bsep = NULL;
15444 
15445 			if (!ep->error && ep->stat == NFS4ERR_BAD_SEQID)
15446 				bsep = nfs4_create_bseqid_entry(oop, NULL,
15447 				    vp, 0,
15448 				    lrp ? TAG_OPEN_DG_LOST : TAG_OPEN_DG,
15449 				    open_dg_seqid);
15450 
15451 			nfs4open_dg_save_lost_rqst(ep->error, &new_lost_rqst,
15452 			    oop, osp, odg_cred_otw, vp, access_bits, 0);
15453 			mutex_exit(&osp->os_sync_lock);
15454 			have_sync_lock = 0;
15455 			abort = nfs4_start_recovery(ep, mi, vp, NULL, NULL,
15456 			    new_lost_rqst.lr_op == OP_OPEN_DOWNGRADE ?
15457 			    &new_lost_rqst : NULL, OP_OPEN_DOWNGRADE,
15458 			    bsep, NULL, NULL);
15459 			if (odg_cred_otw)
15460 				crfree(odg_cred_otw);
15461 			if (bsep)
15462 				kmem_free(bsep, sizeof (*bsep));
15463 
15464 			if (abort == TRUE)
15465 				goto out;
15466 
15467 			if (did_start_seqid_sync) {
15468 				nfs4_end_open_seqid_sync(oop);
15469 				did_start_seqid_sync = 0;
15470 			}
15471 			open_stream_rele(osp, rp);
15472 
15473 			if (did_start_op)
15474 				nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15475 				    &recov_state, FALSE);
15476 			if (did_force_recovlock)
15477 				nfs_rw_exit(&mi->mi_recovlock);
15478 
15479 			goto recov_retry;
15480 		} else {
15481 			if (odg_cred_otw)
15482 				crfree(odg_cred_otw);
15483 		}
15484 		goto out;
15485 	}
15486 
15487 	/*
15488 	 * If this open stream was created as the results of an open
15489 	 * while holding a delegation, then just release it; no need
15490 	 * to do an OTW close.  Otherwise do a "normal" OTW close.
15491 	 */
15492 	if (osp->os_delegation) {
15493 		nfs4close_notw(vp, osp, &have_sync_lock);
15494 		nfs4_error_zinit(ep);
15495 		goto out;
15496 	}
15497 
15498 	/*
15499 	 * If this stream is not valid, we're done.
15500 	 */
15501 	if (!osp->os_valid) {
15502 		nfs4_error_zinit(ep);
15503 		goto out;
15504 	}
15505 
15506 	/*
15507 	 * Last open or mmap ref has vanished, need to do an OTW close.
15508 	 * First check to see if a close is still necessary.
15509 	 */
15510 	if (osp->os_failed_reopen) {
15511 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15512 		    "don't close OTW osp %p since reopen failed.",
15513 		    (void *)osp));
15514 		/*
15515 		 * Reopen of the open stream failed, hence the
15516 		 * stateid of the open stream is invalid/stale, and
15517 		 * sending this OTW would incorrectly cause another
15518 		 * round of recovery.  In this case, we need to set
15519 		 * the 'os_valid' bit to 0 so another thread doesn't
15520 		 * come in and re-open this open stream before
15521 		 * this "closing" thread cleans up state (decrementing
15522 		 * the nfs4_server_t's state_ref_count and decrementing
15523 		 * the os_ref_count).
15524 		 */
15525 		osp->os_valid = 0;
15526 		/*
15527 		 * This removes the reference obtained at OPEN; ie,
15528 		 * when the open stream structure was created.
15529 		 *
15530 		 * We don't have to worry about calling 'open_stream_rele'
15531 		 * since we our currently holding a reference to this
15532 		 * open stream which means the count can not go to 0 with
15533 		 * this decrement.
15534 		 */
15535 		ASSERT(osp->os_ref_count >= 2);
15536 		osp->os_ref_count--;
15537 		nfs4_error_zinit(ep);
15538 		close_failed = 0;
15539 		goto close_cleanup;
15540 	}
15541 
15542 	ASSERT(osp->os_ref_count > 1);
15543 
15544 	/*
15545 	 * Sixth, try the CLOSE OTW.
15546 	 */
15547 	nfs4close_otw(rp, cred_otw, oop, osp, &retry, &did_start_seqid_sync,
15548 	    close_type, ep, &have_sync_lock);
15549 
15550 	if (ep->error == EINTR || NFS4_FRC_UNMT_ERR(ep->error, vp->v_vfsp)) {
15551 		/*
15552 		 * Let the recovery thread be responsible for
15553 		 * removing the state for CLOSE.
15554 		 */
15555 		close_failed = 1;
15556 		force_close = 0;
15557 		retry = 0;
15558 	}
15559 
15560 	/* See if we need to retry with a different cred */
15561 	if ((ep->error == EACCES ||
15562 	    (ep->error == 0 && ep->stat == NFS4ERR_ACCESS)) &&
15563 	    cred_otw != cr) {
15564 		crfree(cred_otw);
15565 		cred_otw = cr;
15566 		crhold(cred_otw);
15567 		retry = 1;
15568 	}
15569 
15570 	if (ep->error || ep->stat)
15571 		close_failed = 1;
15572 
15573 	if (retry && !isrecov && num_retries-- > 0) {
15574 		if (have_sync_lock) {
15575 			mutex_exit(&osp->os_sync_lock);
15576 			have_sync_lock = 0;
15577 		}
15578 		if (did_start_seqid_sync) {
15579 			nfs4_end_open_seqid_sync(oop);
15580 			did_start_seqid_sync = 0;
15581 		}
15582 		open_stream_rele(osp, rp);
15583 
15584 		if (did_start_op)
15585 			nfs4_end_fop(mi, vp, NULL, OH_CLOSE,
15586 			    &recov_state, FALSE);
15587 		if (did_force_recovlock)
15588 			nfs_rw_exit(&mi->mi_recovlock);
15589 		NFS4_DEBUG(nfs4_client_recov_debug, (CE_NOTE,
15590 		    "nfs4close_one: need to retry the close "
15591 		    "operation"));
15592 		goto recov_retry;
15593 	}
15594 close_cleanup:
15595 	/*
15596 	 * Seventh and lastly, process our results.
15597 	 */
15598 	if (close_failed && force_close) {
15599 		/*
15600 		 * It's ok to drop and regrab the 'os_sync_lock' since
15601 		 * nfs4close_notw() will recheck to make sure the
15602 		 * "close"/removal of state should happen.
15603 		 */
15604 		if (!have_sync_lock) {
15605 			mutex_enter(&osp->os_sync_lock);
15606 			have_sync_lock = 1;
15607 		}
15608 		/*
15609 		 * This is last call, remove the ref on the open
15610 		 * stream created by open and clean everything up.
15611 		 */
15612 		osp->os_pending_close = 0;
15613 		nfs4close_notw(vp, osp, &have_sync_lock);
15614 		nfs4_error_zinit(ep);
15615 	}
15616 
15617 	if (!close_failed) {
15618 		if (have_sync_lock) {
15619 			osp->os_pending_close = 0;
15620 			mutex_exit(&osp->os_sync_lock);
15621 			have_sync_lock = 0;
15622 		} else {
15623 			mutex_enter(&osp->os_sync_lock);
15624 			osp->os_pending_close = 0;
15625 			mutex_exit(&osp->os_sync_lock);
15626 		}
15627 		if (did_start_op && recov_state.rs_sp != NULL) {
15628 			mutex_enter(&recov_state.rs_sp->s_lock);
15629 			nfs4_dec_state_ref_count_nolock(recov_state.rs_sp, mi);
15630 			mutex_exit(&recov_state.rs_sp->s_lock);
15631 		} else {
15632 			nfs4_dec_state_ref_count(mi);
15633 		}
15634 		nfs4_error_zinit(ep);
15635 	}
15636 
15637 out:
15638 	if (have_sync_lock)
15639 		mutex_exit(&osp->os_sync_lock);
15640 	if (did_start_op)
15641 		nfs4_end_fop(mi, vp, NULL, OH_CLOSE, &recov_state,
15642 		    recovonly ? TRUE : FALSE);
15643 	if (did_force_recovlock)
15644 		nfs_rw_exit(&mi->mi_recovlock);
15645 	if (cred_otw)
15646 		crfree(cred_otw);
15647 	if (osp)
15648 		open_stream_rele(osp, rp);
15649 	if (oop) {
15650 		if (did_start_seqid_sync)
15651 			nfs4_end_open_seqid_sync(oop);
15652 		open_owner_rele(oop);
15653 	}
15654 }
15655 
15656 /*
15657  * Convert information returned by the server in the LOCK4denied
15658  * structure to the form required by fcntl.
15659  */
15660 static void
denied_to_flk(LOCK4denied * lockt_denied,flock64_t * flk,LOCKT4args * lockt_args)15661 denied_to_flk(LOCK4denied *lockt_denied, flock64_t *flk, LOCKT4args *lockt_args)
15662 {
15663 	nfs4_lo_name_t *lo;
15664 
15665 #ifdef	DEBUG
15666 	if (denied_to_flk_debug) {
15667 		lockt_denied_debug = lockt_denied;
15668 		debug_enter("lockt_denied");
15669 	}
15670 #endif
15671 
15672 	flk->l_type = lockt_denied->locktype == READ_LT ? F_RDLCK : F_WRLCK;
15673 	flk->l_whence = 0;	/* aka SEEK_SET */
15674 	flk->l_start = lockt_denied->offset;
15675 	flk->l_len = lockt_denied->length;
15676 
15677 	/*
15678 	 * If the blocking clientid matches our client id, then we can
15679 	 * interpret the lockowner (since we built it).  If not, then
15680 	 * fabricate a sysid and pid.  Note that the l_sysid field
15681 	 * in *flk already has the local sysid.
15682 	 */
15683 
15684 	if (lockt_denied->owner.clientid == lockt_args->owner.clientid) {
15685 
15686 		if (lockt_denied->owner.owner_len == sizeof (*lo)) {
15687 			lo = (nfs4_lo_name_t *)
15688 			    lockt_denied->owner.owner_val;
15689 
15690 			flk->l_pid = lo->ln_pid;
15691 		} else {
15692 			NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15693 			    "denied_to_flk: bad lock owner length\n"));
15694 
15695 			flk->l_pid = lo_to_pid(&lockt_denied->owner);
15696 		}
15697 	} else {
15698 		NFS4_DEBUG(nfs4_client_lock_debug, (CE_NOTE,
15699 		"denied_to_flk: foreign clientid\n"));
15700 
15701 		/*
15702 		 * Construct a new sysid which should be different from
15703 		 * sysids of other systems.
15704 		 */
15705 
15706 		flk->l_sysid++;
15707 		flk->l_pid = lo_to_pid(&lockt_denied->owner);
15708 	}
15709 }
15710 
15711 static pid_t
lo_to_pid(lock_owner4 * lop)15712 lo_to_pid(lock_owner4 *lop)
15713 {
15714 	pid_t pid = 0;
15715 	uchar_t *cp;
15716 	int i;
15717 
15718 	cp = (uchar_t *)&lop->clientid;
15719 
15720 	for (i = 0; i < sizeof (lop->clientid); i++)
15721 		pid += (pid_t)*cp++;
15722 
15723 	cp = (uchar_t *)lop->owner_val;
15724 
15725 	for (i = 0; i < lop->owner_len; i++)
15726 		pid += (pid_t)*cp++;
15727 
15728 	return (pid);
15729 }
15730 
15731 /*
15732  * Given a lock pointer, returns the length of that lock.
15733  * "end" is the last locked offset the "l_len" covers from
15734  * the start of the lock.
15735  */
15736 static off64_t
lock_to_end(flock64_t * lock)15737 lock_to_end(flock64_t *lock)
15738 {
15739 	off64_t lock_end;
15740 
15741 	if (lock->l_len == 0)
15742 		lock_end = (off64_t)MAXEND;
15743 	else
15744 		lock_end = lock->l_start + lock->l_len - 1;
15745 
15746 	return (lock_end);
15747 }
15748 
15749 /*
15750  * Given the end of a lock, it will return you the length "l_len" for that lock.
15751  */
15752 static off64_t
end_to_len(off64_t start,off64_t end)15753 end_to_len(off64_t start, off64_t end)
15754 {
15755 	off64_t lock_len;
15756 
15757 	ASSERT(end >= start);
15758 	if (end == MAXEND)
15759 		lock_len = 0;
15760 	else
15761 		lock_len = end - start + 1;
15762 
15763 	return (lock_len);
15764 }
15765 
15766 /*
15767  * On given end for a lock it determines if it is the last locked offset
15768  * or not, if so keeps it as is, else adds one to return the length for
15769  * valid start.
15770  */
15771 static off64_t
start_check(off64_t x)15772 start_check(off64_t x)
15773 {
15774 	if (x == MAXEND)
15775 		return (x);
15776 	else
15777 		return (x + 1);
15778 }
15779 
15780 /*
15781  * See if these two locks overlap, and if so return 1;
15782  * otherwise, return 0.
15783  */
15784 static int
locks_intersect(flock64_t * llfp,flock64_t * curfp)15785 locks_intersect(flock64_t *llfp, flock64_t *curfp)
15786 {
15787 	off64_t llfp_end, curfp_end;
15788 
15789 	llfp_end = lock_to_end(llfp);
15790 	curfp_end = lock_to_end(curfp);
15791 
15792 	if (((llfp_end >= curfp->l_start) &&
15793 	    (llfp->l_start <= curfp->l_start)) ||
15794 	    ((curfp->l_start <= llfp->l_start) && (curfp_end >= llfp->l_start)))
15795 		return (1);
15796 	return (0);
15797 }
15798 
15799 /*
15800  * Determine what the intersecting lock region is, and add that to the
15801  * 'nl_llpp' locklist in increasing order (by l_start).
15802  */
15803 static void
nfs4_add_lock_range(flock64_t * lost_flp,flock64_t * local_flp,locklist_t ** nl_llpp,vnode_t * vp)15804 nfs4_add_lock_range(flock64_t *lost_flp, flock64_t *local_flp,
15805     locklist_t **nl_llpp, vnode_t *vp)
15806 {
15807 	locklist_t *intersect_llp, *tmp_fllp, *cur_fllp;
15808 	off64_t lost_flp_end, local_flp_end, len, start;
15809 
15810 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range:"));
15811 
15812 	if (!locks_intersect(lost_flp, local_flp))
15813 		return;
15814 
15815 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15816 	    "locks intersect"));
15817 
15818 	lost_flp_end = lock_to_end(lost_flp);
15819 	local_flp_end = lock_to_end(local_flp);
15820 
15821 	/* Find the starting point of the intersecting region */
15822 	if (local_flp->l_start > lost_flp->l_start)
15823 		start = local_flp->l_start;
15824 	else
15825 		start = lost_flp->l_start;
15826 
15827 	/* Find the lenght of the intersecting region */
15828 	if (lost_flp_end < local_flp_end)
15829 		len = end_to_len(start, lost_flp_end);
15830 	else
15831 		len = end_to_len(start, local_flp_end);
15832 
15833 	/*
15834 	 * Prepare the flock structure for the intersection found and insert
15835 	 * it into the new list in increasing l_start order. This list contains
15836 	 * intersections of locks registered by the client with the local host
15837 	 * and the lost lock.
15838 	 * The lock type of this lock is the same as that of the local_flp.
15839 	 */
15840 	intersect_llp = (locklist_t *)kmem_alloc(sizeof (locklist_t), KM_SLEEP);
15841 	intersect_llp->ll_flock.l_start = start;
15842 	intersect_llp->ll_flock.l_len = len;
15843 	intersect_llp->ll_flock.l_type = local_flp->l_type;
15844 	intersect_llp->ll_flock.l_pid = local_flp->l_pid;
15845 	intersect_llp->ll_flock.l_sysid = local_flp->l_sysid;
15846 	intersect_llp->ll_flock.l_whence = 0;	/* aka SEEK_SET */
15847 	intersect_llp->ll_vp = vp;
15848 
15849 	tmp_fllp = *nl_llpp;
15850 	cur_fllp = NULL;
15851 	while (tmp_fllp != NULL && tmp_fllp->ll_flock.l_start <
15852 	    intersect_llp->ll_flock.l_start) {
15853 			cur_fllp = tmp_fllp;
15854 			tmp_fllp = tmp_fllp->ll_next;
15855 	}
15856 	if (cur_fllp == NULL) {
15857 		/* first on the list */
15858 		intersect_llp->ll_next = *nl_llpp;
15859 		*nl_llpp = intersect_llp;
15860 	} else {
15861 		intersect_llp->ll_next = cur_fllp->ll_next;
15862 		cur_fllp->ll_next = intersect_llp;
15863 	}
15864 
15865 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE, "nfs4_add_lock_range: "
15866 	    "created lock region: start %"PRIx64" end %"PRIx64" : %s\n",
15867 	    intersect_llp->ll_flock.l_start,
15868 	    intersect_llp->ll_flock.l_start + intersect_llp->ll_flock.l_len,
15869 	    intersect_llp->ll_flock.l_type == F_RDLCK ? "READ" : "WRITE"));
15870 }
15871 
15872 /*
15873  * Our local locking current state is potentially different than
15874  * what the NFSv4 server thinks we have due to a lost lock that was
15875  * resent and then received.  We need to reset our "NFSv4" locking
15876  * state to match the current local locking state for this pid since
15877  * that is what the user/application sees as what the world is.
15878  *
15879  * We cannot afford to drop the open/lock seqid sync since then we can
15880  * get confused about what the current local locking state "is" versus
15881  * "was".
15882  *
15883  * If we are unable to fix up the locks, we send SIGLOST to the affected
15884  * process.  This is not done if the filesystem has been forcibly
15885  * unmounted, in case the process has already exited and a new process
15886  * exists with the same pid.
15887  */
15888 static void
nfs4_reinstitute_local_lock_state(vnode_t * vp,flock64_t * lost_flp,cred_t * cr,nfs4_lock_owner_t * lop)15889 nfs4_reinstitute_local_lock_state(vnode_t *vp, flock64_t *lost_flp, cred_t *cr,
15890     nfs4_lock_owner_t *lop)
15891 {
15892 	locklist_t *locks, *llp, *ri_llp, *tmp_llp;
15893 	mntinfo4_t *mi = VTOMI4(vp);
15894 	const int cmd = F_SETLK;
15895 	off64_t cur_start, llp_ll_flock_end, lost_flp_end;
15896 	flock64_t ul_fl;
15897 
15898 	NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15899 	    "nfs4_reinstitute_local_lock_state"));
15900 
15901 	/*
15902 	 * Find active locks for this vp from the local locking code.
15903 	 * Scan through this list and find out the locks that intersect with
15904 	 * the lost lock. Once we find the lock that intersects, add the
15905 	 * intersection area as a new lock to a new list "ri_llp". The lock
15906 	 * type of the intersection region lock added to ri_llp is the same
15907 	 * as that found in the active lock list, "list". The intersecting
15908 	 * region locks are added to ri_llp in increasing l_start order.
15909 	 */
15910 	ASSERT(nfs_zone() == mi->mi_zone);
15911 
15912 	locks = flk_active_locks_for_vp(vp);
15913 	ri_llp = NULL;
15914 
15915 	for (llp = locks; llp != NULL; llp = llp->ll_next) {
15916 		ASSERT(llp->ll_vp == vp);
15917 		/*
15918 		 * Pick locks that belong to this pid/lockowner
15919 		 */
15920 		if (llp->ll_flock.l_pid != lost_flp->l_pid)
15921 			continue;
15922 
15923 		nfs4_add_lock_range(lost_flp, &llp->ll_flock, &ri_llp, vp);
15924 	}
15925 
15926 	/*
15927 	 * Now we have the list of intersections with the lost lock. These are
15928 	 * the locks that were/are active before the server replied to the
15929 	 * last/lost lock. Issue these locks to the server here. Playing these
15930 	 * locks to the server will re-establish aur current local locking state
15931 	 * with the v4 server.
15932 	 * If we get an error, send SIGLOST to the application for that lock.
15933 	 */
15934 
15935 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15936 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15937 		    "nfs4_reinstitute_local_lock_state: need to issue "
15938 		    "flock: [%"PRIx64" - %"PRIx64"] : %s",
15939 		    llp->ll_flock.l_start,
15940 		    llp->ll_flock.l_start + llp->ll_flock.l_len,
15941 		    llp->ll_flock.l_type == F_RDLCK ? "READ" :
15942 		    llp->ll_flock.l_type == F_WRLCK ? "WRITE" : "INVALID"));
15943 		/*
15944 		 * No need to relock what we already have
15945 		 */
15946 		if (llp->ll_flock.l_type == lost_flp->l_type)
15947 			continue;
15948 
15949 		push_reinstate(vp, cmd, &llp->ll_flock, cr, lop);
15950 	}
15951 
15952 	/*
15953 	 * Now keeping the start of the lost lock as our reference parse the
15954 	 * newly created ri_llp locklist to find the ranges that we have locked
15955 	 * with the v4 server but not in the current local locking. We need
15956 	 * to unlock these ranges.
15957 	 * These ranges can also be reffered to as those ranges, where the lost
15958 	 * lock does not overlap with the locks in the ri_llp but are locked
15959 	 * since the server replied to the lost lock.
15960 	 */
15961 	cur_start = lost_flp->l_start;
15962 	lost_flp_end = lock_to_end(lost_flp);
15963 
15964 	ul_fl.l_type = F_UNLCK;
15965 	ul_fl.l_whence = 0;	/* aka SEEK_SET */
15966 	ul_fl.l_sysid = lost_flp->l_sysid;
15967 	ul_fl.l_pid = lost_flp->l_pid;
15968 
15969 	for (llp = ri_llp; llp != NULL; llp = llp->ll_next) {
15970 		llp_ll_flock_end = lock_to_end(&llp->ll_flock);
15971 
15972 		if (llp->ll_flock.l_start <= cur_start) {
15973 			cur_start = start_check(llp_ll_flock_end);
15974 			continue;
15975 		}
15976 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15977 		    "nfs4_reinstitute_local_lock_state: "
15978 		    "UNLOCK [%"PRIx64" - %"PRIx64"]",
15979 		    cur_start, llp->ll_flock.l_start));
15980 
15981 		ul_fl.l_start = cur_start;
15982 		ul_fl.l_len = end_to_len(cur_start,
15983 		    (llp->ll_flock.l_start - 1));
15984 
15985 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
15986 		cur_start = start_check(llp_ll_flock_end);
15987 	}
15988 
15989 	/*
15990 	 * In the case where the lost lock ends after all intersecting locks,
15991 	 * unlock the last part of the lost lock range.
15992 	 */
15993 	if (cur_start != start_check(lost_flp_end)) {
15994 		NFS4_DEBUG(nfs4_lost_rqst_debug, (CE_NOTE,
15995 		    "nfs4_reinstitute_local_lock_state: UNLOCK end of the "
15996 		    "lost lock region [%"PRIx64" - %"PRIx64"]",
15997 		    cur_start, lost_flp->l_start + lost_flp->l_len));
15998 
15999 		ul_fl.l_start = cur_start;
16000 		/*
16001 		 * Is it an to-EOF lock? if so unlock till the end
16002 		 */
16003 		if (lost_flp->l_len == 0)
16004 			ul_fl.l_len = 0;
16005 		else
16006 			ul_fl.l_len = start_check(lost_flp_end) - cur_start;
16007 
16008 		push_reinstate(vp, cmd, &ul_fl, cr, lop);
16009 	}
16010 
16011 	if (locks != NULL)
16012 		flk_free_locklist(locks);
16013 
16014 	/* Free up our newly created locklist */
16015 	for (llp = ri_llp; llp != NULL; ) {
16016 		tmp_llp = llp->ll_next;
16017 		kmem_free(llp, sizeof (locklist_t));
16018 		llp = tmp_llp;
16019 	}
16020 
16021 	/*
16022 	 * Now return back to the original calling nfs4frlock()
16023 	 * and let us naturally drop our seqid syncs.
16024 	 */
16025 }
16026 
16027 /*
16028  * Create a lost state record for the given lock reinstantiation request
16029  * and push it onto the lost state queue.
16030  */
16031 static void
push_reinstate(vnode_t * vp,int cmd,flock64_t * flk,cred_t * cr,nfs4_lock_owner_t * lop)16032 push_reinstate(vnode_t *vp, int cmd, flock64_t *flk, cred_t *cr,
16033     nfs4_lock_owner_t *lop)
16034 {
16035 	nfs4_lost_rqst_t req;
16036 	nfs_lock_type4 locktype;
16037 	nfs4_error_t e = { EINTR, NFS4_OK, RPC_SUCCESS };
16038 
16039 	ASSERT(nfs_zone() == VTOMI4(vp)->mi_zone);
16040 
16041 	locktype = flk_to_locktype(cmd, flk->l_type);
16042 	nfs4frlock_save_lost_rqst(NFS4_LCK_CTYPE_REINSTATE, EINTR, locktype,
16043 	    NULL, NULL, lop, flk, &req, cr, vp);
16044 	(void) nfs4_start_recovery(&e, VTOMI4(vp), vp, NULL, NULL,
16045 	    (req.lr_op == OP_LOCK || req.lr_op == OP_LOCKU) ?
16046 	    &req : NULL, flk->l_type == F_UNLCK ? OP_LOCKU : OP_LOCK,
16047 	    NULL, NULL, NULL);
16048 }
16049