xref: /freebsd/sys/contrib/openzfs/module/os/freebsd/zfs/zfs_vnops_os.c (revision d0b3ecdc274930e190ea233b6b69ff03782eaf8d)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * CDDL HEADER START
4  *
5  * The contents of this file are subject to the terms of the
6  * Common Development and Distribution License (the "License").
7  * You may not use this file except in compliance with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or https://opensource.org/licenses/CDDL-1.0.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 
23 /*
24  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
25  * Copyright (c) 2012, 2015 by Delphix. All rights reserved.
26  * Copyright (c) 2014 Integros [integros.com]
27  * Copyright 2017 Nexenta Systems, Inc.
28  * Copyright (c) 2025, Klara, Inc.
29  */
30 
31 /* Portions Copyright 2007 Jeremy Teo */
32 /* Portions Copyright 2010 Robert Milkowski */
33 
34 #include <sys/param.h>
35 #include <sys/time.h>
36 #include <sys/systm.h>
37 #include <sys/sysmacros.h>
38 #include <sys/resource.h>
39 #include <security/mac/mac_framework.h>
40 #include <sys/vfs.h>
41 #include <sys/endian.h>
42 #include <sys/vm.h>
43 #include <sys/vnode.h>
44 #include <sys/smr.h>
45 #include <sys/dirent.h>
46 #include <sys/file.h>
47 #include <sys/stat.h>
48 #include <sys/kmem.h>
49 #include <sys/taskq.h>
50 #include <sys/uio.h>
51 #include <sys/atomic.h>
52 #include <sys/namei.h>
53 #include <sys/mman.h>
54 #include <sys/cmn_err.h>
55 #include <sys/kdb.h>
56 #include <sys/sysproto.h>
57 #include <sys/errno.h>
58 #include <sys/unistd.h>
59 #include <sys/zfs_dir.h>
60 #include <sys/zfs_ioctl.h>
61 #include <sys/fs/zfs.h>
62 #include <sys/dmu.h>
63 #include <sys/dmu_objset.h>
64 #include <sys/dsl_dataset.h>
65 #include <sys/spa.h>
66 #include <sys/txg.h>
67 #include <sys/dbuf.h>
68 #include <sys/zap.h>
69 #include <sys/sa.h>
70 #include <sys/policy.h>
71 #include <sys/sunddi.h>
72 #include <sys/filio.h>
73 #include <sys/sid.h>
74 #include <sys/zfs_ctldir.h>
75 #include <sys/zfs_fuid.h>
76 #include <sys/zfs_quota.h>
77 #include <sys/zfs_sa.h>
78 #include <sys/zfs_rlock.h>
79 #include <sys/zfs_project.h>
80 #include <sys/bio.h>
81 #include <sys/buf.h>
82 #include <sys/sched.h>
83 #include <sys/acl.h>
84 #include <sys/vmmeter.h>
85 #include <vm/vm_param.h>
86 #include <sys/zil.h>
87 #include <sys/zfs_vnops.h>
88 #include <sys/module.h>
89 #include <sys/sysent.h>
90 #include <sys/dmu_impl.h>
91 #include <sys/brt.h>
92 #include <sys/zfeature.h>
93 
94 #include <vm/vm_object.h>
95 
96 #include <sys/extattr.h>
97 #include <sys/priv.h>
98 
99 #ifndef VN_OPEN_INVFS
100 #define	VN_OPEN_INVFS	0x0
101 #endif
102 
103 VFS_SMR_DECLARE;
104 
105 #if __FreeBSD_version >= 1400045
106 typedef uint64_t cookie_t;
107 #else
108 typedef ulong_t cookie_t;
109 #endif
110 
111 static int zfs_check_attrname(const char *name);
112 
113 /*
114  * Programming rules.
115  *
116  * Each vnode op performs some logical unit of work.  To do this, the ZPL must
117  * properly lock its in-core state, create a DMU transaction, do the work,
118  * record this work in the intent log (ZIL), commit the DMU transaction,
119  * and wait for the intent log to commit if it is a synchronous operation.
120  * Moreover, the vnode ops must work in both normal and log replay context.
121  * The ordering of events is important to avoid deadlocks and references
122  * to freed memory.  The example below illustrates the following Big Rules:
123  *
124  *  (1)	A check must be made in each zfs thread for a mounted file system.
125  *	This is done avoiding races using zfs_enter(zfsvfs).
126  *	A zfs_exit(zfsvfs) is needed before all returns.  Any znodes
127  *	must be checked with zfs_verify_zp(zp).  Both of these macros
128  *	can return EIO from the calling function.
129  *
130  *  (2)	VN_RELE() should always be the last thing except for zil_commit()
131  *	(if necessary) and zfs_exit(). This is for 3 reasons:
132  *	First, if it's the last reference, the vnode/znode
133  *	can be freed, so the zp may point to freed memory.  Second, the last
134  *	reference will call zfs_zinactive(), which may induce a lot of work --
135  *	pushing cached pages (which acquires range locks) and syncing out
136  *	cached atime changes.  Third, zfs_zinactive() may require a new tx,
137  *	which could deadlock the system if you were already holding one.
138  *	If you must call VN_RELE() within a tx then use VN_RELE_ASYNC().
139  *
140  *  (3)	All range locks must be grabbed before calling dmu_tx_assign(),
141  *	as they can span dmu_tx_assign() calls.
142  *
143  *  (4) If ZPL locks are held, pass DMU_TX_NOWAIT as the second argument to
144  *      dmu_tx_assign().  This is critical because we don't want to block
145  *      while holding locks.
146  *
147  *	If no ZPL locks are held (aside from zfs_enter()), use DMU_TX_WAIT.
148  *	This reduces lock contention and CPU usage when we must wait (note
149  *	that if throughput is constrained by the storage, nearly every
150  *	transaction must wait).
151  *
152  *      Note, in particular, that if a lock is sometimes acquired before
153  *      the tx assigns, and sometimes after (e.g. z_lock), then failing
154  *      to use a non-blocking assign can deadlock the system.  The scenario:
155  *
156  *	Thread A has grabbed a lock before calling dmu_tx_assign().
157  *	Thread B is in an already-assigned tx, and blocks for this lock.
158  *	Thread A calls dmu_tx_assign(DMU_TX_WAIT) and blocks in
159  *	txg_wait_open() forever, because the previous txg can't quiesce
160  *	until B's tx commits.
161  *
162  *	If dmu_tx_assign() returns ERESTART and zfsvfs->z_assign is
163  *	DMU_TX_NOWAIT, then drop all locks, call dmu_tx_wait(), and try
164  *	again.  On subsequent calls to dmu_tx_assign(), pass
165  *	DMU_TX_NOTHROTTLE in addition to DMU_TX_NOWAIT, to indicate that
166  *	this operation has already called dmu_tx_wait().  This will ensure
167  *	that we don't retry forever, waiting a short bit each time.
168  *
169  *  (5)	If the operation succeeded, generate the intent log entry for it
170  *	before dropping locks.  This ensures that the ordering of events
171  *	in the intent log matches the order in which they actually occurred.
172  *	During ZIL replay the zfs_log_* functions will update the sequence
173  *	number to indicate the zil transaction has replayed.
174  *
175  *  (6)	At the end of each vnode op, the DMU tx must always commit,
176  *	regardless of whether there were any errors.
177  *
178  *  (7)	After dropping all locks, invoke zil_commit(zilog, foid)
179  *	to ensure that synchronous semantics are provided when necessary.
180  *
181  * In general, this is how things should be ordered in each vnode op:
182  *
183  *	zfs_enter(zfsvfs);		// exit if unmounted
184  * top:
185  *	zfs_dirent_lookup(&dl, ...)	// lock directory entry (may VN_HOLD())
186  *	rw_enter(...);			// grab any other locks you need
187  *	tx = dmu_tx_create(...);	// get DMU tx
188  *	dmu_tx_hold_*();		// hold each object you might modify
189  *	error = dmu_tx_assign(tx,
190  *	    (waited ? DMU_TX_NOTHROTTLE : 0) | DMU_TX_NOWAIT);
191  *	if (error) {
192  *		rw_exit(...);		// drop locks
193  *		zfs_dirent_unlock(dl);	// unlock directory entry
194  *		VN_RELE(...);		// release held vnodes
195  *		if (error == ERESTART) {
196  *			waited = B_TRUE;
197  *			dmu_tx_wait(tx);
198  *			dmu_tx_abort(tx);
199  *			goto top;
200  *		}
201  *		dmu_tx_abort(tx);	// abort DMU tx
202  *		zfs_exit(zfsvfs);	// finished in zfs
203  *		return (error);		// really out of space
204  *	}
205  *	error = do_real_work();		// do whatever this VOP does
206  *	if (error == 0)
207  *		zfs_log_*(...);		// on success, make ZIL entry
208  *	dmu_tx_commit(tx);		// commit DMU tx -- error or not
209  *	rw_exit(...);			// drop locks
210  *	zfs_dirent_unlock(dl);		// unlock directory entry
211  *	VN_RELE(...);			// release held vnodes
212  *	zil_commit(zilog, foid);	// synchronous when necessary
213  *	zfs_exit(zfsvfs);		// finished in zfs
214  *	return (error);			// done, report error
215  */
216 static int
zfs_open(vnode_t ** vpp,int flag,cred_t * cr)217 zfs_open(vnode_t **vpp, int flag, cred_t *cr)
218 {
219 	(void) cr;
220 	znode_t	*zp = VTOZ(*vpp);
221 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
222 	int error;
223 
224 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
225 		return (error);
226 
227 	if ((flag & FWRITE) && (zp->z_pflags & ZFS_APPENDONLY) &&
228 	    ((flag & FAPPEND) == 0)) {
229 		zfs_exit(zfsvfs, FTAG);
230 		return (SET_ERROR(EPERM));
231 	}
232 
233 	/*
234 	 * Keep a count of the synchronous opens in the znode.  On first
235 	 * synchronous open we must convert all previous async transactions
236 	 * into sync to keep correct ordering.
237 	 * Skip it for snapshot, as it won't have any transactions.
238 	 */
239 	if (!zfsvfs->z_issnap && (flag & O_SYNC)) {
240 		if (atomic_inc_32_nv(&zp->z_sync_cnt) == 1)
241 			zil_async_to_sync(zfsvfs->z_log, zp->z_id);
242 	}
243 
244 	zfs_exit(zfsvfs, FTAG);
245 	return (0);
246 }
247 
248 static int
zfs_close(vnode_t * vp,int flag,int count,offset_t offset,cred_t * cr)249 zfs_close(vnode_t *vp, int flag, int count, offset_t offset, cred_t *cr)
250 {
251 	(void) offset, (void) cr;
252 	znode_t	*zp = VTOZ(vp);
253 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
254 	int error;
255 
256 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
257 		return (error);
258 
259 	/* Decrement the synchronous opens in the znode */
260 	if (!zfsvfs->z_issnap && (flag & O_SYNC) && (count == 1))
261 		atomic_dec_32(&zp->z_sync_cnt);
262 
263 	zfs_exit(zfsvfs, FTAG);
264 	return (0);
265 }
266 
267 static int
zfs_ioctl_getxattr(vnode_t * vp,zfsxattr_t * fsx)268 zfs_ioctl_getxattr(vnode_t *vp, zfsxattr_t *fsx)
269 {
270 	znode_t *zp = VTOZ(vp);
271 
272 	memset(fsx, 0, sizeof (*fsx));
273 	fsx->fsx_xflags = (zp->z_pflags & ZFS_PROJINHERIT) ?
274 	    FS_PROJINHERIT_FL : 0;
275 	fsx->fsx_projid = zp->z_projid;
276 
277 	return (0);
278 }
279 
280 static int
zfs_ioctl_setflags(vnode_t * vp,uint32_t ioctl_flags,xvattr_t * xva)281 zfs_ioctl_setflags(vnode_t *vp, uint32_t ioctl_flags, xvattr_t *xva)
282 {
283 	uint64_t zfs_flags = VTOZ(vp)->z_pflags;
284 	xoptattr_t *xoap;
285 
286 	if (ioctl_flags & ~(FS_PROJINHERIT_FL))
287 		return (SET_ERROR(EOPNOTSUPP));
288 
289 	xva_init(xva);
290 	xoap = xva_getxoptattr(xva);
291 
292 #define	FLAG_CHANGE(iflag, zflag, xflag, xfield)	do {		\
293 	if (((ioctl_flags & (iflag)) && !(zfs_flags & (zflag))) ||	\
294 	    ((zfs_flags & (zflag)) && !(ioctl_flags & (iflag)))) {	\
295 		XVA_SET_REQ(xva, (xflag));				\
296 		(xfield) = ((ioctl_flags & (iflag)) != 0);		\
297 	}								\
298 } while (0)
299 
300 	FLAG_CHANGE(FS_PROJINHERIT_FL, ZFS_PROJINHERIT, XAT_PROJINHERIT,
301 	    xoap->xoa_projinherit);
302 
303 #undef	FLAG_CHANGE
304 
305 	return (0);
306 }
307 
308 static int
zfs_ioctl_setxattr(vnode_t * vp,zfsxattr_t * fsx,cred_t * cr)309 zfs_ioctl_setxattr(vnode_t *vp, zfsxattr_t *fsx, cred_t *cr)
310 {
311 	znode_t *zp = VTOZ(vp);
312 	xvattr_t xva;
313 	xoptattr_t *xoap;
314 	int err;
315 
316 	if (!zpl_is_valid_projid(fsx->fsx_projid))
317 		return (SET_ERROR(EINVAL));
318 
319 	err = zfs_ioctl_setflags(vp, fsx->fsx_xflags, &xva);
320 	if (err)
321 		return (err);
322 
323 	xoap = xva_getxoptattr(&xva);
324 	XVA_SET_REQ(&xva, XAT_PROJID);
325 	xoap->xoa_projid = fsx->fsx_projid;
326 
327 	err = zfs_setattr(zp, (vattr_t *)&xva, 0, cr, NULL);
328 
329 	return (err);
330 }
331 
332 static int
zfs_ioctl(vnode_t * vp,ulong_t com,intptr_t data,int flag,cred_t * cred,int * rvalp)333 zfs_ioctl(vnode_t *vp, ulong_t com, intptr_t data, int flag, cred_t *cred,
334     int *rvalp)
335 {
336 	(void) flag, (void) cred, (void) rvalp;
337 	loff_t off;
338 	int error;
339 
340 	switch (com) {
341 	case _FIOFFS:
342 	{
343 		return (0);
344 
345 		/*
346 		 * The following two ioctls are used by bfu.  Faking out,
347 		 * necessary to avoid bfu errors.
348 		 */
349 	}
350 	case _FIOGDIO:
351 	case _FIOSDIO:
352 	{
353 		return (0);
354 	}
355 
356 	case F_SEEK_DATA:
357 	case F_SEEK_HOLE:
358 	{
359 		off = *(offset_t *)data;
360 		error = vn_lock(vp, LK_SHARED);
361 		if (error)
362 			return (error);
363 		/* offset parameter is in/out */
364 		error = zfs_holey(VTOZ(vp), com, &off);
365 		VOP_UNLOCK(vp);
366 		if (error)
367 			return (error);
368 		*(offset_t *)data = off;
369 		return (0);
370 	}
371 	case ZFS_IOC_FSGETXATTR: {
372 		zfsxattr_t *fsx = (zfsxattr_t *)data;
373 		error = vn_lock(vp, LK_SHARED);
374 		if (error)
375 			return (error);
376 		error = zfs_ioctl_getxattr(vp, fsx);
377 		VOP_UNLOCK(vp);
378 		return (error);
379 	}
380 	case ZFS_IOC_FSSETXATTR: {
381 		zfsxattr_t *fsx = (zfsxattr_t *)data;
382 		error = vn_lock(vp, LK_EXCLUSIVE);
383 		if (error)
384 			return (error);
385 		vn_seqc_write_begin(vp);
386 		error = zfs_ioctl_setxattr(vp, fsx, cred);
387 		vn_seqc_write_end(vp);
388 		VOP_UNLOCK(vp);
389 		return (error);
390 	}
391 	case ZFS_IOC_REWRITE: {
392 		zfs_rewrite_args_t *args = (zfs_rewrite_args_t *)data;
393 		if ((flag & FWRITE) == 0)
394 			return (SET_ERROR(EBADF));
395 		error = vn_lock(vp, LK_SHARED);
396 		if (error)
397 			return (error);
398 		error = zfs_rewrite(VTOZ(vp), args->off, args->len,
399 		    args->flags, args->arg);
400 		VOP_UNLOCK(vp);
401 		return (error);
402 	}
403 	}
404 	return (SET_ERROR(ENOTTY));
405 }
406 
407 static vm_page_t
page_busy(vnode_t * vp,int64_t start,int64_t off,int64_t nbytes)408 page_busy(vnode_t *vp, int64_t start, int64_t off, int64_t nbytes)
409 {
410 	vm_object_t obj;
411 	vm_page_t pp;
412 	int64_t end;
413 
414 	/*
415 	 * At present vm_page_clear_dirty extends the cleared range to DEV_BSIZE
416 	 * aligned boundaries, if the range is not aligned.  As a result a
417 	 * DEV_BSIZE subrange with partially dirty data may get marked as clean.
418 	 * It may happen that all DEV_BSIZE subranges are marked clean and thus
419 	 * the whole page would be considered clean despite have some
420 	 * dirty data.
421 	 * For this reason we should shrink the range to DEV_BSIZE aligned
422 	 * boundaries before calling vm_page_clear_dirty.
423 	 */
424 	end = rounddown2(off + nbytes, DEV_BSIZE);
425 	off = roundup2(off, DEV_BSIZE);
426 	nbytes = end - off;
427 
428 	obj = vp->v_object;
429 	vm_page_grab_valid_unlocked(&pp, obj, OFF_TO_IDX(start),
430 	    VM_ALLOC_NOCREAT | VM_ALLOC_SBUSY | VM_ALLOC_NORMAL |
431 	    VM_ALLOC_IGN_SBUSY);
432 	if (pp != NULL) {
433 		ASSERT3U(pp->valid, ==, VM_PAGE_BITS_ALL);
434 		vm_object_pip_add(obj, 1);
435 		pmap_remove_write(pp);
436 		if (nbytes != 0)
437 			vm_page_clear_dirty(pp, off, nbytes);
438 	}
439 	return (pp);
440 }
441 
442 static void
page_unbusy(vm_page_t pp)443 page_unbusy(vm_page_t pp)
444 {
445 
446 	vm_page_sunbusy(pp);
447 	vm_object_pip_wakeup(pp->object);
448 }
449 
450 static vm_page_t
page_hold(vnode_t * vp,int64_t start)451 page_hold(vnode_t *vp, int64_t start)
452 {
453 	vm_object_t obj;
454 	vm_page_t m;
455 
456 	obj = vp->v_object;
457 	vm_page_grab_valid_unlocked(&m, obj, OFF_TO_IDX(start),
458 	    VM_ALLOC_NOCREAT | VM_ALLOC_WIRED | VM_ALLOC_IGN_SBUSY |
459 	    VM_ALLOC_NOBUSY);
460 	return (m);
461 }
462 
463 static void
page_unhold(vm_page_t pp)464 page_unhold(vm_page_t pp)
465 {
466 	vm_page_unwire(pp, PQ_ACTIVE);
467 }
468 
469 /*
470  * When a file is memory mapped, we must keep the IO data synchronized
471  * between the DMU cache and the memory mapped pages.  What this means:
472  *
473  * On Write:	If we find a memory mapped page, we write to *both*
474  *		the page and the dmu buffer.
475  */
476 void
update_pages(znode_t * zp,int64_t start,int len,objset_t * os)477 update_pages(znode_t *zp, int64_t start, int len, objset_t *os)
478 {
479 	vm_object_t obj;
480 	struct sf_buf *sf;
481 	vnode_t *vp = ZTOV(zp);
482 	caddr_t va;
483 	int off;
484 
485 	ASSERT3P(vp->v_mount, !=, NULL);
486 	obj = vp->v_object;
487 	ASSERT3P(obj, !=, NULL);
488 
489 	off = start & PAGEOFFSET;
490 	vm_object_pip_add(obj, 1);
491 	for (start &= PAGEMASK; len > 0; start += PAGESIZE) {
492 		vm_page_t pp;
493 		int nbytes = imin(PAGESIZE - off, len);
494 
495 		if ((pp = page_busy(vp, start, off, nbytes)) != NULL) {
496 			va = zfs_map_page(pp, &sf);
497 			(void) dmu_read(os, zp->z_id, start + off, nbytes,
498 			    va + off, DMU_READ_PREFETCH);
499 			zfs_unmap_page(sf);
500 			page_unbusy(pp);
501 		}
502 		len -= nbytes;
503 		off = 0;
504 	}
505 	vm_object_pip_wakeup(obj);
506 }
507 
508 /*
509  * Read with UIO_NOCOPY flag means that sendfile(2) requests
510  * ZFS to populate a range of page cache pages with data.
511  *
512  * NOTE: this function could be optimized to pre-allocate
513  * all pages in advance, drain exclusive busy on all of them,
514  * map them into contiguous KVA region and populate them
515  * in one single dmu_read() call.
516  */
517 int
mappedread_sf(znode_t * zp,int nbytes,zfs_uio_t * uio)518 mappedread_sf(znode_t *zp, int nbytes, zfs_uio_t *uio)
519 {
520 	vnode_t *vp = ZTOV(zp);
521 	objset_t *os = zp->z_zfsvfs->z_os;
522 	struct sf_buf *sf;
523 	vm_object_t obj;
524 	vm_page_t pp;
525 	int64_t start;
526 	caddr_t va;
527 	int len = nbytes;
528 	int error = 0;
529 
530 	ASSERT3U(zfs_uio_segflg(uio), ==, UIO_NOCOPY);
531 	ASSERT3P(vp->v_mount, !=, NULL);
532 	obj = vp->v_object;
533 	ASSERT3P(obj, !=, NULL);
534 	ASSERT0(zfs_uio_offset(uio) & PAGEOFFSET);
535 
536 	for (start = zfs_uio_offset(uio); len > 0; start += PAGESIZE) {
537 		int bytes = MIN(PAGESIZE, len);
538 
539 		pp = vm_page_grab_unlocked(obj, OFF_TO_IDX(start),
540 		    VM_ALLOC_SBUSY | VM_ALLOC_NORMAL | VM_ALLOC_IGN_SBUSY);
541 		if (vm_page_none_valid(pp)) {
542 			va = zfs_map_page(pp, &sf);
543 			error = dmu_read(os, zp->z_id, start, bytes, va,
544 			    DMU_READ_PREFETCH);
545 			if (bytes != PAGESIZE && error == 0)
546 				memset(va + bytes, 0, PAGESIZE - bytes);
547 			zfs_unmap_page(sf);
548 			if (error == 0) {
549 				vm_page_valid(pp);
550 				vm_page_activate(pp);
551 				vm_page_sunbusy(pp);
552 			} else {
553 				zfs_vmobject_wlock(obj);
554 				if (!vm_page_wired(pp) && pp->valid == 0 &&
555 				    vm_page_busy_tryupgrade(pp))
556 					vm_page_free(pp);
557 				else {
558 					vm_page_deactivate_noreuse(pp);
559 					vm_page_sunbusy(pp);
560 				}
561 				zfs_vmobject_wunlock(obj);
562 			}
563 		} else {
564 			ASSERT3U(pp->valid, ==, VM_PAGE_BITS_ALL);
565 			vm_page_sunbusy(pp);
566 		}
567 		if (error)
568 			break;
569 		zfs_uio_advance(uio, bytes);
570 		len -= bytes;
571 	}
572 	return (error);
573 }
574 
575 /*
576  * When a file is memory mapped, we must keep the IO data synchronized
577  * between the DMU cache and the memory mapped pages.  What this means:
578  *
579  * On Read:	We "read" preferentially from memory mapped pages,
580  *		else we default from the dmu buffer.
581  *
582  * NOTE: We will always "break up" the IO into PAGESIZE uiomoves when
583  *	 the file is memory mapped.
584  */
585 int
mappedread(znode_t * zp,int nbytes,zfs_uio_t * uio)586 mappedread(znode_t *zp, int nbytes, zfs_uio_t *uio)
587 {
588 	vnode_t *vp = ZTOV(zp);
589 	vm_object_t obj;
590 	int64_t start;
591 	int len = nbytes;
592 	int off;
593 	int error = 0;
594 
595 	ASSERT3P(vp->v_mount, !=, NULL);
596 	obj = vp->v_object;
597 	ASSERT3P(obj, !=, NULL);
598 
599 	start = zfs_uio_offset(uio);
600 	off = start & PAGEOFFSET;
601 	for (start &= PAGEMASK; len > 0; start += PAGESIZE) {
602 		vm_page_t pp;
603 		uint64_t bytes = MIN(PAGESIZE - off, len);
604 
605 		if ((pp = page_hold(vp, start))) {
606 			struct sf_buf *sf;
607 			caddr_t va;
608 
609 			va = zfs_map_page(pp, &sf);
610 			error = vn_io_fault_uiomove(va + off, bytes,
611 			    GET_UIO_STRUCT(uio));
612 			zfs_unmap_page(sf);
613 			page_unhold(pp);
614 		} else {
615 			error = dmu_read_uio_dbuf(sa_get_db(zp->z_sa_hdl),
616 			    uio, bytes, DMU_READ_PREFETCH);
617 		}
618 		len -= bytes;
619 		off = 0;
620 		if (error)
621 			break;
622 	}
623 	return (error);
624 }
625 
626 int
zfs_write_simple(znode_t * zp,const void * data,size_t len,loff_t pos,size_t * presid)627 zfs_write_simple(znode_t *zp, const void *data, size_t len,
628     loff_t pos, size_t *presid)
629 {
630 	int error = 0;
631 	ssize_t resid;
632 
633 	error = vn_rdwr(UIO_WRITE, ZTOV(zp), __DECONST(void *, data), len, pos,
634 	    UIO_SYSSPACE, IO_SYNC, kcred, NOCRED, &resid, curthread);
635 
636 	if (error) {
637 		return (SET_ERROR(error));
638 	} else if (presid == NULL) {
639 		if (resid != 0) {
640 			error = SET_ERROR(EIO);
641 		}
642 	} else {
643 		*presid = resid;
644 	}
645 	return (error);
646 }
647 
648 void
zfs_zrele_async(znode_t * zp)649 zfs_zrele_async(znode_t *zp)
650 {
651 	vnode_t *vp = ZTOV(zp);
652 	objset_t *os = ITOZSB(vp)->z_os;
653 
654 	VN_RELE_ASYNC(vp, dsl_pool_zrele_taskq(dmu_objset_pool(os)));
655 }
656 
657 static int
zfs_dd_callback(struct mount * mp,void * arg,int lkflags,struct vnode ** vpp)658 zfs_dd_callback(struct mount *mp, void *arg, int lkflags, struct vnode **vpp)
659 {
660 	int error;
661 
662 	*vpp = arg;
663 	error = vn_lock(*vpp, lkflags);
664 	if (error != 0)
665 		vrele(*vpp);
666 	return (error);
667 }
668 
669 static int
zfs_lookup_lock(vnode_t * dvp,vnode_t * vp,const char * name,int lkflags)670 zfs_lookup_lock(vnode_t *dvp, vnode_t *vp, const char *name, int lkflags)
671 {
672 	znode_t *zdp = VTOZ(dvp);
673 	zfsvfs_t *zfsvfs __unused = zdp->z_zfsvfs;
674 	int error;
675 	int ltype;
676 
677 	if (zfsvfs->z_replay == B_FALSE)
678 		ASSERT_VOP_LOCKED(dvp, __func__);
679 
680 	if (name[0] == 0 || (name[0] == '.' && name[1] == 0)) {
681 		ASSERT3P(dvp, ==, vp);
682 		vref(dvp);
683 		ltype = lkflags & LK_TYPE_MASK;
684 		if (ltype != VOP_ISLOCKED(dvp)) {
685 			if (ltype == LK_EXCLUSIVE)
686 				vn_lock(dvp, LK_UPGRADE | LK_RETRY);
687 			else /* if (ltype == LK_SHARED) */
688 				vn_lock(dvp, LK_DOWNGRADE | LK_RETRY);
689 
690 			/*
691 			 * Relock for the "." case could leave us with
692 			 * reclaimed vnode.
693 			 */
694 			if (VN_IS_DOOMED(dvp)) {
695 				vrele(dvp);
696 				return (SET_ERROR(ENOENT));
697 			}
698 		}
699 		return (0);
700 	} else if (name[0] == '.' && name[1] == '.' && name[2] == 0) {
701 		/*
702 		 * Note that in this case, dvp is the child vnode, and we
703 		 * are looking up the parent vnode - exactly reverse from
704 		 * normal operation.  Unlocking dvp requires some rather
705 		 * tricky unlock/relock dance to prevent mp from being freed;
706 		 * use vn_vget_ino_gen() which takes care of all that.
707 		 *
708 		 * XXX Note that there is a time window when both vnodes are
709 		 * unlocked.  It is possible, although highly unlikely, that
710 		 * during that window the parent-child relationship between
711 		 * the vnodes may change, for example, get reversed.
712 		 * In that case we would have a wrong lock order for the vnodes.
713 		 * All other filesystems seem to ignore this problem, so we
714 		 * do the same here.
715 		 * A potential solution could be implemented as follows:
716 		 * - using LK_NOWAIT when locking the second vnode and retrying
717 		 *   if necessary
718 		 * - checking that the parent-child relationship still holds
719 		 *   after locking both vnodes and retrying if it doesn't
720 		 */
721 		error = vn_vget_ino_gen(dvp, zfs_dd_callback, vp, lkflags, &vp);
722 		return (error);
723 	} else {
724 		error = vn_lock(vp, lkflags);
725 		if (error != 0)
726 			vrele(vp);
727 		return (error);
728 	}
729 }
730 
731 /*
732  * Lookup an entry in a directory, or an extended attribute directory.
733  * If it exists, return a held vnode reference for it.
734  *
735  *	IN:	dvp	- vnode of directory to search.
736  *		nm	- name of entry to lookup.
737  *		pnp	- full pathname to lookup [UNUSED].
738  *		flags	- LOOKUP_XATTR set if looking for an attribute.
739  *		rdir	- root directory vnode [UNUSED].
740  *		cr	- credentials of caller.
741  *		ct	- caller context
742  *
743  *	OUT:	vpp	- vnode of located entry, NULL if not found.
744  *
745  *	RETURN:	0 on success, error code on failure.
746  *
747  * Timestamps:
748  *	NA
749  */
750 static int
zfs_lookup(vnode_t * dvp,const char * nm,vnode_t ** vpp,struct componentname * cnp,int nameiop,cred_t * cr,int flags,boolean_t cached)751 zfs_lookup(vnode_t *dvp, const char *nm, vnode_t **vpp,
752     struct componentname *cnp, int nameiop, cred_t *cr, int flags,
753     boolean_t cached)
754 {
755 	znode_t *zdp = VTOZ(dvp);
756 	znode_t *zp;
757 	zfsvfs_t *zfsvfs = zdp->z_zfsvfs;
758 	seqc_t dvp_seqc;
759 	int	error = 0;
760 
761 	/*
762 	 * Fast path lookup, however we must skip DNLC lookup
763 	 * for case folding or normalizing lookups because the
764 	 * DNLC code only stores the passed in name.  This means
765 	 * creating 'a' and removing 'A' on a case insensitive
766 	 * file system would work, but DNLC still thinks 'a'
767 	 * exists and won't let you create it again on the next
768 	 * pass through fast path.
769 	 */
770 	if (!(flags & LOOKUP_XATTR)) {
771 		if (dvp->v_type != VDIR) {
772 			return (SET_ERROR(ENOTDIR));
773 		} else if (zdp->z_sa_hdl == NULL) {
774 			return (SET_ERROR(EIO));
775 		}
776 	}
777 
778 	DTRACE_PROBE2(zfs__fastpath__lookup__miss, vnode_t *, dvp,
779 	    const char *, nm);
780 
781 	if ((error = zfs_enter_verify_zp(zfsvfs, zdp, FTAG)) != 0)
782 		return (error);
783 
784 	dvp_seqc = vn_seqc_read_notmodify(dvp);
785 
786 	*vpp = NULL;
787 
788 	if (flags & LOOKUP_XATTR) {
789 		/*
790 		 * If the xattr property is off, refuse the lookup request.
791 		 */
792 		if (!(zfsvfs->z_flags & ZSB_XATTR)) {
793 			zfs_exit(zfsvfs, FTAG);
794 			return (SET_ERROR(EOPNOTSUPP));
795 		}
796 
797 		/*
798 		 * We don't allow recursive attributes..
799 		 * Maybe someday we will.
800 		 */
801 		if (zdp->z_pflags & ZFS_XATTR) {
802 			zfs_exit(zfsvfs, FTAG);
803 			return (SET_ERROR(EINVAL));
804 		}
805 
806 		if ((error = zfs_get_xattrdir(VTOZ(dvp), &zp, cr, flags))) {
807 			zfs_exit(zfsvfs, FTAG);
808 			return (error);
809 		}
810 		*vpp = ZTOV(zp);
811 
812 		/*
813 		 * Do we have permission to get into attribute directory?
814 		 */
815 		if (flags & LOOKUP_NAMED_ATTR)
816 			error = zfs_zaccess(zp, ACE_EXECUTE, V_NAMEDATTR,
817 			    B_FALSE, cr, NULL);
818 		else
819 			error = zfs_zaccess(zp, ACE_EXECUTE, 0, B_FALSE, cr,
820 			    NULL);
821 		if (error) {
822 			vrele(ZTOV(zp));
823 		}
824 
825 		zfs_exit(zfsvfs, FTAG);
826 		return (error);
827 	}
828 
829 	/*
830 	 * Check accessibility of directory if we're not coming in via
831 	 * VOP_CACHEDLOOKUP.
832 	 */
833 	if (!cached) {
834 #ifdef NOEXECCHECK
835 		if ((cnp->cn_flags & NOEXECCHECK) != 0) {
836 			cnp->cn_flags &= ~NOEXECCHECK;
837 		} else
838 #endif
839 		if ((error = zfs_zaccess(zdp, ACE_EXECUTE, 0, B_FALSE, cr,
840 		    NULL))) {
841 			zfs_exit(zfsvfs, FTAG);
842 			return (error);
843 		}
844 	}
845 
846 	if (zfsvfs->z_utf8 && u8_validate(nm, strlen(nm),
847 	    NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
848 		zfs_exit(zfsvfs, FTAG);
849 		return (SET_ERROR(EILSEQ));
850 	}
851 
852 
853 	/*
854 	 * First handle the special cases.
855 	 */
856 	if ((cnp->cn_flags & ISDOTDOT) != 0) {
857 		/*
858 		 * If we are a snapshot mounted under .zfs, return
859 		 * the vp for the snapshot directory.
860 		 */
861 		if (zdp->z_id == zfsvfs->z_root && zfsvfs->z_parent != zfsvfs) {
862 			struct componentname cn;
863 			vnode_t *zfsctl_vp;
864 			int ltype;
865 
866 			zfs_exit(zfsvfs, FTAG);
867 			ltype = VOP_ISLOCKED(dvp);
868 			VOP_UNLOCK(dvp);
869 			error = zfsctl_root(zfsvfs->z_parent, LK_SHARED,
870 			    &zfsctl_vp);
871 			if (error == 0) {
872 				cn.cn_nameptr = "snapshot";
873 				cn.cn_namelen = strlen(cn.cn_nameptr);
874 				cn.cn_nameiop = cnp->cn_nameiop;
875 				cn.cn_flags = cnp->cn_flags & ~ISDOTDOT;
876 				cn.cn_lkflags = cnp->cn_lkflags;
877 				error = VOP_LOOKUP(zfsctl_vp, vpp, &cn);
878 				vput(zfsctl_vp);
879 			}
880 			vn_lock(dvp, ltype | LK_RETRY);
881 			return (error);
882 		}
883 	}
884 	if (zfs_has_ctldir(zdp) && strcmp(nm, ZFS_CTLDIR_NAME) == 0) {
885 		zfs_exit(zfsvfs, FTAG);
886 		if (zfsvfs->z_show_ctldir == ZFS_SNAPDIR_DISABLED)
887 			return (SET_ERROR(ENOENT));
888 		if ((cnp->cn_flags & ISLASTCN) != 0 && nameiop != LOOKUP)
889 			return (SET_ERROR(ENOTSUP));
890 		error = zfsctl_root(zfsvfs, cnp->cn_lkflags, vpp);
891 		return (error);
892 	}
893 
894 	/*
895 	 * The loop is retry the lookup if the parent-child relationship
896 	 * changes during the dot-dot locking complexities.
897 	 */
898 	for (;;) {
899 		uint64_t parent;
900 
901 		error = zfs_dirlook(zdp, nm, &zp);
902 		if (error == 0)
903 			*vpp = ZTOV(zp);
904 
905 		zfs_exit(zfsvfs, FTAG);
906 		if (error != 0)
907 			break;
908 
909 		error = zfs_lookup_lock(dvp, *vpp, nm, cnp->cn_lkflags);
910 		if (error != 0) {
911 			/*
912 			 * If we've got a locking error, then the vnode
913 			 * got reclaimed because of a force unmount.
914 			 * We never enter doomed vnodes into the name cache.
915 			 */
916 			*vpp = NULL;
917 			return (error);
918 		}
919 
920 		if ((cnp->cn_flags & ISDOTDOT) == 0)
921 			break;
922 
923 		if ((error = zfs_enter(zfsvfs, FTAG)) != 0) {
924 			vput(ZTOV(zp));
925 			*vpp = NULL;
926 			return (error);
927 		}
928 		if (zdp->z_sa_hdl == NULL) {
929 			error = SET_ERROR(EIO);
930 		} else {
931 			error = sa_lookup(zdp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs),
932 			    &parent, sizeof (parent));
933 		}
934 		if (error != 0) {
935 			zfs_exit(zfsvfs, FTAG);
936 			vput(ZTOV(zp));
937 			break;
938 		}
939 		if (zp->z_id == parent) {
940 			zfs_exit(zfsvfs, FTAG);
941 			break;
942 		}
943 		vput(ZTOV(zp));
944 	}
945 
946 	if (error != 0)
947 		*vpp = NULL;
948 
949 	/* Translate errors and add SAVENAME when needed. */
950 	if (cnp->cn_flags & ISLASTCN) {
951 		switch (nameiop) {
952 		case CREATE:
953 		case RENAME:
954 			if (error == ENOENT) {
955 				error = EJUSTRETURN;
956 #if __FreeBSD_version < 1400068
957 				cnp->cn_flags |= SAVENAME;
958 #endif
959 				break;
960 			}
961 			zfs_fallthrough;
962 		case DELETE:
963 #if __FreeBSD_version < 1400068
964 			if (error == 0)
965 				cnp->cn_flags |= SAVENAME;
966 #endif
967 			break;
968 		}
969 	}
970 
971 	if ((cnp->cn_flags & ISDOTDOT) != 0) {
972 		/*
973 		 * FIXME: zfs_lookup_lock relocks vnodes and does nothing to
974 		 * handle races. In particular different callers may end up
975 		 * with different vnodes and will try to add conflicting
976 		 * entries to the namecache.
977 		 *
978 		 * While finding different result may be acceptable in face
979 		 * of concurrent modification, adding conflicting entries
980 		 * trips over an assert in the namecache.
981 		 *
982 		 * Ultimately let an entry through once everything settles.
983 		 */
984 		if (!vn_seqc_consistent(dvp, dvp_seqc)) {
985 			cnp->cn_flags &= ~MAKEENTRY;
986 		}
987 	}
988 
989 	/* Insert name into cache (as non-existent) if appropriate. */
990 	if (zfsvfs->z_use_namecache && !zfsvfs->z_replay &&
991 	    error == ENOENT && (cnp->cn_flags & MAKEENTRY) != 0)
992 		cache_enter(dvp, NULL, cnp);
993 
994 	/* Insert name into cache if appropriate. */
995 	if (zfsvfs->z_use_namecache && !zfsvfs->z_replay &&
996 	    error == 0 && (cnp->cn_flags & MAKEENTRY)) {
997 		if (!(cnp->cn_flags & ISLASTCN) ||
998 		    (nameiop != DELETE && nameiop != RENAME)) {
999 			cache_enter(dvp, *vpp, cnp);
1000 		}
1001 	}
1002 
1003 	return (error);
1004 }
1005 
1006 static inline bool
is_nametoolong(zfsvfs_t * zfsvfs,const char * name)1007 is_nametoolong(zfsvfs_t *zfsvfs, const char *name)
1008 {
1009 	size_t dlen = strlen(name);
1010 	return ((!zfsvfs->z_longname && dlen >= ZAP_MAXNAMELEN) ||
1011 	    dlen >= ZAP_MAXNAMELEN_NEW);
1012 }
1013 
1014 /*
1015  * Attempt to create a new entry in a directory.  If the entry
1016  * already exists, truncate the file if permissible, else return
1017  * an error.  Return the vp of the created or trunc'd file.
1018  *
1019  *	IN:	dvp	- vnode of directory to put new file entry in.
1020  *		name	- name of new file entry.
1021  *		vap	- attributes of new file.
1022  *		excl	- flag indicating exclusive or non-exclusive mode.
1023  *		mode	- mode to open file with.
1024  *		cr	- credentials of caller.
1025  *		flag	- large file flag [UNUSED].
1026  *		ct	- caller context
1027  *		vsecp	- ACL to be set
1028  *		mnt_ns	- Unused on FreeBSD
1029  *
1030  *	OUT:	vpp	- vnode of created or trunc'd entry.
1031  *
1032  *	RETURN:	0 on success, error code on failure.
1033  *
1034  * Timestamps:
1035  *	dvp - ctime|mtime updated if new entry created
1036  *	 vp - ctime|mtime always, atime if new
1037  */
1038 int
zfs_create(znode_t * dzp,const char * name,vattr_t * vap,int excl,int mode,znode_t ** zpp,cred_t * cr,int flag,vsecattr_t * vsecp,zidmap_t * mnt_ns)1039 zfs_create(znode_t *dzp, const char *name, vattr_t *vap, int excl, int mode,
1040     znode_t **zpp, cred_t *cr, int flag, vsecattr_t *vsecp, zidmap_t *mnt_ns)
1041 {
1042 	(void) excl, (void) mode, (void) flag;
1043 	znode_t		*zp;
1044 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1045 	zilog_t		*zilog;
1046 	objset_t	*os;
1047 	dmu_tx_t	*tx;
1048 	int		error;
1049 	uid_t		uid = crgetuid(cr);
1050 	gid_t		gid = crgetgid(cr);
1051 	uint64_t	projid = ZFS_DEFAULT_PROJID;
1052 	zfs_acl_ids_t   acl_ids;
1053 	boolean_t	fuid_dirtied;
1054 	uint64_t	txtype;
1055 
1056 	if (is_nametoolong(zfsvfs, name))
1057 		return (SET_ERROR(ENAMETOOLONG));
1058 
1059 	/*
1060 	 * If we have an ephemeral id, ACL, or XVATTR then
1061 	 * make sure file system is at proper version
1062 	 */
1063 	if (zfsvfs->z_use_fuids == B_FALSE &&
1064 	    (vsecp || (vap->va_mask & AT_XVATTR) ||
1065 	    IS_EPHEMERAL(uid) || IS_EPHEMERAL(gid)))
1066 		return (SET_ERROR(EINVAL));
1067 
1068 	if ((error = zfs_enter_verify_zp(zfsvfs, dzp, FTAG)) != 0)
1069 		return (error);
1070 	os = zfsvfs->z_os;
1071 	zilog = zfsvfs->z_log;
1072 
1073 	if (zfsvfs->z_utf8 && u8_validate(name, strlen(name),
1074 	    NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
1075 		zfs_exit(zfsvfs, FTAG);
1076 		return (SET_ERROR(EILSEQ));
1077 	}
1078 
1079 	if (vap->va_mask & AT_XVATTR) {
1080 		if ((error = secpolicy_xvattr(ZTOV(dzp), (xvattr_t *)vap,
1081 		    crgetuid(cr), cr, vap->va_type)) != 0) {
1082 			zfs_exit(zfsvfs, FTAG);
1083 			return (error);
1084 		}
1085 	}
1086 
1087 	*zpp = NULL;
1088 
1089 	if ((vap->va_mode & S_ISVTX) && secpolicy_vnode_stky_modify(cr))
1090 		vap->va_mode &= ~S_ISVTX;
1091 
1092 	error = zfs_dirent_lookup(dzp, name, &zp, ZNEW);
1093 	if (error) {
1094 		zfs_exit(zfsvfs, FTAG);
1095 		return (error);
1096 	}
1097 	ASSERT0P(zp);
1098 
1099 	/*
1100 	 * Create a new file object and update the directory
1101 	 * to reference it.
1102 	 */
1103 	if ((error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr, mnt_ns))) {
1104 		goto out;
1105 	}
1106 
1107 	/*
1108 	 * We only support the creation of regular files in
1109 	 * extended attribute directories.
1110 	 */
1111 
1112 	if ((dzp->z_pflags & ZFS_XATTR) &&
1113 	    (vap->va_type != VREG)) {
1114 		error = SET_ERROR(EINVAL);
1115 		goto out;
1116 	}
1117 
1118 	if ((error = zfs_acl_ids_create(dzp, 0, vap,
1119 	    cr, vsecp, &acl_ids, NULL)) != 0)
1120 		goto out;
1121 
1122 	if (S_ISREG(vap->va_mode) || S_ISDIR(vap->va_mode))
1123 		projid = zfs_inherit_projid(dzp);
1124 	if (zfs_acl_ids_overquota(zfsvfs, &acl_ids, projid)) {
1125 		zfs_acl_ids_free(&acl_ids);
1126 		error = SET_ERROR(EDQUOT);
1127 		goto out;
1128 	}
1129 
1130 	getnewvnode_reserve();
1131 
1132 	tx = dmu_tx_create(os);
1133 
1134 	dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
1135 	    ZFS_SA_BASE_ATTR_SIZE);
1136 
1137 	fuid_dirtied = zfsvfs->z_fuid_dirty;
1138 	if (fuid_dirtied)
1139 		zfs_fuid_txhold(zfsvfs, tx);
1140 	dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
1141 	dmu_tx_hold_sa(tx, dzp->z_sa_hdl, ZFS_SEQ_MAY_GROW(dzp));
1142 	if (!zfsvfs->z_use_sa &&
1143 	    acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
1144 		dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
1145 		    0, acl_ids.z_aclp->z_acl_bytes);
1146 	}
1147 	error = dmu_tx_assign(tx, DMU_TX_WAIT);
1148 	if (error) {
1149 		zfs_acl_ids_free(&acl_ids);
1150 		dmu_tx_abort(tx);
1151 		getnewvnode_drop_reserve();
1152 		zfs_exit(zfsvfs, FTAG);
1153 		return (error);
1154 	}
1155 	zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
1156 
1157 	error = zfs_link_create(dzp, name, zp, tx, ZNEW);
1158 	if (error != 0) {
1159 		/*
1160 		 * Since, we failed to add the directory entry for it,
1161 		 * delete the newly created dnode.
1162 		 */
1163 		zfs_znode_delete(zp, tx);
1164 		VOP_UNLOCK(ZTOV(zp));
1165 		zrele(zp);
1166 		zfs_acl_ids_free(&acl_ids);
1167 		dmu_tx_commit(tx);
1168 		getnewvnode_drop_reserve();
1169 		goto out;
1170 	}
1171 
1172 	if (fuid_dirtied)
1173 		zfs_fuid_sync(zfsvfs, tx);
1174 
1175 	txtype = zfs_log_create_txtype(Z_FILE, vsecp, vap);
1176 	zfs_log_create(zilog, tx, txtype, dzp, zp, name,
1177 	    vsecp, acl_ids.z_fuidp, vap);
1178 	zfs_acl_ids_free(&acl_ids);
1179 	dmu_tx_commit(tx);
1180 
1181 	getnewvnode_drop_reserve();
1182 
1183 out:
1184 	VNASSERT(ZTOV(dzp)->v_holdcnt > 0 && ZTOV(dzp)->v_usecount > 0,
1185 	    ZTOV(dzp), ("%s: wrong ref counts", __func__));
1186 	if (error == 0) {
1187 		*zpp = zp;
1188 	}
1189 
1190 	if (error == 0 && zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1191 		error = zil_commit(zilog, 0);
1192 
1193 	zfs_exit(zfsvfs, FTAG);
1194 	return (error);
1195 }
1196 
1197 /*
1198  * Remove an entry from a directory.
1199  *
1200  *	IN:	dvp	- vnode of directory to remove entry from.
1201  *		name	- name of entry to remove.
1202  *		cr	- credentials of caller.
1203  *		ct	- caller context
1204  *		flags	- case flags
1205  *
1206  *	RETURN:	0 on success, error code on failure.
1207  *
1208  * Timestamps:
1209  *	dvp - ctime|mtime
1210  *	 vp - ctime (if nlink > 0)
1211  */
1212 static int
zfs_remove_(vnode_t * dvp,vnode_t * vp,const char * name,cred_t * cr)1213 zfs_remove_(vnode_t *dvp, vnode_t *vp, const char *name, cred_t *cr)
1214 {
1215 	znode_t		*dzp = VTOZ(dvp);
1216 	znode_t		*zp;
1217 	znode_t		*xzp;
1218 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1219 	zilog_t		*zilog;
1220 	uint64_t	xattr_obj;
1221 	uint64_t	obj = 0;
1222 	dmu_tx_t	*tx;
1223 	boolean_t	unlinked;
1224 	uint64_t	txtype;
1225 	int		error;
1226 
1227 
1228 	if ((error = zfs_enter_verify_zp(zfsvfs, dzp, FTAG)) != 0)
1229 		return (error);
1230 	zp = VTOZ(vp);
1231 	if ((error = zfs_verify_zp(zp)) != 0) {
1232 		zfs_exit(zfsvfs, FTAG);
1233 		return (error);
1234 	}
1235 	zilog = zfsvfs->z_log;
1236 
1237 	xattr_obj = 0;
1238 	xzp = NULL;
1239 
1240 	if ((error = zfs_zaccess_delete(dzp, zp, cr, NULL))) {
1241 		goto out;
1242 	}
1243 
1244 	/*
1245 	 * Need to use rmdir for removing directories.
1246 	 */
1247 	if (vp->v_type == VDIR) {
1248 		error = SET_ERROR(EPERM);
1249 		goto out;
1250 	}
1251 
1252 	vnevent_remove(vp, dvp, name, ct);
1253 
1254 	obj = zp->z_id;
1255 
1256 	/* are there any extended attributes? */
1257 	error = sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
1258 	    &xattr_obj, sizeof (xattr_obj));
1259 	if (error == 0 && xattr_obj) {
1260 		error = zfs_zget(zfsvfs, xattr_obj, &xzp);
1261 		ASSERT0(error);
1262 	}
1263 
1264 	/*
1265 	 * We may delete the znode now, or we may put it in the unlinked set;
1266 	 * it depends on whether we're the last link, and on whether there are
1267 	 * other holds on the vnode.  So we dmu_tx_hold() the right things to
1268 	 * allow for either case.
1269 	 */
1270 	tx = dmu_tx_create(zfsvfs->z_os);
1271 	dmu_tx_hold_zap(tx, dzp->z_id, FALSE, name);
1272 	dmu_tx_hold_sa(tx, zp->z_sa_hdl, ZFS_SEQ_MAY_GROW(zp));
1273 	dmu_tx_hold_sa(tx, dzp->z_sa_hdl, ZFS_SEQ_MAY_GROW(dzp));
1274 	zfs_sa_upgrade_txholds(tx, zp);
1275 	zfs_sa_upgrade_txholds(tx, dzp);
1276 
1277 	if (xzp) {
1278 		dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
1279 		dmu_tx_hold_sa(tx, xzp->z_sa_hdl, B_FALSE);
1280 	}
1281 
1282 	/* charge as an update -- would be nice not to charge at all */
1283 	dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
1284 
1285 	/*
1286 	 * Mark this transaction as typically resulting in a net free of space
1287 	 */
1288 	dmu_tx_mark_netfree(tx);
1289 
1290 	error = dmu_tx_assign(tx, DMU_TX_WAIT);
1291 	if (error) {
1292 		dmu_tx_abort(tx);
1293 		zfs_exit(zfsvfs, FTAG);
1294 		return (error);
1295 	}
1296 
1297 	/*
1298 	 * Remove the directory entry.
1299 	 */
1300 	error = zfs_link_destroy(dzp, name, zp, tx, ZEXISTS, &unlinked);
1301 
1302 	if (error) {
1303 		dmu_tx_commit(tx);
1304 		goto out;
1305 	}
1306 
1307 	if (unlinked) {
1308 		zfs_unlinked_add(zp, tx);
1309 		vp->v_vflag |= VV_NOSYNC;
1310 	}
1311 	/* XXX check changes to linux vnops */
1312 	txtype = TX_REMOVE;
1313 	zfs_log_remove(zilog, tx, txtype, dzp, name, obj, unlinked);
1314 
1315 	dmu_tx_commit(tx);
1316 out:
1317 
1318 	if (xzp)
1319 		vrele(ZTOV(xzp));
1320 
1321 	if (error == 0 && zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1322 		error = zil_commit(zilog, 0);
1323 
1324 	zfs_exit(zfsvfs, FTAG);
1325 	return (error);
1326 }
1327 
1328 
1329 static int
zfs_lookup_internal(znode_t * dzp,const char * name,vnode_t ** vpp,struct componentname * cnp,int nameiop)1330 zfs_lookup_internal(znode_t *dzp, const char *name, vnode_t **vpp,
1331     struct componentname *cnp, int nameiop)
1332 {
1333 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1334 	int error;
1335 
1336 	cnp->cn_nameptr = __DECONST(char *, name);
1337 	cnp->cn_namelen = strlen(name);
1338 	cnp->cn_nameiop = nameiop;
1339 	cnp->cn_flags = ISLASTCN;
1340 #if __FreeBSD_version < 1400068
1341 	cnp->cn_flags |= SAVENAME;
1342 #endif
1343 	cnp->cn_lkflags = LK_EXCLUSIVE | LK_RETRY;
1344 	cnp->cn_cred = kcred;
1345 #if __FreeBSD_version < 1400037
1346 	cnp->cn_thread = curthread;
1347 #endif
1348 
1349 	if (zfsvfs->z_use_namecache && !zfsvfs->z_replay) {
1350 		struct vop_lookup_args a;
1351 
1352 		a.a_gen.a_desc = &vop_lookup_desc;
1353 		a.a_dvp = ZTOV(dzp);
1354 		a.a_vpp = vpp;
1355 		a.a_cnp = cnp;
1356 		error = vfs_cache_lookup(&a);
1357 	} else {
1358 		error = zfs_lookup(ZTOV(dzp), name, vpp, cnp, nameiop, kcred, 0,
1359 		    B_FALSE);
1360 	}
1361 #ifdef ZFS_DEBUG
1362 	if (error) {
1363 		printf("got error %d on name %s on op %d\n", error, name,
1364 		    nameiop);
1365 		kdb_backtrace();
1366 	}
1367 #endif
1368 	return (error);
1369 }
1370 
1371 int
zfs_remove(znode_t * dzp,const char * name,cred_t * cr,int flags)1372 zfs_remove(znode_t *dzp, const char *name, cred_t *cr, int flags)
1373 {
1374 	vnode_t *vp;
1375 	int error;
1376 	struct componentname cn;
1377 
1378 	if ((error = zfs_lookup_internal(dzp, name, &vp, &cn, DELETE)))
1379 		return (error);
1380 
1381 	error = zfs_remove_(ZTOV(dzp), vp, name, cr);
1382 	vput(vp);
1383 	return (error);
1384 }
1385 /*
1386  * Create a new directory and insert it into dvp using the name
1387  * provided.  Return a pointer to the inserted directory.
1388  *
1389  *	IN:	dvp	- vnode of directory to add subdir to.
1390  *		dirname	- name of new directory.
1391  *		vap	- attributes of new directory.
1392  *		cr	- credentials of caller.
1393  *		ct	- caller context
1394  *		flags	- case flags
1395  *		vsecp	- ACL to be set
1396  *		mnt_ns	- Unused on FreeBSD
1397  *
1398  *	OUT:	vpp	- vnode of created directory.
1399  *
1400  *	RETURN:	0 on success, error code on failure.
1401  *
1402  * Timestamps:
1403  *	dvp - ctime|mtime updated
1404  *	 vp - ctime|mtime|atime updated
1405  */
1406 int
zfs_mkdir(znode_t * dzp,const char * dirname,vattr_t * vap,znode_t ** zpp,cred_t * cr,int flags,vsecattr_t * vsecp,zidmap_t * mnt_ns)1407 zfs_mkdir(znode_t *dzp, const char *dirname, vattr_t *vap, znode_t **zpp,
1408     cred_t *cr, int flags, vsecattr_t *vsecp, zidmap_t *mnt_ns)
1409 {
1410 	(void) flags, (void) vsecp;
1411 	znode_t		*zp;
1412 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1413 	zilog_t		*zilog;
1414 	uint64_t	txtype;
1415 	dmu_tx_t	*tx;
1416 	int		error;
1417 	uid_t		uid = crgetuid(cr);
1418 	gid_t		gid = crgetgid(cr);
1419 	zfs_acl_ids_t   acl_ids;
1420 	boolean_t	fuid_dirtied;
1421 
1422 	ASSERT3U(vap->va_type, ==, VDIR);
1423 
1424 	if (is_nametoolong(zfsvfs, dirname))
1425 		return (SET_ERROR(ENAMETOOLONG));
1426 
1427 	/*
1428 	 * If we have an ephemeral id, ACL, or XVATTR then
1429 	 * make sure file system is at proper version
1430 	 */
1431 	if (zfsvfs->z_use_fuids == B_FALSE &&
1432 	    ((vap->va_mask & AT_XVATTR) ||
1433 	    IS_EPHEMERAL(uid) || IS_EPHEMERAL(gid)))
1434 		return (SET_ERROR(EINVAL));
1435 
1436 	if ((error = zfs_enter_verify_zp(zfsvfs, dzp, FTAG)) != 0)
1437 		return (error);
1438 	zilog = zfsvfs->z_log;
1439 
1440 	if (dzp->z_pflags & ZFS_XATTR) {
1441 		zfs_exit(zfsvfs, FTAG);
1442 		return (SET_ERROR(EINVAL));
1443 	}
1444 
1445 	if (zfsvfs->z_utf8 && u8_validate(dirname,
1446 	    strlen(dirname), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
1447 		zfs_exit(zfsvfs, FTAG);
1448 		return (SET_ERROR(EILSEQ));
1449 	}
1450 
1451 	if (vap->va_mask & AT_XVATTR) {
1452 		if ((error = secpolicy_xvattr(ZTOV(dzp), (xvattr_t *)vap,
1453 		    crgetuid(cr), cr, vap->va_type)) != 0) {
1454 			zfs_exit(zfsvfs, FTAG);
1455 			return (error);
1456 		}
1457 	}
1458 
1459 	if ((error = zfs_acl_ids_create(dzp, 0, vap, cr,
1460 	    NULL, &acl_ids, NULL)) != 0) {
1461 		zfs_exit(zfsvfs, FTAG);
1462 		return (error);
1463 	}
1464 
1465 	/*
1466 	 * First make sure the new directory doesn't exist.
1467 	 *
1468 	 * Existence is checked first to make sure we don't return
1469 	 * EACCES instead of EEXIST which can cause some applications
1470 	 * to fail.
1471 	 */
1472 	*zpp = NULL;
1473 
1474 	if ((error = zfs_dirent_lookup(dzp, dirname, &zp, ZNEW))) {
1475 		zfs_acl_ids_free(&acl_ids);
1476 		zfs_exit(zfsvfs, FTAG);
1477 		return (error);
1478 	}
1479 	ASSERT0P(zp);
1480 
1481 	if ((error = zfs_zaccess(dzp, ACE_ADD_SUBDIRECTORY, 0, B_FALSE, cr,
1482 	    mnt_ns))) {
1483 		zfs_acl_ids_free(&acl_ids);
1484 		zfs_exit(zfsvfs, FTAG);
1485 		return (error);
1486 	}
1487 
1488 	if (zfs_acl_ids_overquota(zfsvfs, &acl_ids, zfs_inherit_projid(dzp))) {
1489 		zfs_acl_ids_free(&acl_ids);
1490 		zfs_exit(zfsvfs, FTAG);
1491 		return (SET_ERROR(EDQUOT));
1492 	}
1493 
1494 	/*
1495 	 * Add a new entry to the directory.
1496 	 */
1497 	getnewvnode_reserve();
1498 	tx = dmu_tx_create(zfsvfs->z_os);
1499 	dmu_tx_hold_zap(tx, dzp->z_id, TRUE, dirname);
1500 	dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, FALSE, NULL);
1501 	dmu_tx_hold_sa(tx, dzp->z_sa_hdl, ZFS_SEQ_MAY_GROW(dzp));
1502 	fuid_dirtied = zfsvfs->z_fuid_dirty;
1503 	if (fuid_dirtied)
1504 		zfs_fuid_txhold(zfsvfs, tx);
1505 	if (!zfsvfs->z_use_sa && acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
1506 		dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0,
1507 		    acl_ids.z_aclp->z_acl_bytes);
1508 	}
1509 
1510 	dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
1511 	    ZFS_SA_BASE_ATTR_SIZE);
1512 
1513 	error = dmu_tx_assign(tx, DMU_TX_WAIT);
1514 	if (error) {
1515 		zfs_acl_ids_free(&acl_ids);
1516 		dmu_tx_abort(tx);
1517 		getnewvnode_drop_reserve();
1518 		zfs_exit(zfsvfs, FTAG);
1519 		return (error);
1520 	}
1521 
1522 	/*
1523 	 * Create new node.
1524 	 */
1525 	zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
1526 
1527 	/*
1528 	 * Now put new name in parent dir.
1529 	 */
1530 	error = zfs_link_create(dzp, dirname, zp, tx, ZNEW);
1531 	if (error != 0) {
1532 		zfs_znode_delete(zp, tx);
1533 		VOP_UNLOCK(ZTOV(zp));
1534 		zrele(zp);
1535 		goto out;
1536 	}
1537 
1538 	if (fuid_dirtied)
1539 		zfs_fuid_sync(zfsvfs, tx);
1540 
1541 	*zpp = zp;
1542 
1543 	txtype = zfs_log_create_txtype(Z_DIR, NULL, vap);
1544 	zfs_log_create(zilog, tx, txtype, dzp, zp, dirname, NULL,
1545 	    acl_ids.z_fuidp, vap);
1546 
1547 out:
1548 	zfs_acl_ids_free(&acl_ids);
1549 
1550 	dmu_tx_commit(tx);
1551 
1552 	getnewvnode_drop_reserve();
1553 
1554 	if (error == 0 && zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1555 		error = zil_commit(zilog, 0);
1556 
1557 	zfs_exit(zfsvfs, FTAG);
1558 	return (error);
1559 }
1560 
1561 /*
1562  * Remove a directory subdir entry.  If the current working
1563  * directory is the same as the subdir to be removed, the
1564  * remove will fail.
1565  *
1566  *	IN:	dvp	- vnode of directory to remove from.
1567  *		name	- name of directory to be removed.
1568  *		cwd	- vnode of current working directory.
1569  *		cr	- credentials of caller.
1570  *		ct	- caller context
1571  *		flags	- case flags
1572  *
1573  *	RETURN:	0 on success, error code on failure.
1574  *
1575  * Timestamps:
1576  *	dvp - ctime|mtime updated
1577  */
1578 static int
zfs_rmdir_(vnode_t * dvp,vnode_t * vp,const char * name,cred_t * cr)1579 zfs_rmdir_(vnode_t *dvp, vnode_t *vp, const char *name, cred_t *cr)
1580 {
1581 	znode_t		*dzp = VTOZ(dvp);
1582 	znode_t		*zp = VTOZ(vp);
1583 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1584 	zilog_t		*zilog;
1585 	dmu_tx_t	*tx;
1586 	int		error;
1587 
1588 	if ((error = zfs_enter_verify_zp(zfsvfs, dzp, FTAG)) != 0)
1589 		return (error);
1590 	if ((error = zfs_verify_zp(zp)) != 0) {
1591 		zfs_exit(zfsvfs, FTAG);
1592 		return (error);
1593 	}
1594 	zilog = zfsvfs->z_log;
1595 
1596 
1597 	if ((error = zfs_zaccess_delete(dzp, zp, cr, NULL))) {
1598 		goto out;
1599 	}
1600 
1601 	if (vp->v_type != VDIR) {
1602 		error = SET_ERROR(ENOTDIR);
1603 		goto out;
1604 	}
1605 
1606 	vnevent_rmdir(vp, dvp, name, ct);
1607 
1608 	tx = dmu_tx_create(zfsvfs->z_os);
1609 	dmu_tx_hold_zap(tx, dzp->z_id, FALSE, name);
1610 	dmu_tx_hold_sa(tx, zp->z_sa_hdl, ZFS_SEQ_MAY_GROW(zp));
1611 	dmu_tx_hold_sa(tx, dzp->z_sa_hdl, ZFS_SEQ_MAY_GROW(dzp));
1612 	dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
1613 	zfs_sa_upgrade_txholds(tx, zp);
1614 	zfs_sa_upgrade_txholds(tx, dzp);
1615 	dmu_tx_mark_netfree(tx);
1616 	error = dmu_tx_assign(tx, DMU_TX_WAIT);
1617 	if (error) {
1618 		dmu_tx_abort(tx);
1619 		zfs_exit(zfsvfs, FTAG);
1620 		return (error);
1621 	}
1622 
1623 	error = zfs_link_destroy(dzp, name, zp, tx, ZEXISTS, NULL);
1624 
1625 	if (error == 0) {
1626 		uint64_t txtype = TX_RMDIR;
1627 		zfs_log_remove(zilog, tx, txtype, dzp, name,
1628 		    ZFS_NO_OBJECT, B_FALSE);
1629 	}
1630 
1631 	dmu_tx_commit(tx);
1632 
1633 	if (zfsvfs->z_use_namecache)
1634 		cache_vop_rmdir(dvp, vp);
1635 out:
1636 	if (error == 0 && zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1637 		error = zil_commit(zilog, 0);
1638 
1639 	zfs_exit(zfsvfs, FTAG);
1640 	return (error);
1641 }
1642 
1643 int
zfs_rmdir(znode_t * dzp,const char * name,znode_t * cwd,cred_t * cr,int flags)1644 zfs_rmdir(znode_t *dzp, const char *name, znode_t *cwd, cred_t *cr, int flags)
1645 {
1646 	struct componentname cn;
1647 	vnode_t *vp;
1648 	int error;
1649 
1650 	if ((error = zfs_lookup_internal(dzp, name, &vp, &cn, DELETE)))
1651 		return (error);
1652 
1653 	error = zfs_rmdir_(ZTOV(dzp), vp, name, cr);
1654 	vput(vp);
1655 	return (error);
1656 }
1657 
1658 /*
1659  * Read as many directory entries as will fit into the provided
1660  * buffer from the given directory cursor position (specified in
1661  * the uio structure).
1662  *
1663  *	IN:	vp	- vnode of directory to read.
1664  *		uio	- structure supplying read location, range info,
1665  *			  and return buffer.
1666  *		cr	- credentials of caller.
1667  *		ct	- caller context
1668  *
1669  *	OUT:	uio	- updated offset and range, buffer filled.
1670  *		eofp	- set to true if end-of-file detected.
1671  *		ncookies- number of entries in cookies
1672  *		cookies	- offsets to directory entries
1673  *
1674  *	RETURN:	0 on success, error code on failure.
1675  *
1676  * Timestamps:
1677  *	vp - atime updated
1678  *
1679  * Note that the low 4 bits of the cookie returned by zap is always zero.
1680  * This allows us to use the low range for "special" directory entries:
1681  * We use 0 for '.', and 1 for '..'.  If this is the root of the filesystem,
1682  * we use the offset 2 for the '.zfs' directory.
1683  */
1684 static int
zfs_readdir(vnode_t * vp,zfs_uio_t * uio,cred_t * cr,int * eofp,int * ncookies,cookie_t ** cookies)1685 zfs_readdir(vnode_t *vp, zfs_uio_t *uio, cred_t *cr, int *eofp,
1686     int *ncookies, cookie_t **cookies)
1687 {
1688 	znode_t		*zp = VTOZ(vp);
1689 	iovec_t		*iovp;
1690 	dirent64_t	*odp;
1691 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
1692 	objset_t	*os;
1693 	caddr_t		outbuf;
1694 	size_t		bufsize;
1695 	zap_cursor_t	zc;
1696 	zap_attribute_t	*zap;
1697 	uint_t		bytes_wanted;
1698 	uint64_t	offset; /* must be unsigned; checks for < 1 */
1699 	uint64_t	parent;
1700 	int		local_eof;
1701 	int		outcount;
1702 	int		error;
1703 	uint8_t		prefetch;
1704 	uint8_t		type;
1705 	int		ncooks;
1706 	cookie_t	*cooks = NULL;
1707 
1708 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
1709 		return (error);
1710 
1711 	if ((error = sa_lookup(zp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs),
1712 	    &parent, sizeof (parent))) != 0) {
1713 		zfs_exit(zfsvfs, FTAG);
1714 		return (error);
1715 	}
1716 
1717 	/*
1718 	 * If we are not given an eof variable,
1719 	 * use a local one.
1720 	 */
1721 	if (eofp == NULL)
1722 		eofp = &local_eof;
1723 
1724 	/*
1725 	 * Check for valid iov_len.
1726 	 */
1727 	if (GET_UIO_STRUCT(uio)->uio_iov->iov_len <= 0) {
1728 		zfs_exit(zfsvfs, FTAG);
1729 		return (SET_ERROR(EINVAL));
1730 	}
1731 
1732 	/*
1733 	 * Quit if directory has been removed (posix)
1734 	 */
1735 	if ((*eofp = (zp->z_unlinked != 0)) != 0) {
1736 		zfs_exit(zfsvfs, FTAG);
1737 		return (0);
1738 	}
1739 
1740 	error = 0;
1741 	os = zfsvfs->z_os;
1742 	offset = zfs_uio_offset(uio);
1743 	prefetch = zp->z_zn_prefetch;
1744 	zap = zap_attribute_long_alloc();
1745 
1746 	/*
1747 	 * Initialize the iterator cursor.
1748 	 */
1749 	if (offset <= 3) {
1750 		/*
1751 		 * Start iteration from the beginning of the directory.
1752 		 */
1753 		zap_cursor_init(&zc, os, zp->z_id);
1754 	} else {
1755 		/*
1756 		 * The offset is a serialized cursor.
1757 		 */
1758 		zap_cursor_init_serialized(&zc, os, zp->z_id, offset);
1759 	}
1760 
1761 	/*
1762 	 * Get space to change directory entries into fs independent format.
1763 	 */
1764 	iovp = GET_UIO_STRUCT(uio)->uio_iov;
1765 	bytes_wanted = iovp->iov_len;
1766 	if (zfs_uio_segflg(uio) != UIO_SYSSPACE || zfs_uio_iovcnt(uio) != 1) {
1767 		bufsize = bytes_wanted;
1768 		outbuf = kmem_alloc(bufsize, KM_SLEEP);
1769 		odp = (struct dirent64 *)outbuf;
1770 	} else {
1771 		bufsize = bytes_wanted;
1772 		outbuf = NULL;
1773 		odp = (struct dirent64 *)iovp->iov_base;
1774 	}
1775 
1776 	if (ncookies != NULL) {
1777 		/*
1778 		 * Minimum entry size is dirent size and 1 byte for a file name.
1779 		 */
1780 		ncooks = zfs_uio_resid(uio) / (sizeof (struct dirent) -
1781 		    sizeof (((struct dirent *)NULL)->d_name) + 1);
1782 		cooks = malloc(ncooks * sizeof (*cooks), M_TEMP, M_WAITOK);
1783 		*cookies = cooks;
1784 		*ncookies = ncooks;
1785 	}
1786 
1787 	/*
1788 	 * Transform to file-system independent format
1789 	 */
1790 	outcount = 0;
1791 	while (outcount < bytes_wanted) {
1792 		ino64_t objnum;
1793 		ushort_t reclen;
1794 		off64_t *next = NULL;
1795 
1796 		/*
1797 		 * Special case `.', `..', and `.zfs'.
1798 		 */
1799 		if (offset == 0) {
1800 			(void) strcpy(zap->za_name, ".");
1801 			zap->za_normalization_conflict = 0;
1802 			objnum = zp->z_id;
1803 			type = DT_DIR;
1804 		} else if (offset == 1) {
1805 			(void) strcpy(zap->za_name, "..");
1806 			zap->za_normalization_conflict = 0;
1807 			objnum = parent;
1808 			type = DT_DIR;
1809 		} else if (offset == 2 && zfs_show_ctldir(zp)) {
1810 			(void) strcpy(zap->za_name, ZFS_CTLDIR_NAME);
1811 			zap->za_normalization_conflict = 0;
1812 			objnum = ZFSCTL_INO_ROOT;
1813 			type = DT_DIR;
1814 		} else {
1815 			/*
1816 			 * Grab next entry.
1817 			 */
1818 			if ((error = zap_cursor_retrieve(&zc, zap))) {
1819 				if ((*eofp = (error == ENOENT)) != 0)
1820 					break;
1821 				else
1822 					goto update;
1823 			}
1824 
1825 			if (zap->za_integer_length != 8 ||
1826 			    zap->za_num_integers != 1) {
1827 				cmn_err(CE_WARN, "zap_readdir: bad directory "
1828 				    "entry, obj = %lld, offset = %lld\n",
1829 				    (u_longlong_t)zp->z_id,
1830 				    (u_longlong_t)offset);
1831 				error = SET_ERROR(ENXIO);
1832 				goto update;
1833 			}
1834 
1835 			objnum = ZFS_DIRENT_OBJ(zap->za_first_integer);
1836 			/*
1837 			 * MacOS X can extract the object type here such as:
1838 			 * uint8_t type = ZFS_DIRENT_TYPE(zap.za_first_integer);
1839 			 */
1840 			type = ZFS_DIRENT_TYPE(zap->za_first_integer);
1841 		}
1842 
1843 		reclen = DIRENT64_RECLEN(strlen(zap->za_name));
1844 
1845 		/*
1846 		 * Will this entry fit in the buffer?
1847 		 */
1848 		if (outcount + reclen > bufsize) {
1849 			/*
1850 			 * Did we manage to fit anything in the buffer?
1851 			 */
1852 			if (!outcount) {
1853 				error = SET_ERROR(EINVAL);
1854 				goto update;
1855 			}
1856 			break;
1857 		}
1858 		/*
1859 		 * Add normal entry:
1860 		 */
1861 		odp->d_ino = objnum;
1862 		odp->d_reclen = reclen;
1863 		odp->d_namlen = strlen(zap->za_name);
1864 		/* NOTE: d_off is the offset for the *next* entry. */
1865 		next = &odp->d_off;
1866 		strlcpy(odp->d_name, zap->za_name, odp->d_namlen + 1);
1867 		odp->d_type = type;
1868 		dirent_terminate(odp);
1869 		odp = (dirent64_t *)((intptr_t)odp + reclen);
1870 
1871 		outcount += reclen;
1872 
1873 		ASSERT3S(outcount, <=, bufsize);
1874 
1875 		if (prefetch)
1876 			dmu_prefetch_dnode(os, objnum, ZIO_PRIORITY_SYNC_READ);
1877 
1878 		/*
1879 		 * Move to the next entry, fill in the previous offset.
1880 		 */
1881 		if (offset > 2 || (offset == 2 && !zfs_show_ctldir(zp))) {
1882 			zap_cursor_advance(&zc);
1883 			offset = zap_cursor_serialize(&zc);
1884 		} else {
1885 			offset += 1;
1886 		}
1887 
1888 		/* Fill the offset right after advancing the cursor. */
1889 		if (next != NULL)
1890 			*next = offset;
1891 		if (cooks != NULL) {
1892 			*cooks++ = offset;
1893 			ncooks--;
1894 			KASSERT(ncooks >= 0, ("ncookies=%d", ncooks));
1895 		}
1896 	}
1897 	zp->z_zn_prefetch = B_FALSE; /* a lookup will re-enable pre-fetching */
1898 
1899 	/* Subtract unused cookies */
1900 	if (ncookies != NULL)
1901 		*ncookies -= ncooks;
1902 
1903 	if (zfs_uio_segflg(uio) == UIO_SYSSPACE && zfs_uio_iovcnt(uio) == 1) {
1904 		iovp->iov_base += outcount;
1905 		iovp->iov_len -= outcount;
1906 		zfs_uio_resid(uio) -= outcount;
1907 	} else if ((error =
1908 	    zfs_uiomove(outbuf, (long)outcount, UIO_READ, uio))) {
1909 		/*
1910 		 * Reset the pointer.
1911 		 */
1912 		offset = zfs_uio_offset(uio);
1913 	}
1914 
1915 update:
1916 	zap_cursor_fini(&zc);
1917 	zap_attribute_free(zap);
1918 	if (zfs_uio_segflg(uio) != UIO_SYSSPACE || zfs_uio_iovcnt(uio) != 1)
1919 		kmem_free(outbuf, bufsize);
1920 
1921 	if (error == ENOENT)
1922 		error = 0;
1923 
1924 	ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
1925 
1926 	zfs_uio_setoffset(uio, offset);
1927 	zfs_exit(zfsvfs, FTAG);
1928 	if (error != 0 && cookies != NULL) {
1929 		free(*cookies, M_TEMP);
1930 		*cookies = NULL;
1931 		*ncookies = 0;
1932 	}
1933 	return (error);
1934 }
1935 
1936 /*
1937  * Get the requested file attributes and place them in the provided
1938  * vattr structure.
1939  *
1940  *	IN:	vp	- vnode of file.
1941  *		vap	- va_mask identifies requested attributes.
1942  *			  If AT_XVATTR set, then optional attrs are requested
1943  *		flags	- ATTR_NOACLCHECK (CIFS server context)
1944  *		cr	- credentials of caller.
1945  *
1946  *	OUT:	vap	- attribute values.
1947  *
1948  *	RETURN:	0 (always succeeds).
1949  */
1950 static int
zfs_getattr(vnode_t * vp,vattr_t * vap,int flags,cred_t * cr)1951 zfs_getattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr)
1952 {
1953 	znode_t *zp = VTOZ(vp);
1954 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1955 	int	error = 0;
1956 	uint32_t blksize;
1957 	u_longlong_t nblocks;
1958 	uint64_t mtime[2], ctime[2], crtime[2], rdev;
1959 	xvattr_t *xvap = (xvattr_t *)vap;	/* vap may be an xvattr_t * */
1960 	xoptattr_t *xoap = NULL;
1961 	boolean_t skipaclchk = (flags & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
1962 	sa_bulk_attr_t bulk[4];
1963 	int count = 0;
1964 
1965 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
1966 		return (error);
1967 
1968 	zfs_fuid_map_ids(zp, cr, &vap->va_uid, &vap->va_gid);
1969 
1970 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16);
1971 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16);
1972 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CRTIME(zfsvfs), NULL, &crtime, 16);
1973 	if (vp->v_type == VBLK || vp->v_type == VCHR)
1974 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_RDEV(zfsvfs), NULL,
1975 		    &rdev, 8);
1976 
1977 	if ((error = sa_bulk_lookup(zp->z_sa_hdl, bulk, count)) != 0) {
1978 		zfs_exit(zfsvfs, FTAG);
1979 		return (error);
1980 	}
1981 
1982 	/*
1983 	 * If ACL is trivial don't bother looking for ACE_READ_ATTRIBUTES.
1984 	 * Also, if we are the owner don't bother, since owner should
1985 	 * always be allowed to read basic attributes of file.
1986 	 */
1987 	if (!(zp->z_pflags & ZFS_ACL_TRIVIAL) &&
1988 	    (vap->va_uid != crgetuid(cr))) {
1989 		if ((error = zfs_zaccess(zp, ACE_READ_ATTRIBUTES, 0,
1990 		    skipaclchk, cr, NULL))) {
1991 			zfs_exit(zfsvfs, FTAG);
1992 			return (error);
1993 		}
1994 	}
1995 
1996 	/*
1997 	 * Return all attributes.  It's cheaper to provide the answer
1998 	 * than to determine whether we were asked the question.
1999 	 */
2000 
2001 	vap->va_type = IFTOVT(zp->z_mode);
2002 	vap->va_mode = zp->z_mode & ~S_IFMT;
2003 	vn_fsid(vp, vap);
2004 	vap->va_nodeid = zp->z_id;
2005 	vap->va_nlink = zp->z_links;
2006 	if ((vp->v_flag & VROOT) && zfs_show_ctldir(zp) &&
2007 	    zp->z_links < ZFS_LINK_MAX)
2008 		vap->va_nlink++;
2009 	vap->va_size = zp->z_size;
2010 	if (vp->v_type == VBLK || vp->v_type == VCHR)
2011 		vap->va_rdev = zfs_cmpldev(rdev);
2012 	else
2013 		vap->va_rdev = NODEV;
2014 	vap->va_gen = zp->z_gen;
2015 	vap->va_flags = 0;	/* FreeBSD: Reset chflags(2) flags. */
2016 	vap->va_filerev = atomic_load_64(&zp->z_seq);
2017 
2018 	/*
2019 	 * Add in any requested optional attributes and the create time.
2020 	 * Also set the corresponding bits in the returned attribute bitmap.
2021 	 */
2022 	if ((xoap = xva_getxoptattr(xvap)) != NULL && zfsvfs->z_use_fuids) {
2023 		if (XVA_ISSET_REQ(xvap, XAT_ARCHIVE)) {
2024 			xoap->xoa_archive =
2025 			    ((zp->z_pflags & ZFS_ARCHIVE) != 0);
2026 			XVA_SET_RTN(xvap, XAT_ARCHIVE);
2027 		}
2028 
2029 		if (XVA_ISSET_REQ(xvap, XAT_READONLY)) {
2030 			xoap->xoa_readonly =
2031 			    ((zp->z_pflags & ZFS_READONLY) != 0);
2032 			XVA_SET_RTN(xvap, XAT_READONLY);
2033 		}
2034 
2035 		if (XVA_ISSET_REQ(xvap, XAT_SYSTEM)) {
2036 			xoap->xoa_system =
2037 			    ((zp->z_pflags & ZFS_SYSTEM) != 0);
2038 			XVA_SET_RTN(xvap, XAT_SYSTEM);
2039 		}
2040 
2041 		if (XVA_ISSET_REQ(xvap, XAT_HIDDEN)) {
2042 			xoap->xoa_hidden =
2043 			    ((zp->z_pflags & ZFS_HIDDEN) != 0);
2044 			XVA_SET_RTN(xvap, XAT_HIDDEN);
2045 		}
2046 
2047 		if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
2048 			xoap->xoa_nounlink =
2049 			    ((zp->z_pflags & ZFS_NOUNLINK) != 0);
2050 			XVA_SET_RTN(xvap, XAT_NOUNLINK);
2051 		}
2052 
2053 		if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
2054 			xoap->xoa_immutable =
2055 			    ((zp->z_pflags & ZFS_IMMUTABLE) != 0);
2056 			XVA_SET_RTN(xvap, XAT_IMMUTABLE);
2057 		}
2058 
2059 		if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
2060 			xoap->xoa_appendonly =
2061 			    ((zp->z_pflags & ZFS_APPENDONLY) != 0);
2062 			XVA_SET_RTN(xvap, XAT_APPENDONLY);
2063 		}
2064 
2065 		if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
2066 			xoap->xoa_nodump =
2067 			    ((zp->z_pflags & ZFS_NODUMP) != 0);
2068 			XVA_SET_RTN(xvap, XAT_NODUMP);
2069 		}
2070 
2071 		if (XVA_ISSET_REQ(xvap, XAT_OPAQUE)) {
2072 			xoap->xoa_opaque =
2073 			    ((zp->z_pflags & ZFS_OPAQUE) != 0);
2074 			XVA_SET_RTN(xvap, XAT_OPAQUE);
2075 		}
2076 
2077 		if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
2078 			xoap->xoa_av_quarantined =
2079 			    ((zp->z_pflags & ZFS_AV_QUARANTINED) != 0);
2080 			XVA_SET_RTN(xvap, XAT_AV_QUARANTINED);
2081 		}
2082 
2083 		if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
2084 			xoap->xoa_av_modified =
2085 			    ((zp->z_pflags & ZFS_AV_MODIFIED) != 0);
2086 			XVA_SET_RTN(xvap, XAT_AV_MODIFIED);
2087 		}
2088 
2089 		if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP) &&
2090 		    vp->v_type == VREG) {
2091 			zfs_sa_get_scanstamp(zp, xvap);
2092 		}
2093 
2094 		if (XVA_ISSET_REQ(xvap, XAT_REPARSE)) {
2095 			xoap->xoa_reparse = ((zp->z_pflags & ZFS_REPARSE) != 0);
2096 			XVA_SET_RTN(xvap, XAT_REPARSE);
2097 		}
2098 		if (XVA_ISSET_REQ(xvap, XAT_GEN)) {
2099 			xoap->xoa_generation = zp->z_gen;
2100 			XVA_SET_RTN(xvap, XAT_GEN);
2101 		}
2102 
2103 		if (XVA_ISSET_REQ(xvap, XAT_OFFLINE)) {
2104 			xoap->xoa_offline =
2105 			    ((zp->z_pflags & ZFS_OFFLINE) != 0);
2106 			XVA_SET_RTN(xvap, XAT_OFFLINE);
2107 		}
2108 
2109 		if (XVA_ISSET_REQ(xvap, XAT_SPARSE)) {
2110 			xoap->xoa_sparse =
2111 			    ((zp->z_pflags & ZFS_SPARSE) != 0);
2112 			XVA_SET_RTN(xvap, XAT_SPARSE);
2113 		}
2114 
2115 		if (XVA_ISSET_REQ(xvap, XAT_PROJINHERIT)) {
2116 			xoap->xoa_projinherit =
2117 			    ((zp->z_pflags & ZFS_PROJINHERIT) != 0);
2118 			XVA_SET_RTN(xvap, XAT_PROJINHERIT);
2119 		}
2120 
2121 		if (XVA_ISSET_REQ(xvap, XAT_PROJID)) {
2122 			xoap->xoa_projid = zp->z_projid;
2123 			XVA_SET_RTN(xvap, XAT_PROJID);
2124 		}
2125 	}
2126 
2127 	ZFS_TIME_DECODE(&vap->va_atime, zp->z_atime);
2128 	ZFS_TIME_DECODE(&vap->va_mtime, mtime);
2129 	ZFS_TIME_DECODE(&vap->va_ctime, ctime);
2130 	ZFS_TIME_DECODE(&vap->va_birthtime, crtime);
2131 
2132 
2133 	sa_object_size(zp->z_sa_hdl, &blksize, &nblocks);
2134 	vap->va_blksize = blksize;
2135 	vap->va_bytes = nblocks << 9;	/* nblocks * 512 */
2136 
2137 	if (zp->z_blksz == 0) {
2138 		/*
2139 		 * Block size hasn't been set; suggest maximal I/O transfers.
2140 		 */
2141 		vap->va_blksize = zfsvfs->z_max_blksz;
2142 	}
2143 
2144 	zfs_exit(zfsvfs, FTAG);
2145 	return (0);
2146 }
2147 
2148 /*
2149  * For the operation of changing file's user/group/project, we need to
2150  * handle not only the main object that is assigned to the file directly,
2151  * but also the ones that are used by the file via hidden xattr directory.
2152  *
2153  * Because the xattr directory may contains many EA entries, as to it may
2154  * be impossible to change all of them via the transaction of changing the
2155  * main object's user/group/project attributes. Then we have to change them
2156  * via other multiple independent transactions one by one. It may be not good
2157  * solution, but we have no better idea yet.
2158  */
2159 static int
zfs_setattr_dir(znode_t * dzp)2160 zfs_setattr_dir(znode_t *dzp)
2161 {
2162 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
2163 	objset_t	*os = zfsvfs->z_os;
2164 	zap_cursor_t	zc;
2165 	zap_attribute_t	*zap;
2166 	znode_t		*zp = NULL;
2167 	dmu_tx_t	*tx = NULL;
2168 	uint64_t	uid, gid;
2169 	sa_bulk_attr_t	bulk[4];
2170 	int		count;
2171 	int		err;
2172 
2173 	zap = zap_attribute_alloc();
2174 	zap_cursor_init(&zc, os, dzp->z_id);
2175 	while ((err = zap_cursor_retrieve(&zc, zap)) == 0) {
2176 		count = 0;
2177 		if (zap->za_integer_length != 8 || zap->za_num_integers != 1) {
2178 			err = ENXIO;
2179 			break;
2180 		}
2181 
2182 		err = zfs_dirent_lookup(dzp, zap->za_name, &zp, ZEXISTS);
2183 		if (err == ENOENT)
2184 			goto next;
2185 		if (err)
2186 			break;
2187 
2188 		if (zp->z_uid == dzp->z_uid &&
2189 		    zp->z_gid == dzp->z_gid &&
2190 		    zp->z_projid == dzp->z_projid)
2191 			goto next;
2192 
2193 		tx = dmu_tx_create(os);
2194 		if (!(zp->z_pflags & ZFS_PROJID))
2195 			dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
2196 		else
2197 			dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
2198 
2199 		err = dmu_tx_assign(tx, DMU_TX_WAIT);
2200 		if (err)
2201 			break;
2202 
2203 		vn_seqc_write_begin(ZTOV(zp));
2204 		mutex_enter(&dzp->z_lock);
2205 
2206 		if (zp->z_uid != dzp->z_uid) {
2207 			uid = dzp->z_uid;
2208 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_UID(zfsvfs), NULL,
2209 			    &uid, sizeof (uid));
2210 			zp->z_uid = uid;
2211 		}
2212 
2213 		if (zp->z_gid != dzp->z_gid) {
2214 			gid = dzp->z_gid;
2215 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GID(zfsvfs), NULL,
2216 			    &gid, sizeof (gid));
2217 			zp->z_gid = gid;
2218 		}
2219 
2220 		uint64_t projid = dzp->z_projid;
2221 		if (zp->z_projid != projid) {
2222 			if (!(zp->z_pflags & ZFS_PROJID)) {
2223 				err = sa_add_projid(zp->z_sa_hdl, tx, projid);
2224 				if (unlikely(err == EEXIST)) {
2225 					err = 0;
2226 				} else if (err != 0) {
2227 					goto sa_add_projid_err;
2228 				} else {
2229 					projid = ZFS_INVALID_PROJID;
2230 				}
2231 			}
2232 
2233 			if (projid != ZFS_INVALID_PROJID) {
2234 				zp->z_projid = projid;
2235 				SA_ADD_BULK_ATTR(bulk, count,
2236 				    SA_ZPL_PROJID(zfsvfs), NULL, &zp->z_projid,
2237 				    sizeof (zp->z_projid));
2238 			}
2239 		}
2240 
2241 sa_add_projid_err:
2242 		mutex_exit(&dzp->z_lock);
2243 
2244 		if (likely(count > 0)) {
2245 			err = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
2246 			dmu_tx_commit(tx);
2247 		} else if (projid == ZFS_INVALID_PROJID) {
2248 			dmu_tx_commit(tx);
2249 		} else {
2250 			dmu_tx_abort(tx);
2251 		}
2252 		tx = NULL;
2253 		vn_seqc_write_end(ZTOV(zp));
2254 		if (err != 0 && err != ENOENT)
2255 			break;
2256 
2257 next:
2258 		if (zp) {
2259 			zrele(zp);
2260 			zp = NULL;
2261 		}
2262 		zap_cursor_advance(&zc);
2263 	}
2264 
2265 	if (tx)
2266 		dmu_tx_abort(tx);
2267 	if (zp) {
2268 		zrele(zp);
2269 	}
2270 	zap_cursor_fini(&zc);
2271 	zap_attribute_free(zap);
2272 
2273 	return (err == ENOENT ? 0 : err);
2274 }
2275 
2276 /*
2277  * Set the file attributes to the values contained in the
2278  * vattr structure.
2279  *
2280  *	IN:	zp	- znode of file to be modified.
2281  *		vap	- new attribute values.
2282  *			  If AT_XVATTR set, then optional attrs are being set
2283  *		flags	- ATTR_UTIME set if non-default time values provided.
2284  *			- ATTR_NOACLCHECK (CIFS context only).
2285  *		cr	- credentials of caller.
2286  *		mnt_ns	- Unused on FreeBSD
2287  *
2288  *	RETURN:	0 on success, error code on failure.
2289  *
2290  * Timestamps:
2291  *	vp - ctime updated, mtime updated if size changed.
2292  */
2293 int
zfs_setattr(znode_t * zp,vattr_t * vap,int flags,cred_t * cr,zidmap_t * mnt_ns)2294 zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr, zidmap_t *mnt_ns)
2295 {
2296 	vnode_t		*vp = ZTOV(zp);
2297 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
2298 	objset_t	*os;
2299 	zilog_t		*zilog;
2300 	dmu_tx_t	*tx;
2301 	vattr_t		oldva;
2302 	xvattr_t	tmpxvattr;
2303 	uint_t		mask = vap->va_mask;
2304 	uint_t		saved_mask = 0;
2305 	uint64_t	saved_mode;
2306 	int		trim_mask = 0;
2307 	uint64_t	new_mode;
2308 	uint64_t	new_uid, new_gid;
2309 	uint64_t	xattr_obj;
2310 	uint64_t	mtime[2], ctime[2];
2311 	uint64_t	projid = ZFS_INVALID_PROJID;
2312 	znode_t		*attrzp;
2313 	int		need_policy = FALSE;
2314 	int		err, err2;
2315 	zfs_fuid_info_t *fuidp = NULL;
2316 	xvattr_t *xvap = (xvattr_t *)vap;	/* vap may be an xvattr_t * */
2317 	xoptattr_t	*xoap;
2318 	zfs_acl_t	*aclp;
2319 	boolean_t skipaclchk = (flags & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
2320 	boolean_t	fuid_dirtied = B_FALSE;
2321 	boolean_t	handle_eadir = B_FALSE;
2322 	sa_bulk_attr_t	bulk[9], xattr_bulk[6];
2323 	int		count = 0, xattr_count = 0;
2324 
2325 	if (mask == 0)
2326 		return (0);
2327 
2328 	if (mask & AT_NOSET)
2329 		return (SET_ERROR(EINVAL));
2330 
2331 	if ((err = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
2332 		return (err);
2333 
2334 	os = zfsvfs->z_os;
2335 	zilog = zfsvfs->z_log;
2336 
2337 	/*
2338 	 * Make sure that if we have ephemeral uid/gid or xvattr specified
2339 	 * that file system is at proper version level
2340 	 */
2341 
2342 	if (zfsvfs->z_use_fuids == B_FALSE &&
2343 	    (((mask & AT_UID) && IS_EPHEMERAL(vap->va_uid)) ||
2344 	    ((mask & AT_GID) && IS_EPHEMERAL(vap->va_gid)) ||
2345 	    (mask & AT_XVATTR))) {
2346 		zfs_exit(zfsvfs, FTAG);
2347 		return (SET_ERROR(EINVAL));
2348 	}
2349 
2350 	if (mask & AT_SIZE && vp->v_type == VDIR) {
2351 		zfs_exit(zfsvfs, FTAG);
2352 		return (SET_ERROR(EISDIR));
2353 	}
2354 
2355 	if (mask & AT_SIZE && vp->v_type != VREG && vp->v_type != VFIFO) {
2356 		zfs_exit(zfsvfs, FTAG);
2357 		return (SET_ERROR(EINVAL));
2358 	}
2359 
2360 	/*
2361 	 * If this is an xvattr_t, then get a pointer to the structure of
2362 	 * optional attributes.  If this is NULL, then we have a vattr_t.
2363 	 */
2364 	xoap = xva_getxoptattr(xvap);
2365 
2366 	xva_init(&tmpxvattr);
2367 
2368 	/*
2369 	 * Immutable files can only alter immutable bit and atime
2370 	 */
2371 	if ((zp->z_pflags & ZFS_IMMUTABLE) &&
2372 	    ((mask & (AT_SIZE|AT_UID|AT_GID|AT_MTIME|AT_MODE)) ||
2373 	    ((mask & AT_XVATTR) && XVA_ISSET_REQ(xvap, XAT_CREATETIME)))) {
2374 		zfs_exit(zfsvfs, FTAG);
2375 		return (SET_ERROR(EPERM));
2376 	}
2377 
2378 	/*
2379 	 * Note: ZFS_READONLY is handled in zfs_zaccess_common.
2380 	 */
2381 
2382 	/*
2383 	 * Verify timestamps doesn't overflow 32 bits.
2384 	 * ZFS can handle large timestamps, but 32bit syscalls can't
2385 	 * handle times greater than 2039.  This check should be removed
2386 	 * once large timestamps are fully supported.
2387 	 */
2388 	if (mask & (AT_ATIME | AT_MTIME)) {
2389 		if (((mask & AT_ATIME) && TIMESPEC_OVERFLOW(&vap->va_atime)) ||
2390 		    ((mask & AT_MTIME) && TIMESPEC_OVERFLOW(&vap->va_mtime))) {
2391 			zfs_exit(zfsvfs, FTAG);
2392 			return (SET_ERROR(EOVERFLOW));
2393 		}
2394 	}
2395 	if (xoap != NULL && (mask & AT_XVATTR)) {
2396 		if (XVA_ISSET_REQ(xvap, XAT_CREATETIME) &&
2397 		    TIMESPEC_OVERFLOW(&vap->va_birthtime)) {
2398 			zfs_exit(zfsvfs, FTAG);
2399 			return (SET_ERROR(EOVERFLOW));
2400 		}
2401 
2402 		if (XVA_ISSET_REQ(xvap, XAT_PROJID)) {
2403 			if (!dmu_objset_projectquota_enabled(os) ||
2404 			    (!S_ISREG(zp->z_mode) && !S_ISDIR(zp->z_mode))) {
2405 				zfs_exit(zfsvfs, FTAG);
2406 				return (SET_ERROR(EOPNOTSUPP));
2407 			}
2408 
2409 			projid = xoap->xoa_projid;
2410 			if (unlikely(projid == ZFS_INVALID_PROJID)) {
2411 				zfs_exit(zfsvfs, FTAG);
2412 				return (SET_ERROR(EINVAL));
2413 			}
2414 
2415 			if (projid == zp->z_projid && zp->z_pflags & ZFS_PROJID)
2416 				projid = ZFS_INVALID_PROJID;
2417 			else
2418 				need_policy = TRUE;
2419 		}
2420 
2421 		if (XVA_ISSET_REQ(xvap, XAT_PROJINHERIT) &&
2422 		    (xoap->xoa_projinherit !=
2423 		    ((zp->z_pflags & ZFS_PROJINHERIT) != 0)) &&
2424 		    (!dmu_objset_projectquota_enabled(os) ||
2425 		    (!S_ISREG(zp->z_mode) && !S_ISDIR(zp->z_mode)))) {
2426 			zfs_exit(zfsvfs, FTAG);
2427 			return (SET_ERROR(EOPNOTSUPP));
2428 		}
2429 	}
2430 
2431 	attrzp = NULL;
2432 	aclp = NULL;
2433 
2434 	if (zfsvfs->z_vfs->vfs_flag & VFS_RDONLY) {
2435 		zfs_exit(zfsvfs, FTAG);
2436 		return (SET_ERROR(EROFS));
2437 	}
2438 
2439 	/*
2440 	 * First validate permissions
2441 	 */
2442 
2443 	if (mask & AT_SIZE) {
2444 		/*
2445 		 * XXX - Note, we are not providing any open
2446 		 * mode flags here (like FNDELAY), so we may
2447 		 * block if there are locks present... this
2448 		 * should be addressed in openat().
2449 		 */
2450 		/* XXX - would it be OK to generate a log record here? */
2451 		err = zfs_freesp(zp, vap->va_size, 0, 0, FALSE);
2452 		if (err) {
2453 			zfs_exit(zfsvfs, FTAG);
2454 			return (err);
2455 		}
2456 	}
2457 
2458 	if (mask & (AT_ATIME|AT_MTIME) ||
2459 	    ((mask & AT_XVATTR) && (XVA_ISSET_REQ(xvap, XAT_HIDDEN) ||
2460 	    XVA_ISSET_REQ(xvap, XAT_READONLY) ||
2461 	    XVA_ISSET_REQ(xvap, XAT_ARCHIVE) ||
2462 	    XVA_ISSET_REQ(xvap, XAT_OFFLINE) ||
2463 	    XVA_ISSET_REQ(xvap, XAT_SPARSE) ||
2464 	    XVA_ISSET_REQ(xvap, XAT_CREATETIME) ||
2465 	    XVA_ISSET_REQ(xvap, XAT_SYSTEM)))) {
2466 		need_policy = zfs_zaccess(zp, ACE_WRITE_ATTRIBUTES, 0,
2467 		    skipaclchk, cr, mnt_ns);
2468 	}
2469 
2470 	if (mask & (AT_UID|AT_GID)) {
2471 		int	idmask = (mask & (AT_UID|AT_GID));
2472 		int	take_owner;
2473 		int	take_group;
2474 
2475 		/*
2476 		 * NOTE: even if a new mode is being set,
2477 		 * we may clear S_ISUID/S_ISGID bits.
2478 		 */
2479 
2480 		if (!(mask & AT_MODE))
2481 			vap->va_mode = zp->z_mode;
2482 
2483 		/*
2484 		 * Take ownership or chgrp to group we are a member of
2485 		 */
2486 
2487 		take_owner = (mask & AT_UID) && (vap->va_uid == crgetuid(cr));
2488 		take_group = (mask & AT_GID) &&
2489 		    zfs_groupmember(zfsvfs, vap->va_gid, cr);
2490 
2491 		/*
2492 		 * If both AT_UID and AT_GID are set then take_owner and
2493 		 * take_group must both be set in order to allow taking
2494 		 * ownership.
2495 		 *
2496 		 * Otherwise, send the check through secpolicy_vnode_setattr()
2497 		 *
2498 		 */
2499 
2500 		if (((idmask == (AT_UID|AT_GID)) && take_owner && take_group) ||
2501 		    ((idmask == AT_UID) && take_owner) ||
2502 		    ((idmask == AT_GID) && take_group)) {
2503 			if (zfs_zaccess(zp, ACE_WRITE_OWNER, 0,
2504 			    skipaclchk, cr, mnt_ns) == 0) {
2505 				/*
2506 				 * Remove setuid/setgid for non-privileged users
2507 				 */
2508 				secpolicy_setid_clear(vap, vp, cr);
2509 				trim_mask = (mask & (AT_UID|AT_GID));
2510 			} else {
2511 				need_policy =  TRUE;
2512 			}
2513 		} else {
2514 			need_policy =  TRUE;
2515 		}
2516 	}
2517 
2518 	oldva.va_mode = zp->z_mode;
2519 	zfs_fuid_map_ids(zp, cr, &oldva.va_uid, &oldva.va_gid);
2520 	if (mask & AT_XVATTR) {
2521 		/*
2522 		 * Update xvattr mask to include only those attributes
2523 		 * that are actually changing.
2524 		 *
2525 		 * the bits will be restored prior to actually setting
2526 		 * the attributes so the caller thinks they were set.
2527 		 */
2528 		if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
2529 			if (xoap->xoa_appendonly !=
2530 			    ((zp->z_pflags & ZFS_APPENDONLY) != 0)) {
2531 				need_policy = TRUE;
2532 			} else {
2533 				XVA_CLR_REQ(xvap, XAT_APPENDONLY);
2534 				XVA_SET_REQ(&tmpxvattr, XAT_APPENDONLY);
2535 			}
2536 		}
2537 
2538 		if (XVA_ISSET_REQ(xvap, XAT_PROJINHERIT)) {
2539 			if (xoap->xoa_projinherit !=
2540 			    ((zp->z_pflags & ZFS_PROJINHERIT) != 0)) {
2541 				need_policy = TRUE;
2542 			} else {
2543 				XVA_CLR_REQ(xvap, XAT_PROJINHERIT);
2544 				XVA_SET_REQ(&tmpxvattr, XAT_PROJINHERIT);
2545 			}
2546 		}
2547 
2548 		if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
2549 			if (xoap->xoa_nounlink !=
2550 			    ((zp->z_pflags & ZFS_NOUNLINK) != 0)) {
2551 				need_policy = TRUE;
2552 			} else {
2553 				XVA_CLR_REQ(xvap, XAT_NOUNLINK);
2554 				XVA_SET_REQ(&tmpxvattr, XAT_NOUNLINK);
2555 			}
2556 		}
2557 
2558 		if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
2559 			if (xoap->xoa_immutable !=
2560 			    ((zp->z_pflags & ZFS_IMMUTABLE) != 0)) {
2561 				need_policy = TRUE;
2562 			} else {
2563 				XVA_CLR_REQ(xvap, XAT_IMMUTABLE);
2564 				XVA_SET_REQ(&tmpxvattr, XAT_IMMUTABLE);
2565 			}
2566 		}
2567 
2568 		if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
2569 			if (xoap->xoa_nodump !=
2570 			    ((zp->z_pflags & ZFS_NODUMP) != 0)) {
2571 				need_policy = TRUE;
2572 			} else {
2573 				XVA_CLR_REQ(xvap, XAT_NODUMP);
2574 				XVA_SET_REQ(&tmpxvattr, XAT_NODUMP);
2575 			}
2576 		}
2577 
2578 		if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
2579 			if (xoap->xoa_av_modified !=
2580 			    ((zp->z_pflags & ZFS_AV_MODIFIED) != 0)) {
2581 				need_policy = TRUE;
2582 			} else {
2583 				XVA_CLR_REQ(xvap, XAT_AV_MODIFIED);
2584 				XVA_SET_REQ(&tmpxvattr, XAT_AV_MODIFIED);
2585 			}
2586 		}
2587 
2588 		if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
2589 			if ((vp->v_type != VREG &&
2590 			    xoap->xoa_av_quarantined) ||
2591 			    xoap->xoa_av_quarantined !=
2592 			    ((zp->z_pflags & ZFS_AV_QUARANTINED) != 0)) {
2593 				need_policy = TRUE;
2594 			} else {
2595 				XVA_CLR_REQ(xvap, XAT_AV_QUARANTINED);
2596 				XVA_SET_REQ(&tmpxvattr, XAT_AV_QUARANTINED);
2597 			}
2598 		}
2599 
2600 		if (XVA_ISSET_REQ(xvap, XAT_REPARSE)) {
2601 			zfs_exit(zfsvfs, FTAG);
2602 			return (SET_ERROR(EPERM));
2603 		}
2604 
2605 		if (need_policy == FALSE &&
2606 		    (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP) ||
2607 		    XVA_ISSET_REQ(xvap, XAT_OPAQUE))) {
2608 			need_policy = TRUE;
2609 		}
2610 	}
2611 
2612 	if (mask & AT_MODE) {
2613 		if (zfs_zaccess(zp, ACE_WRITE_ACL, 0, skipaclchk, cr,
2614 		    mnt_ns) == 0) {
2615 			err = secpolicy_setid_setsticky_clear(vp, vap,
2616 			    &oldva, cr);
2617 			if (err) {
2618 				zfs_exit(zfsvfs, FTAG);
2619 				return (err);
2620 			}
2621 			trim_mask |= AT_MODE;
2622 		} else {
2623 			need_policy = TRUE;
2624 		}
2625 	}
2626 
2627 	if (need_policy) {
2628 		/*
2629 		 * If trim_mask is set then take ownership
2630 		 * has been granted or write_acl is present and user
2631 		 * has the ability to modify mode.  In that case remove
2632 		 * UID|GID and or MODE from mask so that
2633 		 * secpolicy_vnode_setattr() doesn't revoke it.
2634 		 */
2635 
2636 		if (trim_mask) {
2637 			saved_mask = vap->va_mask;
2638 			vap->va_mask &= ~trim_mask;
2639 			if (trim_mask & AT_MODE) {
2640 				/*
2641 				 * Save the mode, as secpolicy_vnode_setattr()
2642 				 * will overwrite it with ova.va_mode.
2643 				 */
2644 				saved_mode = vap->va_mode;
2645 			}
2646 		}
2647 		err = secpolicy_vnode_setattr(cr, vp, vap, &oldva, flags,
2648 		    (int (*)(void *, int, cred_t *))zfs_zaccess_unix, zp);
2649 		if (err) {
2650 			zfs_exit(zfsvfs, FTAG);
2651 			return (err);
2652 		}
2653 
2654 		if (trim_mask) {
2655 			vap->va_mask |= saved_mask;
2656 			if (trim_mask & AT_MODE) {
2657 				/*
2658 				 * Recover the mode after
2659 				 * secpolicy_vnode_setattr().
2660 				 */
2661 				vap->va_mode = saved_mode;
2662 			}
2663 		}
2664 	}
2665 
2666 	/*
2667 	 * secpolicy_vnode_setattr, or take ownership may have
2668 	 * changed va_mask
2669 	 */
2670 	mask = vap->va_mask;
2671 
2672 	if ((mask & (AT_UID | AT_GID)) || projid != ZFS_INVALID_PROJID) {
2673 		handle_eadir = B_TRUE;
2674 		err = sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
2675 		    &xattr_obj, sizeof (xattr_obj));
2676 
2677 		if (err == 0 && xattr_obj) {
2678 			err = zfs_zget(zp->z_zfsvfs, xattr_obj, &attrzp);
2679 			if (err == 0) {
2680 				err = vn_lock(ZTOV(attrzp), LK_EXCLUSIVE);
2681 				if (err != 0)
2682 					vrele(ZTOV(attrzp));
2683 			}
2684 			if (err)
2685 				goto out2;
2686 		}
2687 		if (mask & AT_UID) {
2688 			new_uid = zfs_fuid_create(zfsvfs,
2689 			    (uint64_t)vap->va_uid, cr, ZFS_OWNER, &fuidp);
2690 			if (new_uid != zp->z_uid &&
2691 			    zfs_id_overquota(zfsvfs, DMU_USERUSED_OBJECT,
2692 			    new_uid)) {
2693 				if (attrzp)
2694 					vput(ZTOV(attrzp));
2695 				err = SET_ERROR(EDQUOT);
2696 				goto out2;
2697 			}
2698 		}
2699 
2700 		if (mask & AT_GID) {
2701 			new_gid = zfs_fuid_create(zfsvfs, (uint64_t)vap->va_gid,
2702 			    cr, ZFS_GROUP, &fuidp);
2703 			if (new_gid != zp->z_gid &&
2704 			    zfs_id_overquota(zfsvfs, DMU_GROUPUSED_OBJECT,
2705 			    new_gid)) {
2706 				if (attrzp)
2707 					vput(ZTOV(attrzp));
2708 				err = SET_ERROR(EDQUOT);
2709 				goto out2;
2710 			}
2711 		}
2712 
2713 		if (projid != ZFS_INVALID_PROJID &&
2714 		    zfs_id_overquota(zfsvfs, DMU_PROJECTUSED_OBJECT, projid)) {
2715 			if (attrzp)
2716 				vput(ZTOV(attrzp));
2717 			err = SET_ERROR(EDQUOT);
2718 			goto out2;
2719 		}
2720 	}
2721 	tx = dmu_tx_create(os);
2722 
2723 	if (mask & AT_MODE) {
2724 		uint64_t pmode = zp->z_mode;
2725 		uint64_t acl_obj;
2726 		new_mode = (pmode & S_IFMT) | (vap->va_mode & ~S_IFMT);
2727 
2728 		if (zp->z_zfsvfs->z_acl_mode == ZFS_ACL_RESTRICTED &&
2729 		    !(zp->z_pflags & ZFS_ACL_TRIVIAL)) {
2730 			err = SET_ERROR(EPERM);
2731 			goto out;
2732 		}
2733 
2734 		if ((err = zfs_acl_chmod_setattr(zp, &aclp, new_mode)))
2735 			goto out;
2736 
2737 		if (!zp->z_is_sa && ((acl_obj = zfs_external_acl(zp)) != 0)) {
2738 			/*
2739 			 * Are we upgrading ACL from old V0 format
2740 			 * to V1 format?
2741 			 */
2742 			if (zfsvfs->z_version >= ZPL_VERSION_FUID &&
2743 			    zfs_znode_acl_version(zp) ==
2744 			    ZFS_ACL_VERSION_INITIAL) {
2745 				dmu_tx_hold_free(tx, acl_obj, 0,
2746 				    DMU_OBJECT_END);
2747 				dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
2748 				    0, aclp->z_acl_bytes);
2749 			} else {
2750 				dmu_tx_hold_write(tx, acl_obj, 0,
2751 				    aclp->z_acl_bytes);
2752 			}
2753 		} else if (!zp->z_is_sa && aclp->z_acl_bytes > ZFS_ACE_SPACE) {
2754 			dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
2755 			    0, aclp->z_acl_bytes);
2756 		}
2757 		dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
2758 	} else {
2759 		if (((mask & AT_XVATTR) &&
2760 		    XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP)) ||
2761 		    (projid != ZFS_INVALID_PROJID &&
2762 		    !(zp->z_pflags & ZFS_PROJID)) ||
2763 		    !zp->z_has_seq)
2764 			dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
2765 		else
2766 			dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
2767 	}
2768 
2769 	if (attrzp) {
2770 		dmu_tx_hold_sa(tx, attrzp->z_sa_hdl, ZFS_SEQ_MAY_GROW(attrzp));
2771 	}
2772 
2773 	fuid_dirtied = zfsvfs->z_fuid_dirty;
2774 	if (fuid_dirtied)
2775 		zfs_fuid_txhold(zfsvfs, tx);
2776 
2777 	zfs_sa_upgrade_txholds(tx, zp);
2778 
2779 	err = dmu_tx_assign(tx, DMU_TX_WAIT);
2780 	if (err)
2781 		goto out;
2782 
2783 	count = 0;
2784 	/*
2785 	 * Set each attribute requested.
2786 	 * We group settings according to the locks they need to acquire.
2787 	 *
2788 	 * Note: you cannot set ctime directly, although it will be
2789 	 * updated as a side-effect of calling this function.
2790 	 */
2791 
2792 	if (projid != ZFS_INVALID_PROJID && !(zp->z_pflags & ZFS_PROJID)) {
2793 		/*
2794 		 * For the existed object that is upgraded from old system,
2795 		 * its on-disk layout has no slot for the project ID attribute.
2796 		 * But quota accounting logic needs to access related slots by
2797 		 * offset directly. So we need to adjust old objects' layout
2798 		 * to make the project ID to some unified and fixed offset.
2799 		 */
2800 		if (attrzp)
2801 			err = sa_add_projid(attrzp->z_sa_hdl, tx, projid);
2802 		if (err == 0)
2803 			err = sa_add_projid(zp->z_sa_hdl, tx, projid);
2804 
2805 		if (unlikely(err == EEXIST))
2806 			err = 0;
2807 		else if (err != 0)
2808 			goto out;
2809 		else
2810 			projid = ZFS_INVALID_PROJID;
2811 	}
2812 
2813 	if (mask & (AT_UID|AT_GID|AT_MODE))
2814 		mutex_enter(&zp->z_acl_lock);
2815 
2816 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
2817 	    &zp->z_pflags, sizeof (zp->z_pflags));
2818 
2819 	if (attrzp) {
2820 		if (mask & (AT_UID|AT_GID|AT_MODE))
2821 			mutex_enter(&attrzp->z_acl_lock);
2822 		SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
2823 		    SA_ZPL_FLAGS(zfsvfs), NULL, &attrzp->z_pflags,
2824 		    sizeof (attrzp->z_pflags));
2825 		if (projid != ZFS_INVALID_PROJID) {
2826 			attrzp->z_projid = projid;
2827 			SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
2828 			    SA_ZPL_PROJID(zfsvfs), NULL, &attrzp->z_projid,
2829 			    sizeof (attrzp->z_projid));
2830 		}
2831 	}
2832 
2833 	if (mask & (AT_UID|AT_GID)) {
2834 
2835 		if (mask & AT_UID) {
2836 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_UID(zfsvfs), NULL,
2837 			    &new_uid, sizeof (new_uid));
2838 			zp->z_uid = new_uid;
2839 			if (attrzp) {
2840 				SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
2841 				    SA_ZPL_UID(zfsvfs), NULL, &new_uid,
2842 				    sizeof (new_uid));
2843 				attrzp->z_uid = new_uid;
2844 			}
2845 		}
2846 
2847 		if (mask & AT_GID) {
2848 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GID(zfsvfs),
2849 			    NULL, &new_gid, sizeof (new_gid));
2850 			zp->z_gid = new_gid;
2851 			if (attrzp) {
2852 				SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
2853 				    SA_ZPL_GID(zfsvfs), NULL, &new_gid,
2854 				    sizeof (new_gid));
2855 				attrzp->z_gid = new_gid;
2856 			}
2857 		}
2858 		if (!(mask & AT_MODE)) {
2859 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zfsvfs),
2860 			    NULL, &new_mode, sizeof (new_mode));
2861 			new_mode = zp->z_mode;
2862 		}
2863 		err = zfs_acl_chown_setattr(zp);
2864 		ASSERT0(err);
2865 		if (attrzp) {
2866 			vn_seqc_write_begin(ZTOV(attrzp));
2867 			err = zfs_acl_chown_setattr(attrzp);
2868 			vn_seqc_write_end(ZTOV(attrzp));
2869 			ASSERT0(err);
2870 		}
2871 	}
2872 
2873 	if (mask & AT_MODE) {
2874 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zfsvfs), NULL,
2875 		    &new_mode, sizeof (new_mode));
2876 		zp->z_mode = new_mode;
2877 		ASSERT3P(aclp, !=, NULL);
2878 		err = zfs_aclset_common(zp, aclp, cr, tx);
2879 		ASSERT0(err);
2880 		if (zp->z_acl_cached)
2881 			zfs_acl_free(zp->z_acl_cached);
2882 		zp->z_acl_cached = aclp;
2883 		aclp = NULL;
2884 	}
2885 
2886 
2887 	if (mask & AT_ATIME) {
2888 		ZFS_TIME_ENCODE(&vap->va_atime, zp->z_atime);
2889 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_ATIME(zfsvfs), NULL,
2890 		    &zp->z_atime, sizeof (zp->z_atime));
2891 	}
2892 
2893 	if (mask & AT_MTIME) {
2894 		ZFS_TIME_ENCODE(&vap->va_mtime, mtime);
2895 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL,
2896 		    mtime, sizeof (mtime));
2897 	}
2898 
2899 	if (projid != ZFS_INVALID_PROJID) {
2900 		zp->z_projid = projid;
2901 		SA_ADD_BULK_ATTR(bulk, count,
2902 		    SA_ZPL_PROJID(zfsvfs), NULL, &zp->z_projid,
2903 		    sizeof (zp->z_projid));
2904 	}
2905 
2906 	/* XXX - shouldn't this be done *before* the ATIME/MTIME checks? */
2907 	if (mask & AT_SIZE && !(mask & AT_MTIME)) {
2908 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs),
2909 		    NULL, mtime, sizeof (mtime));
2910 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
2911 		    &ctime, sizeof (ctime));
2912 		zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime);
2913 		ZFS_PERSIST_SEQ(zp, bulk, count);
2914 	} else if (mask != 0) {
2915 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
2916 		    &ctime, sizeof (ctime));
2917 		zfs_tstamp_update_setup(zp, STATE_CHANGED, mtime, ctime);
2918 		ZFS_PERSIST_SEQ(zp, bulk, count);
2919 		if (attrzp) {
2920 			SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
2921 			    SA_ZPL_CTIME(zfsvfs), NULL,
2922 			    &ctime, sizeof (ctime));
2923 			zfs_tstamp_update_setup(attrzp, STATE_CHANGED,
2924 			    mtime, ctime);
2925 			ZFS_PERSIST_SEQ(attrzp, xattr_bulk, xattr_count);
2926 		}
2927 	}
2928 
2929 	/*
2930 	 * Do this after setting timestamps to prevent timestamp
2931 	 * update from toggling bit
2932 	 */
2933 
2934 	if (xoap && (mask & AT_XVATTR)) {
2935 
2936 		if (XVA_ISSET_REQ(xvap, XAT_CREATETIME))
2937 			xoap->xoa_createtime = vap->va_birthtime;
2938 		/*
2939 		 * restore trimmed off masks
2940 		 * so that return masks can be set for caller.
2941 		 */
2942 
2943 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_APPENDONLY)) {
2944 			XVA_SET_REQ(xvap, XAT_APPENDONLY);
2945 		}
2946 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_NOUNLINK)) {
2947 			XVA_SET_REQ(xvap, XAT_NOUNLINK);
2948 		}
2949 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_IMMUTABLE)) {
2950 			XVA_SET_REQ(xvap, XAT_IMMUTABLE);
2951 		}
2952 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_NODUMP)) {
2953 			XVA_SET_REQ(xvap, XAT_NODUMP);
2954 		}
2955 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_AV_MODIFIED)) {
2956 			XVA_SET_REQ(xvap, XAT_AV_MODIFIED);
2957 		}
2958 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_AV_QUARANTINED)) {
2959 			XVA_SET_REQ(xvap, XAT_AV_QUARANTINED);
2960 		}
2961 		if (XVA_ISSET_REQ(&tmpxvattr, XAT_PROJINHERIT)) {
2962 			XVA_SET_REQ(xvap, XAT_PROJINHERIT);
2963 		}
2964 
2965 		if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP))
2966 			ASSERT3S(vp->v_type, ==, VREG);
2967 
2968 		zfs_xvattr_set(zp, xvap, tx);
2969 	}
2970 
2971 	if (fuid_dirtied)
2972 		zfs_fuid_sync(zfsvfs, tx);
2973 
2974 	if (mask != 0)
2975 		zfs_log_setattr(zilog, tx, TX_SETATTR, zp, vap, mask, fuidp);
2976 
2977 	if (mask & (AT_UID|AT_GID|AT_MODE))
2978 		mutex_exit(&zp->z_acl_lock);
2979 
2980 	if (attrzp) {
2981 		if (mask & (AT_UID|AT_GID|AT_MODE))
2982 			mutex_exit(&attrzp->z_acl_lock);
2983 	}
2984 out:
2985 	if (err == 0 && attrzp) {
2986 		ASSERT3S(xattr_count, <=, ARRAY_SIZE(xattr_bulk));
2987 		err2 = sa_bulk_update(attrzp->z_sa_hdl, xattr_bulk,
2988 		    xattr_count, tx);
2989 		ASSERT0(err2);
2990 	}
2991 
2992 	if (aclp)
2993 		zfs_acl_free(aclp);
2994 
2995 	if (fuidp) {
2996 		zfs_fuid_info_free(fuidp);
2997 		fuidp = NULL;
2998 	}
2999 
3000 	if (err) {
3001 		dmu_tx_abort(tx);
3002 		if (attrzp)
3003 			vput(ZTOV(attrzp));
3004 	} else {
3005 		ASSERT3S(count, <=, ARRAY_SIZE(bulk));
3006 		err2 = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
3007 		dmu_tx_commit(tx);
3008 		if (attrzp) {
3009 			if (err2 == 0 && handle_eadir)
3010 				err = zfs_setattr_dir(attrzp);
3011 			vput(ZTOV(attrzp));
3012 		}
3013 	}
3014 
3015 out2:
3016 	if (err == 0 && os->os_sync == ZFS_SYNC_ALWAYS)
3017 		err = zil_commit(zilog, 0);
3018 
3019 	zfs_exit(zfsvfs, FTAG);
3020 	return (err);
3021 }
3022 
3023 /*
3024  * Look up the directory entries corresponding to the source and target
3025  * directory/name pairs.
3026  */
3027 static int
zfs_rename_relock_lookup(znode_t * sdzp,const struct componentname * scnp,znode_t ** szpp,znode_t * tdzp,const struct componentname * tcnp,znode_t ** tzpp)3028 zfs_rename_relock_lookup(znode_t *sdzp, const struct componentname *scnp,
3029     znode_t **szpp, znode_t *tdzp, const struct componentname *tcnp,
3030     znode_t **tzpp)
3031 {
3032 	zfsvfs_t *zfsvfs;
3033 	znode_t *szp, *tzp;
3034 	int error;
3035 
3036 	/*
3037 	 * Before using sdzp and tdzp we must ensure that they are live.
3038 	 * As a porting legacy from illumos we have two things to worry
3039 	 * about.  One is typical for FreeBSD and it is that the vnode is
3040 	 * not reclaimed (doomed).  The other is that the znode is live.
3041 	 * The current code can invalidate the znode without acquiring the
3042 	 * corresponding vnode lock if the object represented by the znode
3043 	 * and vnode is no longer valid after a rollback or receive operation.
3044 	 * z_teardown_lock hidden behind zfs_enter and zfs_exit is the lock
3045 	 * that protects the znodes from the invalidation.
3046 	 */
3047 	zfsvfs = sdzp->z_zfsvfs;
3048 	ASSERT3P(zfsvfs, ==, tdzp->z_zfsvfs);
3049 	if ((error = zfs_enter_verify_zp(zfsvfs, sdzp, FTAG)) != 0)
3050 		return (error);
3051 	if ((error = zfs_verify_zp(tdzp)) != 0) {
3052 		zfs_exit(zfsvfs, FTAG);
3053 		return (error);
3054 	}
3055 
3056 	/*
3057 	 * Re-resolve svp to be certain it still exists and fetch the
3058 	 * correct vnode.
3059 	 */
3060 	error = zfs_dirent_lookup(sdzp, scnp->cn_nameptr, &szp, ZEXISTS);
3061 	if (error != 0) {
3062 		/* Source entry invalid or not there. */
3063 		if ((scnp->cn_flags & ISDOTDOT) != 0 ||
3064 		    (scnp->cn_namelen == 1 && scnp->cn_nameptr[0] == '.'))
3065 			error = SET_ERROR(EINVAL);
3066 		goto out;
3067 	}
3068 	*szpp = szp;
3069 
3070 	/*
3071 	 * Re-resolve tvp, if it disappeared we just carry on.
3072 	 */
3073 	error = zfs_dirent_lookup(tdzp, tcnp->cn_nameptr, &tzp, 0);
3074 	if (error != 0) {
3075 		vrele(ZTOV(szp));
3076 		if ((tcnp->cn_flags & ISDOTDOT) != 0)
3077 			error = SET_ERROR(EINVAL);
3078 		goto out;
3079 	}
3080 	*tzpp = tzp;
3081 out:
3082 	zfs_exit(zfsvfs, FTAG);
3083 	return (error);
3084 }
3085 
3086 /*
3087  * We acquire all but fdvp locks using non-blocking acquisitions.  If we
3088  * fail to acquire any lock in the path we will drop all held locks,
3089  * acquire the new lock in a blocking fashion, and then release it and
3090  * restart the rename.  This acquire/release step ensures that we do not
3091  * spin on a lock waiting for release.  On error release all vnode locks
3092  * and decrement references the way tmpfs_rename() would do.
3093  */
3094 static int
zfs_rename_relock(struct vnode * sdvp,struct vnode ** svpp,struct vnode * tdvp,struct vnode ** tvpp,const struct componentname * scnp,const struct componentname * tcnp)3095 zfs_rename_relock(struct vnode *sdvp, struct vnode **svpp,
3096     struct vnode *tdvp, struct vnode **tvpp,
3097     const struct componentname *scnp, const struct componentname *tcnp)
3098 {
3099 	struct vnode	*nvp, *svp, *tvp;
3100 	znode_t		*sdzp, *tdzp, *szp, *tzp;
3101 	int		error;
3102 
3103 	VOP_UNLOCK(tdvp);
3104 	if (*tvpp != NULL && *tvpp != tdvp)
3105 		VOP_UNLOCK(*tvpp);
3106 
3107 relock:
3108 	error = vn_lock(sdvp, LK_EXCLUSIVE);
3109 	if (error)
3110 		goto out;
3111 	error = vn_lock(tdvp, LK_EXCLUSIVE | LK_NOWAIT);
3112 	if (error != 0) {
3113 		VOP_UNLOCK(sdvp);
3114 		if (error != EBUSY)
3115 			goto out;
3116 		error = vn_lock(tdvp, LK_EXCLUSIVE);
3117 		if (error)
3118 			goto out;
3119 		VOP_UNLOCK(tdvp);
3120 		goto relock;
3121 	}
3122 	tdzp = VTOZ(tdvp);
3123 	sdzp = VTOZ(sdvp);
3124 
3125 	error = zfs_rename_relock_lookup(sdzp, scnp, &szp, tdzp, tcnp, &tzp);
3126 	if (error != 0) {
3127 		VOP_UNLOCK(sdvp);
3128 		VOP_UNLOCK(tdvp);
3129 		goto out;
3130 	}
3131 	svp = ZTOV(szp);
3132 	tvp = tzp != NULL ? ZTOV(tzp) : NULL;
3133 
3134 	/*
3135 	 * Now try acquire locks on svp and tvp.
3136 	 */
3137 	nvp = svp;
3138 	error = vn_lock(nvp, LK_EXCLUSIVE | LK_NOWAIT);
3139 	if (error != 0) {
3140 		VOP_UNLOCK(sdvp);
3141 		VOP_UNLOCK(tdvp);
3142 		if (tvp != NULL)
3143 			vrele(tvp);
3144 		if (error != EBUSY) {
3145 			vrele(nvp);
3146 			goto out;
3147 		}
3148 		error = vn_lock(nvp, LK_EXCLUSIVE);
3149 		if (error != 0) {
3150 			vrele(nvp);
3151 			goto out;
3152 		}
3153 		VOP_UNLOCK(nvp);
3154 		/*
3155 		 * Concurrent rename race.
3156 		 * XXX ?
3157 		 */
3158 		if (nvp == tdvp) {
3159 			vrele(nvp);
3160 			error = SET_ERROR(EINVAL);
3161 			goto out;
3162 		}
3163 		vrele(*svpp);
3164 		*svpp = nvp;
3165 		goto relock;
3166 	}
3167 	vrele(*svpp);
3168 	*svpp = nvp;
3169 
3170 	if (*tvpp != NULL)
3171 		vrele(*tvpp);
3172 	*tvpp = NULL;
3173 	if (tvp != NULL) {
3174 		nvp = tvp;
3175 		error = vn_lock(nvp, LK_EXCLUSIVE | LK_NOWAIT);
3176 		if (error != 0) {
3177 			VOP_UNLOCK(sdvp);
3178 			VOP_UNLOCK(tdvp);
3179 			VOP_UNLOCK(*svpp);
3180 			if (error != EBUSY) {
3181 				vrele(nvp);
3182 				goto out;
3183 			}
3184 			error = vn_lock(nvp, LK_EXCLUSIVE);
3185 			if (error != 0) {
3186 				vrele(nvp);
3187 				goto out;
3188 			}
3189 			vput(nvp);
3190 			goto relock;
3191 		}
3192 		*tvpp = nvp;
3193 	}
3194 
3195 	return (0);
3196 
3197 out:
3198 	return (error);
3199 }
3200 
3201 /*
3202  * Note that we must use VRELE_ASYNC in this function as it walks
3203  * up the directory tree and vrele may need to acquire an exclusive
3204  * lock if a last reference to a vnode is dropped.
3205  */
3206 static int
zfs_rename_check(znode_t * szp,znode_t * sdzp,znode_t * tdzp)3207 zfs_rename_check(znode_t *szp, znode_t *sdzp, znode_t *tdzp)
3208 {
3209 	zfsvfs_t	*zfsvfs;
3210 	znode_t		*zp, *zp1;
3211 	uint64_t	parent;
3212 	int		error;
3213 
3214 	zfsvfs = tdzp->z_zfsvfs;
3215 	if (tdzp == szp)
3216 		return (SET_ERROR(EINVAL));
3217 	if (tdzp == sdzp)
3218 		return (0);
3219 	if (tdzp->z_id == zfsvfs->z_root)
3220 		return (0);
3221 	zp = tdzp;
3222 	for (;;) {
3223 		ASSERT(!zp->z_unlinked);
3224 		if ((error = sa_lookup(zp->z_sa_hdl,
3225 		    SA_ZPL_PARENT(zfsvfs), &parent, sizeof (parent))) != 0)
3226 			break;
3227 
3228 		if (parent == szp->z_id) {
3229 			error = SET_ERROR(EINVAL);
3230 			break;
3231 		}
3232 		if (parent == zfsvfs->z_root)
3233 			break;
3234 		if (parent == sdzp->z_id)
3235 			break;
3236 
3237 		error = zfs_zget(zfsvfs, parent, &zp1);
3238 		if (error != 0)
3239 			break;
3240 
3241 		if (zp != tdzp)
3242 			VN_RELE_ASYNC(ZTOV(zp),
3243 			    dsl_pool_zrele_taskq(
3244 			    dmu_objset_pool(zfsvfs->z_os)));
3245 		zp = zp1;
3246 	}
3247 
3248 	if (error == ENOTDIR)
3249 		panic("checkpath: .. not a directory\n");
3250 	if (zp != tdzp)
3251 		VN_RELE_ASYNC(ZTOV(zp),
3252 		    dsl_pool_zrele_taskq(dmu_objset_pool(zfsvfs->z_os)));
3253 	return (error);
3254 }
3255 
3256 static int
3257 zfs_do_rename_impl(vnode_t *sdvp, vnode_t **svpp, struct componentname *scnp,
3258     vnode_t *tdvp, vnode_t **tvpp, struct componentname *tcnp,
3259     cred_t *cr, u_int at_flags);
3260 
3261 /*
3262  * Move an entry from the provided source directory to the target
3263  * directory.  Change the entry name as indicated.
3264  *
3265  *	IN:	sdvp	- Source directory containing the "old entry".
3266  *		scnp	- Old entry name.
3267  *		tdvp	- Target directory to contain the "new entry".
3268  *		tcnp	- New entry name.
3269  *		cr	- credentials of caller.
3270  *		at_flags - AT_RENAME_*
3271  *	INOUT:	svpp	- Source file
3272  *		tvpp	- Target file, may point to NULL initially
3273  *
3274  *	RETURN:	0 on success, error code on failure.
3275  *
3276  * Timestamps:
3277  *	sdvp,tdvp - ctime|mtime updated
3278  */
3279 static int
zfs_do_rename(vnode_t * sdvp,vnode_t ** svpp,struct componentname * scnp,vnode_t * tdvp,vnode_t ** tvpp,struct componentname * tcnp,cred_t * cr,u_int at_flags)3280 zfs_do_rename(vnode_t *sdvp, vnode_t **svpp, struct componentname *scnp,
3281     vnode_t *tdvp, vnode_t **tvpp, struct componentname *tcnp,
3282     cred_t *cr, u_int at_flags)
3283 {
3284 	int	error;
3285 
3286 	ASSERT_VOP_ELOCKED(tdvp, __func__);
3287 	if (*tvpp != NULL)
3288 		ASSERT_VOP_ELOCKED(*tvpp, __func__);
3289 
3290 	/* Reject renames across filesystems. */
3291 	if ((*svpp)->v_mount != tdvp->v_mount ||
3292 	    ((*tvpp) != NULL && (*svpp)->v_mount != (*tvpp)->v_mount)) {
3293 		error = SET_ERROR(EXDEV);
3294 		goto out;
3295 	}
3296 
3297 	if (zfsctl_is_node(tdvp)) {
3298 		error = SET_ERROR(EXDEV);
3299 		goto out;
3300 	}
3301 
3302 	/*
3303 	 * Lock all four vnodes to ensure safety and semantics of renaming.
3304 	 */
3305 	error = zfs_rename_relock(sdvp, svpp, tdvp, tvpp, scnp, tcnp);
3306 	if (error != 0) {
3307 		/* no vnodes are locked in the case of error here */
3308 		return (error);
3309 	}
3310 
3311 	error = zfs_do_rename_impl(sdvp, svpp, scnp, tdvp, tvpp, tcnp, cr,
3312 	    at_flags);
3313 	VOP_UNLOCK(sdvp);
3314 	VOP_UNLOCK(*svpp);
3315 out:
3316 	if (*tvpp != NULL)
3317 		VOP_UNLOCK(*tvpp);
3318 	if (tdvp != *tvpp)
3319 		VOP_UNLOCK(tdvp);
3320 
3321 	return (error);
3322 }
3323 
3324 static int
zfs_do_rename_impl(vnode_t * sdvp,vnode_t ** svpp,struct componentname * scnp,vnode_t * tdvp,vnode_t ** tvpp,struct componentname * tcnp,cred_t * cr,u_int at_flags)3325 zfs_do_rename_impl(vnode_t *sdvp, vnode_t **svpp, struct componentname *scnp,
3326     vnode_t *tdvp, vnode_t **tvpp, struct componentname *tcnp,
3327     cred_t *cr, u_int at_flags)
3328 {
3329 	dmu_tx_t	*tx;
3330 	zfsvfs_t	*zfsvfs;
3331 	zilog_t		*zilog;
3332 	znode_t		*tdzp, *sdzp, *tzp, *szp;
3333 	const char	*snm = scnp->cn_nameptr;
3334 	const char	*tnm = tcnp->cn_nameptr;
3335 	int		error;
3336 
3337 	tdzp = VTOZ(tdvp);
3338 	sdzp = VTOZ(sdvp);
3339 	zfsvfs = tdzp->z_zfsvfs;
3340 
3341 	if ((error = zfs_enter_verify_zp(zfsvfs, tdzp, FTAG)) != 0)
3342 		return (error);
3343 	if ((error = zfs_verify_zp(sdzp)) != 0) {
3344 		zfs_exit(zfsvfs, FTAG);
3345 		return (error);
3346 	}
3347 	zilog = zfsvfs->z_log;
3348 
3349 	if (zfsvfs->z_utf8 && u8_validate(tnm,
3350 	    strlen(tnm), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
3351 		error = SET_ERROR(EILSEQ);
3352 		goto out;
3353 	}
3354 
3355 	/* If source and target are the same file, there is nothing to do. */
3356 	if ((*svpp) == (*tvpp)) {
3357 		error = 0;
3358 		goto out;
3359 	}
3360 
3361 	if (((*svpp)->v_type == VDIR && (*svpp)->v_mountedhere != NULL) ||
3362 	    ((*tvpp) != NULL && (*tvpp)->v_type == VDIR &&
3363 	    (*tvpp)->v_mountedhere != NULL)) {
3364 		error = SET_ERROR(EXDEV);
3365 		goto out;
3366 	}
3367 
3368 	szp = VTOZ(*svpp);
3369 	if ((error = zfs_verify_zp(szp)) != 0) {
3370 		zfs_exit(zfsvfs, FTAG);
3371 		return (error);
3372 	}
3373 	tzp = *tvpp == NULL ? NULL : VTOZ(*tvpp);
3374 	if (tzp != NULL) {
3375 		if ((error = zfs_verify_zp(tzp)) != 0) {
3376 			zfs_exit(zfsvfs, FTAG);
3377 			return (error);
3378 		}
3379 	}
3380 
3381 	/*
3382 	 * This is to prevent the creation of links into attribute space
3383 	 * by renaming a linked file into/outof an attribute directory.
3384 	 * See the comment in zfs_link() for why this is considered bad.
3385 	 */
3386 	if ((tdzp->z_pflags & ZFS_XATTR) != (sdzp->z_pflags & ZFS_XATTR)) {
3387 		error = SET_ERROR(EINVAL);
3388 		goto out;
3389 	}
3390 
3391 	/*
3392 	 * If we are using project inheritance, means if the directory has
3393 	 * ZFS_PROJINHERIT set, then its descendant directories will inherit
3394 	 * not only the project ID, but also the ZFS_PROJINHERIT flag. Under
3395 	 * such case, we only allow renames into our tree when the project
3396 	 * IDs are the same.
3397 	 */
3398 	if (tdzp->z_pflags & ZFS_PROJINHERIT &&
3399 	    tdzp->z_projid != szp->z_projid) {
3400 		error = SET_ERROR(EXDEV);
3401 		goto out;
3402 	}
3403 
3404 	/*
3405 	 * Must have write access at the source to remove the old entry
3406 	 * and write access at the target to create the new entry.
3407 	 * Note that if target and source are the same, this can be
3408 	 * done in a single check.
3409 	 */
3410 	if ((error = zfs_zaccess_rename(sdzp, szp, tdzp, tzp, cr, NULL)))
3411 		goto out;
3412 
3413 	if ((*svpp)->v_type == VDIR) {
3414 		/*
3415 		 * Avoid ".", "..", and aliases of "." for obvious reasons.
3416 		 */
3417 		if ((scnp->cn_namelen == 1 && scnp->cn_nameptr[0] == '.') ||
3418 		    sdzp == szp ||
3419 		    (scnp->cn_flags | tcnp->cn_flags) & ISDOTDOT) {
3420 			error = EINVAL;
3421 			goto out;
3422 		}
3423 
3424 		/*
3425 		 * Check to make sure rename is valid.
3426 		 * Can't do a move like this: /usr/a/b to /usr/a/b/c/d
3427 		 */
3428 		if ((error = zfs_rename_check(szp, sdzp, tdzp)))
3429 			goto out;
3430 	}
3431 
3432 	/*
3433 	 * Does target exist?
3434 	 */
3435 	if (tzp) {
3436 		if ((at_flags & AT_RENAME_NOREPLACE) != 0) {
3437 			error = SET_ERROR(EEXIST);
3438 			goto out;
3439 		}
3440 
3441 		/*
3442 		 * Source and target must be the same type.
3443 		 */
3444 		if ((*svpp)->v_type == VDIR) {
3445 			if ((*tvpp)->v_type != VDIR) {
3446 				error = SET_ERROR(ENOTDIR);
3447 				goto out;
3448 			} else {
3449 				cache_purge(tdvp);
3450 				if (sdvp != tdvp)
3451 					cache_purge(sdvp);
3452 			}
3453 		} else {
3454 			if ((*tvpp)->v_type == VDIR) {
3455 				error = SET_ERROR(EISDIR);
3456 				goto out;
3457 			}
3458 		}
3459 	}
3460 
3461 	vn_seqc_write_begin(*svpp);
3462 	vn_seqc_write_begin(sdvp);
3463 	if (*tvpp != NULL)
3464 		vn_seqc_write_begin(*tvpp);
3465 	if (tdvp != *tvpp)
3466 		vn_seqc_write_begin(tdvp);
3467 
3468 	vnevent_rename_src(*svpp, sdvp, scnp->cn_nameptr, ct);
3469 	if (tzp)
3470 		vnevent_rename_dest(*tvpp, tdvp, tnm, ct);
3471 
3472 	/*
3473 	 * notify the target directory if it is not the same
3474 	 * as source directory.
3475 	 */
3476 	if (tdvp != sdvp) {
3477 		vnevent_rename_dest_dir(tdvp, ct);
3478 	}
3479 
3480 	tx = dmu_tx_create(zfsvfs->z_os);
3481 	dmu_tx_hold_sa(tx, szp->z_sa_hdl, ZFS_SEQ_MAY_GROW(szp));
3482 	dmu_tx_hold_sa(tx, sdzp->z_sa_hdl, ZFS_SEQ_MAY_GROW(sdzp));
3483 	dmu_tx_hold_zap(tx, sdzp->z_id, FALSE, snm);
3484 	dmu_tx_hold_zap(tx, tdzp->z_id, TRUE, tnm);
3485 	if (sdzp != tdzp) {
3486 		dmu_tx_hold_sa(tx, tdzp->z_sa_hdl, ZFS_SEQ_MAY_GROW(tdzp));
3487 		zfs_sa_upgrade_txholds(tx, tdzp);
3488 	}
3489 	if (tzp) {
3490 		dmu_tx_hold_sa(tx, tzp->z_sa_hdl, ZFS_SEQ_MAY_GROW(tzp));
3491 		zfs_sa_upgrade_txholds(tx, tzp);
3492 	}
3493 
3494 	zfs_sa_upgrade_txholds(tx, szp);
3495 	dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
3496 	error = dmu_tx_assign(tx, DMU_TX_WAIT);
3497 	if (error) {
3498 		dmu_tx_abort(tx);
3499 		goto out_seq;
3500 	}
3501 
3502 	if (tzp)	/* Attempt to remove the existing target */
3503 		error = zfs_link_destroy(tdzp, tnm, tzp, tx, 0, NULL);
3504 
3505 	if (error == 0) {
3506 		error = zfs_link_create(tdzp, tnm, szp, tx, ZRENAMING);
3507 		if (error == 0) {
3508 			szp->z_pflags |= ZFS_AV_MODIFIED;
3509 
3510 			error = sa_update(szp->z_sa_hdl, SA_ZPL_FLAGS(zfsvfs),
3511 			    (void *)&szp->z_pflags, sizeof (uint64_t), tx);
3512 			ASSERT0(error);
3513 
3514 			error = zfs_link_destroy(sdzp, snm, szp, tx, ZRENAMING,
3515 			    NULL);
3516 			if (error == 0) {
3517 				zfs_log_rename(zilog, tx, TX_RENAME, sdzp,
3518 				    snm, tdzp, tnm, szp);
3519 			} else {
3520 				/*
3521 				 * At this point, we have successfully created
3522 				 * the target name, but have failed to remove
3523 				 * the source name.  Since the create was done
3524 				 * with the ZRENAMING flag, there are
3525 				 * complications; for one, the link count is
3526 				 * wrong.  The easiest way to deal with this
3527 				 * is to remove the newly created target, and
3528 				 * return the original error.  This must
3529 				 * succeed; fortunately, it is very unlikely to
3530 				 * fail, since we just created it.
3531 				 */
3532 				VERIFY0(zfs_link_destroy(tdzp, tnm, szp, tx,
3533 				    ZRENAMING, NULL));
3534 			}
3535 		}
3536 		if (error == 0 && zfsvfs->z_use_namecache) {
3537 			cache_vop_rename(sdvp, *svpp, tdvp, *tvpp, scnp, tcnp);
3538 		}
3539 	}
3540 
3541 	dmu_tx_commit(tx);
3542 
3543 out_seq:
3544 	vn_seqc_write_end(*svpp);
3545 	vn_seqc_write_end(sdvp);
3546 	if (*tvpp != NULL)
3547 		vn_seqc_write_end(*tvpp);
3548 	if (tdvp != *tvpp)
3549 		vn_seqc_write_end(tdvp);
3550 
3551 out:
3552 	if (error == 0 && zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
3553 		error = zil_commit(zilog, 0);
3554 	zfs_exit(zfsvfs, FTAG);
3555 
3556 	return (error);
3557 }
3558 
3559 int
zfs_rename(znode_t * sdzp,const char * sname,znode_t * tdzp,const char * tname,cred_t * cr,int flags,uint64_t rflags,u_int at_flags,vattr_t * wo_vap,zidmap_t * mnt_ns)3560 zfs_rename(znode_t *sdzp, const char *sname, znode_t *tdzp, const char *tname,
3561     cred_t *cr, int flags, uint64_t rflags, u_int at_flags, vattr_t *wo_vap,
3562     zidmap_t *mnt_ns)
3563 {
3564 	struct componentname scn, tcn;
3565 	vnode_t *sdvp, *tdvp;
3566 	vnode_t *svp, *tvp;
3567 	int error;
3568 	svp = tvp = NULL;
3569 
3570 	if (is_nametoolong(tdzp->z_zfsvfs, tname))
3571 		return (SET_ERROR(ENAMETOOLONG));
3572 
3573 	if (rflags != 0 || wo_vap != NULL)
3574 		return (SET_ERROR(EINVAL));
3575 
3576 	sdvp = ZTOV(sdzp);
3577 	tdvp = ZTOV(tdzp);
3578 	error = zfs_lookup_internal(sdzp, sname, &svp, &scn, DELETE);
3579 	if (sdzp->z_zfsvfs->z_replay == B_FALSE)
3580 		VOP_UNLOCK(sdvp);
3581 	if (error != 0)
3582 		goto fail;
3583 	VOP_UNLOCK(svp);
3584 
3585 	vn_lock(tdvp, LK_EXCLUSIVE | LK_RETRY);
3586 	error = zfs_lookup_internal(tdzp, tname, &tvp, &tcn, RENAME);
3587 	if (error == EJUSTRETURN)
3588 		tvp = NULL;
3589 	else if (error != 0) {
3590 		VOP_UNLOCK(tdvp);
3591 		goto fail;
3592 	}
3593 
3594 	error = zfs_do_rename(sdvp, &svp, &scn, tdvp, &tvp, &tcn, cr,
3595 	    at_flags);
3596 fail:
3597 	if (svp != NULL)
3598 		vrele(svp);
3599 	if (tvp != NULL)
3600 		vrele(tvp);
3601 
3602 	return (error);
3603 }
3604 
3605 /*
3606  * Insert the indicated symbolic reference entry into the directory.
3607  *
3608  *	IN:	dvp	- Directory to contain new symbolic link.
3609  *		link	- Name for new symlink entry.
3610  *		vap	- Attributes of new entry.
3611  *		cr	- credentials of caller.
3612  *		ct	- caller context
3613  *		flags	- case flags
3614  *		mnt_ns	- Unused on FreeBSD
3615  *
3616  *	RETURN:	0 on success, error code on failure.
3617  *
3618  * Timestamps:
3619  *	dvp - ctime|mtime updated
3620  */
3621 int
zfs_symlink(znode_t * dzp,const char * name,vattr_t * vap,const char * link,znode_t ** zpp,cred_t * cr,int flags,zidmap_t * mnt_ns)3622 zfs_symlink(znode_t *dzp, const char *name, vattr_t *vap,
3623     const char *link, znode_t **zpp, cred_t *cr, int flags, zidmap_t *mnt_ns)
3624 {
3625 	(void) flags;
3626 	znode_t		*zp;
3627 	dmu_tx_t	*tx;
3628 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
3629 	zilog_t		*zilog;
3630 	uint64_t	len = strlen(link);
3631 	int		error;
3632 	zfs_acl_ids_t	acl_ids;
3633 	boolean_t	fuid_dirtied;
3634 	uint64_t	txtype = TX_SYMLINK;
3635 
3636 	ASSERT3S(vap->va_type, ==, VLNK);
3637 
3638 	if (is_nametoolong(zfsvfs, name))
3639 		return (SET_ERROR(ENAMETOOLONG));
3640 
3641 	if ((error = zfs_enter_verify_zp(zfsvfs, dzp, FTAG)) != 0)
3642 		return (error);
3643 	zilog = zfsvfs->z_log;
3644 
3645 	if (zfsvfs->z_utf8 && u8_validate(name, strlen(name),
3646 	    NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
3647 		zfs_exit(zfsvfs, FTAG);
3648 		return (SET_ERROR(EILSEQ));
3649 	}
3650 
3651 	if (len > MAXPATHLEN) {
3652 		zfs_exit(zfsvfs, FTAG);
3653 		return (SET_ERROR(ENAMETOOLONG));
3654 	}
3655 
3656 	if ((error = zfs_acl_ids_create(dzp, 0,
3657 	    vap, cr, NULL, &acl_ids, NULL)) != 0) {
3658 		zfs_exit(zfsvfs, FTAG);
3659 		return (error);
3660 	}
3661 
3662 	/*
3663 	 * Attempt to lock directory; fail if entry already exists.
3664 	 */
3665 	error = zfs_dirent_lookup(dzp, name, &zp, ZNEW);
3666 	if (error) {
3667 		zfs_acl_ids_free(&acl_ids);
3668 		zfs_exit(zfsvfs, FTAG);
3669 		return (error);
3670 	}
3671 
3672 	if ((error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr, mnt_ns))) {
3673 		zfs_acl_ids_free(&acl_ids);
3674 		zfs_exit(zfsvfs, FTAG);
3675 		return (error);
3676 	}
3677 
3678 	if (zfs_acl_ids_overquota(zfsvfs, &acl_ids, ZFS_DEFAULT_PROJID)) {
3679 		zfs_acl_ids_free(&acl_ids);
3680 		zfs_exit(zfsvfs, FTAG);
3681 		return (SET_ERROR(EDQUOT));
3682 	}
3683 
3684 	getnewvnode_reserve();
3685 	tx = dmu_tx_create(zfsvfs->z_os);
3686 	fuid_dirtied = zfsvfs->z_fuid_dirty;
3687 	dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0, MAX(1, len));
3688 	dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
3689 	dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
3690 	    ZFS_SA_BASE_ATTR_SIZE + len);
3691 	dmu_tx_hold_sa(tx, dzp->z_sa_hdl, ZFS_SEQ_MAY_GROW(dzp));
3692 	if (!zfsvfs->z_use_sa && acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
3693 		dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0,
3694 		    acl_ids.z_aclp->z_acl_bytes);
3695 	}
3696 	if (fuid_dirtied)
3697 		zfs_fuid_txhold(zfsvfs, tx);
3698 	error = dmu_tx_assign(tx, DMU_TX_WAIT);
3699 	if (error) {
3700 		zfs_acl_ids_free(&acl_ids);
3701 		dmu_tx_abort(tx);
3702 		getnewvnode_drop_reserve();
3703 		zfs_exit(zfsvfs, FTAG);
3704 		return (error);
3705 	}
3706 
3707 	/*
3708 	 * Create a new object for the symlink.
3709 	 * for version 4 ZPL datasets the symlink will be an SA attribute
3710 	 */
3711 	zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
3712 
3713 	if (fuid_dirtied)
3714 		zfs_fuid_sync(zfsvfs, tx);
3715 
3716 	if (zp->z_is_sa)
3717 		error = sa_update(zp->z_sa_hdl, SA_ZPL_SYMLINK(zfsvfs),
3718 		    __DECONST(void *, link), len, tx);
3719 	else
3720 		zfs_sa_symlink(zp, __DECONST(char *, link), len, tx);
3721 
3722 	zp->z_size = len;
3723 	(void) sa_update(zp->z_sa_hdl, SA_ZPL_SIZE(zfsvfs),
3724 	    &zp->z_size, sizeof (zp->z_size), tx);
3725 	/*
3726 	 * Insert the new object into the directory.
3727 	 */
3728 	error = zfs_link_create(dzp, name, zp, tx, ZNEW);
3729 	if (error != 0) {
3730 		zfs_znode_delete(zp, tx);
3731 		VOP_UNLOCK(ZTOV(zp));
3732 		zrele(zp);
3733 	} else {
3734 		zfs_log_symlink(zilog, tx, txtype, dzp, zp, name, link);
3735 	}
3736 
3737 	zfs_acl_ids_free(&acl_ids);
3738 
3739 	dmu_tx_commit(tx);
3740 
3741 	getnewvnode_drop_reserve();
3742 
3743 	if (error == 0) {
3744 		*zpp = zp;
3745 
3746 		if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
3747 			error = zil_commit(zilog, 0);
3748 	}
3749 
3750 	zfs_exit(zfsvfs, FTAG);
3751 	return (error);
3752 }
3753 
3754 /*
3755  * Return, in the buffer contained in the provided uio structure,
3756  * the symbolic path referred to by vp.
3757  *
3758  *	IN:	vp	- vnode of symbolic link.
3759  *		uio	- structure to contain the link path.
3760  *		cr	- credentials of caller.
3761  *		ct	- caller context
3762  *
3763  *	OUT:	uio	- structure containing the link path.
3764  *
3765  *	RETURN:	0 on success, error code on failure.
3766  *
3767  * Timestamps:
3768  *	vp - atime updated
3769  */
3770 static int
zfs_readlink(vnode_t * vp,zfs_uio_t * uio,cred_t * cr,caller_context_t * ct)3771 zfs_readlink(vnode_t *vp, zfs_uio_t *uio, cred_t *cr, caller_context_t *ct)
3772 {
3773 	(void) cr, (void) ct;
3774 	znode_t		*zp = VTOZ(vp);
3775 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
3776 	int		error;
3777 
3778 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
3779 		return (error);
3780 
3781 	if (zp->z_is_sa)
3782 		error = sa_lookup_uio(zp->z_sa_hdl,
3783 		    SA_ZPL_SYMLINK(zfsvfs), uio);
3784 	else
3785 		error = zfs_sa_readlink(zp, uio);
3786 
3787 	ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
3788 
3789 	zfs_exit(zfsvfs, FTAG);
3790 	return (error);
3791 }
3792 
3793 /*
3794  * Insert a new entry into directory tdvp referencing svp.
3795  *
3796  *	IN:	tdvp	- Directory to contain new entry.
3797  *		svp	- vnode of new entry.
3798  *		name	- name of new entry.
3799  *		cr	- credentials of caller.
3800  *
3801  *	RETURN:	0 on success, error code on failure.
3802  *
3803  * Timestamps:
3804  *	tdvp - ctime|mtime updated
3805  *	 svp - ctime updated
3806  */
3807 int
zfs_link(znode_t * tdzp,znode_t * szp,const char * name,cred_t * cr,int flags)3808 zfs_link(znode_t *tdzp, znode_t *szp, const char *name, cred_t *cr,
3809     int flags)
3810 {
3811 	(void) flags;
3812 	znode_t		*tzp;
3813 	zfsvfs_t	*zfsvfs = tdzp->z_zfsvfs;
3814 	zilog_t		*zilog;
3815 	dmu_tx_t	*tx;
3816 	int		error;
3817 	uint64_t	parent;
3818 	uid_t		owner;
3819 
3820 	ASSERT3S(ZTOV(tdzp)->v_type, ==, VDIR);
3821 
3822 	if (is_nametoolong(zfsvfs, name))
3823 		return (SET_ERROR(ENAMETOOLONG));
3824 
3825 	if ((error = zfs_enter_verify_zp(zfsvfs, tdzp, FTAG)) != 0)
3826 		return (error);
3827 	zilog = zfsvfs->z_log;
3828 
3829 	/*
3830 	 * POSIX dictates that we return EPERM here.
3831 	 * Better choices include ENOTSUP or EISDIR.
3832 	 */
3833 	if (ZTOV(szp)->v_type == VDIR) {
3834 		zfs_exit(zfsvfs, FTAG);
3835 		return (SET_ERROR(EPERM));
3836 	}
3837 
3838 	if ((error = zfs_verify_zp(szp)) != 0) {
3839 		zfs_exit(zfsvfs, FTAG);
3840 		return (error);
3841 	}
3842 
3843 	/*
3844 	 * If we are using project inheritance, means if the directory has
3845 	 * ZFS_PROJINHERIT set, then its descendant directories will inherit
3846 	 * not only the project ID, but also the ZFS_PROJINHERIT flag. Under
3847 	 * such case, we only allow hard link creation in our tree when the
3848 	 * project IDs are the same.
3849 	 */
3850 	if (tdzp->z_pflags & ZFS_PROJINHERIT &&
3851 	    tdzp->z_projid != szp->z_projid) {
3852 		zfs_exit(zfsvfs, FTAG);
3853 		return (SET_ERROR(EXDEV));
3854 	}
3855 
3856 	if (szp->z_pflags & (ZFS_APPENDONLY |
3857 	    ZFS_IMMUTABLE | ZFS_READONLY)) {
3858 		zfs_exit(zfsvfs, FTAG);
3859 		return (SET_ERROR(EPERM));
3860 	}
3861 
3862 	/* Prevent links to .zfs/shares files */
3863 
3864 	if ((error = sa_lookup(szp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs),
3865 	    &parent, sizeof (uint64_t))) != 0) {
3866 		zfs_exit(zfsvfs, FTAG);
3867 		return (error);
3868 	}
3869 	if (parent == zfsvfs->z_shares_dir) {
3870 		zfs_exit(zfsvfs, FTAG);
3871 		return (SET_ERROR(EPERM));
3872 	}
3873 
3874 	if (zfsvfs->z_utf8 && u8_validate(name,
3875 	    strlen(name), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
3876 		zfs_exit(zfsvfs, FTAG);
3877 		return (SET_ERROR(EILSEQ));
3878 	}
3879 
3880 	/*
3881 	 * We do not support links between attributes and non-attributes
3882 	 * because of the potential security risk of creating links
3883 	 * into "normal" file space in order to circumvent restrictions
3884 	 * imposed in attribute space.
3885 	 */
3886 	if ((szp->z_pflags & ZFS_XATTR) != (tdzp->z_pflags & ZFS_XATTR)) {
3887 		zfs_exit(zfsvfs, FTAG);
3888 		return (SET_ERROR(EINVAL));
3889 	}
3890 
3891 
3892 	owner = zfs_fuid_map_id(zfsvfs, szp->z_uid, cr, ZFS_OWNER);
3893 	if (owner != crgetuid(cr) && secpolicy_basic_link(ZTOV(szp), cr) != 0) {
3894 		zfs_exit(zfsvfs, FTAG);
3895 		return (SET_ERROR(EPERM));
3896 	}
3897 
3898 	if ((error = zfs_zaccess(tdzp, ACE_ADD_FILE, 0, B_FALSE, cr, NULL))) {
3899 		zfs_exit(zfsvfs, FTAG);
3900 		return (error);
3901 	}
3902 
3903 	/*
3904 	 * Attempt to lock directory; fail if entry already exists.
3905 	 */
3906 	error = zfs_dirent_lookup(tdzp, name, &tzp, ZNEW);
3907 	if (error) {
3908 		zfs_exit(zfsvfs, FTAG);
3909 		return (error);
3910 	}
3911 
3912 	tx = dmu_tx_create(zfsvfs->z_os);
3913 	dmu_tx_hold_sa(tx, szp->z_sa_hdl, ZFS_SEQ_MAY_GROW(szp));
3914 	dmu_tx_hold_sa(tx, tdzp->z_sa_hdl, ZFS_SEQ_MAY_GROW(tdzp));
3915 	dmu_tx_hold_zap(tx, tdzp->z_id, TRUE, name);
3916 	zfs_sa_upgrade_txholds(tx, szp);
3917 	zfs_sa_upgrade_txholds(tx, tdzp);
3918 	error = dmu_tx_assign(tx, DMU_TX_WAIT);
3919 	if (error) {
3920 		dmu_tx_abort(tx);
3921 		zfs_exit(zfsvfs, FTAG);
3922 		return (error);
3923 	}
3924 
3925 	error = zfs_link_create(tdzp, name, szp, tx, 0);
3926 
3927 	if (error == 0) {
3928 		uint64_t txtype = TX_LINK;
3929 		zfs_log_link(zilog, tx, txtype, tdzp, szp, name);
3930 	}
3931 
3932 	dmu_tx_commit(tx);
3933 
3934 	if (error == 0) {
3935 		vnevent_link(ZTOV(szp), ct);
3936 	}
3937 
3938 	if (error == 0 && zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
3939 		error = zil_commit(zilog, 0);
3940 
3941 	zfs_exit(zfsvfs, FTAG);
3942 	return (error);
3943 }
3944 
3945 /*
3946  * Free or allocate space in a file.  Currently, this function only
3947  * supports the `F_FREESP' command.  However, this command is somewhat
3948  * misnamed, as its functionality includes the ability to allocate as
3949  * well as free space.
3950  *
3951  *	IN:	ip	- inode of file to free data in.
3952  *		cmd	- action to take (only F_FREESP supported).
3953  *		bfp	- section of file to free/alloc.
3954  *		flag	- current file open mode flags.
3955  *		offset	- current file offset.
3956  *		cr	- credentials of caller.
3957  *
3958  *	RETURN:	0 on success, error code on failure.
3959  *
3960  * Timestamps:
3961  *	ip - ctime|mtime updated
3962  */
3963 int
zfs_space(znode_t * zp,int cmd,flock64_t * bfp,int flag,offset_t offset,cred_t * cr)3964 zfs_space(znode_t *zp, int cmd, flock64_t *bfp, int flag,
3965     offset_t offset, cred_t *cr)
3966 {
3967 	(void) offset;
3968 	zfsvfs_t	*zfsvfs = ZTOZSB(zp);
3969 	uint64_t	off, len;
3970 	int		error;
3971 
3972 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
3973 		return (error);
3974 
3975 	if (cmd != F_FREESP) {
3976 		zfs_exit(zfsvfs, FTAG);
3977 		return (SET_ERROR(EINVAL));
3978 	}
3979 
3980 	/*
3981 	 * Callers might not be able to detect properly that we are read-only,
3982 	 * so check it explicitly here.
3983 	 */
3984 	if (zfs_is_readonly(zfsvfs)) {
3985 		zfs_exit(zfsvfs, FTAG);
3986 		return (SET_ERROR(EROFS));
3987 	}
3988 
3989 	if (bfp->l_len < 0) {
3990 		zfs_exit(zfsvfs, FTAG);
3991 		return (SET_ERROR(EINVAL));
3992 	}
3993 
3994 	/*
3995 	 * Permissions aren't checked on Solaris because on this OS
3996 	 * zfs_space() can only be called with an opened file handle.
3997 	 * On Linux we can get here through truncate_range() which
3998 	 * operates directly on inodes, so we need to check access rights.
3999 	 */
4000 	if ((error = zfs_zaccess(zp, ACE_WRITE_DATA, 0, B_FALSE, cr, NULL))) {
4001 		zfs_exit(zfsvfs, FTAG);
4002 		return (error);
4003 	}
4004 
4005 	off = bfp->l_start;
4006 	len = bfp->l_len; /* 0 means from off to end of file */
4007 
4008 	error = zfs_freesp(zp, off, len, flag, TRUE);
4009 
4010 	zfs_exit(zfsvfs, FTAG);
4011 	return (error);
4012 }
4013 
4014 static void
zfs_inactive(vnode_t * vp,cred_t * cr,caller_context_t * ct)4015 zfs_inactive(vnode_t *vp, cred_t *cr, caller_context_t *ct)
4016 {
4017 	(void) cr, (void) ct;
4018 	znode_t	*zp = VTOZ(vp);
4019 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
4020 	int error;
4021 
4022 	ZFS_TEARDOWN_INACTIVE_ENTER_READ(zfsvfs);
4023 	if (zp->z_sa_hdl == NULL) {
4024 		/*
4025 		 * The fs has been unmounted, or we did a
4026 		 * suspend/resume and this file no longer exists.
4027 		 */
4028 		ZFS_TEARDOWN_INACTIVE_EXIT_READ(zfsvfs);
4029 		vrecycle(vp);
4030 		return;
4031 	}
4032 
4033 	if (zp->z_unlinked) {
4034 		/*
4035 		 * Fast path to recycle a vnode of a removed file.
4036 		 */
4037 		ZFS_TEARDOWN_INACTIVE_EXIT_READ(zfsvfs);
4038 		vrecycle(vp);
4039 		return;
4040 	}
4041 
4042 	if (zp->z_atime_dirty && zp->z_unlinked == 0) {
4043 		dmu_tx_t *tx = dmu_tx_create(zfsvfs->z_os);
4044 
4045 		dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
4046 		zfs_sa_upgrade_txholds(tx, zp);
4047 		error = dmu_tx_assign(tx, DMU_TX_WAIT);
4048 		if (error) {
4049 			dmu_tx_abort(tx);
4050 		} else {
4051 			(void) sa_update(zp->z_sa_hdl, SA_ZPL_ATIME(zfsvfs),
4052 			    (void *)&zp->z_atime, sizeof (zp->z_atime), tx);
4053 			zp->z_atime_dirty = 0;
4054 			dmu_tx_commit(tx);
4055 		}
4056 	}
4057 	ZFS_TEARDOWN_INACTIVE_EXIT_READ(zfsvfs);
4058 }
4059 
4060 
4061 _Static_assert(sizeof (struct zfid_short) <= sizeof (struct fid),
4062 	"struct zfid_short bigger than struct fid");
4063 _Static_assert(sizeof (struct zfid_long) <= sizeof (struct fid),
4064 	"struct zfid_long bigger than struct fid");
4065 
4066 static int
zfs_fid(vnode_t * vp,fid_t * fidp,caller_context_t * ct)4067 zfs_fid(vnode_t *vp, fid_t *fidp, caller_context_t *ct)
4068 {
4069 	(void) ct;
4070 	znode_t		*zp = VTOZ(vp);
4071 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
4072 	uint32_t	gen;
4073 	uint64_t	gen64;
4074 	uint64_t	object = zp->z_id;
4075 	zfid_short_t	*zfid;
4076 	int		size, i, error;
4077 
4078 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
4079 		return (error);
4080 
4081 	if ((error = sa_lookup(zp->z_sa_hdl, SA_ZPL_GEN(zfsvfs),
4082 	    &gen64, sizeof (uint64_t))) != 0) {
4083 		zfs_exit(zfsvfs, FTAG);
4084 		return (error);
4085 	}
4086 
4087 	gen = (uint32_t)gen64;
4088 
4089 	size = (zfsvfs->z_parent != zfsvfs) ? LONG_FID_LEN : SHORT_FID_LEN;
4090 	fidp->fid_len = size;
4091 
4092 	zfid = (zfid_short_t *)fidp;
4093 
4094 	zfid->zf_len = size;
4095 
4096 	for (i = 0; i < sizeof (zfid->zf_object); i++)
4097 		zfid->zf_object[i] = (uint8_t)(object >> (8 * i));
4098 
4099 	/* Must have a non-zero generation number to distinguish from .zfs */
4100 	if (gen == 0)
4101 		gen = 1;
4102 	for (i = 0; i < sizeof (zfid->zf_gen); i++)
4103 		zfid->zf_gen[i] = (uint8_t)(gen >> (8 * i));
4104 
4105 	if (size == LONG_FID_LEN) {
4106 		uint64_t	objsetid = dmu_objset_id(zfsvfs->z_os);
4107 		zfid_long_t	*zlfid;
4108 
4109 		zlfid = (zfid_long_t *)fidp;
4110 
4111 		for (i = 0; i < sizeof (zlfid->zf_setid); i++)
4112 			zlfid->zf_setid[i] = (uint8_t)(objsetid >> (8 * i));
4113 
4114 		/* XXX - this should be the generation number for the objset */
4115 		for (i = 0; i < sizeof (zlfid->zf_setgen); i++)
4116 			zlfid->zf_setgen[i] = 0;
4117 	}
4118 
4119 	zfs_exit(zfsvfs, FTAG);
4120 	return (0);
4121 }
4122 
4123 static int
zfs_pathconf(vnode_t * vp,int cmd,ulong_t * valp,cred_t * cr,caller_context_t * ct)4124 zfs_pathconf(vnode_t *vp, int cmd, ulong_t *valp, cred_t *cr,
4125     caller_context_t *ct)
4126 {
4127 	znode_t *zp;
4128 	zfsvfs_t *zfsvfs;
4129 	uint_t blksize, iosize;
4130 	int error;
4131 
4132 	switch (cmd) {
4133 	case _PC_LINK_MAX:
4134 		*valp = MIN(LONG_MAX, ZFS_LINK_MAX);
4135 		return (0);
4136 
4137 	case _PC_FILESIZEBITS:
4138 		*valp = 64;
4139 		return (0);
4140 	case _PC_MIN_HOLE_SIZE:
4141 		iosize = vp->v_mount->mnt_stat.f_iosize;
4142 		if (vp->v_type == VREG) {
4143 			zp = VTOZ(vp);
4144 			blksize = zp->z_blksz;
4145 			if (zp->z_size <= blksize)
4146 				blksize = MAX(blksize, iosize);
4147 			*valp = (int)blksize;
4148 			return (0);
4149 		}
4150 		if (vp->v_type == VDIR) {
4151 			*valp = (int)iosize;
4152 			return (0);
4153 		}
4154 		return (EINVAL);
4155 	case _PC_ACL_EXTENDED:
4156 #if 0		/* POSIX ACLs are not implemented for ZFS on FreeBSD yet. */
4157 		zp = VTOZ(vp);
4158 		zfsvfs = zp->z_zfsvfs;
4159 		if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
4160 			return (error);
4161 		*valp = zfsvfs->z_acl_type == ZFSACLTYPE_POSIX ? 1 : 0;
4162 		zfs_exit(zfsvfs, FTAG);
4163 #else
4164 		*valp = 0;
4165 #endif
4166 		return (0);
4167 
4168 	case _PC_ACL_NFS4:
4169 		zp = VTOZ(vp);
4170 		zfsvfs = zp->z_zfsvfs;
4171 		if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
4172 			return (error);
4173 		*valp = zfsvfs->z_acl_type == ZFS_ACLTYPE_NFSV4 ? 1 : 0;
4174 		zfs_exit(zfsvfs, FTAG);
4175 		return (0);
4176 
4177 	case _PC_ACL_PATH_MAX:
4178 		*valp = ACL_MAX_ENTRIES;
4179 		return (0);
4180 
4181 	default:
4182 		return (EOPNOTSUPP);
4183 	}
4184 }
4185 
4186 static int
zfs_getpages(struct vnode * vp,vm_page_t * ma,int count,int * rbehind,int * rahead)4187 zfs_getpages(struct vnode *vp, vm_page_t *ma, int count, int *rbehind,
4188     int *rahead)
4189 {
4190 	znode_t *zp = VTOZ(vp);
4191 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
4192 	zfs_locked_range_t *lr;
4193 	vm_object_t object;
4194 	off_t start, end, obj_size;
4195 	uint_t blksz;
4196 	int pgsin_b, pgsin_a;
4197 	int error;
4198 
4199 	if (zfs_enter_verify_zp(zfsvfs, zp, FTAG) != 0)
4200 		return (zfs_vm_pagerret_error);
4201 
4202 	object = ma[0]->object;
4203 	start = IDX_TO_OFF(ma[0]->pindex);
4204 	end = IDX_TO_OFF(ma[count - 1]->pindex + 1);
4205 
4206 	/*
4207 	 * Lock a range covering all required and optional pages.
4208 	 * Note that we need to handle the case of the block size growing.
4209 	 */
4210 	for (;;) {
4211 		uint64_t len;
4212 
4213 		blksz = zp->z_blksz;
4214 		len = roundup(end, blksz) - rounddown(start, blksz);
4215 
4216 		lr = zfs_rangelock_tryenter(&zp->z_rangelock,
4217 		    rounddown(start, blksz), len, RL_READER);
4218 		if (lr == NULL) {
4219 			/*
4220 			 * Avoid a deadlock with update_pages().  We need to
4221 			 * hold the range lock when copying from the DMU, so
4222 			 * give up the busy lock to allow update_pages() to
4223 			 * proceed.  We might need to allocate new pages, which
4224 			 * isn't quite right since this allocation isn't subject
4225 			 * to the page fault handler's OOM logic, but this is
4226 			 * the best we can do for now.
4227 			 */
4228 			for (int i = 0; i < count; i++)
4229 				vm_page_xunbusy(ma[i]);
4230 
4231 			lr = zfs_rangelock_enter(&zp->z_rangelock,
4232 			    rounddown(start, blksz), len, RL_READER);
4233 
4234 			zfs_vmobject_wlock(object);
4235 			(void) vm_page_grab_pages(object, OFF_TO_IDX(start),
4236 			    VM_ALLOC_NORMAL | VM_ALLOC_WAITOK,
4237 			    ma, count);
4238 			if (!vm_page_all_valid(ma[count - 1])) {
4239 				/*
4240 				 * Later in this function, we copy DMU data to
4241 				 * invalid pages only. The last page may not be
4242 				 * entirely filled though, if the file does not
4243 				 * end on a page boundary. Therefore, we zero
4244 				 * that last page here to make sure it does not
4245 				 * contain garbage after the end of file.
4246 				 */
4247 				ASSERT(vm_page_none_valid(ma[count - 1]));
4248 				vm_page_zero_invalid(ma[count - 1], FALSE);
4249 			}
4250 			zfs_vmobject_wunlock(object);
4251 		}
4252 		if (blksz == zp->z_blksz)
4253 			break;
4254 		zfs_rangelock_exit(lr);
4255 	}
4256 
4257 	zfs_vmobject_wlock(object);
4258 	obj_size = object->un_pager.vnp.vnp_size;
4259 	zfs_vmobject_wunlock(object);
4260 	if (IDX_TO_OFF(ma[count - 1]->pindex) >= obj_size) {
4261 		zfs_rangelock_exit(lr);
4262 		zfs_exit(zfsvfs, FTAG);
4263 		return (zfs_vm_pagerret_bad);
4264 	}
4265 
4266 	pgsin_b = 0;
4267 	if (rbehind != NULL) {
4268 		pgsin_b = OFF_TO_IDX(start - rounddown(start, blksz));
4269 		pgsin_b = MIN(*rbehind, pgsin_b);
4270 	}
4271 
4272 	pgsin_a = 0;
4273 	if (rahead != NULL) {
4274 		pgsin_a = OFF_TO_IDX(roundup(end, blksz) - end);
4275 		if (end + IDX_TO_OFF(pgsin_a) >= obj_size)
4276 			pgsin_a = OFF_TO_IDX(round_page(obj_size) - end);
4277 		pgsin_a = MIN(*rahead, pgsin_a);
4278 	}
4279 
4280 	/*
4281 	 * NB: we need to pass the exact byte size of the data that we expect
4282 	 * to read after accounting for the file size.  This is required because
4283 	 * ZFS will panic if we request DMU to read beyond the end of the last
4284 	 * allocated block.
4285 	 */
4286 	for (int i = 0; i < count; i++) {
4287 		int dummypgsin, count1, j, last_size;
4288 
4289 		if (vm_page_any_valid(ma[i])) {
4290 			ASSERT(vm_page_all_valid(ma[i]));
4291 			continue;
4292 		}
4293 		for (j = i + 1; j < count; j++) {
4294 			if (vm_page_any_valid(ma[j])) {
4295 				ASSERT(vm_page_all_valid(ma[j]));
4296 				break;
4297 			}
4298 		}
4299 		count1 = j - i;
4300 		dummypgsin = 0;
4301 		last_size = j == count ?
4302 		    MIN(end, obj_size) - (end - PAGE_SIZE) : PAGE_SIZE;
4303 		error = dmu_read_pages(zfsvfs->z_os, zp->z_id, &ma[i], count1,
4304 		    i == 0 ? &pgsin_b : &dummypgsin,
4305 		    j == count ? &pgsin_a : &dummypgsin,
4306 		    last_size);
4307 		if (error != 0)
4308 			break;
4309 		i += count1 - 1;
4310 	}
4311 
4312 	zfs_rangelock_exit(lr);
4313 	ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
4314 
4315 	dataset_kstats_update_read_kstats(&zfsvfs->z_kstat, count*PAGE_SIZE);
4316 
4317 	zfs_exit(zfsvfs, FTAG);
4318 
4319 	if (error != 0)
4320 		return (zfs_vm_pagerret_error);
4321 
4322 	VM_CNT_INC(v_vnodein);
4323 	VM_CNT_ADD(v_vnodepgsin, count + pgsin_b + pgsin_a);
4324 	if (rbehind != NULL)
4325 		*rbehind = pgsin_b;
4326 	if (rahead != NULL)
4327 		*rahead = pgsin_a;
4328 	return (zfs_vm_pagerret_ok);
4329 }
4330 
4331 #ifndef _SYS_SYSPROTO_H_
4332 struct vop_getpages_args {
4333 	struct vnode *a_vp;
4334 	vm_page_t *a_m;
4335 	int a_count;
4336 	int *a_rbehind;
4337 	int *a_rahead;
4338 };
4339 #endif
4340 
4341 static int
zfs_freebsd_getpages(struct vop_getpages_args * ap)4342 zfs_freebsd_getpages(struct vop_getpages_args *ap)
4343 {
4344 
4345 	return (zfs_getpages(ap->a_vp, ap->a_m, ap->a_count, ap->a_rbehind,
4346 	    ap->a_rahead));
4347 }
4348 
4349 typedef struct {
4350 	uint_t		pca_npages;
4351 	vm_page_t	pca_pages[];
4352 } putpage_commit_arg_t;
4353 
4354 static void
zfs_putpage_commit_cb(void * arg,int err)4355 zfs_putpage_commit_cb(void *arg, int err)
4356 {
4357 	putpage_commit_arg_t *pca = arg;
4358 	vm_object_t object = pca->pca_pages[0]->object;
4359 
4360 	zfs_vmobject_wlock(object);
4361 
4362 	for (uint_t i = 0; i < pca->pca_npages; i++) {
4363 		vm_page_t pp = pca->pca_pages[i];
4364 
4365 		if (err == 0) {
4366 			/*
4367 			 * Writeback succeeded, so undirty the page. If it
4368 			 * fails, we leave it in the same state it was. That's
4369 			 * most likely dirty, so it will get tried again some
4370 			 * other time.
4371 			 */
4372 			vm_page_undirty(pp);
4373 		}
4374 
4375 		vm_page_sunbusy(pp);
4376 	}
4377 
4378 	vm_object_pip_wakeupn(object, pca->pca_npages);
4379 
4380 	zfs_vmobject_wunlock(object);
4381 
4382 	kmem_free(pca,
4383 	    offsetof(putpage_commit_arg_t, pca_pages[pca->pca_npages]));
4384 }
4385 
4386 static int
zfs_putpages(struct vnode * vp,vm_page_t * ma,size_t len,int flags,int * rtvals)4387 zfs_putpages(struct vnode *vp, vm_page_t *ma, size_t len, int flags,
4388     int *rtvals)
4389 {
4390 	znode_t		*zp = VTOZ(vp);
4391 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
4392 	zfs_locked_range_t		*lr;
4393 	dmu_tx_t	*tx;
4394 	struct sf_buf	*sf;
4395 	vm_object_t	object;
4396 	vm_page_t	m;
4397 	caddr_t		va;
4398 	size_t		tocopy;
4399 	size_t		lo_len;
4400 	vm_ooffset_t	lo_off;
4401 	vm_ooffset_t	off;
4402 	uint_t		blksz;
4403 	int		ncount;
4404 	int		pcount;
4405 	int		err;
4406 	int		i;
4407 
4408 	object = vp->v_object;
4409 	KASSERT(ma[0]->object == object, ("mismatching object"));
4410 	KASSERT(len > 0 && (len & PAGE_MASK) == 0, ("unexpected length"));
4411 
4412 	pcount = btoc(len);
4413 	ncount = pcount;
4414 	for (i = 0; i < pcount; i++)
4415 		rtvals[i] = zfs_vm_pagerret_error;
4416 
4417 	if (zfs_enter_verify_zp(zfsvfs, zp, FTAG) != 0)
4418 		return (zfs_vm_pagerret_error);
4419 
4420 	off = IDX_TO_OFF(ma[0]->pindex);
4421 	blksz = zp->z_blksz;
4422 	lo_off = rounddown(off, blksz);
4423 	lo_len = roundup(len + (off - lo_off), blksz);
4424 	lr = zfs_rangelock_enter(&zp->z_rangelock, lo_off, lo_len, RL_WRITER);
4425 
4426 	zfs_vmobject_wlock(object);
4427 	if (len + off > object->un_pager.vnp.vnp_size) {
4428 		if (object->un_pager.vnp.vnp_size > off) {
4429 			int pgoff;
4430 
4431 			len = object->un_pager.vnp.vnp_size - off;
4432 			ncount = btoc(len);
4433 			if ((pgoff = (int)len & PAGE_MASK) != 0) {
4434 				/*
4435 				 * If the object is locked and the following
4436 				 * conditions hold, then the page's dirty
4437 				 * field cannot be concurrently changed by a
4438 				 * pmap operation.
4439 				 */
4440 				m = ma[ncount - 1];
4441 				vm_page_assert_sbusied(m);
4442 				KASSERT(!pmap_page_is_write_mapped(m),
4443 				    ("zfs_putpages: page %p is not read-only",
4444 				    m));
4445 				vm_page_clear_dirty(m, pgoff, PAGE_SIZE -
4446 				    pgoff);
4447 			}
4448 		} else {
4449 			len = 0;
4450 			ncount = 0;
4451 		}
4452 		if (ncount < pcount) {
4453 			for (i = ncount; i < pcount; i++) {
4454 				rtvals[i] = zfs_vm_pagerret_bad;
4455 			}
4456 		}
4457 	}
4458 	zfs_vmobject_wunlock(object);
4459 
4460 	boolean_t commit = (flags & (zfs_vm_pagerput_sync |
4461 	    zfs_vm_pagerput_inval)) != 0 ||
4462 	    zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS;
4463 
4464 	if (ncount == 0)
4465 		goto out;
4466 
4467 	if (zfs_id_overblockquota(zfsvfs, DMU_USERUSED_OBJECT, zp->z_uid) ||
4468 	    zfs_id_overblockquota(zfsvfs, DMU_GROUPUSED_OBJECT, zp->z_gid) ||
4469 	    (zp->z_projid != ZFS_DEFAULT_PROJID &&
4470 	    zfs_id_overblockquota(zfsvfs, DMU_PROJECTUSED_OBJECT,
4471 	    zp->z_projid))) {
4472 		goto out;
4473 	}
4474 
4475 	tx = dmu_tx_create(zfsvfs->z_os);
4476 	dmu_tx_hold_write(tx, zp->z_id, off, len);
4477 
4478 	dmu_tx_hold_sa(tx, zp->z_sa_hdl, ZFS_SEQ_MAY_GROW(zp));
4479 	zfs_sa_upgrade_txholds(tx, zp);
4480 	err = dmu_tx_assign(tx, DMU_TX_WAIT);
4481 	if (err != 0) {
4482 		dmu_tx_abort(tx);
4483 		goto out;
4484 	}
4485 
4486 	if (zp->z_blksz < PAGE_SIZE) {
4487 		vm_ooffset_t woff = off;
4488 		size_t wlen = len;
4489 		for (i = 0; wlen > 0; woff += tocopy, wlen -= tocopy, i++) {
4490 			tocopy = MIN(PAGE_SIZE, wlen);
4491 			va = zfs_map_page(ma[i], &sf);
4492 			dmu_write(zfsvfs->z_os, zp->z_id, woff, tocopy, va, tx,
4493 			    DMU_READ_PREFETCH);
4494 			zfs_unmap_page(sf);
4495 		}
4496 	} else {
4497 		err = dmu_write_pages(zfsvfs->z_os, zp->z_id, off, len, ma, tx);
4498 	}
4499 
4500 	if (err == 0) {
4501 		uint64_t mtime[2], ctime[2];
4502 		sa_bulk_attr_t bulk[4];
4503 		int count = 0;
4504 
4505 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL,
4506 		    &mtime, 16);
4507 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
4508 		    &ctime, 16);
4509 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
4510 		    &zp->z_pflags, 8);
4511 		zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime);
4512 		ZFS_PERSIST_SEQ(zp, bulk, count);
4513 		ASSERT3S(count, <=, ARRAY_SIZE(bulk));
4514 		err = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
4515 		ASSERT0(err);
4516 
4517 		if (commit) {
4518 			/*
4519 			 * Caller requested that we commit immediately. We set
4520 			 * a callback on the log entry, to be called once its
4521 			 * on disk after the call to zil_commit() below. The
4522 			 * pages will be undirtied and unbusied there.
4523 			 */
4524 			putpage_commit_arg_t *pca = kmem_alloc(
4525 			    offsetof(putpage_commit_arg_t, pca_pages[ncount]),
4526 			    KM_SLEEP);
4527 			pca->pca_npages = ncount;
4528 			memcpy(pca->pca_pages, ma, sizeof (vm_page_t) * ncount);
4529 
4530 			zfs_log_write(zfsvfs->z_log, tx, TX_WRITE, zp, off, len,
4531 			    B_TRUE, B_FALSE, zfs_putpage_commit_cb, pca);
4532 
4533 			for (i = 0; i < ncount; i++)
4534 				rtvals[i] = zfs_vm_pagerret_pend;
4535 		} else {
4536 			/*
4537 			 * Caller just wants the page written back somewhere,
4538 			 * but doesn't need it committed yet. We've already
4539 			 * written it back to the DMU, so we just need to put
4540 			 * it on the async log, then undirty the page and
4541 			 * return.
4542 			 *
4543 			 * We cannot use a callback here, because it would keep
4544 			 * the page busy (locked) until it is eventually
4545 			 * written down at txg sync.
4546 			 */
4547 			zfs_log_write(zfsvfs->z_log, tx, TX_WRITE, zp, off, len,
4548 			    B_FALSE, B_FALSE, NULL, NULL);
4549 
4550 			zfs_vmobject_wlock(object);
4551 			for (i = 0; i < ncount; i++) {
4552 				rtvals[i] = zfs_vm_pagerret_ok;
4553 				vm_page_undirty(ma[i]);
4554 			}
4555 			zfs_vmobject_wunlock(object);
4556 		}
4557 
4558 		VM_CNT_INC(v_vnodeout);
4559 		VM_CNT_ADD(v_vnodepgsout, ncount);
4560 	}
4561 	dmu_tx_commit(tx);
4562 
4563 out:
4564 	zfs_rangelock_exit(lr);
4565 	if (commit) {
4566 		err = zil_commit(zfsvfs->z_log, zp->z_id);
4567 		if (err != 0) {
4568 			zfs_exit(zfsvfs, FTAG);
4569 			return (err);
4570 		}
4571 	}
4572 
4573 	dataset_kstats_update_write_kstats(&zfsvfs->z_kstat, len);
4574 
4575 	zfs_exit(zfsvfs, FTAG);
4576 	return (rtvals[0]);
4577 }
4578 
4579 #ifndef _SYS_SYSPROTO_H_
4580 struct vop_putpages_args {
4581 	struct vnode *a_vp;
4582 	vm_page_t *a_m;
4583 	int a_count;
4584 	int a_sync;
4585 	int *a_rtvals;
4586 };
4587 #endif
4588 
4589 static int
zfs_freebsd_putpages(struct vop_putpages_args * ap)4590 zfs_freebsd_putpages(struct vop_putpages_args *ap)
4591 {
4592 
4593 	return (zfs_putpages(ap->a_vp, ap->a_m, ap->a_count, ap->a_sync,
4594 	    ap->a_rtvals));
4595 }
4596 
4597 #ifndef _SYS_SYSPROTO_H_
4598 struct vop_bmap_args {
4599 	struct vnode *a_vp;
4600 	daddr_t  a_bn;
4601 	struct bufobj **a_bop;
4602 	daddr_t *a_bnp;
4603 	int *a_runp;
4604 	int *a_runb;
4605 };
4606 #endif
4607 
4608 static int
zfs_freebsd_bmap(struct vop_bmap_args * ap)4609 zfs_freebsd_bmap(struct vop_bmap_args *ap)
4610 {
4611 
4612 	if (ap->a_bop != NULL)
4613 		*ap->a_bop = &ap->a_vp->v_bufobj;
4614 	if (ap->a_bnp != NULL)
4615 		*ap->a_bnp = ap->a_bn;
4616 	if (ap->a_runp != NULL)
4617 		*ap->a_runp = 0;
4618 	if (ap->a_runb != NULL)
4619 		*ap->a_runb = 0;
4620 
4621 	return (0);
4622 }
4623 
4624 #ifndef _SYS_SYSPROTO_H_
4625 struct vop_open_args {
4626 	struct vnode *a_vp;
4627 	int a_mode;
4628 	struct ucred *a_cred;
4629 	struct thread *a_td;
4630 };
4631 #endif
4632 
4633 static int
zfs_freebsd_open(struct vop_open_args * ap)4634 zfs_freebsd_open(struct vop_open_args *ap)
4635 {
4636 	vnode_t	*vp = ap->a_vp;
4637 	znode_t *zp = VTOZ(vp);
4638 	int error;
4639 
4640 	error = zfs_open(&vp, ap->a_mode, ap->a_cred);
4641 	if (error == 0)
4642 		vnode_create_vobject(vp, zp->z_size, ap->a_td);
4643 	return (error);
4644 }
4645 
4646 #ifndef _SYS_SYSPROTO_H_
4647 struct vop_close_args {
4648 	struct vnode *a_vp;
4649 	int  a_fflag;
4650 	struct ucred *a_cred;
4651 	struct thread *a_td;
4652 };
4653 #endif
4654 
4655 static int
zfs_freebsd_close(struct vop_close_args * ap)4656 zfs_freebsd_close(struct vop_close_args *ap)
4657 {
4658 
4659 	return (zfs_close(ap->a_vp, ap->a_fflag, 1, 0, ap->a_cred));
4660 }
4661 
4662 #ifndef _SYS_SYSPROTO_H_
4663 struct vop_ioctl_args {
4664 	struct vnode *a_vp;
4665 	ulong_t a_command;
4666 	caddr_t a_data;
4667 	int a_fflag;
4668 	struct ucred *cred;
4669 	struct thread *td;
4670 };
4671 #endif
4672 
4673 static int
zfs_freebsd_ioctl(struct vop_ioctl_args * ap)4674 zfs_freebsd_ioctl(struct vop_ioctl_args *ap)
4675 {
4676 
4677 	return (zfs_ioctl(ap->a_vp, ap->a_command, (intptr_t)ap->a_data,
4678 	    ap->a_fflag, ap->a_cred, NULL));
4679 }
4680 
4681 static int
ioflags(int ioflags)4682 ioflags(int ioflags)
4683 {
4684 	int flags = 0;
4685 
4686 	if (ioflags & IO_APPEND)
4687 		flags |= O_APPEND;
4688 	if (ioflags & IO_NDELAY)
4689 		flags |= O_NONBLOCK;
4690 	if (ioflags & IO_DIRECT)
4691 		flags |= O_DIRECT;
4692 	if (ioflags & IO_SYNC)
4693 		flags |= O_SYNC;
4694 
4695 	return (flags);
4696 }
4697 
4698 #ifndef _SYS_SYSPROTO_H_
4699 struct vop_read_args {
4700 	struct vnode *a_vp;
4701 	struct uio *a_uio;
4702 	int a_ioflag;
4703 	struct ucred *a_cred;
4704 };
4705 #endif
4706 
4707 static int
zfs_freebsd_read(struct vop_read_args * ap)4708 zfs_freebsd_read(struct vop_read_args *ap)
4709 {
4710 	zfs_uio_t uio;
4711 	int error = 0;
4712 	zfs_uio_init(&uio, ap->a_uio);
4713 	error = zfs_read(VTOZ(ap->a_vp), &uio, ioflags(ap->a_ioflag),
4714 	    ap->a_cred);
4715 	/*
4716 	 * XXX We occasionally get an EFAULT for Direct I/O reads on
4717 	 * FreeBSD 13. This still needs to be resolved. The EFAULT comes
4718 	 * from:
4719 	 * zfs_uio_get__dio_pages_alloc() ->
4720 	 * zfs_uio_get_dio_pages_impl() ->
4721 	 * zfs_uio_iov_step() ->
4722 	 * zfs_uio_get_user_pages().
4723 	 * We return EFAULT from zfs_uio_iov_step(). When a Direct I/O
4724 	 * read fails to map in the user pages (returning EFAULT) the
4725 	 * Direct I/O request is broken up into two separate IO requests
4726 	 * and issued separately using Direct I/O.
4727 	 */
4728 #ifdef ZFS_DEBUG
4729 	if (error == EFAULT && uio.uio_extflg & UIO_DIRECT) {
4730 #if 0
4731 		printf("%s(%d): Direct I/O read returning EFAULT "
4732 		    "uio = %p, zfs_uio_offset(uio) = %lu "
4733 		    "zfs_uio_resid(uio) = %lu\n",
4734 		    __FUNCTION__, __LINE__, &uio, zfs_uio_offset(&uio),
4735 		    zfs_uio_resid(&uio));
4736 #endif
4737 	}
4738 
4739 #endif
4740 	return (error);
4741 }
4742 
4743 #ifndef _SYS_SYSPROTO_H_
4744 struct vop_write_args {
4745 	struct vnode *a_vp;
4746 	struct uio *a_uio;
4747 	int a_ioflag;
4748 	struct ucred *a_cred;
4749 };
4750 #endif
4751 
4752 static int
zfs_freebsd_write(struct vop_write_args * ap)4753 zfs_freebsd_write(struct vop_write_args *ap)
4754 {
4755 	zfs_uio_t uio;
4756 	zfs_uio_init(&uio, ap->a_uio);
4757 	return (zfs_write(VTOZ(ap->a_vp), &uio, ioflags(ap->a_ioflag),
4758 	    ap->a_cred));
4759 }
4760 
4761 /*
4762  * VOP_FPLOOKUP_VEXEC routines are subject to special circumstances, see
4763  * the comment above cache_fplookup for details.
4764  */
4765 static int
zfs_freebsd_fplookup_vexec(struct vop_fplookup_vexec_args * v)4766 zfs_freebsd_fplookup_vexec(struct vop_fplookup_vexec_args *v)
4767 {
4768 	vnode_t *vp;
4769 	znode_t *zp;
4770 	uint64_t pflags;
4771 
4772 	vp = v->a_vp;
4773 	zp = VTOZ_SMR(vp);
4774 	if (__predict_false(zp == NULL))
4775 		return (EAGAIN);
4776 	pflags = atomic_load_64(&zp->z_pflags);
4777 	if (pflags & ZFS_AV_QUARANTINED)
4778 		return (EAGAIN);
4779 	if (pflags & ZFS_XATTR)
4780 		return (EAGAIN);
4781 	if ((pflags & ZFS_NO_EXECS_DENIED) == 0)
4782 		return (EAGAIN);
4783 	return (0);
4784 }
4785 
4786 static int
zfs_freebsd_fplookup_symlink(struct vop_fplookup_symlink_args * v)4787 zfs_freebsd_fplookup_symlink(struct vop_fplookup_symlink_args *v)
4788 {
4789 	vnode_t *vp;
4790 	znode_t *zp;
4791 	char *target;
4792 
4793 	vp = v->a_vp;
4794 	zp = VTOZ_SMR(vp);
4795 	if (__predict_false(zp == NULL)) {
4796 		return (EAGAIN);
4797 	}
4798 
4799 	target = atomic_load_consume_ptr(&zp->z_cached_symlink);
4800 	if (target == NULL) {
4801 		return (EAGAIN);
4802 	}
4803 	return (cache_symlink_resolve(v->a_fpl, target, strlen(target)));
4804 }
4805 
4806 #ifndef _SYS_SYSPROTO_H_
4807 struct vop_access_args {
4808 	struct vnode *a_vp;
4809 	accmode_t a_accmode;
4810 	struct ucred *a_cred;
4811 	struct thread *a_td;
4812 };
4813 #endif
4814 
4815 static int
zfs_freebsd_access(struct vop_access_args * ap)4816 zfs_freebsd_access(struct vop_access_args *ap)
4817 {
4818 	vnode_t *vp = ap->a_vp;
4819 	znode_t *zp = VTOZ(vp);
4820 	accmode_t accmode;
4821 	int error = 0;
4822 
4823 
4824 	if (ap->a_accmode == VEXEC) {
4825 		if (zfs_fastaccesschk_execute(zp, ap->a_cred) == 0)
4826 			return (0);
4827 	}
4828 
4829 	/*
4830 	 * ZFS itself only knowns about VREAD, VWRITE, VEXEC and VAPPEND,
4831 	 */
4832 	accmode = ap->a_accmode & (VREAD|VWRITE|VEXEC|VAPPEND);
4833 	if (accmode != 0) {
4834 #if __FreeBSD_version >= 1500040
4835 		/* For named attributes, do the checks. */
4836 		if ((vn_irflag_read(vp) & VIRF_NAMEDATTR) != 0)
4837 			error = zfs_access(zp, accmode, V_NAMEDATTR,
4838 			    ap->a_cred);
4839 		else
4840 #endif
4841 			error = zfs_access(zp, accmode, 0, ap->a_cred);
4842 	}
4843 
4844 	/*
4845 	 * VADMIN has to be handled by vaccess().
4846 	 */
4847 	if (error == 0) {
4848 		accmode = ap->a_accmode & ~(VREAD|VWRITE|VEXEC|VAPPEND);
4849 		if (accmode != 0) {
4850 			error = vaccess(vp->v_type, zp->z_mode, zp->z_uid,
4851 			    zp->z_gid, accmode, ap->a_cred);
4852 		}
4853 	}
4854 
4855 	/*
4856 	 * For VEXEC, ensure that at least one execute bit is set for
4857 	 * non-directories.
4858 	 */
4859 	if (error == 0 && (ap->a_accmode & VEXEC) != 0 && vp->v_type != VDIR &&
4860 	    (zp->z_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) == 0) {
4861 		error = EACCES;
4862 	}
4863 
4864 	return (error);
4865 }
4866 
4867 #ifndef _SYS_SYSPROTO_H_
4868 struct vop_lookup_args {
4869 	struct vnode *a_dvp;
4870 	struct vnode **a_vpp;
4871 	struct componentname *a_cnp;
4872 };
4873 #endif
4874 
4875 #if __FreeBSD_version >= 1500040
4876 static int
zfs_lookup_nameddir(struct vnode * dvp,struct componentname * cnp,struct vnode ** vpp)4877 zfs_lookup_nameddir(struct vnode *dvp, struct componentname *cnp,
4878     struct vnode **vpp)
4879 {
4880 	struct vnode *xvp;
4881 	int error, flags;
4882 
4883 	*vpp = NULL;
4884 	flags = LOOKUP_XATTR | LOOKUP_NAMED_ATTR;
4885 	if ((cnp->cn_flags & CREATENAMED) != 0)
4886 		flags |= CREATE_XATTR_DIR;
4887 	error = zfs_lookup(dvp, NULL, &xvp, NULL, 0, cnp->cn_cred, flags,
4888 	    B_FALSE);
4889 	if (error == 0) {
4890 		if ((cnp->cn_flags & LOCKLEAF) != 0)
4891 			error = vn_lock(xvp, cnp->cn_lkflags);
4892 		if (error == 0) {
4893 			vn_irflag_set_cond(xvp, VIRF_NAMEDDIR);
4894 			*vpp = xvp;
4895 		} else {
4896 			vrele(xvp);
4897 		}
4898 	}
4899 	return (error);
4900 }
4901 
4902 static ssize_t
zfs_readdir_named(struct vnode * vp,char * buf,ssize_t blen,off_t * offp,int * eofflagp,struct ucred * cred,struct thread * td)4903 zfs_readdir_named(struct vnode *vp, char *buf, ssize_t blen, off_t *offp,
4904     int *eofflagp, struct ucred *cred, struct thread *td)
4905 {
4906 	struct uio io;
4907 	struct iovec iv;
4908 	zfs_uio_t uio;
4909 	int error;
4910 
4911 	io.uio_offset = *offp;
4912 	io.uio_segflg = UIO_SYSSPACE;
4913 	io.uio_rw = UIO_READ;
4914 	io.uio_td = td;
4915 	iv.iov_base = buf;
4916 	iv.iov_len = blen;
4917 	io.uio_iov = &iv;
4918 	io.uio_iovcnt = 1;
4919 	io.uio_resid = blen;
4920 	zfs_uio_init(&uio, &io);
4921 	error = zfs_readdir(vp, &uio, cred, eofflagp, NULL, NULL);
4922 	if (error != 0)
4923 		return (-1);
4924 	*offp = io.uio_offset;
4925 	return (blen - io.uio_resid);
4926 }
4927 
4928 static bool
zfs_has_namedattr(struct vnode * vp,struct ucred * cred)4929 zfs_has_namedattr(struct vnode *vp, struct ucred *cred)
4930 {
4931 	struct componentname cn;
4932 	struct vnode *xvp;
4933 	struct dirent *dp;
4934 	off_t offs;
4935 	ssize_t rsize;
4936 	char *buf, *cp, *endcp;
4937 	int eofflag, error;
4938 	bool ret;
4939 
4940 	MNT_ILOCK(vp->v_mount);
4941 	if ((vp->v_mount->mnt_flag & MNT_NAMEDATTR) == 0) {
4942 		MNT_IUNLOCK(vp->v_mount);
4943 		return (false);
4944 	}
4945 	MNT_IUNLOCK(vp->v_mount);
4946 
4947 	/* Now see if a named attribute directory exists. */
4948 	cn.cn_flags = LOCKLEAF;
4949 	cn.cn_lkflags = LK_SHARED;
4950 	cn.cn_cred = cred;
4951 	error = zfs_lookup_nameddir(vp, &cn, &xvp);
4952 	if (error != 0)
4953 		return (false);
4954 
4955 	/* It exists, so see if there is any entry other than "." and "..". */
4956 	buf = malloc(DEV_BSIZE, M_TEMP, M_WAITOK);
4957 	ret = false;
4958 	offs = 0;
4959 	do {
4960 		rsize = zfs_readdir_named(xvp, buf, DEV_BSIZE, &offs, &eofflag,
4961 		    cred, curthread);
4962 		if (rsize <= 0)
4963 			break;
4964 		cp = buf;
4965 		endcp = &buf[rsize];
4966 		while (cp < endcp) {
4967 			dp = (struct dirent *)cp;
4968 			if (dp->d_fileno != 0 && (dp->d_type == DT_REG ||
4969 			    dp->d_type == DT_UNKNOWN) &&
4970 			    !ZFS_XA_NS_PREFIX_FORBIDDEN(dp->d_name) &&
4971 			    ((dp->d_namlen == 1 && dp->d_name[0] != '.') ||
4972 			    (dp->d_namlen == 2 && (dp->d_name[0] != '.' ||
4973 			    dp->d_name[1] != '.')) || dp->d_namlen > 2)) {
4974 				ret = true;
4975 				break;
4976 			}
4977 			cp += dp->d_reclen;
4978 		}
4979 	} while (!ret && rsize > 0 && eofflag == 0);
4980 	vput(xvp);
4981 	free(buf, M_TEMP);
4982 	return (ret);
4983 }
4984 
4985 static int
zfs_freebsd_lookup(struct vop_lookup_args * ap,boolean_t cached)4986 zfs_freebsd_lookup(struct vop_lookup_args *ap, boolean_t cached)
4987 {
4988 	struct componentname *cnp = ap->a_cnp;
4989 	char nm[NAME_MAX + 1];
4990 	int error;
4991 	struct vnode **vpp = ap->a_vpp, *dvp = ap->a_dvp, *xvp;
4992 	bool is_nameddir, needs_nameddir, opennamed = false;
4993 
4994 	/*
4995 	 * These variables are used to handle the named attribute cases:
4996 	 * opennamed - Is true when this is a call from open with O_NAMEDATTR
4997 	 *    specified and it is the last component.
4998 	 * is_nameddir - Is true when the directory is a named attribute dir.
4999 	 * needs_nameddir - Is set when the lookup needs to look for/create
5000 	 *    a named attribute directory.  It is only set when is_nameddir
5001 	 *    is_nameddir is false and opennamed is true.
5002 	 * xvp - Is the directory that the lookup needs to be done in.
5003 	 *    Usually dvp, unless needs_nameddir is true where it is the
5004 	 *    result of the first non-named directory lookup.
5005 	 * Note that name caching must be disabled for named attribute
5006 	 * handling.
5007 	 */
5008 	needs_nameddir = false;
5009 	xvp = dvp;
5010 	opennamed = (cnp->cn_flags & (OPENNAMED | ISLASTCN)) ==
5011 	    (OPENNAMED | ISLASTCN);
5012 	is_nameddir = (vn_irflag_read(dvp) & VIRF_NAMEDDIR) != 0;
5013 	if (is_nameddir && (cnp->cn_flags & ISLASTCN) == 0)
5014 		return (ENOATTR);
5015 	if (opennamed && !is_nameddir && (cnp->cn_flags & ISDOTDOT) != 0)
5016 		return (ENOATTR);
5017 	if (opennamed || is_nameddir)
5018 		cnp->cn_flags &= ~MAKEENTRY;
5019 	if (opennamed && !is_nameddir)
5020 		needs_nameddir = true;
5021 	ASSERT3U(cnp->cn_namelen, <, sizeof (nm));
5022 	error = 0;
5023 	*vpp = NULL;
5024 	if (needs_nameddir) {
5025 		if (VOP_ISLOCKED(dvp) != LK_EXCLUSIVE)
5026 			vn_lock(dvp, LK_UPGRADE | LK_RETRY);
5027 		error = zfs_lookup_nameddir(dvp, cnp, &xvp);
5028 		if (error == 0)
5029 			is_nameddir = true;
5030 	}
5031 	if (error == 0) {
5032 		if (!needs_nameddir || cnp->cn_namelen != 1 ||
5033 		    *cnp->cn_nameptr != '.') {
5034 			strlcpy(nm, cnp->cn_nameptr, MIN(cnp->cn_namelen + 1,
5035 			    sizeof (nm)));
5036 			error = zfs_lookup(xvp, nm, vpp, cnp, cnp->cn_nameiop,
5037 			    cnp->cn_cred, 0, cached);
5038 			if (is_nameddir && error == 0 &&
5039 			    (cnp->cn_namelen != 1 || *cnp->cn_nameptr != '.') &&
5040 			    (cnp->cn_flags & ISDOTDOT) == 0) {
5041 				if ((*vpp)->v_type == VDIR)
5042 					vn_irflag_set_cond(*vpp, VIRF_NAMEDDIR);
5043 				else
5044 					vn_irflag_set_cond(*vpp,
5045 					    VIRF_NAMEDATTR);
5046 			}
5047 			if (needs_nameddir && xvp != *vpp)
5048 				vput(xvp);
5049 		} else {
5050 			/*
5051 			 * Lookup of "." when a named attribute dir is needed.
5052 			 */
5053 			*vpp = xvp;
5054 		}
5055 	}
5056 	return (error);
5057 }
5058 #else
5059 static int
zfs_freebsd_lookup(struct vop_lookup_args * ap,boolean_t cached)5060 zfs_freebsd_lookup(struct vop_lookup_args *ap, boolean_t cached)
5061 {
5062 	struct componentname *cnp = ap->a_cnp;
5063 	char nm[NAME_MAX + 1];
5064 
5065 	ASSERT3U(cnp->cn_namelen, <, sizeof (nm));
5066 	strlcpy(nm, cnp->cn_nameptr, MIN(cnp->cn_namelen + 1, sizeof (nm)));
5067 
5068 	return (zfs_lookup(ap->a_dvp, nm, ap->a_vpp, cnp, cnp->cn_nameiop,
5069 	    cnp->cn_cred, 0, cached));
5070 }
5071 #endif
5072 
5073 static int
zfs_freebsd_cachedlookup(struct vop_cachedlookup_args * ap)5074 zfs_freebsd_cachedlookup(struct vop_cachedlookup_args *ap)
5075 {
5076 
5077 	return (zfs_freebsd_lookup((struct vop_lookup_args *)ap, B_TRUE));
5078 }
5079 
5080 #ifndef _SYS_SYSPROTO_H_
5081 struct vop_lookup_args {
5082 	struct vnode *a_dvp;
5083 	struct vnode **a_vpp;
5084 	struct componentname *a_cnp;
5085 };
5086 #endif
5087 
5088 static int
zfs_cache_lookup(struct vop_lookup_args * ap)5089 zfs_cache_lookup(struct vop_lookup_args *ap)
5090 {
5091 	zfsvfs_t *zfsvfs;
5092 
5093 	zfsvfs = ap->a_dvp->v_mount->mnt_data;
5094 #if __FreeBSD_version >= 1500040
5095 	if (zfsvfs->z_use_namecache && (ap->a_cnp->cn_flags & OPENNAMED) == 0)
5096 #else
5097 	if (zfsvfs->z_use_namecache)
5098 #endif
5099 		return (vfs_cache_lookup(ap));
5100 	else
5101 		return (zfs_freebsd_lookup(ap, B_FALSE));
5102 }
5103 
5104 #ifndef _SYS_SYSPROTO_H_
5105 struct vop_create_args {
5106 	struct vnode *a_dvp;
5107 	struct vnode **a_vpp;
5108 	struct componentname *a_cnp;
5109 	struct vattr *a_vap;
5110 };
5111 #endif
5112 
5113 static int
zfs_freebsd_create(struct vop_create_args * ap)5114 zfs_freebsd_create(struct vop_create_args *ap)
5115 {
5116 	zfsvfs_t *zfsvfs;
5117 	struct componentname *cnp = ap->a_cnp;
5118 	vattr_t *vap = ap->a_vap;
5119 	znode_t *zp = NULL;
5120 	int rc, mode;
5121 	struct vnode *dvp = ap->a_dvp;
5122 #if __FreeBSD_version >= 1500040
5123 	struct vnode *xvp;
5124 	bool is_nameddir;
5125 #endif
5126 
5127 #if __FreeBSD_version < 1400068
5128 	ASSERT(cnp->cn_flags & SAVENAME);
5129 #endif
5130 
5131 	vattr_init_mask(vap);
5132 	mode = vap->va_mode & ALLPERMS;
5133 	zfsvfs = ap->a_dvp->v_mount->mnt_data;
5134 	*ap->a_vpp = NULL;
5135 
5136 	rc = 0;
5137 #if __FreeBSD_version >= 1500040
5138 	xvp = NULL;
5139 	is_nameddir = (vn_irflag_read(dvp) & VIRF_NAMEDDIR) != 0;
5140 	if (!is_nameddir && (cnp->cn_flags & OPENNAMED) != 0) {
5141 		/* Needs a named attribute directory. */
5142 		rc = zfs_lookup_nameddir(dvp, cnp, &xvp);
5143 		if (rc == 0) {
5144 			dvp = xvp;
5145 			is_nameddir = true;
5146 		}
5147 	}
5148 	if (is_nameddir && rc == 0)
5149 		rc = zfs_check_attrname(cnp->cn_nameptr);
5150 #endif
5151 
5152 	if (rc == 0)
5153 		rc = zfs_create(VTOZ(dvp), cnp->cn_nameptr, vap, 0, mode,
5154 		    &zp, cnp->cn_cred, 0 /* flag */, NULL /* vsecattr */, NULL);
5155 #if __FreeBSD_version >= 1500040
5156 	if (xvp != NULL)
5157 		vput(xvp);
5158 #endif
5159 	if (rc == 0) {
5160 		*ap->a_vpp = ZTOV(zp);
5161 #if __FreeBSD_version >= 1500040
5162 		if (is_nameddir)
5163 			vn_irflag_set_cond(*ap->a_vpp, VIRF_NAMEDATTR);
5164 #endif
5165 	}
5166 	if (zfsvfs->z_use_namecache &&
5167 	    rc == 0 && (cnp->cn_flags & MAKEENTRY) != 0)
5168 		cache_enter(ap->a_dvp, *ap->a_vpp, cnp);
5169 
5170 	return (rc);
5171 }
5172 
5173 #ifndef _SYS_SYSPROTO_H_
5174 struct vop_remove_args {
5175 	struct vnode *a_dvp;
5176 	struct vnode *a_vp;
5177 	struct componentname *a_cnp;
5178 };
5179 #endif
5180 
5181 static int
zfs_freebsd_remove(struct vop_remove_args * ap)5182 zfs_freebsd_remove(struct vop_remove_args *ap)
5183 {
5184 	int error = 0;
5185 
5186 #if __FreeBSD_version < 1400068
5187 	ASSERT(ap->a_cnp->cn_flags & SAVENAME);
5188 #endif
5189 
5190 #if __FreeBSD_version >= 1500040
5191 	if ((vn_irflag_read(ap->a_dvp) & VIRF_NAMEDDIR) != 0)
5192 		error = zfs_check_attrname(ap->a_cnp->cn_nameptr);
5193 #endif
5194 
5195 	if (error == 0)
5196 		error = zfs_remove_(ap->a_dvp, ap->a_vp, ap->a_cnp->cn_nameptr,
5197 		    ap->a_cnp->cn_cred);
5198 	return (error);
5199 }
5200 
5201 #ifndef _SYS_SYSPROTO_H_
5202 struct vop_mkdir_args {
5203 	struct vnode *a_dvp;
5204 	struct vnode **a_vpp;
5205 	struct componentname *a_cnp;
5206 	struct vattr *a_vap;
5207 };
5208 #endif
5209 
5210 static int
zfs_freebsd_mkdir(struct vop_mkdir_args * ap)5211 zfs_freebsd_mkdir(struct vop_mkdir_args *ap)
5212 {
5213 	vattr_t *vap = ap->a_vap;
5214 	znode_t *zp = NULL;
5215 	int rc;
5216 
5217 #if __FreeBSD_version < 1400068
5218 	ASSERT(ap->a_cnp->cn_flags & SAVENAME);
5219 #endif
5220 
5221 	vattr_init_mask(vap);
5222 	*ap->a_vpp = NULL;
5223 
5224 	rc = zfs_mkdir(VTOZ(ap->a_dvp), ap->a_cnp->cn_nameptr, vap, &zp,
5225 	    ap->a_cnp->cn_cred, 0, NULL, NULL);
5226 
5227 	if (rc == 0)
5228 		*ap->a_vpp = ZTOV(zp);
5229 	return (rc);
5230 }
5231 
5232 #ifndef _SYS_SYSPROTO_H_
5233 struct vop_rmdir_args {
5234 	struct vnode *a_dvp;
5235 	struct vnode *a_vp;
5236 	struct componentname *a_cnp;
5237 };
5238 #endif
5239 
5240 static int
zfs_freebsd_rmdir(struct vop_rmdir_args * ap)5241 zfs_freebsd_rmdir(struct vop_rmdir_args *ap)
5242 {
5243 	struct componentname *cnp = ap->a_cnp;
5244 
5245 #if __FreeBSD_version < 1400068
5246 	ASSERT(cnp->cn_flags & SAVENAME);
5247 #endif
5248 
5249 	return (zfs_rmdir_(ap->a_dvp, ap->a_vp, cnp->cn_nameptr, cnp->cn_cred));
5250 }
5251 
5252 #ifndef _SYS_SYSPROTO_H_
5253 struct vop_readdir_args {
5254 	struct vnode *a_vp;
5255 	struct uio *a_uio;
5256 	struct ucred *a_cred;
5257 	int *a_eofflag;
5258 	int *a_ncookies;
5259 	cookie_t **a_cookies;
5260 };
5261 #endif
5262 
5263 static int
zfs_freebsd_readdir(struct vop_readdir_args * ap)5264 zfs_freebsd_readdir(struct vop_readdir_args *ap)
5265 {
5266 	zfs_uio_t uio;
5267 	zfs_uio_init(&uio, ap->a_uio);
5268 	return (zfs_readdir(ap->a_vp, &uio, ap->a_cred, ap->a_eofflag,
5269 	    ap->a_ncookies, ap->a_cookies));
5270 }
5271 
5272 #ifndef _SYS_SYSPROTO_H_
5273 struct vop_fsync_args {
5274 	struct vnode *a_vp;
5275 	int a_waitfor;
5276 	struct thread *a_td;
5277 };
5278 #endif
5279 
5280 static int
zfs_freebsd_fsync(struct vop_fsync_args * ap)5281 zfs_freebsd_fsync(struct vop_fsync_args *ap)
5282 {
5283 	vnode_t *vp = ap->a_vp;
5284 	int err = 0;
5285 
5286 	/*
5287 	 * Push any dirty mmap()'d data out to the DMU and ZIL, ready for
5288 	 * zil_commit() to be called in zfs_fsync().
5289 	 */
5290 	if (vp->v_object != NULL && vm_object_mightbedirty(vp->v_object)) {
5291 		zfs_vmobject_wlock(vp->v_object);
5292 		if (!vm_object_page_clean(vp->v_object, 0, 0, 0))
5293 			err = SET_ERROR(EIO);
5294 		zfs_vmobject_wunlock(vp->v_object);
5295 		if (err) {
5296 			/*
5297 			 * Unclear what state things are in. zfs_putpages()
5298 			 * will ensure the pages remain dirty if they haven't
5299 			 * been written down to the DMU, but because there may
5300 			 * be nothing logged, we can't assume that zfs_sync()
5301 			 * -> zil_commit() will give us a useful error. It's
5302 			 *  safest if we just error out here.
5303 			 */
5304 			return (err);
5305 		}
5306 	}
5307 
5308 	return (zfs_fsync(VTOZ(vp), 0, ap->a_td->td_ucred));
5309 }
5310 
5311 #ifndef _SYS_SYSPROTO_H_
5312 struct vop_getattr_args {
5313 	struct vnode *a_vp;
5314 	struct vattr *a_vap;
5315 	struct ucred *a_cred;
5316 };
5317 #endif
5318 
5319 static int
zfs_freebsd_getattr(struct vop_getattr_args * ap)5320 zfs_freebsd_getattr(struct vop_getattr_args *ap)
5321 {
5322 	vattr_t *vap = ap->a_vap;
5323 	xvattr_t xvap;
5324 	ulong_t fflags = 0;
5325 	int error;
5326 
5327 	xva_init(&xvap);
5328 	xvap.xva_vattr = *vap;
5329 	xvap.xva_vattr.va_mask |= AT_XVATTR;
5330 
5331 	/* Convert chflags into ZFS-type flags. */
5332 	/* XXX: what about SF_SETTABLE?. */
5333 	XVA_SET_REQ(&xvap, XAT_IMMUTABLE);
5334 	XVA_SET_REQ(&xvap, XAT_APPENDONLY);
5335 	XVA_SET_REQ(&xvap, XAT_NOUNLINK);
5336 	XVA_SET_REQ(&xvap, XAT_NODUMP);
5337 	XVA_SET_REQ(&xvap, XAT_READONLY);
5338 	XVA_SET_REQ(&xvap, XAT_ARCHIVE);
5339 	XVA_SET_REQ(&xvap, XAT_SYSTEM);
5340 	XVA_SET_REQ(&xvap, XAT_HIDDEN);
5341 	XVA_SET_REQ(&xvap, XAT_REPARSE);
5342 	XVA_SET_REQ(&xvap, XAT_OFFLINE);
5343 	XVA_SET_REQ(&xvap, XAT_SPARSE);
5344 
5345 	error = zfs_getattr(ap->a_vp, (vattr_t *)&xvap, 0, ap->a_cred);
5346 	if (error != 0)
5347 		return (error);
5348 
5349 	/* Convert ZFS xattr into chflags. */
5350 #define	FLAG_CHECK(fflag, xflag, xfield)	do {			\
5351 	if (XVA_ISSET_RTN(&xvap, (xflag)) && (xfield) != 0)		\
5352 		fflags |= (fflag);					\
5353 } while (0)
5354 	FLAG_CHECK(SF_IMMUTABLE, XAT_IMMUTABLE,
5355 	    xvap.xva_xoptattrs.xoa_immutable);
5356 	FLAG_CHECK(SF_APPEND, XAT_APPENDONLY,
5357 	    xvap.xva_xoptattrs.xoa_appendonly);
5358 	FLAG_CHECK(SF_NOUNLINK, XAT_NOUNLINK,
5359 	    xvap.xva_xoptattrs.xoa_nounlink);
5360 	FLAG_CHECK(UF_ARCHIVE, XAT_ARCHIVE,
5361 	    xvap.xva_xoptattrs.xoa_archive);
5362 	FLAG_CHECK(UF_NODUMP, XAT_NODUMP,
5363 	    xvap.xva_xoptattrs.xoa_nodump);
5364 	FLAG_CHECK(UF_READONLY, XAT_READONLY,
5365 	    xvap.xva_xoptattrs.xoa_readonly);
5366 	FLAG_CHECK(UF_SYSTEM, XAT_SYSTEM,
5367 	    xvap.xva_xoptattrs.xoa_system);
5368 	FLAG_CHECK(UF_HIDDEN, XAT_HIDDEN,
5369 	    xvap.xva_xoptattrs.xoa_hidden);
5370 	FLAG_CHECK(UF_REPARSE, XAT_REPARSE,
5371 	    xvap.xva_xoptattrs.xoa_reparse);
5372 	FLAG_CHECK(UF_OFFLINE, XAT_OFFLINE,
5373 	    xvap.xva_xoptattrs.xoa_offline);
5374 	FLAG_CHECK(UF_SPARSE, XAT_SPARSE,
5375 	    xvap.xva_xoptattrs.xoa_sparse);
5376 
5377 #undef	FLAG_CHECK
5378 	*vap = xvap.xva_vattr;
5379 	vap->va_flags = fflags;
5380 
5381 #if __FreeBSD_version >= 1500040
5382 	if ((vn_irflag_read(ap->a_vp) & (VIRF_NAMEDDIR | VIRF_NAMEDATTR)) != 0)
5383 		vap->va_bsdflags |= SFBSD_NAMEDATTR;
5384 #endif
5385 	return (0);
5386 }
5387 
5388 #ifndef _SYS_SYSPROTO_H_
5389 struct vop_setattr_args {
5390 	struct vnode *a_vp;
5391 	struct vattr *a_vap;
5392 	struct ucred *a_cred;
5393 };
5394 #endif
5395 
5396 static int
zfs_freebsd_setattr(struct vop_setattr_args * ap)5397 zfs_freebsd_setattr(struct vop_setattr_args *ap)
5398 {
5399 	vnode_t *vp = ap->a_vp;
5400 	vattr_t *vap = ap->a_vap;
5401 	cred_t *cred = ap->a_cred;
5402 	xvattr_t xvap;
5403 	ulong_t fflags;
5404 	uint64_t zflags;
5405 
5406 	vattr_init_mask(vap);
5407 	vap->va_mask &= ~AT_NOSET;
5408 
5409 	xva_init(&xvap);
5410 	xvap.xva_vattr = *vap;
5411 
5412 	zflags = VTOZ(vp)->z_pflags;
5413 
5414 	if (vap->va_flags != VNOVAL) {
5415 		zfsvfs_t *zfsvfs = VTOZ(vp)->z_zfsvfs;
5416 		int error;
5417 
5418 		if (zfsvfs->z_use_fuids == B_FALSE)
5419 			return (EOPNOTSUPP);
5420 
5421 		fflags = vap->va_flags;
5422 		/*
5423 		 * XXX KDM
5424 		 * We need to figure out whether it makes sense to allow
5425 		 * UF_REPARSE through, since we don't really have other
5426 		 * facilities to handle reparse points and zfs_setattr()
5427 		 * doesn't currently allow setting that attribute anyway.
5428 		 */
5429 		if ((fflags & ~(SF_IMMUTABLE|SF_APPEND|SF_NOUNLINK|UF_ARCHIVE|
5430 		    UF_NODUMP|UF_SYSTEM|UF_HIDDEN|UF_READONLY|UF_REPARSE|
5431 		    UF_OFFLINE|UF_SPARSE)) != 0)
5432 			return (EOPNOTSUPP);
5433 		/*
5434 		 * Unprivileged processes are not permitted to unset system
5435 		 * flags, or modify flags if any system flags are set.
5436 		 * Privileged non-jail processes may not modify system flags
5437 		 * if securelevel > 0 and any existing system flags are set.
5438 		 * Privileged jail processes behave like privileged non-jail
5439 		 * processes if the PR_ALLOW_CHFLAGS permission bit is set;
5440 		 * otherwise, they behave like unprivileged processes.
5441 		 */
5442 		if (secpolicy_fs_owner(vp->v_mount, cred) == 0 ||
5443 		    priv_check_cred(cred, PRIV_VFS_SYSFLAGS) == 0) {
5444 			if (zflags &
5445 			    (ZFS_IMMUTABLE | ZFS_APPENDONLY | ZFS_NOUNLINK)) {
5446 				error = securelevel_gt(cred, 0);
5447 				if (error != 0)
5448 					return (error);
5449 			}
5450 		} else {
5451 			/*
5452 			 * Callers may only modify the file flags on
5453 			 * objects they have VADMIN rights for.
5454 			 */
5455 			if ((error = VOP_ACCESS(vp, VADMIN, cred,
5456 			    curthread)) != 0)
5457 				return (error);
5458 			if (zflags &
5459 			    (ZFS_IMMUTABLE | ZFS_APPENDONLY |
5460 			    ZFS_NOUNLINK)) {
5461 				return (EPERM);
5462 			}
5463 			if (fflags &
5464 			    (SF_IMMUTABLE | SF_APPEND | SF_NOUNLINK)) {
5465 				return (EPERM);
5466 			}
5467 		}
5468 
5469 #define	FLAG_CHANGE(fflag, zflag, xflag, xfield)	do {		\
5470 	if (((fflags & (fflag)) && !(zflags & (zflag))) ||		\
5471 	    ((zflags & (zflag)) && !(fflags & (fflag)))) {		\
5472 		XVA_SET_REQ(&xvap, (xflag));				\
5473 		(xfield) = ((fflags & (fflag)) != 0);			\
5474 	}								\
5475 } while (0)
5476 		/* Convert chflags into ZFS-type flags. */
5477 		/* XXX: what about SF_SETTABLE?. */
5478 		FLAG_CHANGE(SF_IMMUTABLE, ZFS_IMMUTABLE, XAT_IMMUTABLE,
5479 		    xvap.xva_xoptattrs.xoa_immutable);
5480 		FLAG_CHANGE(SF_APPEND, ZFS_APPENDONLY, XAT_APPENDONLY,
5481 		    xvap.xva_xoptattrs.xoa_appendonly);
5482 		FLAG_CHANGE(SF_NOUNLINK, ZFS_NOUNLINK, XAT_NOUNLINK,
5483 		    xvap.xva_xoptattrs.xoa_nounlink);
5484 		FLAG_CHANGE(UF_ARCHIVE, ZFS_ARCHIVE, XAT_ARCHIVE,
5485 		    xvap.xva_xoptattrs.xoa_archive);
5486 		FLAG_CHANGE(UF_NODUMP, ZFS_NODUMP, XAT_NODUMP,
5487 		    xvap.xva_xoptattrs.xoa_nodump);
5488 		FLAG_CHANGE(UF_READONLY, ZFS_READONLY, XAT_READONLY,
5489 		    xvap.xva_xoptattrs.xoa_readonly);
5490 		FLAG_CHANGE(UF_SYSTEM, ZFS_SYSTEM, XAT_SYSTEM,
5491 		    xvap.xva_xoptattrs.xoa_system);
5492 		FLAG_CHANGE(UF_HIDDEN, ZFS_HIDDEN, XAT_HIDDEN,
5493 		    xvap.xva_xoptattrs.xoa_hidden);
5494 		FLAG_CHANGE(UF_REPARSE, ZFS_REPARSE, XAT_REPARSE,
5495 		    xvap.xva_xoptattrs.xoa_reparse);
5496 		FLAG_CHANGE(UF_OFFLINE, ZFS_OFFLINE, XAT_OFFLINE,
5497 		    xvap.xva_xoptattrs.xoa_offline);
5498 		FLAG_CHANGE(UF_SPARSE, ZFS_SPARSE, XAT_SPARSE,
5499 		    xvap.xva_xoptattrs.xoa_sparse);
5500 #undef	FLAG_CHANGE
5501 	}
5502 	if (vap->va_birthtime.tv_sec != VNOVAL) {
5503 		xvap.xva_vattr.va_mask |= AT_XVATTR;
5504 		XVA_SET_REQ(&xvap, XAT_CREATETIME);
5505 	}
5506 	return (zfs_setattr(VTOZ(vp), (vattr_t *)&xvap, 0, cred, NULL));
5507 }
5508 
5509 #ifndef _SYS_SYSPROTO_H_
5510 struct vop_rename_args {
5511 	struct vnode *a_fdvp;
5512 	struct vnode *a_fvp;
5513 	struct componentname *a_fcnp;
5514 	struct vnode *a_tdvp;
5515 	struct vnode *a_tvp;
5516 	struct componentname *a_tcnp;
5517 };
5518 #endif
5519 
5520 static int
zfs_freebsd_rename(struct vop_rename_args * ap)5521 zfs_freebsd_rename(struct vop_rename_args *ap)
5522 {
5523 	vnode_t *fdvp = ap->a_fdvp;
5524 	vnode_t *fvp = ap->a_fvp;
5525 	vnode_t *tdvp = ap->a_tdvp;
5526 	vnode_t *tvp = ap->a_tvp;
5527 	int error = 0;
5528 
5529 #if __FreeBSD_version < 1400068
5530 	ASSERT(ap->a_fcnp->cn_flags & (SAVENAME|SAVESTART));
5531 	ASSERT(ap->a_tcnp->cn_flags & (SAVENAME|SAVESTART));
5532 #endif
5533 
5534 #if __FreeBSD_version >= 1500040
5535 	if ((vn_irflag_read(fdvp) & VIRF_NAMEDDIR) != 0) {
5536 		error = zfs_check_attrname(ap->a_fcnp->cn_nameptr);
5537 		if (error == 0)
5538 			error = zfs_check_attrname(ap->a_tcnp->cn_nameptr);
5539 	}
5540 #endif
5541 
5542 	if (error == 0 && (ap->a_flags & ~(AT_RENAME_NOREPLACE)) != 0)
5543 		error = EOPNOTSUPP;
5544 
5545 	if (error == 0) {
5546 		error = zfs_do_rename(fdvp, &fvp, ap->a_fcnp, tdvp, &tvp,
5547 		    ap->a_tcnp, ap->a_fcnp->cn_cred, ap->a_flags);
5548 		vrele(fdvp);
5549 		vrele(fvp);
5550 		vrele(tdvp);
5551 		if (tvp != NULL)
5552 			vrele(tvp);
5553 	} else {
5554 		if (tdvp == tvp)
5555 			vrele(tdvp);
5556 		else
5557 			vput(tdvp);
5558 		if (tvp != NULL)
5559 			vput(tvp);
5560 		vrele(fdvp);
5561 		vrele(fvp);
5562 	}
5563 
5564 	return (error);
5565 }
5566 
5567 #ifndef _SYS_SYSPROTO_H_
5568 struct vop_symlink_args {
5569 	struct vnode *a_dvp;
5570 	struct vnode **a_vpp;
5571 	struct componentname *a_cnp;
5572 	struct vattr *a_vap;
5573 	char *a_target;
5574 };
5575 #endif
5576 
5577 static int
zfs_freebsd_symlink(struct vop_symlink_args * ap)5578 zfs_freebsd_symlink(struct vop_symlink_args *ap)
5579 {
5580 	struct componentname *cnp = ap->a_cnp;
5581 	vattr_t *vap = ap->a_vap;
5582 	znode_t *zp = NULL;
5583 	char *symlink;
5584 	size_t symlink_len;
5585 	int rc;
5586 
5587 #if __FreeBSD_version < 1400068
5588 	ASSERT(cnp->cn_flags & SAVENAME);
5589 #endif
5590 
5591 	vap->va_type = VLNK;	/* FreeBSD: Syscall only sets va_mode. */
5592 	vattr_init_mask(vap);
5593 	*ap->a_vpp = NULL;
5594 
5595 	rc = zfs_symlink(VTOZ(ap->a_dvp), cnp->cn_nameptr, vap,
5596 	    ap->a_target, &zp, cnp->cn_cred, 0 /* flags */, NULL);
5597 	if (rc == 0) {
5598 		*ap->a_vpp = ZTOV(zp);
5599 		ASSERT_VOP_ELOCKED(ZTOV(zp), __func__);
5600 		MPASS(zp->z_cached_symlink == NULL);
5601 		symlink_len = strlen(ap->a_target);
5602 		symlink = cache_symlink_alloc(symlink_len + 1, M_WAITOK);
5603 		if (symlink != NULL) {
5604 			memcpy(symlink, ap->a_target, symlink_len);
5605 			symlink[symlink_len] = '\0';
5606 			atomic_store_rel_ptr((uintptr_t *)&zp->z_cached_symlink,
5607 			    (uintptr_t)symlink);
5608 		}
5609 	}
5610 	return (rc);
5611 }
5612 
5613 #ifndef _SYS_SYSPROTO_H_
5614 struct vop_readlink_args {
5615 	struct vnode *a_vp;
5616 	struct uio *a_uio;
5617 	struct ucred *a_cred;
5618 };
5619 #endif
5620 
5621 static int
zfs_freebsd_readlink(struct vop_readlink_args * ap)5622 zfs_freebsd_readlink(struct vop_readlink_args *ap)
5623 {
5624 	zfs_uio_t uio;
5625 	int error;
5626 	znode_t	*zp = VTOZ(ap->a_vp);
5627 	char *symlink, *base;
5628 	size_t symlink_len;
5629 	bool trycache;
5630 
5631 	zfs_uio_init(&uio, ap->a_uio);
5632 	trycache = false;
5633 	if (zfs_uio_segflg(&uio) == UIO_SYSSPACE &&
5634 	    zfs_uio_iovcnt(&uio) == 1) {
5635 		base = zfs_uio_iovbase(&uio, 0);
5636 		symlink_len = zfs_uio_iovlen(&uio, 0);
5637 		trycache = true;
5638 	}
5639 	error = zfs_readlink(ap->a_vp, &uio, ap->a_cred, NULL);
5640 	if (atomic_load_ptr(&zp->z_cached_symlink) != NULL ||
5641 	    error != 0 || !trycache) {
5642 		return (error);
5643 	}
5644 	symlink_len -= zfs_uio_resid(&uio);
5645 	symlink = cache_symlink_alloc(symlink_len + 1, M_WAITOK);
5646 	if (symlink != NULL) {
5647 		memcpy(symlink, base, symlink_len);
5648 		symlink[symlink_len] = '\0';
5649 		if (!atomic_cmpset_rel_ptr((uintptr_t *)&zp->z_cached_symlink,
5650 		    (uintptr_t)NULL, (uintptr_t)symlink)) {
5651 			cache_symlink_free(symlink, symlink_len + 1);
5652 		}
5653 	}
5654 	return (error);
5655 }
5656 
5657 #ifndef _SYS_SYSPROTO_H_
5658 struct vop_link_args {
5659 	struct vnode *a_tdvp;
5660 	struct vnode *a_vp;
5661 	struct componentname *a_cnp;
5662 };
5663 #endif
5664 
5665 static int
zfs_freebsd_link(struct vop_link_args * ap)5666 zfs_freebsd_link(struct vop_link_args *ap)
5667 {
5668 	struct componentname *cnp = ap->a_cnp;
5669 	vnode_t *vp = ap->a_vp;
5670 	vnode_t *tdvp = ap->a_tdvp;
5671 
5672 	if (tdvp->v_mount != vp->v_mount)
5673 		return (EXDEV);
5674 
5675 #if __FreeBSD_version < 1400068
5676 	ASSERT(cnp->cn_flags & SAVENAME);
5677 #endif
5678 
5679 	return (zfs_link(VTOZ(tdvp), VTOZ(vp),
5680 	    cnp->cn_nameptr, cnp->cn_cred, 0));
5681 }
5682 
5683 #ifndef _SYS_SYSPROTO_H_
5684 struct vop_inactive_args {
5685 	struct vnode *a_vp;
5686 	struct thread *a_td;
5687 };
5688 #endif
5689 
5690 static int
zfs_freebsd_inactive(struct vop_inactive_args * ap)5691 zfs_freebsd_inactive(struct vop_inactive_args *ap)
5692 {
5693 	vnode_t *vp = ap->a_vp;
5694 
5695 	zfs_inactive(vp, curthread->td_ucred, NULL);
5696 	return (0);
5697 }
5698 
5699 #ifndef _SYS_SYSPROTO_H_
5700 struct vop_need_inactive_args {
5701 	struct vnode *a_vp;
5702 	struct thread *a_td;
5703 };
5704 #endif
5705 
5706 static int
zfs_freebsd_need_inactive(struct vop_need_inactive_args * ap)5707 zfs_freebsd_need_inactive(struct vop_need_inactive_args *ap)
5708 {
5709 	vnode_t *vp = ap->a_vp;
5710 	znode_t	*zp = VTOZ(vp);
5711 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
5712 	int need;
5713 
5714 	if (vn_need_pageq_flush(vp))
5715 		return (1);
5716 
5717 	if (!ZFS_TEARDOWN_INACTIVE_TRY_ENTER_READ(zfsvfs))
5718 		return (1);
5719 	need = (zp->z_sa_hdl == NULL || zp->z_unlinked || zp->z_atime_dirty);
5720 	ZFS_TEARDOWN_INACTIVE_EXIT_READ(zfsvfs);
5721 
5722 	return (need);
5723 }
5724 
5725 #ifndef _SYS_SYSPROTO_H_
5726 struct vop_reclaim_args {
5727 	struct vnode *a_vp;
5728 	struct thread *a_td;
5729 };
5730 #endif
5731 
5732 static int
zfs_freebsd_reclaim(struct vop_reclaim_args * ap)5733 zfs_freebsd_reclaim(struct vop_reclaim_args *ap)
5734 {
5735 	vnode_t	*vp = ap->a_vp;
5736 	znode_t	*zp = VTOZ(vp);
5737 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
5738 
5739 	ASSERT3P(zp, !=, NULL);
5740 
5741 	/*
5742 	 * z_teardown_inactive_lock protects from a race with
5743 	 * zfs_znode_dmu_fini in zfsvfs_teardown during
5744 	 * force unmount.
5745 	 */
5746 	ZFS_TEARDOWN_INACTIVE_ENTER_READ(zfsvfs);
5747 	if (zp->z_sa_hdl == NULL)
5748 		zfs_znode_free(zp);
5749 	else
5750 		zfs_zinactive(zp);
5751 	ZFS_TEARDOWN_INACTIVE_EXIT_READ(zfsvfs);
5752 
5753 	vp->v_data = NULL;
5754 	return (0);
5755 }
5756 
5757 #ifndef _SYS_SYSPROTO_H_
5758 struct vop_fid_args {
5759 	struct vnode *a_vp;
5760 	struct fid *a_fid;
5761 };
5762 #endif
5763 
5764 static int
zfs_freebsd_fid(struct vop_fid_args * ap)5765 zfs_freebsd_fid(struct vop_fid_args *ap)
5766 {
5767 
5768 	return (zfs_fid(ap->a_vp, (void *)ap->a_fid, NULL));
5769 }
5770 
5771 
5772 #ifndef _SYS_SYSPROTO_H_
5773 struct vop_pathconf_args {
5774 	struct vnode *a_vp;
5775 	int a_name;
5776 	register_t *a_retval;
5777 } *ap;
5778 #endif
5779 
5780 static int
zfs_freebsd_pathconf(struct vop_pathconf_args * ap)5781 zfs_freebsd_pathconf(struct vop_pathconf_args *ap)
5782 {
5783 	ulong_t val;
5784 	int error;
5785 #if defined(_PC_CLONE_BLKSIZE) || defined(_PC_CASE_INSENSITIVE) || \
5786 	defined(_PC_HAS_HIDDENSYSTEM)
5787 	zfsvfs_t *zfsvfs;
5788 #endif
5789 
5790 	error = zfs_pathconf(ap->a_vp, ap->a_name, &val,
5791 	    curthread->td_ucred, NULL);
5792 	if (error == 0) {
5793 		*ap->a_retval = val;
5794 		return (error);
5795 	}
5796 	if (error != EOPNOTSUPP)
5797 		return (error);
5798 
5799 	switch (ap->a_name) {
5800 	case _PC_NAME_MAX:
5801 		*ap->a_retval = NAME_MAX;
5802 		return (0);
5803 #if __FreeBSD_version >= 1400032
5804 	case _PC_DEALLOC_PRESENT:
5805 		*ap->a_retval = 1;
5806 		return (0);
5807 #endif
5808 	case _PC_PIPE_BUF:
5809 		if (ap->a_vp->v_type == VDIR || ap->a_vp->v_type == VFIFO) {
5810 			*ap->a_retval = PIPE_BUF;
5811 			return (0);
5812 		}
5813 		return (EINVAL);
5814 #if __FreeBSD_version >= 1500040
5815 	case _PC_NAMEDATTR_ENABLED:
5816 		MNT_ILOCK(ap->a_vp->v_mount);
5817 		if ((ap->a_vp->v_mount->mnt_flag & MNT_NAMEDATTR) != 0)
5818 			*ap->a_retval = 1;
5819 		else
5820 			*ap->a_retval = 0;
5821 		MNT_IUNLOCK(ap->a_vp->v_mount);
5822 		return (0);
5823 	case _PC_HAS_NAMEDATTR:
5824 		if (zfs_has_namedattr(ap->a_vp, curthread->td_ucred))
5825 			*ap->a_retval = 1;
5826 		else
5827 			*ap->a_retval = 0;
5828 		return (0);
5829 #endif
5830 #ifdef _PC_HAS_HIDDENSYSTEM
5831 	case _PC_HAS_HIDDENSYSTEM:
5832 		zfsvfs = (zfsvfs_t *)ap->a_vp->v_mount->mnt_data;
5833 		if (zfsvfs->z_use_fuids == B_TRUE)
5834 			*ap->a_retval = 1;
5835 		else
5836 			*ap->a_retval = 0;
5837 		return (0);
5838 #endif
5839 #ifdef _PC_CLONE_BLKSIZE
5840 	case _PC_CLONE_BLKSIZE:
5841 		zfsvfs = (zfsvfs_t *)ap->a_vp->v_mount->mnt_data;
5842 		if (zfs_bclone_enabled &&
5843 		    spa_feature_is_enabled(dmu_objset_spa(zfsvfs->z_os),
5844 		    SPA_FEATURE_BLOCK_CLONING))
5845 			*ap->a_retval = dsl_dataset_feature_is_active(
5846 			    zfsvfs->z_os->os_dsl_dataset,
5847 			    SPA_FEATURE_LARGE_BLOCKS) ?
5848 			    SPA_MAXBLOCKSIZE :
5849 			    SPA_OLD_MAXBLOCKSIZE;
5850 		else
5851 			*ap->a_retval = 0;
5852 		return (0);
5853 #endif
5854 #ifdef _PC_CASE_INSENSITIVE
5855 	case _PC_CASE_INSENSITIVE:
5856 		zfsvfs = (zfsvfs_t *)ap->a_vp->v_mount->mnt_data;
5857 		if (zfsvfs->z_case == ZFS_CASE_INSENSITIVE)
5858 			*ap->a_retval = 1;
5859 		else
5860 			*ap->a_retval = 0;
5861 		return (0);
5862 #endif
5863 	default:
5864 		return (vop_stdpathconf(ap));
5865 	}
5866 }
5867 
5868 int zfs_xattr_compat = 1;
5869 
5870 static int
zfs_check_attrname(const char * name)5871 zfs_check_attrname(const char *name)
5872 {
5873 	/* We don't allow '/' character in attribute name. */
5874 	if (strchr(name, '/') != NULL)
5875 		return (SET_ERROR(EINVAL));
5876 	/* We don't allow attribute names that start with a namespace prefix. */
5877 	if (ZFS_XA_NS_PREFIX_FORBIDDEN(name))
5878 		return (SET_ERROR(EINVAL));
5879 	return (0);
5880 }
5881 
5882 /*
5883  * FreeBSD's extended attributes namespace defines file name prefix for ZFS'
5884  * extended attribute name:
5885  *
5886  *	NAMESPACE	XATTR_COMPAT	PREFIX
5887  *	system		*		freebsd:system:
5888  *	user		1		(none, can be used to access ZFS
5889  *					fsattr(5) attributes created on Solaris)
5890  *	user		0		user.
5891  */
5892 static int
zfs_create_attrname(int attrnamespace,const char * name,char * attrname,size_t size,boolean_t compat)5893 zfs_create_attrname(int attrnamespace, const char *name, char *attrname,
5894     size_t size, boolean_t compat)
5895 {
5896 	const char *namespace, *prefix, *suffix;
5897 
5898 	memset(attrname, 0, size);
5899 
5900 	switch (attrnamespace) {
5901 	case EXTATTR_NAMESPACE_USER:
5902 		if (compat) {
5903 			/*
5904 			 * This is the default namespace by which we can access
5905 			 * all attributes created on Solaris.
5906 			 */
5907 			prefix = namespace = suffix = "";
5908 		} else {
5909 			/*
5910 			 * This is compatible with the user namespace encoding
5911 			 * on Linux prior to xattr_compat, but nothing
5912 			 * else.
5913 			 */
5914 			prefix = "";
5915 			namespace = "user";
5916 			suffix = ".";
5917 		}
5918 		break;
5919 	case EXTATTR_NAMESPACE_SYSTEM:
5920 		prefix = "freebsd:";
5921 		namespace = EXTATTR_NAMESPACE_SYSTEM_STRING;
5922 		suffix = ":";
5923 		break;
5924 	case EXTATTR_NAMESPACE_EMPTY:
5925 	default:
5926 		return (SET_ERROR(EINVAL));
5927 	}
5928 	if (snprintf(attrname, size, "%s%s%s%s", prefix, namespace, suffix,
5929 	    name) >= size) {
5930 		return (SET_ERROR(ENAMETOOLONG));
5931 	}
5932 	return (0);
5933 }
5934 
5935 static int
zfs_ensure_xattr_cached(znode_t * zp)5936 zfs_ensure_xattr_cached(znode_t *zp)
5937 {
5938 	int error = 0;
5939 
5940 	ASSERT(RW_LOCK_HELD(&zp->z_xattr_lock));
5941 
5942 	if (zp->z_xattr_cached != NULL)
5943 		return (0);
5944 
5945 	if (rw_write_held(&zp->z_xattr_lock))
5946 		return (zfs_sa_get_xattr(zp));
5947 
5948 	if (!rw_tryupgrade(&zp->z_xattr_lock)) {
5949 		rw_exit(&zp->z_xattr_lock);
5950 		rw_enter(&zp->z_xattr_lock, RW_WRITER);
5951 	}
5952 	if (zp->z_xattr_cached == NULL)
5953 		error = zfs_sa_get_xattr(zp);
5954 	rw_downgrade(&zp->z_xattr_lock);
5955 	return (error);
5956 }
5957 
5958 #ifndef _SYS_SYSPROTO_H_
5959 struct vop_getextattr {
5960 	IN struct vnode *a_vp;
5961 	IN int a_attrnamespace;
5962 	IN const char *a_name;
5963 	INOUT struct uio *a_uio;
5964 	OUT size_t *a_size;
5965 	IN struct ucred *a_cred;
5966 	IN struct thread *a_td;
5967 };
5968 #endif
5969 
5970 static int
zfs_getextattr_dir(struct vop_getextattr_args * ap,const char * attrname)5971 zfs_getextattr_dir(struct vop_getextattr_args *ap, const char *attrname)
5972 {
5973 	struct thread *td = ap->a_td;
5974 	struct nameidata nd;
5975 	struct vattr va;
5976 	vnode_t *xvp = NULL, *vp;
5977 	int error, flags;
5978 
5979 	error = zfs_lookup(ap->a_vp, NULL, &xvp, NULL, 0, ap->a_cred,
5980 	    LOOKUP_XATTR, B_FALSE);
5981 	if (error != 0)
5982 		return (error);
5983 
5984 	flags = FREAD;
5985 #if __FreeBSD_version < 1400043
5986 	NDINIT_ATVP(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, attrname,
5987 	    xvp, td);
5988 #else
5989 	NDINIT_ATVP(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, attrname, xvp);
5990 #endif
5991 	error = vn_open_cred(&nd, &flags, 0, VN_OPEN_INVFS, ap->a_cred, NULL);
5992 	if (error != 0)
5993 		return (SET_ERROR(error));
5994 	vp = nd.ni_vp;
5995 	NDFREE_PNBUF(&nd);
5996 
5997 	if (ap->a_size != NULL) {
5998 		error = VOP_GETATTR(vp, &va, ap->a_cred);
5999 		if (error == 0)
6000 			*ap->a_size = (size_t)va.va_size;
6001 	} else if (ap->a_uio != NULL)
6002 		error = VOP_READ(vp, ap->a_uio, IO_UNIT, ap->a_cred);
6003 
6004 	VOP_UNLOCK(vp);
6005 	vn_close(vp, flags, ap->a_cred, td);
6006 	return (error);
6007 }
6008 
6009 static int
zfs_getextattr_sa(struct vop_getextattr_args * ap,const char * attrname)6010 zfs_getextattr_sa(struct vop_getextattr_args *ap, const char *attrname)
6011 {
6012 	znode_t *zp = VTOZ(ap->a_vp);
6013 	uchar_t *nv_value;
6014 	uint_t nv_size;
6015 	int error;
6016 
6017 	error = zfs_ensure_xattr_cached(zp);
6018 	if (error != 0)
6019 		return (error);
6020 
6021 	ASSERT(RW_LOCK_HELD(&zp->z_xattr_lock));
6022 	ASSERT3P(zp->z_xattr_cached, !=, NULL);
6023 
6024 	error = nvlist_lookup_byte_array(zp->z_xattr_cached, attrname,
6025 	    &nv_value, &nv_size);
6026 	if (error != 0)
6027 		return (SET_ERROR(error));
6028 
6029 	if (ap->a_size != NULL)
6030 		*ap->a_size = nv_size;
6031 	else if (ap->a_uio != NULL)
6032 		error = uiomove(nv_value, nv_size, ap->a_uio);
6033 	if (error != 0)
6034 		return (SET_ERROR(error));
6035 
6036 	return (0);
6037 }
6038 
6039 static int
zfs_getextattr_impl(struct vop_getextattr_args * ap,boolean_t compat)6040 zfs_getextattr_impl(struct vop_getextattr_args *ap, boolean_t compat)
6041 {
6042 	znode_t *zp = VTOZ(ap->a_vp);
6043 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
6044 	char attrname[EXTATTR_MAXNAMELEN+1];
6045 	int error;
6046 
6047 	error = zfs_create_attrname(ap->a_attrnamespace, ap->a_name, attrname,
6048 	    sizeof (attrname), compat);
6049 	if (error != 0)
6050 		return (error);
6051 
6052 	error = ENOENT;
6053 	if (zfsvfs->z_use_sa && zp->z_is_sa)
6054 		error = zfs_getextattr_sa(ap, attrname);
6055 	if (error == ENOENT && !zp->z_xattr_dir_absent)
6056 		error = zfs_getextattr_dir(ap, attrname);
6057 	return (error);
6058 }
6059 
6060 /*
6061  * Vnode operation to retrieve a named extended attribute.
6062  */
6063 static int
zfs_getextattr(struct vop_getextattr_args * ap)6064 zfs_getextattr(struct vop_getextattr_args *ap)
6065 {
6066 	znode_t *zp = VTOZ(ap->a_vp);
6067 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
6068 	int error;
6069 
6070 	/*
6071 	 * If the xattr property is off, refuse the request.
6072 	 */
6073 	if (!(zfsvfs->z_flags & ZSB_XATTR))
6074 		return (SET_ERROR(EOPNOTSUPP));
6075 
6076 	error = extattr_check_cred(ap->a_vp, ap->a_attrnamespace,
6077 	    ap->a_cred, ap->a_td, VREAD);
6078 	if (error != 0)
6079 		return (SET_ERROR(error));
6080 
6081 	error = zfs_check_attrname(ap->a_name);
6082 	if (error != 0)
6083 		return (error);
6084 
6085 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
6086 		return (error);
6087 	error = ENOENT;
6088 	rw_enter(&zp->z_xattr_lock, RW_READER);
6089 
6090 	error = zfs_getextattr_impl(ap, zfs_xattr_compat);
6091 	if ((error == ENOENT || error == ENOATTR) &&
6092 	    ap->a_attrnamespace == EXTATTR_NAMESPACE_USER) {
6093 		/*
6094 		 * Fall back to the alternate namespace format if we failed to
6095 		 * find a user xattr.
6096 		 */
6097 		error = zfs_getextattr_impl(ap, !zfs_xattr_compat);
6098 	}
6099 
6100 	rw_exit(&zp->z_xattr_lock);
6101 	zfs_exit(zfsvfs, FTAG);
6102 	if (error == ENOENT)
6103 		error = SET_ERROR(ENOATTR);
6104 	return (error);
6105 }
6106 
6107 #ifndef _SYS_SYSPROTO_H_
6108 struct vop_deleteextattr {
6109 	IN struct vnode *a_vp;
6110 	IN int a_attrnamespace;
6111 	IN const char *a_name;
6112 	IN struct ucred *a_cred;
6113 	IN struct thread *a_td;
6114 };
6115 #endif
6116 
6117 static int
zfs_deleteextattr_dir(struct vop_deleteextattr_args * ap,const char * attrname)6118 zfs_deleteextattr_dir(struct vop_deleteextattr_args *ap, const char *attrname)
6119 {
6120 	struct nameidata nd;
6121 	vnode_t *xvp = NULL, *vp;
6122 	int error;
6123 
6124 	error = zfs_lookup(ap->a_vp, NULL, &xvp, NULL, 0, ap->a_cred,
6125 	    LOOKUP_XATTR, B_FALSE);
6126 	if (error != 0)
6127 		return (error);
6128 
6129 #if __FreeBSD_version < 1400043
6130 	NDINIT_ATVP(&nd, DELETE, NOFOLLOW | LOCKPARENT | LOCKLEAF,
6131 	    UIO_SYSSPACE, attrname, xvp, ap->a_td);
6132 #else
6133 	NDINIT_ATVP(&nd, DELETE, NOFOLLOW | LOCKPARENT | LOCKLEAF,
6134 	    UIO_SYSSPACE, attrname, xvp);
6135 #endif
6136 	error = namei(&nd);
6137 	if (error != 0)
6138 		return (SET_ERROR(error));
6139 
6140 	vp = nd.ni_vp;
6141 	error = VOP_REMOVE(nd.ni_dvp, vp, &nd.ni_cnd);
6142 	NDFREE_PNBUF(&nd);
6143 
6144 	vput(nd.ni_dvp);
6145 	if (vp == nd.ni_dvp)
6146 		vrele(vp);
6147 	else
6148 		vput(vp);
6149 
6150 	return (error);
6151 }
6152 
6153 static int
zfs_deleteextattr_sa(struct vop_deleteextattr_args * ap,const char * attrname)6154 zfs_deleteextattr_sa(struct vop_deleteextattr_args *ap, const char *attrname)
6155 {
6156 	znode_t *zp = VTOZ(ap->a_vp);
6157 	nvlist_t *nvl;
6158 	int error;
6159 
6160 	error = zfs_ensure_xattr_cached(zp);
6161 	if (error != 0)
6162 		return (error);
6163 
6164 	ASSERT(RW_WRITE_HELD(&zp->z_xattr_lock));
6165 	ASSERT3P(zp->z_xattr_cached, !=, NULL);
6166 
6167 	nvl = zp->z_xattr_cached;
6168 	error = nvlist_remove(nvl, attrname, DATA_TYPE_BYTE_ARRAY);
6169 	if (error != 0)
6170 		error = SET_ERROR(error);
6171 	else
6172 		error = zfs_sa_set_xattr(zp, attrname, NULL, 0);
6173 	if (error != 0) {
6174 		zp->z_xattr_cached = NULL;
6175 		nvlist_free(nvl);
6176 	}
6177 	return (error);
6178 }
6179 
6180 static int
zfs_deleteextattr_impl(struct vop_deleteextattr_args * ap,boolean_t compat)6181 zfs_deleteextattr_impl(struct vop_deleteextattr_args *ap, boolean_t compat)
6182 {
6183 	znode_t *zp = VTOZ(ap->a_vp);
6184 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
6185 	char attrname[EXTATTR_MAXNAMELEN+1];
6186 	int error;
6187 
6188 	error = zfs_create_attrname(ap->a_attrnamespace, ap->a_name, attrname,
6189 	    sizeof (attrname), compat);
6190 	if (error != 0)
6191 		return (error);
6192 
6193 	error = ENOENT;
6194 	if (zfsvfs->z_use_sa && zp->z_is_sa)
6195 		error = zfs_deleteextattr_sa(ap, attrname);
6196 	if (error == ENOENT)
6197 		error = zfs_deleteextattr_dir(ap, attrname);
6198 	return (error);
6199 }
6200 
6201 /*
6202  * Vnode operation to remove a named attribute.
6203  */
6204 static int
zfs_deleteextattr(struct vop_deleteextattr_args * ap)6205 zfs_deleteextattr(struct vop_deleteextattr_args *ap)
6206 {
6207 	znode_t *zp = VTOZ(ap->a_vp);
6208 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
6209 	int error;
6210 
6211 	/*
6212 	 * If the xattr property is off, refuse the request.
6213 	 */
6214 	if (!(zfsvfs->z_flags & ZSB_XATTR))
6215 		return (SET_ERROR(EOPNOTSUPP));
6216 
6217 	error = extattr_check_cred(ap->a_vp, ap->a_attrnamespace,
6218 	    ap->a_cred, ap->a_td, VWRITE);
6219 	if (error != 0)
6220 		return (SET_ERROR(error));
6221 
6222 	error = zfs_check_attrname(ap->a_name);
6223 	if (error != 0)
6224 		return (error);
6225 
6226 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
6227 		return (error);
6228 	rw_enter(&zp->z_xattr_lock, RW_WRITER);
6229 
6230 	error = zfs_deleteextattr_impl(ap, zfs_xattr_compat);
6231 	if ((error == ENOENT || error == ENOATTR) &&
6232 	    ap->a_attrnamespace == EXTATTR_NAMESPACE_USER) {
6233 		/*
6234 		 * Fall back to the alternate namespace format if we failed to
6235 		 * find a user xattr.
6236 		 */
6237 		error = zfs_deleteextattr_impl(ap, !zfs_xattr_compat);
6238 	}
6239 
6240 	rw_exit(&zp->z_xattr_lock);
6241 	zfs_exit(zfsvfs, FTAG);
6242 	if (error == ENOENT)
6243 		error = SET_ERROR(ENOATTR);
6244 	return (error);
6245 }
6246 
6247 #ifndef _SYS_SYSPROTO_H_
6248 struct vop_setextattr {
6249 	IN struct vnode *a_vp;
6250 	IN int a_attrnamespace;
6251 	IN const char *a_name;
6252 	INOUT struct uio *a_uio;
6253 	IN struct ucred *a_cred;
6254 	IN struct thread *a_td;
6255 };
6256 #endif
6257 
6258 static int
zfs_setextattr_dir(struct vop_setextattr_args * ap,const char * attrname)6259 zfs_setextattr_dir(struct vop_setextattr_args *ap, const char *attrname)
6260 {
6261 	struct thread *td = ap->a_td;
6262 	struct nameidata nd;
6263 	struct vattr va;
6264 	vnode_t *xvp = NULL, *vp;
6265 	int error, flags;
6266 
6267 	error = zfs_lookup(ap->a_vp, NULL, &xvp, NULL, 0, ap->a_cred,
6268 	    LOOKUP_XATTR | CREATE_XATTR_DIR, B_FALSE);
6269 	if (error != 0)
6270 		return (error);
6271 
6272 	flags = FFLAGS(O_WRONLY | O_CREAT);
6273 #if __FreeBSD_version < 1400043
6274 	NDINIT_ATVP(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, attrname, xvp, td);
6275 #else
6276 	NDINIT_ATVP(&nd, LOOKUP, NOFOLLOW, UIO_SYSSPACE, attrname, xvp);
6277 #endif
6278 	error = vn_open_cred(&nd, &flags, 0600, VN_OPEN_INVFS, ap->a_cred,
6279 	    NULL);
6280 	if (error != 0)
6281 		return (SET_ERROR(error));
6282 	vp = nd.ni_vp;
6283 	NDFREE_PNBUF(&nd);
6284 
6285 	VATTR_NULL(&va);
6286 	va.va_size = 0;
6287 	error = VOP_SETATTR(vp, &va, ap->a_cred);
6288 	if (error == 0)
6289 		VOP_WRITE(vp, ap->a_uio, IO_UNIT, ap->a_cred);
6290 
6291 	VOP_UNLOCK(vp);
6292 	vn_close(vp, flags, ap->a_cred, td);
6293 	return (error);
6294 }
6295 
6296 static int
zfs_setextattr_sa(struct vop_setextattr_args * ap,const char * attrname)6297 zfs_setextattr_sa(struct vop_setextattr_args *ap, const char *attrname)
6298 {
6299 	znode_t *zp = VTOZ(ap->a_vp);
6300 	nvlist_t *nvl;
6301 	size_t sa_size;
6302 	int error;
6303 
6304 	error = zfs_ensure_xattr_cached(zp);
6305 	if (error != 0)
6306 		return (error);
6307 
6308 	ASSERT(RW_WRITE_HELD(&zp->z_xattr_lock));
6309 	ASSERT3P(zp->z_xattr_cached, !=, NULL);
6310 
6311 	nvl = zp->z_xattr_cached;
6312 	size_t entry_size = ap->a_uio->uio_resid;
6313 	if (entry_size > DXATTR_MAX_ENTRY_SIZE)
6314 		return (SET_ERROR(EFBIG));
6315 	error = nvlist_size(nvl, &sa_size, NV_ENCODE_XDR);
6316 	if (error != 0)
6317 		return (SET_ERROR(error));
6318 	if (sa_size > DXATTR_MAX_SA_SIZE)
6319 		return (SET_ERROR(EFBIG));
6320 	uchar_t *buf = kmem_alloc(entry_size, KM_SLEEP);
6321 	error = uiomove(buf, entry_size, ap->a_uio);
6322 	if (error != 0) {
6323 		error = SET_ERROR(error);
6324 	} else {
6325 		error = nvlist_add_byte_array(nvl, attrname, buf, entry_size);
6326 		if (error != 0)
6327 			error = SET_ERROR(error);
6328 	}
6329 	if (error == 0)
6330 		error = zfs_sa_set_xattr(zp, attrname, buf, entry_size);
6331 	kmem_free(buf, entry_size);
6332 	if (error != 0) {
6333 		zp->z_xattr_cached = NULL;
6334 		nvlist_free(nvl);
6335 	}
6336 	return (error);
6337 }
6338 
6339 static int
zfs_setextattr_impl(struct vop_setextattr_args * ap,boolean_t compat)6340 zfs_setextattr_impl(struct vop_setextattr_args *ap, boolean_t compat)
6341 {
6342 	znode_t *zp = VTOZ(ap->a_vp);
6343 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
6344 	char attrname[EXTATTR_MAXNAMELEN+1];
6345 	int error;
6346 
6347 	error = zfs_create_attrname(ap->a_attrnamespace, ap->a_name, attrname,
6348 	    sizeof (attrname), compat);
6349 	if (error != 0)
6350 		return (error);
6351 
6352 	struct vop_deleteextattr_args vda = {
6353 		.a_vp = ap->a_vp,
6354 		.a_attrnamespace = ap->a_attrnamespace,
6355 		.a_name = ap->a_name,
6356 		.a_cred = ap->a_cred,
6357 		.a_td = ap->a_td,
6358 	};
6359 	error = ENOENT;
6360 	if (zfsvfs->z_use_sa && zp->z_is_sa && zfsvfs->z_xattr_sa) {
6361 		error = zfs_setextattr_sa(ap, attrname);
6362 		if (error == 0) {
6363 			/*
6364 			 * Successfully put into SA, we need to clear the one
6365 			 * in dir if present.
6366 			 */
6367 			zfs_deleteextattr_dir(&vda, attrname);
6368 		}
6369 	}
6370 	if (error != 0) {
6371 		error = zfs_setextattr_dir(ap, attrname);
6372 		if (error == 0 && zp->z_is_sa) {
6373 			/*
6374 			 * Successfully put into dir, we need to clear the one
6375 			 * in SA if present.
6376 			 */
6377 			zfs_deleteextattr_sa(&vda, attrname);
6378 		}
6379 	}
6380 	if (error == 0 && ap->a_attrnamespace == EXTATTR_NAMESPACE_USER) {
6381 		/*
6382 		 * Also clear all versions of the alternate compat name.
6383 		 */
6384 		zfs_deleteextattr_impl(&vda, !compat);
6385 	}
6386 	return (error);
6387 }
6388 
6389 /*
6390  * Vnode operation to set a named attribute.
6391  */
6392 static int
zfs_setextattr(struct vop_setextattr_args * ap)6393 zfs_setextattr(struct vop_setextattr_args *ap)
6394 {
6395 	znode_t *zp = VTOZ(ap->a_vp);
6396 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
6397 	int error;
6398 
6399 	/*
6400 	 * If the xattr property is off, refuse the request.
6401 	 */
6402 	if (!(zfsvfs->z_flags & ZSB_XATTR))
6403 		return (SET_ERROR(EOPNOTSUPP));
6404 
6405 	error = extattr_check_cred(ap->a_vp, ap->a_attrnamespace,
6406 	    ap->a_cred, ap->a_td, VWRITE);
6407 	if (error != 0)
6408 		return (SET_ERROR(error));
6409 
6410 	error = zfs_check_attrname(ap->a_name);
6411 	if (error != 0)
6412 		return (error);
6413 
6414 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
6415 		return (error);
6416 	rw_enter(&zp->z_xattr_lock, RW_WRITER);
6417 
6418 	error = zfs_setextattr_impl(ap, zfs_xattr_compat);
6419 
6420 	rw_exit(&zp->z_xattr_lock);
6421 	zfs_exit(zfsvfs, FTAG);
6422 	return (error);
6423 }
6424 
6425 #ifndef _SYS_SYSPROTO_H_
6426 struct vop_listextattr {
6427 	IN struct vnode *a_vp;
6428 	IN int a_attrnamespace;
6429 	INOUT struct uio *a_uio;
6430 	OUT size_t *a_size;
6431 	IN struct ucred *a_cred;
6432 	IN struct thread *a_td;
6433 };
6434 #endif
6435 
6436 static int
zfs_listextattr_dir(struct vop_listextattr_args * ap,const char * attrprefix)6437 zfs_listextattr_dir(struct vop_listextattr_args *ap, const char *attrprefix)
6438 {
6439 	struct thread *td = ap->a_td;
6440 	struct nameidata nd;
6441 	uint8_t dirbuf[sizeof (struct dirent)];
6442 	struct iovec aiov;
6443 	struct uio auio;
6444 	vnode_t *xvp = NULL, *vp;
6445 	int error, eof;
6446 
6447 	error = zfs_lookup(ap->a_vp, NULL, &xvp, NULL, 0, ap->a_cred,
6448 	    LOOKUP_XATTR, B_FALSE);
6449 	if (error != 0) {
6450 		/*
6451 		 * ENOATTR means that the EA directory does not yet exist,
6452 		 * i.e. there are no extended attributes there.
6453 		 */
6454 		if (error == ENOATTR)
6455 			error = 0;
6456 		return (error);
6457 	}
6458 
6459 #if __FreeBSD_version < 1400043
6460 	NDINIT_ATVP(&nd, LOOKUP, NOFOLLOW | LOCKLEAF | LOCKSHARED,
6461 	    UIO_SYSSPACE, ".", xvp, td);
6462 #else
6463 	NDINIT_ATVP(&nd, LOOKUP, NOFOLLOW | LOCKLEAF | LOCKSHARED,
6464 	    UIO_SYSSPACE, ".", xvp);
6465 #endif
6466 	error = namei(&nd);
6467 	if (error != 0)
6468 		return (SET_ERROR(error));
6469 	vp = nd.ni_vp;
6470 	NDFREE_PNBUF(&nd);
6471 
6472 	auio.uio_iov = &aiov;
6473 	auio.uio_iovcnt = 1;
6474 	auio.uio_segflg = UIO_SYSSPACE;
6475 	auio.uio_td = td;
6476 	auio.uio_rw = UIO_READ;
6477 	auio.uio_offset = 0;
6478 
6479 	size_t plen = strlen(attrprefix);
6480 
6481 	do {
6482 		aiov.iov_base = (void *)dirbuf;
6483 		aiov.iov_len = sizeof (dirbuf);
6484 		auio.uio_resid = sizeof (dirbuf);
6485 		error = VOP_READDIR(vp, &auio, ap->a_cred, &eof, NULL, NULL);
6486 		if (error != 0)
6487 			break;
6488 		int done = sizeof (dirbuf) - auio.uio_resid;
6489 		for (int pos = 0; pos < done; ) {
6490 			struct dirent *dp = (struct dirent *)(dirbuf + pos);
6491 			pos += dp->d_reclen;
6492 			/*
6493 			 * XXX: Temporarily we also accept DT_UNKNOWN, as this
6494 			 * is what we get when attribute was created on Solaris.
6495 			 */
6496 			if (dp->d_type != DT_REG && dp->d_type != DT_UNKNOWN)
6497 				continue;
6498 			else if (plen == 0 &&
6499 			    ZFS_XA_NS_PREFIX_FORBIDDEN(dp->d_name))
6500 				continue;
6501 			else if (strncmp(dp->d_name, attrprefix, plen) != 0)
6502 				continue;
6503 			uint8_t nlen = dp->d_namlen - plen;
6504 			if (ap->a_size != NULL) {
6505 				*ap->a_size += 1 + nlen;
6506 			} else if (ap->a_uio != NULL) {
6507 				/*
6508 				 * Format of extattr name entry is one byte for
6509 				 * length and the rest for name.
6510 				 */
6511 				error = uiomove(&nlen, 1, ap->a_uio);
6512 				if (error == 0) {
6513 					char *namep = dp->d_name + plen;
6514 					error = uiomove(namep, nlen, ap->a_uio);
6515 				}
6516 				if (error != 0) {
6517 					error = SET_ERROR(error);
6518 					break;
6519 				}
6520 			}
6521 		}
6522 	} while (!eof && error == 0);
6523 
6524 	vput(vp);
6525 	return (error);
6526 }
6527 
6528 static int
zfs_listextattr_sa(struct vop_listextattr_args * ap,const char * attrprefix)6529 zfs_listextattr_sa(struct vop_listextattr_args *ap, const char *attrprefix)
6530 {
6531 	znode_t *zp = VTOZ(ap->a_vp);
6532 	int error;
6533 
6534 	error = zfs_ensure_xattr_cached(zp);
6535 	if (error != 0)
6536 		return (error);
6537 
6538 	ASSERT(RW_LOCK_HELD(&zp->z_xattr_lock));
6539 	ASSERT3P(zp->z_xattr_cached, !=, NULL);
6540 
6541 	size_t plen = strlen(attrprefix);
6542 	nvpair_t *nvp = NULL;
6543 	while ((nvp = nvlist_next_nvpair(zp->z_xattr_cached, nvp)) != NULL) {
6544 		ASSERT3U(nvpair_type(nvp), ==, DATA_TYPE_BYTE_ARRAY);
6545 
6546 		const char *name = nvpair_name(nvp);
6547 		if (plen == 0 && ZFS_XA_NS_PREFIX_FORBIDDEN(name))
6548 			continue;
6549 		else if (strncmp(name, attrprefix, plen) != 0)
6550 			continue;
6551 		uint8_t nlen = strlen(name) - plen;
6552 		if (ap->a_size != NULL) {
6553 			*ap->a_size += 1 + nlen;
6554 		} else if (ap->a_uio != NULL) {
6555 			/*
6556 			 * Format of extattr name entry is one byte for
6557 			 * length and the rest for name.
6558 			 */
6559 			error = uiomove(&nlen, 1, ap->a_uio);
6560 			if (error == 0) {
6561 				char *namep = __DECONST(char *, name) + plen;
6562 				error = uiomove(namep, nlen, ap->a_uio);
6563 			}
6564 			if (error != 0) {
6565 				error = SET_ERROR(error);
6566 				break;
6567 			}
6568 		}
6569 	}
6570 
6571 	return (error);
6572 }
6573 
6574 static int
zfs_listextattr_impl(struct vop_listextattr_args * ap,boolean_t compat)6575 zfs_listextattr_impl(struct vop_listextattr_args *ap, boolean_t compat)
6576 {
6577 	znode_t *zp = VTOZ(ap->a_vp);
6578 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
6579 	char attrprefix[16];
6580 	int error;
6581 
6582 	error = zfs_create_attrname(ap->a_attrnamespace, "", attrprefix,
6583 	    sizeof (attrprefix), compat);
6584 	if (error != 0)
6585 		return (error);
6586 
6587 	if (zfsvfs->z_use_sa && zp->z_is_sa)
6588 		error = zfs_listextattr_sa(ap, attrprefix);
6589 	if (error == 0)
6590 		error = zfs_listextattr_dir(ap, attrprefix);
6591 	return (error);
6592 }
6593 
6594 /*
6595  * Vnode operation to retrieve extended attributes on a vnode.
6596  */
6597 static int
zfs_listextattr(struct vop_listextattr_args * ap)6598 zfs_listextattr(struct vop_listextattr_args *ap)
6599 {
6600 	znode_t *zp = VTOZ(ap->a_vp);
6601 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
6602 	int error;
6603 
6604 	if (ap->a_size != NULL)
6605 		*ap->a_size = 0;
6606 
6607 	/*
6608 	 * If the xattr property is off, refuse the request.
6609 	 */
6610 	if (!(zfsvfs->z_flags & ZSB_XATTR))
6611 		return (SET_ERROR(EOPNOTSUPP));
6612 
6613 	error = extattr_check_cred(ap->a_vp, ap->a_attrnamespace,
6614 	    ap->a_cred, ap->a_td, VREAD);
6615 	if (error != 0)
6616 		return (SET_ERROR(error));
6617 
6618 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
6619 		return (error);
6620 	rw_enter(&zp->z_xattr_lock, RW_READER);
6621 
6622 	error = zfs_listextattr_impl(ap, zfs_xattr_compat);
6623 	if (error == 0 && ap->a_attrnamespace == EXTATTR_NAMESPACE_USER) {
6624 		/* Also list user xattrs with the alternate format. */
6625 		error = zfs_listextattr_impl(ap, !zfs_xattr_compat);
6626 	}
6627 
6628 	rw_exit(&zp->z_xattr_lock);
6629 	zfs_exit(zfsvfs, FTAG);
6630 	return (error);
6631 }
6632 
6633 #ifndef _SYS_SYSPROTO_H_
6634 struct vop_getacl_args {
6635 	struct vnode *vp;
6636 	acl_type_t type;
6637 	struct acl *aclp;
6638 	struct ucred *cred;
6639 	struct thread *td;
6640 };
6641 #endif
6642 
6643 static int
zfs_freebsd_getacl(struct vop_getacl_args * ap)6644 zfs_freebsd_getacl(struct vop_getacl_args *ap)
6645 {
6646 	int		error;
6647 	vsecattr_t	vsecattr;
6648 
6649 	if (ap->a_type != ACL_TYPE_NFS4)
6650 		return (EINVAL);
6651 
6652 	vsecattr.vsa_mask = VSA_ACE | VSA_ACECNT;
6653 	if ((error = zfs_getsecattr(VTOZ(ap->a_vp),
6654 	    &vsecattr, 0, ap->a_cred)))
6655 		return (error);
6656 
6657 	error = acl_from_aces(ap->a_aclp, vsecattr.vsa_aclentp,
6658 	    vsecattr.vsa_aclcnt);
6659 	if (vsecattr.vsa_aclentp != NULL)
6660 		kmem_free(vsecattr.vsa_aclentp, vsecattr.vsa_aclentsz);
6661 
6662 	return (error);
6663 }
6664 
6665 #ifndef _SYS_SYSPROTO_H_
6666 struct vop_setacl_args {
6667 	struct vnode *vp;
6668 	acl_type_t type;
6669 	struct acl *aclp;
6670 	struct ucred *cred;
6671 	struct thread *td;
6672 };
6673 #endif
6674 
6675 static int
zfs_freebsd_setacl(struct vop_setacl_args * ap)6676 zfs_freebsd_setacl(struct vop_setacl_args *ap)
6677 {
6678 	int		error;
6679 	vsecattr_t vsecattr;
6680 	int		aclbsize;	/* size of acl list in bytes */
6681 	aclent_t	*aaclp;
6682 
6683 	if (ap->a_type != ACL_TYPE_NFS4)
6684 		return (EINVAL);
6685 
6686 	if (ap->a_aclp == NULL)
6687 		return (EINVAL);
6688 
6689 	if (ap->a_aclp->acl_cnt < 1 || ap->a_aclp->acl_cnt > MAX_ACL_ENTRIES)
6690 		return (EINVAL);
6691 
6692 	/*
6693 	 * With NFSv4 ACLs, chmod(2) may need to add additional entries,
6694 	 * splitting every entry into two and appending "canonical six"
6695 	 * entries at the end.  Don't allow for setting an ACL that would
6696 	 * cause chmod(2) to run out of ACL entries.
6697 	 */
6698 	if (ap->a_aclp->acl_cnt * 2 + 6 > ACL_MAX_ENTRIES)
6699 		return (ENOSPC);
6700 
6701 	error = acl_nfs4_check(ap->a_aclp, ap->a_vp->v_type == VDIR);
6702 	if (error != 0)
6703 		return (error);
6704 
6705 	vsecattr.vsa_mask = VSA_ACE;
6706 	aclbsize = ap->a_aclp->acl_cnt * sizeof (ace_t);
6707 	vsecattr.vsa_aclentp = kmem_alloc(aclbsize, KM_SLEEP);
6708 	aaclp = vsecattr.vsa_aclentp;
6709 	vsecattr.vsa_aclentsz = aclbsize;
6710 
6711 	aces_from_acl(vsecattr.vsa_aclentp, &vsecattr.vsa_aclcnt, ap->a_aclp);
6712 	error = zfs_setsecattr(VTOZ(ap->a_vp), &vsecattr, 0, ap->a_cred);
6713 	kmem_free(aaclp, aclbsize);
6714 
6715 	return (error);
6716 }
6717 
6718 #ifndef _SYS_SYSPROTO_H_
6719 struct vop_aclcheck_args {
6720 	struct vnode *vp;
6721 	acl_type_t type;
6722 	struct acl *aclp;
6723 	struct ucred *cred;
6724 	struct thread *td;
6725 };
6726 #endif
6727 
6728 static int
zfs_freebsd_aclcheck(struct vop_aclcheck_args * ap)6729 zfs_freebsd_aclcheck(struct vop_aclcheck_args *ap)
6730 {
6731 
6732 	return (EOPNOTSUPP);
6733 }
6734 
6735 #ifndef _SYS_SYSPROTO_H_
6736 struct vop_advise_args {
6737 	struct vnode *a_vp;
6738 	off_t a_start;
6739 	off_t a_end;
6740 	int a_advice;
6741 };
6742 #endif
6743 
6744 static int
zfs_freebsd_advise(struct vop_advise_args * ap)6745 zfs_freebsd_advise(struct vop_advise_args *ap)
6746 {
6747 	vnode_t *vp = ap->a_vp;
6748 	off_t start = ap->a_start;
6749 	off_t end = ap->a_end;
6750 	int advice = ap->a_advice;
6751 	off_t len;
6752 	znode_t *zp;
6753 	zfsvfs_t *zfsvfs;
6754 	objset_t *os;
6755 	int error = 0;
6756 
6757 	if (end < start)
6758 		return (EINVAL);
6759 
6760 	error = vn_lock(vp, LK_SHARED);
6761 	if (error)
6762 		return (error);
6763 
6764 	zp = VTOZ(vp);
6765 	zfsvfs = zp->z_zfsvfs;
6766 	os = zp->z_zfsvfs->z_os;
6767 
6768 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
6769 		goto out_unlock;
6770 
6771 	/* kern_posix_fadvise points to the last byte, we want one past */
6772 	if (end != OFF_MAX)
6773 		end += 1;
6774 	len = end - start;
6775 
6776 	switch (advice) {
6777 	case POSIX_FADV_WILLNEED:
6778 		/*
6779 		 * Pass on the caller's size directly, but note that
6780 		 * dmu_prefetch_max will effectively cap it.  If there really
6781 		 * is a larger sequential access pattern, perhaps dmu_zfetch
6782 		 * will detect it.
6783 		 */
6784 		dmu_prefetch(os, zp->z_id, 0, start, len,
6785 		    ZIO_PRIORITY_ASYNC_READ);
6786 		break;
6787 	case POSIX_FADV_DONTNEED:
6788 		dmu_evict_range(os, zp->z_id, start, len);
6789 		break;
6790 	case POSIX_FADV_NORMAL:
6791 	case POSIX_FADV_RANDOM:
6792 	case POSIX_FADV_SEQUENTIAL:
6793 	case POSIX_FADV_NOREUSE:
6794 		/* ignored for now */
6795 		break;
6796 	default:
6797 		error = EINVAL;
6798 		break;
6799 	}
6800 
6801 	zfs_exit(zfsvfs, FTAG);
6802 
6803 out_unlock:
6804 	VOP_UNLOCK(vp);
6805 
6806 	return (error);
6807 }
6808 
6809 static int
zfs_vptocnp(struct vop_vptocnp_args * ap)6810 zfs_vptocnp(struct vop_vptocnp_args *ap)
6811 {
6812 	vnode_t *covered_vp;
6813 	vnode_t *vp = ap->a_vp;
6814 	zfsvfs_t *zfsvfs = vp->v_vfsp->vfs_data;
6815 	znode_t *zp = VTOZ(vp);
6816 	int ltype;
6817 	int error;
6818 
6819 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
6820 		return (error);
6821 
6822 	/*
6823 	 * If we are a snapshot mounted under .zfs, run the operation
6824 	 * on the covered vnode.
6825 	 */
6826 	if (zp->z_id != zfsvfs->z_root || zfsvfs->z_parent == zfsvfs) {
6827 		char name[MAXNAMLEN + 1];
6828 		znode_t *dzp;
6829 		size_t len;
6830 
6831 		error = zfs_znode_parent_and_name(zp, &dzp, name,
6832 		    sizeof (name));
6833 		if (error == 0) {
6834 			len = strlen(name);
6835 			if (*ap->a_buflen < len)
6836 				error = SET_ERROR(ENOMEM);
6837 		}
6838 		if (error == 0) {
6839 			*ap->a_buflen -= len;
6840 			memcpy(ap->a_buf + *ap->a_buflen, name, len);
6841 			*ap->a_vpp = ZTOV(dzp);
6842 		}
6843 		zfs_exit(zfsvfs, FTAG);
6844 		return (error);
6845 	}
6846 	zfs_exit(zfsvfs, FTAG);
6847 
6848 	covered_vp = vp->v_mount->mnt_vnodecovered;
6849 	enum vgetstate vs = vget_prep(covered_vp);
6850 	ltype = VOP_ISLOCKED(vp);
6851 	VOP_UNLOCK(vp);
6852 	error = vget_finish(covered_vp, LK_SHARED, vs);
6853 	if (error == 0) {
6854 		error = VOP_VPTOCNP(covered_vp, ap->a_vpp, ap->a_buf,
6855 		    ap->a_buflen);
6856 		vput(covered_vp);
6857 	}
6858 	vn_lock(vp, ltype | LK_RETRY);
6859 	if (VN_IS_DOOMED(vp))
6860 		error = SET_ERROR(ENOENT);
6861 	return (error);
6862 }
6863 
6864 #if __FreeBSD_version >= 1400032
6865 static int
zfs_deallocate(struct vop_deallocate_args * ap)6866 zfs_deallocate(struct vop_deallocate_args *ap)
6867 {
6868 	znode_t *zp = VTOZ(ap->a_vp);
6869 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
6870 	zilog_t *zilog;
6871 	off_t off, len, file_sz;
6872 	int error;
6873 
6874 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
6875 		return (error);
6876 
6877 	/*
6878 	 * Callers might not be able to detect properly that we are read-only,
6879 	 * so check it explicitly here.
6880 	 */
6881 	if (zfs_is_readonly(zfsvfs)) {
6882 		zfs_exit(zfsvfs, FTAG);
6883 		return (SET_ERROR(EROFS));
6884 	}
6885 
6886 	zilog = zfsvfs->z_log;
6887 	off = *ap->a_offset;
6888 	len = *ap->a_len;
6889 	file_sz = zp->z_size;
6890 	if (off + len > file_sz)
6891 		len = file_sz - off;
6892 	/* Fast path for out-of-range request. */
6893 	if (len <= 0) {
6894 		*ap->a_len = 0;
6895 		zfs_exit(zfsvfs, FTAG);
6896 		return (0);
6897 	}
6898 
6899 	error = zfs_freesp(zp, off, len, O_RDWR, TRUE);
6900 	if (error == 0) {
6901 		if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS ||
6902 		    (ap->a_ioflag & IO_SYNC) != 0)
6903 			error = zil_commit(zilog, zp->z_id);
6904 		if (error == 0) {
6905 			*ap->a_offset = off + len;
6906 			*ap->a_len = 0;
6907 		}
6908 	}
6909 
6910 	zfs_exit(zfsvfs, FTAG);
6911 	return (error);
6912 }
6913 #endif
6914 
6915 #ifndef _SYS_SYSPROTO_H_
6916 struct vop_copy_file_range_args {
6917 	struct vnode *a_invp;
6918 	off_t *a_inoffp;
6919 	struct vnode *a_outvp;
6920 	off_t *a_outoffp;
6921 	size_t *a_lenp;
6922 	unsigned int a_flags;
6923 	struct ucred *a_incred;
6924 	struct ucred *a_outcred;
6925 	struct thread *a_fsizetd;
6926 }
6927 #endif
6928 /*
6929  * TODO: FreeBSD will only call file system-specific copy_file_range() if both
6930  * files resides under the same mountpoint. In case of ZFS we want to be called
6931  * even is files are in different datasets (but on the same pools, but we need
6932  * to check that ourselves).
6933  */
6934 static int
zfs_freebsd_copy_file_range(struct vop_copy_file_range_args * ap)6935 zfs_freebsd_copy_file_range(struct vop_copy_file_range_args *ap)
6936 {
6937 	zfsvfs_t *outzfsvfs;
6938 	struct vnode *invp = ap->a_invp;
6939 	struct vnode *outvp = ap->a_outvp;
6940 	struct mount *mp;
6941 	int error;
6942 	uint64_t len = *ap->a_lenp;
6943 
6944 	if (!zfs_bclone_enabled) {
6945 		mp = NULL;
6946 		goto bad_write_fallback;
6947 	}
6948 
6949 	/*
6950 	 * TODO: If offset/length is not aligned to recordsize, use
6951 	 * vn_generic_copy_file_range() on this fragment.
6952 	 * It would be better to do this after we lock the vnodes, but then we
6953 	 * need something else than vn_generic_copy_file_range().
6954 	 */
6955 
6956 	vn_start_write(outvp, &mp, V_WAIT);
6957 	if (__predict_true(mp == outvp->v_mount)) {
6958 		outzfsvfs = (zfsvfs_t *)mp->mnt_data;
6959 		if (!spa_feature_is_enabled(dmu_objset_spa(outzfsvfs->z_os),
6960 		    SPA_FEATURE_BLOCK_CLONING)) {
6961 			goto bad_write_fallback;
6962 		}
6963 	}
6964 	if (invp == outvp) {
6965 		if (vn_lock(outvp, LK_EXCLUSIVE) != 0) {
6966 			goto bad_write_fallback;
6967 		}
6968 	} else {
6969 #if (__FreeBSD_version >= 1302506 && __FreeBSD_version < 1400000) || \
6970 	__FreeBSD_version >= 1400086
6971 		vn_lock_pair(invp, false, LK_SHARED, outvp, false,
6972 		    LK_EXCLUSIVE);
6973 #else
6974 		vn_lock_pair(invp, false, outvp, false);
6975 #endif
6976 		if (VN_IS_DOOMED(invp) || VN_IS_DOOMED(outvp)) {
6977 			goto bad_locked_fallback;
6978 		}
6979 	}
6980 
6981 #ifdef MAC
6982 	error = mac_vnode_check_write(curthread->td_ucred, ap->a_outcred,
6983 	    outvp);
6984 	if (error != 0)
6985 		goto out_locked;
6986 #endif
6987 
6988 	error = zfs_clone_range(VTOZ(invp), ap->a_inoffp, VTOZ(outvp),
6989 	    ap->a_outoffp, &len, ap->a_outcred);
6990 	if (error == EXDEV || error == EAGAIN || error == EINVAL ||
6991 	    error == EOPNOTSUPP)
6992 		goto bad_locked_fallback;
6993 	*ap->a_lenp = (size_t)len;
6994 #ifdef MAC
6995 out_locked:
6996 #endif
6997 	if (invp != outvp)
6998 		VOP_UNLOCK(invp);
6999 	VOP_UNLOCK(outvp);
7000 	if (mp != NULL)
7001 		vn_finished_write(mp);
7002 	return (error);
7003 
7004 bad_locked_fallback:
7005 	if (invp != outvp)
7006 		VOP_UNLOCK(invp);
7007 	VOP_UNLOCK(outvp);
7008 bad_write_fallback:
7009 	if (mp != NULL)
7010 		vn_finished_write(mp);
7011 	error = ENOSYS;
7012 	return (error);
7013 }
7014 
7015 struct vop_vector zfs_vnodeops;
7016 struct vop_vector zfs_fifoops;
7017 struct vop_vector zfs_shareops;
7018 
7019 struct vop_vector zfs_vnodeops = {
7020 	.vop_default =		&default_vnodeops,
7021 	.vop_inactive =		zfs_freebsd_inactive,
7022 	.vop_need_inactive =	zfs_freebsd_need_inactive,
7023 	.vop_reclaim =		zfs_freebsd_reclaim,
7024 	.vop_fplookup_vexec = zfs_freebsd_fplookup_vexec,
7025 	.vop_fplookup_symlink = zfs_freebsd_fplookup_symlink,
7026 	.vop_access =		zfs_freebsd_access,
7027 	.vop_allocate =		VOP_EOPNOTSUPP,
7028 #if __FreeBSD_version >= 1400032
7029 	.vop_deallocate =	zfs_deallocate,
7030 #endif
7031 	.vop_lookup =		zfs_cache_lookup,
7032 	.vop_cachedlookup =	zfs_freebsd_cachedlookup,
7033 	.vop_getattr =		zfs_freebsd_getattr,
7034 	.vop_setattr =		zfs_freebsd_setattr,
7035 	.vop_create =		zfs_freebsd_create,
7036 	.vop_mknod =		(vop_mknod_t *)zfs_freebsd_create,
7037 	.vop_mkdir =		zfs_freebsd_mkdir,
7038 	.vop_readdir =		zfs_freebsd_readdir,
7039 	.vop_fsync =		zfs_freebsd_fsync,
7040 	.vop_open =		zfs_freebsd_open,
7041 	.vop_close =		zfs_freebsd_close,
7042 	.vop_rmdir =		zfs_freebsd_rmdir,
7043 	.vop_ioctl =		zfs_freebsd_ioctl,
7044 	.vop_link =		zfs_freebsd_link,
7045 	.vop_symlink =		zfs_freebsd_symlink,
7046 	.vop_readlink =		zfs_freebsd_readlink,
7047 	.vop_advise =		zfs_freebsd_advise,
7048 	.vop_read =		zfs_freebsd_read,
7049 	.vop_write =		zfs_freebsd_write,
7050 	.vop_remove =		zfs_freebsd_remove,
7051 	.vop_rename =		zfs_freebsd_rename,
7052 	.vop_pathconf =		zfs_freebsd_pathconf,
7053 	.vop_bmap =		zfs_freebsd_bmap,
7054 	.vop_fid =		zfs_freebsd_fid,
7055 	.vop_getextattr =	zfs_getextattr,
7056 	.vop_deleteextattr =	zfs_deleteextattr,
7057 	.vop_setextattr =	zfs_setextattr,
7058 	.vop_listextattr =	zfs_listextattr,
7059 	.vop_getacl =		zfs_freebsd_getacl,
7060 	.vop_setacl =		zfs_freebsd_setacl,
7061 	.vop_aclcheck =		zfs_freebsd_aclcheck,
7062 	.vop_getpages =		zfs_freebsd_getpages,
7063 	.vop_putpages =		zfs_freebsd_putpages,
7064 	.vop_vptocnp =		zfs_vptocnp,
7065 	.vop_lock1 =		vop_lock,
7066 	.vop_unlock =		vop_unlock,
7067 	.vop_islocked =		vop_islocked,
7068 #if __FreeBSD_version >= 1400043
7069 	.vop_add_writecount =	vop_stdadd_writecount_nomsync,
7070 #endif
7071 	.vop_copy_file_range =	zfs_freebsd_copy_file_range,
7072 };
7073 VFS_VOP_VECTOR_REGISTER(zfs_vnodeops);
7074 
7075 struct vop_vector zfs_fifoops = {
7076 	.vop_default =		&fifo_specops,
7077 	.vop_fsync =		zfs_freebsd_fsync,
7078 	.vop_fplookup_vexec =	zfs_freebsd_fplookup_vexec,
7079 	.vop_fplookup_symlink = zfs_freebsd_fplookup_symlink,
7080 	.vop_access =		zfs_freebsd_access,
7081 	.vop_getattr =		zfs_freebsd_getattr,
7082 	.vop_inactive =		zfs_freebsd_inactive,
7083 	.vop_read =		VOP_PANIC,
7084 	.vop_reclaim =		zfs_freebsd_reclaim,
7085 	.vop_setattr =		zfs_freebsd_setattr,
7086 	.vop_write =		VOP_PANIC,
7087 	.vop_pathconf = 	zfs_freebsd_pathconf,
7088 	.vop_fid =		zfs_freebsd_fid,
7089 	.vop_getacl =		zfs_freebsd_getacl,
7090 	.vop_setacl =		zfs_freebsd_setacl,
7091 	.vop_aclcheck =		zfs_freebsd_aclcheck,
7092 #if __FreeBSD_version >= 1400043
7093 	.vop_add_writecount =	vop_stdadd_writecount_nomsync,
7094 #endif
7095 };
7096 VFS_VOP_VECTOR_REGISTER(zfs_fifoops);
7097 
7098 /*
7099  * special share hidden files vnode operations template
7100  */
7101 struct vop_vector zfs_shareops = {
7102 	.vop_default =		&default_vnodeops,
7103 	.vop_fplookup_vexec =	VOP_EAGAIN,
7104 	.vop_fplookup_symlink =	VOP_EAGAIN,
7105 	.vop_access =		zfs_freebsd_access,
7106 	.vop_inactive =		zfs_freebsd_inactive,
7107 	.vop_reclaim =		zfs_freebsd_reclaim,
7108 	.vop_fid =		zfs_freebsd_fid,
7109 	.vop_pathconf =		zfs_freebsd_pathconf,
7110 #if __FreeBSD_version >= 1400043
7111 	.vop_add_writecount =	vop_stdadd_writecount_nomsync,
7112 #endif
7113 };
7114 VFS_VOP_VECTOR_REGISTER(zfs_shareops);
7115 
7116 ZFS_MODULE_PARAM(zfs, zfs_, xattr_compat, INT, ZMOD_RW,
7117 	"Use legacy ZFS xattr naming for writing new user namespace xattrs");
7118