1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or https://opensource.org/licenses/CDDL-1.0.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2012, 2018 by Delphix. All rights reserved.
25  * Copyright (c) 2015 by Chunwei Chen. All rights reserved.
26  * Copyright 2017 Nexenta Systems, Inc.
27  */
28 
29 /* Portions Copyright 2007 Jeremy Teo */
30 /* Portions Copyright 2010 Robert Milkowski */
31 
32 
33 #include <sys/types.h>
34 #include <sys/param.h>
35 #include <sys/time.h>
36 #include <sys/sysmacros.h>
37 #include <sys/vfs.h>
38 #include <sys/file.h>
39 #include <sys/stat.h>
40 #include <sys/kmem.h>
41 #include <sys/taskq.h>
42 #include <sys/uio.h>
43 #include <sys/vmsystm.h>
44 #include <sys/atomic.h>
45 #include <sys/pathname.h>
46 #include <sys/cmn_err.h>
47 #include <sys/errno.h>
48 #include <sys/zfs_dir.h>
49 #include <sys/zfs_acl.h>
50 #include <sys/zfs_ioctl.h>
51 #include <sys/fs/zfs.h>
52 #include <sys/dmu.h>
53 #include <sys/dmu_objset.h>
54 #include <sys/spa.h>
55 #include <sys/txg.h>
56 #include <sys/dbuf.h>
57 #include <sys/zap.h>
58 #include <sys/sa.h>
59 #include <sys/policy.h>
60 #include <sys/sunddi.h>
61 #include <sys/sid.h>
62 #include <sys/zfs_ctldir.h>
63 #include <sys/zfs_fuid.h>
64 #include <sys/zfs_quota.h>
65 #include <sys/zfs_sa.h>
66 #include <sys/zfs_vnops.h>
67 #include <sys/zfs_rlock.h>
68 #include <sys/cred.h>
69 #include <sys/zpl.h>
70 #include <sys/zil.h>
71 #include <sys/sa_impl.h>
72 
73 /*
74  * Programming rules.
75  *
76  * Each vnode op performs some logical unit of work.  To do this, the ZPL must
77  * properly lock its in-core state, create a DMU transaction, do the work,
78  * record this work in the intent log (ZIL), commit the DMU transaction,
79  * and wait for the intent log to commit if it is a synchronous operation.
80  * Moreover, the vnode ops must work in both normal and log replay context.
81  * The ordering of events is important to avoid deadlocks and references
82  * to freed memory.  The example below illustrates the following Big Rules:
83  *
84  *  (1) A check must be made in each zfs thread for a mounted file system.
85  *	This is done avoiding races using zfs_enter(zfsvfs).
86  *      A zfs_exit(zfsvfs) is needed before all returns.  Any znodes
87  *      must be checked with zfs_verify_zp(zp).  Both of these macros
88  *      can return EIO from the calling function.
89  *
90  *  (2) zrele() should always be the last thing except for zil_commit() (if
91  *	necessary) and zfs_exit(). This is for 3 reasons: First, if it's the
92  *	last reference, the vnode/znode can be freed, so the zp may point to
93  *	freed memory.  Second, the last reference will call zfs_zinactive(),
94  *	which may induce a lot of work -- pushing cached pages (which acquires
95  *	range locks) and syncing out cached atime changes.  Third,
96  *	zfs_zinactive() may require a new tx, which could deadlock the system
97  *	if you were already holding one. This deadlock occurs because the tx
98  *	currently being operated on prevents a txg from syncing, which
99  *	prevents the new tx from progressing, resulting in a deadlock.  If you
100  *	must call zrele() within a tx, use zfs_zrele_async(). Note that iput()
101  *	is a synonym for zrele().
102  *
103  *  (3)	All range locks must be grabbed before calling dmu_tx_assign(),
104  *	as they can span dmu_tx_assign() calls.
105  *
106  *  (4) If ZPL locks are held, pass TXG_NOWAIT as the second argument to
107  *      dmu_tx_assign().  This is critical because we don't want to block
108  *      while holding locks.
109  *
110  *	If no ZPL locks are held (aside from zfs_enter()), use TXG_WAIT.  This
111  *	reduces lock contention and CPU usage when we must wait (note that if
112  *	throughput is constrained by the storage, nearly every transaction
113  *	must wait).
114  *
115  *      Note, in particular, that if a lock is sometimes acquired before
116  *      the tx assigns, and sometimes after (e.g. z_lock), then failing
117  *      to use a non-blocking assign can deadlock the system.  The scenario:
118  *
119  *	Thread A has grabbed a lock before calling dmu_tx_assign().
120  *	Thread B is in an already-assigned tx, and blocks for this lock.
121  *	Thread A calls dmu_tx_assign(TXG_WAIT) and blocks in txg_wait_open()
122  *	forever, because the previous txg can't quiesce until B's tx commits.
123  *
124  *	If dmu_tx_assign() returns ERESTART and zfsvfs->z_assign is TXG_NOWAIT,
125  *	then drop all locks, call dmu_tx_wait(), and try again.  On subsequent
126  *	calls to dmu_tx_assign(), pass TXG_NOTHROTTLE in addition to TXG_NOWAIT,
127  *	to indicate that this operation has already called dmu_tx_wait().
128  *	This will ensure that we don't retry forever, waiting a short bit
129  *	each time.
130  *
131  *  (5)	If the operation succeeded, generate the intent log entry for it
132  *	before dropping locks.  This ensures that the ordering of events
133  *	in the intent log matches the order in which they actually occurred.
134  *	During ZIL replay the zfs_log_* functions will update the sequence
135  *	number to indicate the zil transaction has replayed.
136  *
137  *  (6)	At the end of each vnode op, the DMU tx must always commit,
138  *	regardless of whether there were any errors.
139  *
140  *  (7)	After dropping all locks, invoke zil_commit(zilog, foid)
141  *	to ensure that synchronous semantics are provided when necessary.
142  *
143  * In general, this is how things should be ordered in each vnode op:
144  *
145  *	zfs_enter(zfsvfs);		// exit if unmounted
146  * top:
147  *	zfs_dirent_lock(&dl, ...)	// lock directory entry (may igrab())
148  *	rw_enter(...);			// grab any other locks you need
149  *	tx = dmu_tx_create(...);	// get DMU tx
150  *	dmu_tx_hold_*();		// hold each object you might modify
151  *	error = dmu_tx_assign(tx, (waited ? TXG_NOTHROTTLE : 0) | TXG_NOWAIT);
152  *	if (error) {
153  *		rw_exit(...);		// drop locks
154  *		zfs_dirent_unlock(dl);	// unlock directory entry
155  *		zrele(...);		// release held znodes
156  *		if (error == ERESTART) {
157  *			waited = B_TRUE;
158  *			dmu_tx_wait(tx);
159  *			dmu_tx_abort(tx);
160  *			goto top;
161  *		}
162  *		dmu_tx_abort(tx);	// abort DMU tx
163  *		zfs_exit(zfsvfs);	// finished in zfs
164  *		return (error);		// really out of space
165  *	}
166  *	error = do_real_work();		// do whatever this VOP does
167  *	if (error == 0)
168  *		zfs_log_*(...);		// on success, make ZIL entry
169  *	dmu_tx_commit(tx);		// commit DMU tx -- error or not
170  *	rw_exit(...);			// drop locks
171  *	zfs_dirent_unlock(dl);		// unlock directory entry
172  *	zrele(...);			// release held znodes
173  *	zil_commit(zilog, foid);	// synchronous when necessary
174  *	zfs_exit(zfsvfs);		// finished in zfs
175  *	return (error);			// done, report error
176  */
177 int
178 zfs_open(struct inode *ip, int mode, int flag, cred_t *cr)
179 {
180 	(void) cr;
181 	znode_t	*zp = ITOZ(ip);
182 	zfsvfs_t *zfsvfs = ITOZSB(ip);
183 	int error;
184 
185 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
186 		return (error);
187 
188 	/* Honor ZFS_APPENDONLY file attribute */
189 	if ((mode & FMODE_WRITE) && (zp->z_pflags & ZFS_APPENDONLY) &&
190 	    ((flag & O_APPEND) == 0)) {
191 		zfs_exit(zfsvfs, FTAG);
192 		return (SET_ERROR(EPERM));
193 	}
194 
195 	/* Keep a count of the synchronous opens in the znode */
196 	if (flag & O_SYNC)
197 		atomic_inc_32(&zp->z_sync_cnt);
198 
199 	zfs_exit(zfsvfs, FTAG);
200 	return (0);
201 }
202 
203 int
204 zfs_close(struct inode *ip, int flag, cred_t *cr)
205 {
206 	(void) cr;
207 	znode_t	*zp = ITOZ(ip);
208 	zfsvfs_t *zfsvfs = ITOZSB(ip);
209 	int error;
210 
211 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
212 		return (error);
213 
214 	/* Decrement the synchronous opens in the znode */
215 	if (flag & O_SYNC)
216 		atomic_dec_32(&zp->z_sync_cnt);
217 
218 	zfs_exit(zfsvfs, FTAG);
219 	return (0);
220 }
221 
222 #if defined(_KERNEL)
223 
224 static int zfs_fillpage(struct inode *ip, struct page *pp);
225 
226 /*
227  * When a file is memory mapped, we must keep the IO data synchronized
228  * between the DMU cache and the memory mapped pages.  Update all mapped
229  * pages with the contents of the coresponding dmu buffer.
230  */
231 void
232 update_pages(znode_t *zp, int64_t start, int len, objset_t *os)
233 {
234 	struct address_space *mp = ZTOI(zp)->i_mapping;
235 	int64_t off = start & (PAGE_SIZE - 1);
236 
237 	for (start &= PAGE_MASK; len > 0; start += PAGE_SIZE) {
238 		uint64_t nbytes = MIN(PAGE_SIZE - off, len);
239 
240 		struct page *pp = find_lock_page(mp, start >> PAGE_SHIFT);
241 		if (pp) {
242 			if (mapping_writably_mapped(mp))
243 				flush_dcache_page(pp);
244 
245 			void *pb = kmap(pp);
246 			int error = dmu_read(os, zp->z_id, start + off,
247 			    nbytes, pb + off, DMU_READ_PREFETCH);
248 			kunmap(pp);
249 
250 			if (error) {
251 				SetPageError(pp);
252 				ClearPageUptodate(pp);
253 			} else {
254 				ClearPageError(pp);
255 				SetPageUptodate(pp);
256 
257 				if (mapping_writably_mapped(mp))
258 					flush_dcache_page(pp);
259 
260 				mark_page_accessed(pp);
261 			}
262 
263 			unlock_page(pp);
264 			put_page(pp);
265 		}
266 
267 		len -= nbytes;
268 		off = 0;
269 	}
270 }
271 
272 /*
273  * When a file is memory mapped, we must keep the I/O data synchronized
274  * between the DMU cache and the memory mapped pages.  Preferentially read
275  * from memory mapped pages, otherwise fallback to reading through the dmu.
276  */
277 int
278 mappedread(znode_t *zp, int nbytes, zfs_uio_t *uio)
279 {
280 	struct inode *ip = ZTOI(zp);
281 	struct address_space *mp = ip->i_mapping;
282 	int64_t start = uio->uio_loffset;
283 	int64_t off = start & (PAGE_SIZE - 1);
284 	int len = nbytes;
285 	int error = 0;
286 
287 	for (start &= PAGE_MASK; len > 0; start += PAGE_SIZE) {
288 		uint64_t bytes = MIN(PAGE_SIZE - off, len);
289 
290 		struct page *pp = find_lock_page(mp, start >> PAGE_SHIFT);
291 		if (pp) {
292 			/*
293 			 * If filemap_fault() retries there exists a window
294 			 * where the page will be unlocked and not up to date.
295 			 * In this case we must try and fill the page.
296 			 */
297 			if (unlikely(!PageUptodate(pp))) {
298 				error = zfs_fillpage(ip, pp);
299 				if (error) {
300 					unlock_page(pp);
301 					put_page(pp);
302 					return (error);
303 				}
304 			}
305 
306 			ASSERT(PageUptodate(pp) || PageDirty(pp));
307 
308 			unlock_page(pp);
309 
310 			void *pb = kmap(pp);
311 			error = zfs_uiomove(pb + off, bytes, UIO_READ, uio);
312 			kunmap(pp);
313 
314 			if (mapping_writably_mapped(mp))
315 				flush_dcache_page(pp);
316 
317 			mark_page_accessed(pp);
318 			put_page(pp);
319 		} else {
320 			error = dmu_read_uio_dbuf(sa_get_db(zp->z_sa_hdl),
321 			    uio, bytes);
322 		}
323 
324 		len -= bytes;
325 		off = 0;
326 
327 		if (error)
328 			break;
329 	}
330 
331 	return (error);
332 }
333 #endif /* _KERNEL */
334 
335 static unsigned long zfs_delete_blocks = DMU_MAX_DELETEBLKCNT;
336 
337 /*
338  * Write the bytes to a file.
339  *
340  *	IN:	zp	- znode of file to be written to
341  *		data	- bytes to write
342  *		len	- number of bytes to write
343  *		pos	- offset to start writing at
344  *
345  *	OUT:	resid	- remaining bytes to write
346  *
347  *	RETURN:	0 if success
348  *		positive error code if failure.  EIO is	returned
349  *		for a short write when residp isn't provided.
350  *
351  * Timestamps:
352  *	zp - ctime|mtime updated if byte count > 0
353  */
354 int
355 zfs_write_simple(znode_t *zp, const void *data, size_t len,
356     loff_t pos, size_t *residp)
357 {
358 	fstrans_cookie_t cookie;
359 	int error;
360 
361 	struct iovec iov;
362 	iov.iov_base = (void *)data;
363 	iov.iov_len = len;
364 
365 	zfs_uio_t uio;
366 	zfs_uio_iovec_init(&uio, &iov, 1, pos, UIO_SYSSPACE, len, 0);
367 
368 	cookie = spl_fstrans_mark();
369 	error = zfs_write(zp, &uio, 0, kcred);
370 	spl_fstrans_unmark(cookie);
371 
372 	if (error == 0) {
373 		if (residp != NULL)
374 			*residp = zfs_uio_resid(&uio);
375 		else if (zfs_uio_resid(&uio) != 0)
376 			error = SET_ERROR(EIO);
377 	}
378 
379 	return (error);
380 }
381 
382 static void
383 zfs_rele_async_task(void *arg)
384 {
385 	iput(arg);
386 }
387 
388 void
389 zfs_zrele_async(znode_t *zp)
390 {
391 	struct inode *ip = ZTOI(zp);
392 	objset_t *os = ITOZSB(ip)->z_os;
393 
394 	ASSERT(atomic_read(&ip->i_count) > 0);
395 	ASSERT(os != NULL);
396 
397 	/*
398 	 * If decrementing the count would put us at 0, we can't do it inline
399 	 * here, because that would be synchronous. Instead, dispatch an iput
400 	 * to run later.
401 	 *
402 	 * For more information on the dangers of a synchronous iput, see the
403 	 * header comment of this file.
404 	 */
405 	if (!atomic_add_unless(&ip->i_count, -1, 1)) {
406 		VERIFY(taskq_dispatch(dsl_pool_zrele_taskq(dmu_objset_pool(os)),
407 		    zfs_rele_async_task, ip, TQ_SLEEP) != TASKQID_INVALID);
408 	}
409 }
410 
411 
412 /*
413  * Lookup an entry in a directory, or an extended attribute directory.
414  * If it exists, return a held inode reference for it.
415  *
416  *	IN:	zdp	- znode of directory to search.
417  *		nm	- name of entry to lookup.
418  *		flags	- LOOKUP_XATTR set if looking for an attribute.
419  *		cr	- credentials of caller.
420  *		direntflags - directory lookup flags
421  *		realpnp - returned pathname.
422  *
423  *	OUT:	zpp	- znode of located entry, NULL if not found.
424  *
425  *	RETURN:	0 on success, error code on failure.
426  *
427  * Timestamps:
428  *	NA
429  */
430 int
431 zfs_lookup(znode_t *zdp, char *nm, znode_t **zpp, int flags, cred_t *cr,
432     int *direntflags, pathname_t *realpnp)
433 {
434 	zfsvfs_t *zfsvfs = ZTOZSB(zdp);
435 	int error = 0;
436 
437 	/*
438 	 * Fast path lookup, however we must skip DNLC lookup
439 	 * for case folding or normalizing lookups because the
440 	 * DNLC code only stores the passed in name.  This means
441 	 * creating 'a' and removing 'A' on a case insensitive
442 	 * file system would work, but DNLC still thinks 'a'
443 	 * exists and won't let you create it again on the next
444 	 * pass through fast path.
445 	 */
446 	if (!(flags & (LOOKUP_XATTR | FIGNORECASE))) {
447 
448 		if (!S_ISDIR(ZTOI(zdp)->i_mode)) {
449 			return (SET_ERROR(ENOTDIR));
450 		} else if (zdp->z_sa_hdl == NULL) {
451 			return (SET_ERROR(EIO));
452 		}
453 
454 		if (nm[0] == 0 || (nm[0] == '.' && nm[1] == '\0')) {
455 			error = zfs_fastaccesschk_execute(zdp, cr);
456 			if (!error) {
457 				*zpp = zdp;
458 				zhold(*zpp);
459 				return (0);
460 			}
461 			return (error);
462 		}
463 	}
464 
465 	if ((error = zfs_enter_verify_zp(zfsvfs, zdp, FTAG)) != 0)
466 		return (error);
467 
468 	*zpp = NULL;
469 
470 	if (flags & LOOKUP_XATTR) {
471 		/*
472 		 * We don't allow recursive attributes..
473 		 * Maybe someday we will.
474 		 */
475 		if (zdp->z_pflags & ZFS_XATTR) {
476 			zfs_exit(zfsvfs, FTAG);
477 			return (SET_ERROR(EINVAL));
478 		}
479 
480 		if ((error = zfs_get_xattrdir(zdp, zpp, cr, flags))) {
481 			zfs_exit(zfsvfs, FTAG);
482 			return (error);
483 		}
484 
485 		/*
486 		 * Do we have permission to get into attribute directory?
487 		 */
488 
489 		if ((error = zfs_zaccess(*zpp, ACE_EXECUTE, 0,
490 		    B_TRUE, cr, kcred->user_ns))) {
491 			zrele(*zpp);
492 			*zpp = NULL;
493 		}
494 
495 		zfs_exit(zfsvfs, FTAG);
496 		return (error);
497 	}
498 
499 	if (!S_ISDIR(ZTOI(zdp)->i_mode)) {
500 		zfs_exit(zfsvfs, FTAG);
501 		return (SET_ERROR(ENOTDIR));
502 	}
503 
504 	/*
505 	 * Check accessibility of directory.
506 	 */
507 
508 	if ((error = zfs_zaccess(zdp, ACE_EXECUTE, 0, B_FALSE, cr,
509 	    kcred->user_ns))) {
510 		zfs_exit(zfsvfs, FTAG);
511 		return (error);
512 	}
513 
514 	if (zfsvfs->z_utf8 && u8_validate(nm, strlen(nm),
515 	    NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
516 		zfs_exit(zfsvfs, FTAG);
517 		return (SET_ERROR(EILSEQ));
518 	}
519 
520 	error = zfs_dirlook(zdp, nm, zpp, flags, direntflags, realpnp);
521 	if ((error == 0) && (*zpp))
522 		zfs_znode_update_vfs(*zpp);
523 
524 	zfs_exit(zfsvfs, FTAG);
525 	return (error);
526 }
527 
528 /*
529  * Attempt to create a new entry in a directory.  If the entry
530  * already exists, truncate the file if permissible, else return
531  * an error.  Return the ip of the created or trunc'd file.
532  *
533  *	IN:	dzp	- znode of directory to put new file entry in.
534  *		name	- name of new file entry.
535  *		vap	- attributes of new file.
536  *		excl	- flag indicating exclusive or non-exclusive mode.
537  *		mode	- mode to open file with.
538  *		cr	- credentials of caller.
539  *		flag	- file flag.
540  *		vsecp	- ACL to be set
541  *		mnt_ns	- user namespace of the mount
542  *
543  *	OUT:	zpp	- znode of created or trunc'd entry.
544  *
545  *	RETURN:	0 on success, error code on failure.
546  *
547  * Timestamps:
548  *	dzp - ctime|mtime updated if new entry created
549  *	 zp - ctime|mtime always, atime if new
550  */
551 int
552 zfs_create(znode_t *dzp, char *name, vattr_t *vap, int excl,
553     int mode, znode_t **zpp, cred_t *cr, int flag, vsecattr_t *vsecp,
554     zuserns_t *mnt_ns)
555 {
556 	znode_t		*zp;
557 	zfsvfs_t	*zfsvfs = ZTOZSB(dzp);
558 	zilog_t		*zilog;
559 	objset_t	*os;
560 	zfs_dirlock_t	*dl;
561 	dmu_tx_t	*tx;
562 	int		error;
563 	uid_t		uid;
564 	gid_t		gid;
565 	zfs_acl_ids_t   acl_ids;
566 	boolean_t	fuid_dirtied;
567 	boolean_t	have_acl = B_FALSE;
568 	boolean_t	waited = B_FALSE;
569 	boolean_t	skip_acl = (flag & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
570 
571 	/*
572 	 * If we have an ephemeral id, ACL, or XVATTR then
573 	 * make sure file system is at proper version
574 	 */
575 
576 	gid = crgetgid(cr);
577 	uid = crgetuid(cr);
578 
579 	if (zfsvfs->z_use_fuids == B_FALSE &&
580 	    (vsecp || IS_EPHEMERAL(uid) || IS_EPHEMERAL(gid)))
581 		return (SET_ERROR(EINVAL));
582 
583 	if (name == NULL)
584 		return (SET_ERROR(EINVAL));
585 
586 	if ((error = zfs_enter_verify_zp(zfsvfs, dzp, FTAG)) != 0)
587 		return (error);
588 	os = zfsvfs->z_os;
589 	zilog = zfsvfs->z_log;
590 
591 	if (zfsvfs->z_utf8 && u8_validate(name, strlen(name),
592 	    NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
593 		zfs_exit(zfsvfs, FTAG);
594 		return (SET_ERROR(EILSEQ));
595 	}
596 
597 	if (vap->va_mask & ATTR_XVATTR) {
598 		if ((error = secpolicy_xvattr((xvattr_t *)vap,
599 		    crgetuid(cr), cr, vap->va_mode)) != 0) {
600 			zfs_exit(zfsvfs, FTAG);
601 			return (error);
602 		}
603 	}
604 
605 top:
606 	*zpp = NULL;
607 	if (*name == '\0') {
608 		/*
609 		 * Null component name refers to the directory itself.
610 		 */
611 		zhold(dzp);
612 		zp = dzp;
613 		dl = NULL;
614 		error = 0;
615 	} else {
616 		/* possible igrab(zp) */
617 		int zflg = 0;
618 
619 		if (flag & FIGNORECASE)
620 			zflg |= ZCILOOK;
621 
622 		error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg,
623 		    NULL, NULL);
624 		if (error) {
625 			if (have_acl)
626 				zfs_acl_ids_free(&acl_ids);
627 			if (strcmp(name, "..") == 0)
628 				error = SET_ERROR(EISDIR);
629 			zfs_exit(zfsvfs, FTAG);
630 			return (error);
631 		}
632 	}
633 
634 	if (zp == NULL) {
635 		uint64_t txtype;
636 		uint64_t projid = ZFS_DEFAULT_PROJID;
637 
638 		/*
639 		 * Create a new file object and update the directory
640 		 * to reference it.
641 		 */
642 		if ((error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, skip_acl, cr,
643 		    mnt_ns))) {
644 			if (have_acl)
645 				zfs_acl_ids_free(&acl_ids);
646 			goto out;
647 		}
648 
649 		/*
650 		 * We only support the creation of regular files in
651 		 * extended attribute directories.
652 		 */
653 
654 		if ((dzp->z_pflags & ZFS_XATTR) && !S_ISREG(vap->va_mode)) {
655 			if (have_acl)
656 				zfs_acl_ids_free(&acl_ids);
657 			error = SET_ERROR(EINVAL);
658 			goto out;
659 		}
660 
661 		if (!have_acl && (error = zfs_acl_ids_create(dzp, 0, vap,
662 		    cr, vsecp, &acl_ids, mnt_ns)) != 0)
663 			goto out;
664 		have_acl = B_TRUE;
665 
666 		if (S_ISREG(vap->va_mode) || S_ISDIR(vap->va_mode))
667 			projid = zfs_inherit_projid(dzp);
668 		if (zfs_acl_ids_overquota(zfsvfs, &acl_ids, projid)) {
669 			zfs_acl_ids_free(&acl_ids);
670 			error = SET_ERROR(EDQUOT);
671 			goto out;
672 		}
673 
674 		tx = dmu_tx_create(os);
675 
676 		dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
677 		    ZFS_SA_BASE_ATTR_SIZE);
678 
679 		fuid_dirtied = zfsvfs->z_fuid_dirty;
680 		if (fuid_dirtied)
681 			zfs_fuid_txhold(zfsvfs, tx);
682 		dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
683 		dmu_tx_hold_sa(tx, dzp->z_sa_hdl, B_FALSE);
684 		if (!zfsvfs->z_use_sa &&
685 		    acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
686 			dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
687 			    0, acl_ids.z_aclp->z_acl_bytes);
688 		}
689 
690 		error = dmu_tx_assign(tx,
691 		    (waited ? TXG_NOTHROTTLE : 0) | TXG_NOWAIT);
692 		if (error) {
693 			zfs_dirent_unlock(dl);
694 			if (error == ERESTART) {
695 				waited = B_TRUE;
696 				dmu_tx_wait(tx);
697 				dmu_tx_abort(tx);
698 				goto top;
699 			}
700 			zfs_acl_ids_free(&acl_ids);
701 			dmu_tx_abort(tx);
702 			zfs_exit(zfsvfs, FTAG);
703 			return (error);
704 		}
705 		zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
706 
707 		error = zfs_link_create(dl, zp, tx, ZNEW);
708 		if (error != 0) {
709 			/*
710 			 * Since, we failed to add the directory entry for it,
711 			 * delete the newly created dnode.
712 			 */
713 			zfs_znode_delete(zp, tx);
714 			remove_inode_hash(ZTOI(zp));
715 			zfs_acl_ids_free(&acl_ids);
716 			dmu_tx_commit(tx);
717 			goto out;
718 		}
719 
720 		if (fuid_dirtied)
721 			zfs_fuid_sync(zfsvfs, tx);
722 
723 		txtype = zfs_log_create_txtype(Z_FILE, vsecp, vap);
724 		if (flag & FIGNORECASE)
725 			txtype |= TX_CI;
726 		zfs_log_create(zilog, tx, txtype, dzp, zp, name,
727 		    vsecp, acl_ids.z_fuidp, vap);
728 		zfs_acl_ids_free(&acl_ids);
729 		dmu_tx_commit(tx);
730 	} else {
731 		int aflags = (flag & O_APPEND) ? V_APPEND : 0;
732 
733 		if (have_acl)
734 			zfs_acl_ids_free(&acl_ids);
735 
736 		/*
737 		 * A directory entry already exists for this name.
738 		 */
739 		/*
740 		 * Can't truncate an existing file if in exclusive mode.
741 		 */
742 		if (excl) {
743 			error = SET_ERROR(EEXIST);
744 			goto out;
745 		}
746 		/*
747 		 * Can't open a directory for writing.
748 		 */
749 		if (S_ISDIR(ZTOI(zp)->i_mode)) {
750 			error = SET_ERROR(EISDIR);
751 			goto out;
752 		}
753 		/*
754 		 * Verify requested access to file.
755 		 */
756 		if (mode && (error = zfs_zaccess_rwx(zp, mode, aflags, cr,
757 		    mnt_ns))) {
758 			goto out;
759 		}
760 
761 		mutex_enter(&dzp->z_lock);
762 		dzp->z_seq++;
763 		mutex_exit(&dzp->z_lock);
764 
765 		/*
766 		 * Truncate regular files if requested.
767 		 */
768 		if (S_ISREG(ZTOI(zp)->i_mode) &&
769 		    (vap->va_mask & ATTR_SIZE) && (vap->va_size == 0)) {
770 			/* we can't hold any locks when calling zfs_freesp() */
771 			if (dl) {
772 				zfs_dirent_unlock(dl);
773 				dl = NULL;
774 			}
775 			error = zfs_freesp(zp, 0, 0, mode, TRUE);
776 		}
777 	}
778 out:
779 
780 	if (dl)
781 		zfs_dirent_unlock(dl);
782 
783 	if (error) {
784 		if (zp)
785 			zrele(zp);
786 	} else {
787 		zfs_znode_update_vfs(dzp);
788 		zfs_znode_update_vfs(zp);
789 		*zpp = zp;
790 	}
791 
792 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
793 		zil_commit(zilog, 0);
794 
795 	zfs_exit(zfsvfs, FTAG);
796 	return (error);
797 }
798 
799 int
800 zfs_tmpfile(struct inode *dip, vattr_t *vap, int excl,
801     int mode, struct inode **ipp, cred_t *cr, int flag, vsecattr_t *vsecp,
802     zuserns_t *mnt_ns)
803 {
804 	(void) excl, (void) mode, (void) flag;
805 	znode_t		*zp = NULL, *dzp = ITOZ(dip);
806 	zfsvfs_t	*zfsvfs = ITOZSB(dip);
807 	objset_t	*os;
808 	dmu_tx_t	*tx;
809 	int		error;
810 	uid_t		uid;
811 	gid_t		gid;
812 	zfs_acl_ids_t   acl_ids;
813 	uint64_t	projid = ZFS_DEFAULT_PROJID;
814 	boolean_t	fuid_dirtied;
815 	boolean_t	have_acl = B_FALSE;
816 	boolean_t	waited = B_FALSE;
817 
818 	/*
819 	 * If we have an ephemeral id, ACL, or XVATTR then
820 	 * make sure file system is at proper version
821 	 */
822 
823 	gid = crgetgid(cr);
824 	uid = crgetuid(cr);
825 
826 	if (zfsvfs->z_use_fuids == B_FALSE &&
827 	    (vsecp || IS_EPHEMERAL(uid) || IS_EPHEMERAL(gid)))
828 		return (SET_ERROR(EINVAL));
829 
830 	if ((error = zfs_enter_verify_zp(zfsvfs, dzp, FTAG)) != 0)
831 		return (error);
832 	os = zfsvfs->z_os;
833 
834 	if (vap->va_mask & ATTR_XVATTR) {
835 		if ((error = secpolicy_xvattr((xvattr_t *)vap,
836 		    crgetuid(cr), cr, vap->va_mode)) != 0) {
837 			zfs_exit(zfsvfs, FTAG);
838 			return (error);
839 		}
840 	}
841 
842 top:
843 	*ipp = NULL;
844 
845 	/*
846 	 * Create a new file object and update the directory
847 	 * to reference it.
848 	 */
849 	if ((error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr, mnt_ns))) {
850 		if (have_acl)
851 			zfs_acl_ids_free(&acl_ids);
852 		goto out;
853 	}
854 
855 	if (!have_acl && (error = zfs_acl_ids_create(dzp, 0, vap,
856 	    cr, vsecp, &acl_ids, mnt_ns)) != 0)
857 		goto out;
858 	have_acl = B_TRUE;
859 
860 	if (S_ISREG(vap->va_mode) || S_ISDIR(vap->va_mode))
861 		projid = zfs_inherit_projid(dzp);
862 	if (zfs_acl_ids_overquota(zfsvfs, &acl_ids, projid)) {
863 		zfs_acl_ids_free(&acl_ids);
864 		error = SET_ERROR(EDQUOT);
865 		goto out;
866 	}
867 
868 	tx = dmu_tx_create(os);
869 
870 	dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
871 	    ZFS_SA_BASE_ATTR_SIZE);
872 	dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
873 
874 	fuid_dirtied = zfsvfs->z_fuid_dirty;
875 	if (fuid_dirtied)
876 		zfs_fuid_txhold(zfsvfs, tx);
877 	if (!zfsvfs->z_use_sa &&
878 	    acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
879 		dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
880 		    0, acl_ids.z_aclp->z_acl_bytes);
881 	}
882 	error = dmu_tx_assign(tx, (waited ? TXG_NOTHROTTLE : 0) | TXG_NOWAIT);
883 	if (error) {
884 		if (error == ERESTART) {
885 			waited = B_TRUE;
886 			dmu_tx_wait(tx);
887 			dmu_tx_abort(tx);
888 			goto top;
889 		}
890 		zfs_acl_ids_free(&acl_ids);
891 		dmu_tx_abort(tx);
892 		zfs_exit(zfsvfs, FTAG);
893 		return (error);
894 	}
895 	zfs_mknode(dzp, vap, tx, cr, IS_TMPFILE, &zp, &acl_ids);
896 
897 	if (fuid_dirtied)
898 		zfs_fuid_sync(zfsvfs, tx);
899 
900 	/* Add to unlinked set */
901 	zp->z_unlinked = B_TRUE;
902 	zfs_unlinked_add(zp, tx);
903 	zfs_acl_ids_free(&acl_ids);
904 	dmu_tx_commit(tx);
905 out:
906 
907 	if (error) {
908 		if (zp)
909 			zrele(zp);
910 	} else {
911 		zfs_znode_update_vfs(dzp);
912 		zfs_znode_update_vfs(zp);
913 		*ipp = ZTOI(zp);
914 	}
915 
916 	zfs_exit(zfsvfs, FTAG);
917 	return (error);
918 }
919 
920 /*
921  * Remove an entry from a directory.
922  *
923  *	IN:	dzp	- znode of directory to remove entry from.
924  *		name	- name of entry to remove.
925  *		cr	- credentials of caller.
926  *		flags	- case flags.
927  *
928  *	RETURN:	0 if success
929  *		error code if failure
930  *
931  * Timestamps:
932  *	dzp - ctime|mtime
933  *	 ip - ctime (if nlink > 0)
934  */
935 
936 static uint64_t null_xattr = 0;
937 
938 int
939 zfs_remove(znode_t *dzp, char *name, cred_t *cr, int flags)
940 {
941 	znode_t		*zp;
942 	znode_t		*xzp;
943 	zfsvfs_t	*zfsvfs = ZTOZSB(dzp);
944 	zilog_t		*zilog;
945 	uint64_t	acl_obj, xattr_obj;
946 	uint64_t	xattr_obj_unlinked = 0;
947 	uint64_t	obj = 0;
948 	uint64_t	links;
949 	zfs_dirlock_t	*dl;
950 	dmu_tx_t	*tx;
951 	boolean_t	may_delete_now, delete_now = FALSE;
952 	boolean_t	unlinked, toobig = FALSE;
953 	uint64_t	txtype;
954 	pathname_t	*realnmp = NULL;
955 	pathname_t	realnm;
956 	int		error;
957 	int		zflg = ZEXISTS;
958 	boolean_t	waited = B_FALSE;
959 
960 	if (name == NULL)
961 		return (SET_ERROR(EINVAL));
962 
963 	if ((error = zfs_enter_verify_zp(zfsvfs, dzp, FTAG)) != 0)
964 		return (error);
965 	zilog = zfsvfs->z_log;
966 
967 	if (flags & FIGNORECASE) {
968 		zflg |= ZCILOOK;
969 		pn_alloc(&realnm);
970 		realnmp = &realnm;
971 	}
972 
973 top:
974 	xattr_obj = 0;
975 	xzp = NULL;
976 	/*
977 	 * Attempt to lock directory; fail if entry doesn't exist.
978 	 */
979 	if ((error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg,
980 	    NULL, realnmp))) {
981 		if (realnmp)
982 			pn_free(realnmp);
983 		zfs_exit(zfsvfs, FTAG);
984 		return (error);
985 	}
986 
987 	if ((error = zfs_zaccess_delete(dzp, zp, cr, kcred->user_ns))) {
988 		goto out;
989 	}
990 
991 	/*
992 	 * Need to use rmdir for removing directories.
993 	 */
994 	if (S_ISDIR(ZTOI(zp)->i_mode)) {
995 		error = SET_ERROR(EPERM);
996 		goto out;
997 	}
998 
999 	mutex_enter(&zp->z_lock);
1000 	may_delete_now = atomic_read(&ZTOI(zp)->i_count) == 1 &&
1001 	    !zn_has_cached_data(zp, 0, LLONG_MAX);
1002 	mutex_exit(&zp->z_lock);
1003 
1004 	/*
1005 	 * We may delete the znode now, or we may put it in the unlinked set;
1006 	 * it depends on whether we're the last link, and on whether there are
1007 	 * other holds on the inode.  So we dmu_tx_hold() the right things to
1008 	 * allow for either case.
1009 	 */
1010 	obj = zp->z_id;
1011 	tx = dmu_tx_create(zfsvfs->z_os);
1012 	dmu_tx_hold_zap(tx, dzp->z_id, FALSE, name);
1013 	dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
1014 	zfs_sa_upgrade_txholds(tx, zp);
1015 	zfs_sa_upgrade_txholds(tx, dzp);
1016 	if (may_delete_now) {
1017 		toobig = zp->z_size > zp->z_blksz * zfs_delete_blocks;
1018 		/* if the file is too big, only hold_free a token amount */
1019 		dmu_tx_hold_free(tx, zp->z_id, 0,
1020 		    (toobig ? DMU_MAX_ACCESS : DMU_OBJECT_END));
1021 	}
1022 
1023 	/* are there any extended attributes? */
1024 	error = sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
1025 	    &xattr_obj, sizeof (xattr_obj));
1026 	if (error == 0 && xattr_obj) {
1027 		error = zfs_zget(zfsvfs, xattr_obj, &xzp);
1028 		ASSERT0(error);
1029 		dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
1030 		dmu_tx_hold_sa(tx, xzp->z_sa_hdl, B_FALSE);
1031 	}
1032 
1033 	mutex_enter(&zp->z_lock);
1034 	if ((acl_obj = zfs_external_acl(zp)) != 0 && may_delete_now)
1035 		dmu_tx_hold_free(tx, acl_obj, 0, DMU_OBJECT_END);
1036 	mutex_exit(&zp->z_lock);
1037 
1038 	/* charge as an update -- would be nice not to charge at all */
1039 	dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
1040 
1041 	/*
1042 	 * Mark this transaction as typically resulting in a net free of space
1043 	 */
1044 	dmu_tx_mark_netfree(tx);
1045 
1046 	error = dmu_tx_assign(tx, (waited ? TXG_NOTHROTTLE : 0) | TXG_NOWAIT);
1047 	if (error) {
1048 		zfs_dirent_unlock(dl);
1049 		if (error == ERESTART) {
1050 			waited = B_TRUE;
1051 			dmu_tx_wait(tx);
1052 			dmu_tx_abort(tx);
1053 			zrele(zp);
1054 			if (xzp)
1055 				zrele(xzp);
1056 			goto top;
1057 		}
1058 		if (realnmp)
1059 			pn_free(realnmp);
1060 		dmu_tx_abort(tx);
1061 		zrele(zp);
1062 		if (xzp)
1063 			zrele(xzp);
1064 		zfs_exit(zfsvfs, FTAG);
1065 		return (error);
1066 	}
1067 
1068 	/*
1069 	 * Remove the directory entry.
1070 	 */
1071 	error = zfs_link_destroy(dl, zp, tx, zflg, &unlinked);
1072 
1073 	if (error) {
1074 		dmu_tx_commit(tx);
1075 		goto out;
1076 	}
1077 
1078 	if (unlinked) {
1079 		/*
1080 		 * Hold z_lock so that we can make sure that the ACL obj
1081 		 * hasn't changed.  Could have been deleted due to
1082 		 * zfs_sa_upgrade().
1083 		 */
1084 		mutex_enter(&zp->z_lock);
1085 		(void) sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
1086 		    &xattr_obj_unlinked, sizeof (xattr_obj_unlinked));
1087 		delete_now = may_delete_now && !toobig &&
1088 		    atomic_read(&ZTOI(zp)->i_count) == 1 &&
1089 		    !zn_has_cached_data(zp, 0, LLONG_MAX) &&
1090 		    xattr_obj == xattr_obj_unlinked &&
1091 		    zfs_external_acl(zp) == acl_obj;
1092 		VERIFY_IMPLY(xattr_obj_unlinked, xzp);
1093 	}
1094 
1095 	if (delete_now) {
1096 		if (xattr_obj_unlinked) {
1097 			ASSERT3U(ZTOI(xzp)->i_nlink, ==, 2);
1098 			mutex_enter(&xzp->z_lock);
1099 			xzp->z_unlinked = B_TRUE;
1100 			clear_nlink(ZTOI(xzp));
1101 			links = 0;
1102 			error = sa_update(xzp->z_sa_hdl, SA_ZPL_LINKS(zfsvfs),
1103 			    &links, sizeof (links), tx);
1104 			ASSERT3U(error,  ==,  0);
1105 			mutex_exit(&xzp->z_lock);
1106 			zfs_unlinked_add(xzp, tx);
1107 
1108 			if (zp->z_is_sa)
1109 				error = sa_remove(zp->z_sa_hdl,
1110 				    SA_ZPL_XATTR(zfsvfs), tx);
1111 			else
1112 				error = sa_update(zp->z_sa_hdl,
1113 				    SA_ZPL_XATTR(zfsvfs), &null_xattr,
1114 				    sizeof (uint64_t), tx);
1115 			ASSERT0(error);
1116 		}
1117 		/*
1118 		 * Add to the unlinked set because a new reference could be
1119 		 * taken concurrently resulting in a deferred destruction.
1120 		 */
1121 		zfs_unlinked_add(zp, tx);
1122 		mutex_exit(&zp->z_lock);
1123 	} else if (unlinked) {
1124 		mutex_exit(&zp->z_lock);
1125 		zfs_unlinked_add(zp, tx);
1126 	}
1127 
1128 	txtype = TX_REMOVE;
1129 	if (flags & FIGNORECASE)
1130 		txtype |= TX_CI;
1131 	zfs_log_remove(zilog, tx, txtype, dzp, name, obj, unlinked);
1132 
1133 	dmu_tx_commit(tx);
1134 out:
1135 	if (realnmp)
1136 		pn_free(realnmp);
1137 
1138 	zfs_dirent_unlock(dl);
1139 	zfs_znode_update_vfs(dzp);
1140 	zfs_znode_update_vfs(zp);
1141 
1142 	if (delete_now)
1143 		zrele(zp);
1144 	else
1145 		zfs_zrele_async(zp);
1146 
1147 	if (xzp) {
1148 		zfs_znode_update_vfs(xzp);
1149 		zfs_zrele_async(xzp);
1150 	}
1151 
1152 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1153 		zil_commit(zilog, 0);
1154 
1155 	zfs_exit(zfsvfs, FTAG);
1156 	return (error);
1157 }
1158 
1159 /*
1160  * Create a new directory and insert it into dzp using the name
1161  * provided.  Return a pointer to the inserted directory.
1162  *
1163  *	IN:	dzp	- znode of directory to add subdir to.
1164  *		dirname	- name of new directory.
1165  *		vap	- attributes of new directory.
1166  *		cr	- credentials of caller.
1167  *		flags	- case flags.
1168  *		vsecp	- ACL to be set
1169  *		mnt_ns	- user namespace of the mount
1170  *
1171  *	OUT:	zpp	- znode of created directory.
1172  *
1173  *	RETURN:	0 if success
1174  *		error code if failure
1175  *
1176  * Timestamps:
1177  *	dzp - ctime|mtime updated
1178  *	zpp - ctime|mtime|atime updated
1179  */
1180 int
1181 zfs_mkdir(znode_t *dzp, char *dirname, vattr_t *vap, znode_t **zpp,
1182     cred_t *cr, int flags, vsecattr_t *vsecp, zuserns_t *mnt_ns)
1183 {
1184 	znode_t		*zp;
1185 	zfsvfs_t	*zfsvfs = ZTOZSB(dzp);
1186 	zilog_t		*zilog;
1187 	zfs_dirlock_t	*dl;
1188 	uint64_t	txtype;
1189 	dmu_tx_t	*tx;
1190 	int		error;
1191 	int		zf = ZNEW;
1192 	uid_t		uid;
1193 	gid_t		gid = crgetgid(cr);
1194 	zfs_acl_ids_t   acl_ids;
1195 	boolean_t	fuid_dirtied;
1196 	boolean_t	waited = B_FALSE;
1197 
1198 	ASSERT(S_ISDIR(vap->va_mode));
1199 
1200 	/*
1201 	 * If we have an ephemeral id, ACL, or XVATTR then
1202 	 * make sure file system is at proper version
1203 	 */
1204 
1205 	uid = crgetuid(cr);
1206 	if (zfsvfs->z_use_fuids == B_FALSE &&
1207 	    (vsecp || IS_EPHEMERAL(uid) || IS_EPHEMERAL(gid)))
1208 		return (SET_ERROR(EINVAL));
1209 
1210 	if (dirname == NULL)
1211 		return (SET_ERROR(EINVAL));
1212 
1213 	if ((error = zfs_enter_verify_zp(zfsvfs, dzp, FTAG)) != 0)
1214 		return (error);
1215 	zilog = zfsvfs->z_log;
1216 
1217 	if (dzp->z_pflags & ZFS_XATTR) {
1218 		zfs_exit(zfsvfs, FTAG);
1219 		return (SET_ERROR(EINVAL));
1220 	}
1221 
1222 	if (zfsvfs->z_utf8 && u8_validate(dirname,
1223 	    strlen(dirname), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
1224 		zfs_exit(zfsvfs, FTAG);
1225 		return (SET_ERROR(EILSEQ));
1226 	}
1227 	if (flags & FIGNORECASE)
1228 		zf |= ZCILOOK;
1229 
1230 	if (vap->va_mask & ATTR_XVATTR) {
1231 		if ((error = secpolicy_xvattr((xvattr_t *)vap,
1232 		    crgetuid(cr), cr, vap->va_mode)) != 0) {
1233 			zfs_exit(zfsvfs, FTAG);
1234 			return (error);
1235 		}
1236 	}
1237 
1238 	if ((error = zfs_acl_ids_create(dzp, 0, vap, cr,
1239 	    vsecp, &acl_ids, mnt_ns)) != 0) {
1240 		zfs_exit(zfsvfs, FTAG);
1241 		return (error);
1242 	}
1243 	/*
1244 	 * First make sure the new directory doesn't exist.
1245 	 *
1246 	 * Existence is checked first to make sure we don't return
1247 	 * EACCES instead of EEXIST which can cause some applications
1248 	 * to fail.
1249 	 */
1250 top:
1251 	*zpp = NULL;
1252 
1253 	if ((error = zfs_dirent_lock(&dl, dzp, dirname, &zp, zf,
1254 	    NULL, NULL))) {
1255 		zfs_acl_ids_free(&acl_ids);
1256 		zfs_exit(zfsvfs, FTAG);
1257 		return (error);
1258 	}
1259 
1260 	if ((error = zfs_zaccess(dzp, ACE_ADD_SUBDIRECTORY, 0, B_FALSE, cr,
1261 	    mnt_ns))) {
1262 		zfs_acl_ids_free(&acl_ids);
1263 		zfs_dirent_unlock(dl);
1264 		zfs_exit(zfsvfs, FTAG);
1265 		return (error);
1266 	}
1267 
1268 	if (zfs_acl_ids_overquota(zfsvfs, &acl_ids, zfs_inherit_projid(dzp))) {
1269 		zfs_acl_ids_free(&acl_ids);
1270 		zfs_dirent_unlock(dl);
1271 		zfs_exit(zfsvfs, FTAG);
1272 		return (SET_ERROR(EDQUOT));
1273 	}
1274 
1275 	/*
1276 	 * Add a new entry to the directory.
1277 	 */
1278 	tx = dmu_tx_create(zfsvfs->z_os);
1279 	dmu_tx_hold_zap(tx, dzp->z_id, TRUE, dirname);
1280 	dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, FALSE, NULL);
1281 	fuid_dirtied = zfsvfs->z_fuid_dirty;
1282 	if (fuid_dirtied)
1283 		zfs_fuid_txhold(zfsvfs, tx);
1284 	if (!zfsvfs->z_use_sa && acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
1285 		dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0,
1286 		    acl_ids.z_aclp->z_acl_bytes);
1287 	}
1288 
1289 	dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
1290 	    ZFS_SA_BASE_ATTR_SIZE);
1291 
1292 	error = dmu_tx_assign(tx, (waited ? TXG_NOTHROTTLE : 0) | TXG_NOWAIT);
1293 	if (error) {
1294 		zfs_dirent_unlock(dl);
1295 		if (error == ERESTART) {
1296 			waited = B_TRUE;
1297 			dmu_tx_wait(tx);
1298 			dmu_tx_abort(tx);
1299 			goto top;
1300 		}
1301 		zfs_acl_ids_free(&acl_ids);
1302 		dmu_tx_abort(tx);
1303 		zfs_exit(zfsvfs, FTAG);
1304 		return (error);
1305 	}
1306 
1307 	/*
1308 	 * Create new node.
1309 	 */
1310 	zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
1311 
1312 	/*
1313 	 * Now put new name in parent dir.
1314 	 */
1315 	error = zfs_link_create(dl, zp, tx, ZNEW);
1316 	if (error != 0) {
1317 		zfs_znode_delete(zp, tx);
1318 		remove_inode_hash(ZTOI(zp));
1319 		goto out;
1320 	}
1321 
1322 	if (fuid_dirtied)
1323 		zfs_fuid_sync(zfsvfs, tx);
1324 
1325 	*zpp = zp;
1326 
1327 	txtype = zfs_log_create_txtype(Z_DIR, vsecp, vap);
1328 	if (flags & FIGNORECASE)
1329 		txtype |= TX_CI;
1330 	zfs_log_create(zilog, tx, txtype, dzp, zp, dirname, vsecp,
1331 	    acl_ids.z_fuidp, vap);
1332 
1333 out:
1334 	zfs_acl_ids_free(&acl_ids);
1335 
1336 	dmu_tx_commit(tx);
1337 
1338 	zfs_dirent_unlock(dl);
1339 
1340 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1341 		zil_commit(zilog, 0);
1342 
1343 	if (error != 0) {
1344 		zrele(zp);
1345 	} else {
1346 		zfs_znode_update_vfs(dzp);
1347 		zfs_znode_update_vfs(zp);
1348 	}
1349 	zfs_exit(zfsvfs, FTAG);
1350 	return (error);
1351 }
1352 
1353 /*
1354  * Remove a directory subdir entry.  If the current working
1355  * directory is the same as the subdir to be removed, the
1356  * remove will fail.
1357  *
1358  *	IN:	dzp	- znode of directory to remove from.
1359  *		name	- name of directory to be removed.
1360  *		cwd	- inode of current working directory.
1361  *		cr	- credentials of caller.
1362  *		flags	- case flags
1363  *
1364  *	RETURN:	0 on success, error code on failure.
1365  *
1366  * Timestamps:
1367  *	dzp - ctime|mtime updated
1368  */
1369 int
1370 zfs_rmdir(znode_t *dzp, char *name, znode_t *cwd, cred_t *cr,
1371     int flags)
1372 {
1373 	znode_t		*zp;
1374 	zfsvfs_t	*zfsvfs = ZTOZSB(dzp);
1375 	zilog_t		*zilog;
1376 	zfs_dirlock_t	*dl;
1377 	dmu_tx_t	*tx;
1378 	int		error;
1379 	int		zflg = ZEXISTS;
1380 	boolean_t	waited = B_FALSE;
1381 
1382 	if (name == NULL)
1383 		return (SET_ERROR(EINVAL));
1384 
1385 	if ((error = zfs_enter_verify_zp(zfsvfs, dzp, FTAG)) != 0)
1386 		return (error);
1387 	zilog = zfsvfs->z_log;
1388 
1389 	if (flags & FIGNORECASE)
1390 		zflg |= ZCILOOK;
1391 top:
1392 	zp = NULL;
1393 
1394 	/*
1395 	 * Attempt to lock directory; fail if entry doesn't exist.
1396 	 */
1397 	if ((error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg,
1398 	    NULL, NULL))) {
1399 		zfs_exit(zfsvfs, FTAG);
1400 		return (error);
1401 	}
1402 
1403 	if ((error = zfs_zaccess_delete(dzp, zp, cr, kcred->user_ns))) {
1404 		goto out;
1405 	}
1406 
1407 	if (!S_ISDIR(ZTOI(zp)->i_mode)) {
1408 		error = SET_ERROR(ENOTDIR);
1409 		goto out;
1410 	}
1411 
1412 	if (zp == cwd) {
1413 		error = SET_ERROR(EINVAL);
1414 		goto out;
1415 	}
1416 
1417 	/*
1418 	 * Grab a lock on the directory to make sure that no one is
1419 	 * trying to add (or lookup) entries while we are removing it.
1420 	 */
1421 	rw_enter(&zp->z_name_lock, RW_WRITER);
1422 
1423 	/*
1424 	 * Grab a lock on the parent pointer to make sure we play well
1425 	 * with the treewalk and directory rename code.
1426 	 */
1427 	rw_enter(&zp->z_parent_lock, RW_WRITER);
1428 
1429 	tx = dmu_tx_create(zfsvfs->z_os);
1430 	dmu_tx_hold_zap(tx, dzp->z_id, FALSE, name);
1431 	dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
1432 	dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
1433 	zfs_sa_upgrade_txholds(tx, zp);
1434 	zfs_sa_upgrade_txholds(tx, dzp);
1435 	dmu_tx_mark_netfree(tx);
1436 	error = dmu_tx_assign(tx, (waited ? TXG_NOTHROTTLE : 0) | TXG_NOWAIT);
1437 	if (error) {
1438 		rw_exit(&zp->z_parent_lock);
1439 		rw_exit(&zp->z_name_lock);
1440 		zfs_dirent_unlock(dl);
1441 		if (error == ERESTART) {
1442 			waited = B_TRUE;
1443 			dmu_tx_wait(tx);
1444 			dmu_tx_abort(tx);
1445 			zrele(zp);
1446 			goto top;
1447 		}
1448 		dmu_tx_abort(tx);
1449 		zrele(zp);
1450 		zfs_exit(zfsvfs, FTAG);
1451 		return (error);
1452 	}
1453 
1454 	error = zfs_link_destroy(dl, zp, tx, zflg, NULL);
1455 
1456 	if (error == 0) {
1457 		uint64_t txtype = TX_RMDIR;
1458 		if (flags & FIGNORECASE)
1459 			txtype |= TX_CI;
1460 		zfs_log_remove(zilog, tx, txtype, dzp, name, ZFS_NO_OBJECT,
1461 		    B_FALSE);
1462 	}
1463 
1464 	dmu_tx_commit(tx);
1465 
1466 	rw_exit(&zp->z_parent_lock);
1467 	rw_exit(&zp->z_name_lock);
1468 out:
1469 	zfs_dirent_unlock(dl);
1470 
1471 	zfs_znode_update_vfs(dzp);
1472 	zfs_znode_update_vfs(zp);
1473 	zrele(zp);
1474 
1475 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1476 		zil_commit(zilog, 0);
1477 
1478 	zfs_exit(zfsvfs, FTAG);
1479 	return (error);
1480 }
1481 
1482 /*
1483  * Read directory entries from the given directory cursor position and emit
1484  * name and position for each entry.
1485  *
1486  *	IN:	ip	- inode of directory to read.
1487  *		ctx	- directory entry context.
1488  *		cr	- credentials of caller.
1489  *
1490  *	RETURN:	0 if success
1491  *		error code if failure
1492  *
1493  * Timestamps:
1494  *	ip - atime updated
1495  *
1496  * Note that the low 4 bits of the cookie returned by zap is always zero.
1497  * This allows us to use the low range for "special" directory entries:
1498  * We use 0 for '.', and 1 for '..'.  If this is the root of the filesystem,
1499  * we use the offset 2 for the '.zfs' directory.
1500  */
1501 int
1502 zfs_readdir(struct inode *ip, zpl_dir_context_t *ctx, cred_t *cr)
1503 {
1504 	(void) cr;
1505 	znode_t		*zp = ITOZ(ip);
1506 	zfsvfs_t	*zfsvfs = ITOZSB(ip);
1507 	objset_t	*os;
1508 	zap_cursor_t	zc;
1509 	zap_attribute_t	zap;
1510 	int		error;
1511 	uint8_t		prefetch;
1512 	uint8_t		type;
1513 	int		done = 0;
1514 	uint64_t	parent;
1515 	uint64_t	offset; /* must be unsigned; checks for < 1 */
1516 
1517 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
1518 		return (error);
1519 
1520 	if ((error = sa_lookup(zp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs),
1521 	    &parent, sizeof (parent))) != 0)
1522 		goto out;
1523 
1524 	/*
1525 	 * Quit if directory has been removed (posix)
1526 	 */
1527 	if (zp->z_unlinked)
1528 		goto out;
1529 
1530 	error = 0;
1531 	os = zfsvfs->z_os;
1532 	offset = ctx->pos;
1533 	prefetch = zp->z_zn_prefetch;
1534 
1535 	/*
1536 	 * Initialize the iterator cursor.
1537 	 */
1538 	if (offset <= 3) {
1539 		/*
1540 		 * Start iteration from the beginning of the directory.
1541 		 */
1542 		zap_cursor_init(&zc, os, zp->z_id);
1543 	} else {
1544 		/*
1545 		 * The offset is a serialized cursor.
1546 		 */
1547 		zap_cursor_init_serialized(&zc, os, zp->z_id, offset);
1548 	}
1549 
1550 	/*
1551 	 * Transform to file-system independent format
1552 	 */
1553 	while (!done) {
1554 		uint64_t objnum;
1555 		/*
1556 		 * Special case `.', `..', and `.zfs'.
1557 		 */
1558 		if (offset == 0) {
1559 			(void) strcpy(zap.za_name, ".");
1560 			zap.za_normalization_conflict = 0;
1561 			objnum = zp->z_id;
1562 			type = DT_DIR;
1563 		} else if (offset == 1) {
1564 			(void) strcpy(zap.za_name, "..");
1565 			zap.za_normalization_conflict = 0;
1566 			objnum = parent;
1567 			type = DT_DIR;
1568 		} else if (offset == 2 && zfs_show_ctldir(zp)) {
1569 			(void) strcpy(zap.za_name, ZFS_CTLDIR_NAME);
1570 			zap.za_normalization_conflict = 0;
1571 			objnum = ZFSCTL_INO_ROOT;
1572 			type = DT_DIR;
1573 		} else {
1574 			/*
1575 			 * Grab next entry.
1576 			 */
1577 			if ((error = zap_cursor_retrieve(&zc, &zap))) {
1578 				if (error == ENOENT)
1579 					break;
1580 				else
1581 					goto update;
1582 			}
1583 
1584 			/*
1585 			 * Allow multiple entries provided the first entry is
1586 			 * the object id.  Non-zpl consumers may safely make
1587 			 * use of the additional space.
1588 			 *
1589 			 * XXX: This should be a feature flag for compatibility
1590 			 */
1591 			if (zap.za_integer_length != 8 ||
1592 			    zap.za_num_integers == 0) {
1593 				cmn_err(CE_WARN, "zap_readdir: bad directory "
1594 				    "entry, obj = %lld, offset = %lld, "
1595 				    "length = %d, num = %lld\n",
1596 				    (u_longlong_t)zp->z_id,
1597 				    (u_longlong_t)offset,
1598 				    zap.za_integer_length,
1599 				    (u_longlong_t)zap.za_num_integers);
1600 				error = SET_ERROR(ENXIO);
1601 				goto update;
1602 			}
1603 
1604 			objnum = ZFS_DIRENT_OBJ(zap.za_first_integer);
1605 			type = ZFS_DIRENT_TYPE(zap.za_first_integer);
1606 		}
1607 
1608 		done = !zpl_dir_emit(ctx, zap.za_name, strlen(zap.za_name),
1609 		    objnum, type);
1610 		if (done)
1611 			break;
1612 
1613 		/* Prefetch znode */
1614 		if (prefetch) {
1615 			dmu_prefetch(os, objnum, 0, 0, 0,
1616 			    ZIO_PRIORITY_SYNC_READ);
1617 		}
1618 
1619 		/*
1620 		 * Move to the next entry, fill in the previous offset.
1621 		 */
1622 		if (offset > 2 || (offset == 2 && !zfs_show_ctldir(zp))) {
1623 			zap_cursor_advance(&zc);
1624 			offset = zap_cursor_serialize(&zc);
1625 		} else {
1626 			offset += 1;
1627 		}
1628 		ctx->pos = offset;
1629 	}
1630 	zp->z_zn_prefetch = B_FALSE; /* a lookup will re-enable pre-fetching */
1631 
1632 update:
1633 	zap_cursor_fini(&zc);
1634 	if (error == ENOENT)
1635 		error = 0;
1636 out:
1637 	zfs_exit(zfsvfs, FTAG);
1638 
1639 	return (error);
1640 }
1641 
1642 /*
1643  * Get the basic file attributes and place them in the provided kstat
1644  * structure.  The inode is assumed to be the authoritative source
1645  * for most of the attributes.  However, the znode currently has the
1646  * authoritative atime, blksize, and block count.
1647  *
1648  *	IN:	ip	- inode of file.
1649  *
1650  *	OUT:	sp	- kstat values.
1651  *
1652  *	RETURN:	0 (always succeeds)
1653  */
1654 int
1655 zfs_getattr_fast(struct user_namespace *user_ns, struct inode *ip,
1656     struct kstat *sp)
1657 {
1658 	znode_t *zp = ITOZ(ip);
1659 	zfsvfs_t *zfsvfs = ITOZSB(ip);
1660 	uint32_t blksize;
1661 	u_longlong_t nblocks;
1662 	int error;
1663 
1664 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
1665 		return (error);
1666 
1667 	mutex_enter(&zp->z_lock);
1668 
1669 	zpl_generic_fillattr(user_ns, ip, sp);
1670 	/*
1671 	 * +1 link count for root inode with visible '.zfs' directory.
1672 	 */
1673 	if ((zp->z_id == zfsvfs->z_root) && zfs_show_ctldir(zp))
1674 		if (sp->nlink < ZFS_LINK_MAX)
1675 			sp->nlink++;
1676 
1677 	sa_object_size(zp->z_sa_hdl, &blksize, &nblocks);
1678 	sp->blksize = blksize;
1679 	sp->blocks = nblocks;
1680 
1681 	if (unlikely(zp->z_blksz == 0)) {
1682 		/*
1683 		 * Block size hasn't been set; suggest maximal I/O transfers.
1684 		 */
1685 		sp->blksize = zfsvfs->z_max_blksz;
1686 	}
1687 
1688 	mutex_exit(&zp->z_lock);
1689 
1690 	/*
1691 	 * Required to prevent NFS client from detecting different inode
1692 	 * numbers of snapshot root dentry before and after snapshot mount.
1693 	 */
1694 	if (zfsvfs->z_issnap) {
1695 		if (ip->i_sb->s_root->d_inode == ip)
1696 			sp->ino = ZFSCTL_INO_SNAPDIRS -
1697 			    dmu_objset_id(zfsvfs->z_os);
1698 	}
1699 
1700 	zfs_exit(zfsvfs, FTAG);
1701 
1702 	return (0);
1703 }
1704 
1705 /*
1706  * For the operation of changing file's user/group/project, we need to
1707  * handle not only the main object that is assigned to the file directly,
1708  * but also the ones that are used by the file via hidden xattr directory.
1709  *
1710  * Because the xattr directory may contains many EA entries, as to it may
1711  * be impossible to change all of them via the transaction of changing the
1712  * main object's user/group/project attributes. Then we have to change them
1713  * via other multiple independent transactions one by one. It may be not good
1714  * solution, but we have no better idea yet.
1715  */
1716 static int
1717 zfs_setattr_dir(znode_t *dzp)
1718 {
1719 	struct inode	*dxip = ZTOI(dzp);
1720 	struct inode	*xip = NULL;
1721 	zfsvfs_t	*zfsvfs = ZTOZSB(dzp);
1722 	objset_t	*os = zfsvfs->z_os;
1723 	zap_cursor_t	zc;
1724 	zap_attribute_t	zap;
1725 	zfs_dirlock_t	*dl;
1726 	znode_t		*zp = NULL;
1727 	dmu_tx_t	*tx = NULL;
1728 	uint64_t	uid, gid;
1729 	sa_bulk_attr_t	bulk[4];
1730 	int		count;
1731 	int		err;
1732 
1733 	zap_cursor_init(&zc, os, dzp->z_id);
1734 	while ((err = zap_cursor_retrieve(&zc, &zap)) == 0) {
1735 		count = 0;
1736 		if (zap.za_integer_length != 8 || zap.za_num_integers != 1) {
1737 			err = ENXIO;
1738 			break;
1739 		}
1740 
1741 		err = zfs_dirent_lock(&dl, dzp, (char *)zap.za_name, &zp,
1742 		    ZEXISTS, NULL, NULL);
1743 		if (err == ENOENT)
1744 			goto next;
1745 		if (err)
1746 			break;
1747 
1748 		xip = ZTOI(zp);
1749 		if (KUID_TO_SUID(xip->i_uid) == KUID_TO_SUID(dxip->i_uid) &&
1750 		    KGID_TO_SGID(xip->i_gid) == KGID_TO_SGID(dxip->i_gid) &&
1751 		    zp->z_projid == dzp->z_projid)
1752 			goto next;
1753 
1754 		tx = dmu_tx_create(os);
1755 		if (!(zp->z_pflags & ZFS_PROJID))
1756 			dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
1757 		else
1758 			dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
1759 
1760 		err = dmu_tx_assign(tx, TXG_WAIT);
1761 		if (err)
1762 			break;
1763 
1764 		mutex_enter(&dzp->z_lock);
1765 
1766 		if (KUID_TO_SUID(xip->i_uid) != KUID_TO_SUID(dxip->i_uid)) {
1767 			xip->i_uid = dxip->i_uid;
1768 			uid = zfs_uid_read(dxip);
1769 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_UID(zfsvfs), NULL,
1770 			    &uid, sizeof (uid));
1771 		}
1772 
1773 		if (KGID_TO_SGID(xip->i_gid) != KGID_TO_SGID(dxip->i_gid)) {
1774 			xip->i_gid = dxip->i_gid;
1775 			gid = zfs_gid_read(dxip);
1776 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GID(zfsvfs), NULL,
1777 			    &gid, sizeof (gid));
1778 		}
1779 
1780 		if (zp->z_projid != dzp->z_projid) {
1781 			if (!(zp->z_pflags & ZFS_PROJID)) {
1782 				zp->z_pflags |= ZFS_PROJID;
1783 				SA_ADD_BULK_ATTR(bulk, count,
1784 				    SA_ZPL_FLAGS(zfsvfs), NULL, &zp->z_pflags,
1785 				    sizeof (zp->z_pflags));
1786 			}
1787 
1788 			zp->z_projid = dzp->z_projid;
1789 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_PROJID(zfsvfs),
1790 			    NULL, &zp->z_projid, sizeof (zp->z_projid));
1791 		}
1792 
1793 		mutex_exit(&dzp->z_lock);
1794 
1795 		if (likely(count > 0)) {
1796 			err = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
1797 			dmu_tx_commit(tx);
1798 		} else {
1799 			dmu_tx_abort(tx);
1800 		}
1801 		tx = NULL;
1802 		if (err != 0 && err != ENOENT)
1803 			break;
1804 
1805 next:
1806 		if (zp) {
1807 			zrele(zp);
1808 			zp = NULL;
1809 			zfs_dirent_unlock(dl);
1810 		}
1811 		zap_cursor_advance(&zc);
1812 	}
1813 
1814 	if (tx)
1815 		dmu_tx_abort(tx);
1816 	if (zp) {
1817 		zrele(zp);
1818 		zfs_dirent_unlock(dl);
1819 	}
1820 	zap_cursor_fini(&zc);
1821 
1822 	return (err == ENOENT ? 0 : err);
1823 }
1824 
1825 /*
1826  * Set the file attributes to the values contained in the
1827  * vattr structure.
1828  *
1829  *	IN:	zp	- znode of file to be modified.
1830  *		vap	- new attribute values.
1831  *			  If ATTR_XVATTR set, then optional attrs are being set
1832  *		flags	- ATTR_UTIME set if non-default time values provided.
1833  *			- ATTR_NOACLCHECK (CIFS context only).
1834  *		cr	- credentials of caller.
1835  *		mnt_ns	- user namespace of the mount
1836  *
1837  *	RETURN:	0 if success
1838  *		error code if failure
1839  *
1840  * Timestamps:
1841  *	ip - ctime updated, mtime updated if size changed.
1842  */
1843 int
1844 zfs_setattr(znode_t *zp, vattr_t *vap, int flags, cred_t *cr, zuserns_t *mnt_ns)
1845 {
1846 	struct inode	*ip;
1847 	zfsvfs_t	*zfsvfs = ZTOZSB(zp);
1848 	objset_t	*os = zfsvfs->z_os;
1849 	zilog_t		*zilog;
1850 	dmu_tx_t	*tx;
1851 	vattr_t		oldva;
1852 	xvattr_t	*tmpxvattr;
1853 	uint_t		mask = vap->va_mask;
1854 	uint_t		saved_mask = 0;
1855 	int		trim_mask = 0;
1856 	uint64_t	new_mode;
1857 	uint64_t	new_kuid = 0, new_kgid = 0, new_uid, new_gid;
1858 	uint64_t	xattr_obj;
1859 	uint64_t	mtime[2], ctime[2], atime[2];
1860 	uint64_t	projid = ZFS_INVALID_PROJID;
1861 	znode_t		*attrzp;
1862 	int		need_policy = FALSE;
1863 	int		err, err2 = 0;
1864 	zfs_fuid_info_t *fuidp = NULL;
1865 	xvattr_t *xvap = (xvattr_t *)vap;	/* vap may be an xvattr_t * */
1866 	xoptattr_t	*xoap;
1867 	zfs_acl_t	*aclp;
1868 	boolean_t skipaclchk = (flags & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
1869 	boolean_t	fuid_dirtied = B_FALSE;
1870 	boolean_t	handle_eadir = B_FALSE;
1871 	sa_bulk_attr_t	*bulk, *xattr_bulk;
1872 	int		count = 0, xattr_count = 0, bulks = 8;
1873 
1874 	if (mask == 0)
1875 		return (0);
1876 
1877 	if ((err = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
1878 		return (err);
1879 	ip = ZTOI(zp);
1880 
1881 	/*
1882 	 * If this is a xvattr_t, then get a pointer to the structure of
1883 	 * optional attributes.  If this is NULL, then we have a vattr_t.
1884 	 */
1885 	xoap = xva_getxoptattr(xvap);
1886 	if (xoap != NULL && (mask & ATTR_XVATTR)) {
1887 		if (XVA_ISSET_REQ(xvap, XAT_PROJID)) {
1888 			if (!dmu_objset_projectquota_enabled(os) ||
1889 			    (!S_ISREG(ip->i_mode) && !S_ISDIR(ip->i_mode))) {
1890 				zfs_exit(zfsvfs, FTAG);
1891 				return (SET_ERROR(ENOTSUP));
1892 			}
1893 
1894 			projid = xoap->xoa_projid;
1895 			if (unlikely(projid == ZFS_INVALID_PROJID)) {
1896 				zfs_exit(zfsvfs, FTAG);
1897 				return (SET_ERROR(EINVAL));
1898 			}
1899 
1900 			if (projid == zp->z_projid && zp->z_pflags & ZFS_PROJID)
1901 				projid = ZFS_INVALID_PROJID;
1902 			else
1903 				need_policy = TRUE;
1904 		}
1905 
1906 		if (XVA_ISSET_REQ(xvap, XAT_PROJINHERIT) &&
1907 		    (xoap->xoa_projinherit !=
1908 		    ((zp->z_pflags & ZFS_PROJINHERIT) != 0)) &&
1909 		    (!dmu_objset_projectquota_enabled(os) ||
1910 		    (!S_ISREG(ip->i_mode) && !S_ISDIR(ip->i_mode)))) {
1911 			zfs_exit(zfsvfs, FTAG);
1912 			return (SET_ERROR(ENOTSUP));
1913 		}
1914 	}
1915 
1916 	zilog = zfsvfs->z_log;
1917 
1918 	/*
1919 	 * Make sure that if we have ephemeral uid/gid or xvattr specified
1920 	 * that file system is at proper version level
1921 	 */
1922 
1923 	if (zfsvfs->z_use_fuids == B_FALSE &&
1924 	    (((mask & ATTR_UID) && IS_EPHEMERAL(vap->va_uid)) ||
1925 	    ((mask & ATTR_GID) && IS_EPHEMERAL(vap->va_gid)) ||
1926 	    (mask & ATTR_XVATTR))) {
1927 		zfs_exit(zfsvfs, FTAG);
1928 		return (SET_ERROR(EINVAL));
1929 	}
1930 
1931 	if (mask & ATTR_SIZE && S_ISDIR(ip->i_mode)) {
1932 		zfs_exit(zfsvfs, FTAG);
1933 		return (SET_ERROR(EISDIR));
1934 	}
1935 
1936 	if (mask & ATTR_SIZE && !S_ISREG(ip->i_mode) && !S_ISFIFO(ip->i_mode)) {
1937 		zfs_exit(zfsvfs, FTAG);
1938 		return (SET_ERROR(EINVAL));
1939 	}
1940 
1941 	tmpxvattr = kmem_alloc(sizeof (xvattr_t), KM_SLEEP);
1942 	xva_init(tmpxvattr);
1943 
1944 	bulk = kmem_alloc(sizeof (sa_bulk_attr_t) * bulks, KM_SLEEP);
1945 	xattr_bulk = kmem_alloc(sizeof (sa_bulk_attr_t) * bulks, KM_SLEEP);
1946 
1947 	/*
1948 	 * Immutable files can only alter immutable bit and atime
1949 	 */
1950 	if ((zp->z_pflags & ZFS_IMMUTABLE) &&
1951 	    ((mask & (ATTR_SIZE|ATTR_UID|ATTR_GID|ATTR_MTIME|ATTR_MODE)) ||
1952 	    ((mask & ATTR_XVATTR) && XVA_ISSET_REQ(xvap, XAT_CREATETIME)))) {
1953 		err = SET_ERROR(EPERM);
1954 		goto out3;
1955 	}
1956 
1957 	if ((mask & ATTR_SIZE) && (zp->z_pflags & ZFS_READONLY)) {
1958 		err = SET_ERROR(EPERM);
1959 		goto out3;
1960 	}
1961 
1962 	/*
1963 	 * Verify timestamps doesn't overflow 32 bits.
1964 	 * ZFS can handle large timestamps, but 32bit syscalls can't
1965 	 * handle times greater than 2039.  This check should be removed
1966 	 * once large timestamps are fully supported.
1967 	 */
1968 	if (mask & (ATTR_ATIME | ATTR_MTIME)) {
1969 		if (((mask & ATTR_ATIME) &&
1970 		    TIMESPEC_OVERFLOW(&vap->va_atime)) ||
1971 		    ((mask & ATTR_MTIME) &&
1972 		    TIMESPEC_OVERFLOW(&vap->va_mtime))) {
1973 			err = SET_ERROR(EOVERFLOW);
1974 			goto out3;
1975 		}
1976 	}
1977 
1978 top:
1979 	attrzp = NULL;
1980 	aclp = NULL;
1981 
1982 	/* Can this be moved to before the top label? */
1983 	if (zfs_is_readonly(zfsvfs)) {
1984 		err = SET_ERROR(EROFS);
1985 		goto out3;
1986 	}
1987 
1988 	/*
1989 	 * First validate permissions
1990 	 */
1991 
1992 	if (mask & ATTR_SIZE) {
1993 		err = zfs_zaccess(zp, ACE_WRITE_DATA, 0, skipaclchk, cr,
1994 		    mnt_ns);
1995 		if (err)
1996 			goto out3;
1997 
1998 		/*
1999 		 * XXX - Note, we are not providing any open
2000 		 * mode flags here (like FNDELAY), so we may
2001 		 * block if there are locks present... this
2002 		 * should be addressed in openat().
2003 		 */
2004 		/* XXX - would it be OK to generate a log record here? */
2005 		err = zfs_freesp(zp, vap->va_size, 0, 0, FALSE);
2006 		if (err)
2007 			goto out3;
2008 	}
2009 
2010 	if (mask & (ATTR_ATIME|ATTR_MTIME) ||
2011 	    ((mask & ATTR_XVATTR) && (XVA_ISSET_REQ(xvap, XAT_HIDDEN) ||
2012 	    XVA_ISSET_REQ(xvap, XAT_READONLY) ||
2013 	    XVA_ISSET_REQ(xvap, XAT_ARCHIVE) ||
2014 	    XVA_ISSET_REQ(xvap, XAT_OFFLINE) ||
2015 	    XVA_ISSET_REQ(xvap, XAT_SPARSE) ||
2016 	    XVA_ISSET_REQ(xvap, XAT_CREATETIME) ||
2017 	    XVA_ISSET_REQ(xvap, XAT_SYSTEM)))) {
2018 		need_policy = zfs_zaccess(zp, ACE_WRITE_ATTRIBUTES, 0,
2019 		    skipaclchk, cr, mnt_ns);
2020 	}
2021 
2022 	if (mask & (ATTR_UID|ATTR_GID)) {
2023 		int	idmask = (mask & (ATTR_UID|ATTR_GID));
2024 		int	take_owner;
2025 		int	take_group;
2026 		uid_t	uid;
2027 		gid_t	gid;
2028 
2029 		/*
2030 		 * NOTE: even if a new mode is being set,
2031 		 * we may clear S_ISUID/S_ISGID bits.
2032 		 */
2033 
2034 		if (!(mask & ATTR_MODE))
2035 			vap->va_mode = zp->z_mode;
2036 
2037 		/*
2038 		 * Take ownership or chgrp to group we are a member of
2039 		 */
2040 
2041 		uid = zfs_uid_to_vfsuid((struct user_namespace *)mnt_ns,
2042 		    zfs_i_user_ns(ip), vap->va_uid);
2043 		gid = zfs_gid_to_vfsgid((struct user_namespace *)mnt_ns,
2044 		    zfs_i_user_ns(ip), vap->va_gid);
2045 		take_owner = (mask & ATTR_UID) && (uid == crgetuid(cr));
2046 		take_group = (mask & ATTR_GID) &&
2047 		    zfs_groupmember(zfsvfs, gid, cr);
2048 
2049 		/*
2050 		 * If both ATTR_UID and ATTR_GID are set then take_owner and
2051 		 * take_group must both be set in order to allow taking
2052 		 * ownership.
2053 		 *
2054 		 * Otherwise, send the check through secpolicy_vnode_setattr()
2055 		 *
2056 		 */
2057 
2058 		if (((idmask == (ATTR_UID|ATTR_GID)) &&
2059 		    take_owner && take_group) ||
2060 		    ((idmask == ATTR_UID) && take_owner) ||
2061 		    ((idmask == ATTR_GID) && take_group)) {
2062 			if (zfs_zaccess(zp, ACE_WRITE_OWNER, 0,
2063 			    skipaclchk, cr, mnt_ns) == 0) {
2064 				/*
2065 				 * Remove setuid/setgid for non-privileged users
2066 				 */
2067 				(void) secpolicy_setid_clear(vap, cr);
2068 				trim_mask = (mask & (ATTR_UID|ATTR_GID));
2069 			} else {
2070 				need_policy =  TRUE;
2071 			}
2072 		} else {
2073 			need_policy =  TRUE;
2074 		}
2075 	}
2076 
2077 	mutex_enter(&zp->z_lock);
2078 	oldva.va_mode = zp->z_mode;
2079 	zfs_fuid_map_ids(zp, cr, &oldva.va_uid, &oldva.va_gid);
2080 	if (mask & ATTR_XVATTR) {
2081 		/*
2082 		 * Update xvattr mask to include only those attributes
2083 		 * that are actually changing.
2084 		 *
2085 		 * the bits will be restored prior to actually setting
2086 		 * the attributes so the caller thinks they were set.
2087 		 */
2088 		if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
2089 			if (xoap->xoa_appendonly !=
2090 			    ((zp->z_pflags & ZFS_APPENDONLY) != 0)) {
2091 				need_policy = TRUE;
2092 			} else {
2093 				XVA_CLR_REQ(xvap, XAT_APPENDONLY);
2094 				XVA_SET_REQ(tmpxvattr, XAT_APPENDONLY);
2095 			}
2096 		}
2097 
2098 		if (XVA_ISSET_REQ(xvap, XAT_PROJINHERIT)) {
2099 			if (xoap->xoa_projinherit !=
2100 			    ((zp->z_pflags & ZFS_PROJINHERIT) != 0)) {
2101 				need_policy = TRUE;
2102 			} else {
2103 				XVA_CLR_REQ(xvap, XAT_PROJINHERIT);
2104 				XVA_SET_REQ(tmpxvattr, XAT_PROJINHERIT);
2105 			}
2106 		}
2107 
2108 		if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
2109 			if (xoap->xoa_nounlink !=
2110 			    ((zp->z_pflags & ZFS_NOUNLINK) != 0)) {
2111 				need_policy = TRUE;
2112 			} else {
2113 				XVA_CLR_REQ(xvap, XAT_NOUNLINK);
2114 				XVA_SET_REQ(tmpxvattr, XAT_NOUNLINK);
2115 			}
2116 		}
2117 
2118 		if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
2119 			if (xoap->xoa_immutable !=
2120 			    ((zp->z_pflags & ZFS_IMMUTABLE) != 0)) {
2121 				need_policy = TRUE;
2122 			} else {
2123 				XVA_CLR_REQ(xvap, XAT_IMMUTABLE);
2124 				XVA_SET_REQ(tmpxvattr, XAT_IMMUTABLE);
2125 			}
2126 		}
2127 
2128 		if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
2129 			if (xoap->xoa_nodump !=
2130 			    ((zp->z_pflags & ZFS_NODUMP) != 0)) {
2131 				need_policy = TRUE;
2132 			} else {
2133 				XVA_CLR_REQ(xvap, XAT_NODUMP);
2134 				XVA_SET_REQ(tmpxvattr, XAT_NODUMP);
2135 			}
2136 		}
2137 
2138 		if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
2139 			if (xoap->xoa_av_modified !=
2140 			    ((zp->z_pflags & ZFS_AV_MODIFIED) != 0)) {
2141 				need_policy = TRUE;
2142 			} else {
2143 				XVA_CLR_REQ(xvap, XAT_AV_MODIFIED);
2144 				XVA_SET_REQ(tmpxvattr, XAT_AV_MODIFIED);
2145 			}
2146 		}
2147 
2148 		if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
2149 			if ((!S_ISREG(ip->i_mode) &&
2150 			    xoap->xoa_av_quarantined) ||
2151 			    xoap->xoa_av_quarantined !=
2152 			    ((zp->z_pflags & ZFS_AV_QUARANTINED) != 0)) {
2153 				need_policy = TRUE;
2154 			} else {
2155 				XVA_CLR_REQ(xvap, XAT_AV_QUARANTINED);
2156 				XVA_SET_REQ(tmpxvattr, XAT_AV_QUARANTINED);
2157 			}
2158 		}
2159 
2160 		if (XVA_ISSET_REQ(xvap, XAT_REPARSE)) {
2161 			mutex_exit(&zp->z_lock);
2162 			err = SET_ERROR(EPERM);
2163 			goto out3;
2164 		}
2165 
2166 		if (need_policy == FALSE &&
2167 		    (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP) ||
2168 		    XVA_ISSET_REQ(xvap, XAT_OPAQUE))) {
2169 			need_policy = TRUE;
2170 		}
2171 	}
2172 
2173 	mutex_exit(&zp->z_lock);
2174 
2175 	if (mask & ATTR_MODE) {
2176 		if (zfs_zaccess(zp, ACE_WRITE_ACL, 0, skipaclchk, cr,
2177 		    mnt_ns) == 0) {
2178 			err = secpolicy_setid_setsticky_clear(ip, vap,
2179 			    &oldva, cr, mnt_ns, zfs_i_user_ns(ip));
2180 			if (err)
2181 				goto out3;
2182 			trim_mask |= ATTR_MODE;
2183 		} else {
2184 			need_policy = TRUE;
2185 		}
2186 	}
2187 
2188 	if (need_policy) {
2189 		/*
2190 		 * If trim_mask is set then take ownership
2191 		 * has been granted or write_acl is present and user
2192 		 * has the ability to modify mode.  In that case remove
2193 		 * UID|GID and or MODE from mask so that
2194 		 * secpolicy_vnode_setattr() doesn't revoke it.
2195 		 */
2196 
2197 		if (trim_mask) {
2198 			saved_mask = vap->va_mask;
2199 			vap->va_mask &= ~trim_mask;
2200 		}
2201 		err = secpolicy_vnode_setattr(cr, ip, vap, &oldva, flags,
2202 		    zfs_zaccess_unix, zp);
2203 		if (err)
2204 			goto out3;
2205 
2206 		if (trim_mask)
2207 			vap->va_mask |= saved_mask;
2208 	}
2209 
2210 	/*
2211 	 * secpolicy_vnode_setattr, or take ownership may have
2212 	 * changed va_mask
2213 	 */
2214 	mask = vap->va_mask;
2215 
2216 	if ((mask & (ATTR_UID | ATTR_GID)) || projid != ZFS_INVALID_PROJID) {
2217 		handle_eadir = B_TRUE;
2218 		err = sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
2219 		    &xattr_obj, sizeof (xattr_obj));
2220 
2221 		if (err == 0 && xattr_obj) {
2222 			err = zfs_zget(ZTOZSB(zp), xattr_obj, &attrzp);
2223 			if (err)
2224 				goto out2;
2225 		}
2226 		if (mask & ATTR_UID) {
2227 			new_kuid = zfs_fuid_create(zfsvfs,
2228 			    (uint64_t)vap->va_uid, cr, ZFS_OWNER, &fuidp);
2229 			if (new_kuid != KUID_TO_SUID(ZTOI(zp)->i_uid) &&
2230 			    zfs_id_overquota(zfsvfs, DMU_USERUSED_OBJECT,
2231 			    new_kuid)) {
2232 				if (attrzp)
2233 					zrele(attrzp);
2234 				err = SET_ERROR(EDQUOT);
2235 				goto out2;
2236 			}
2237 		}
2238 
2239 		if (mask & ATTR_GID) {
2240 			new_kgid = zfs_fuid_create(zfsvfs,
2241 			    (uint64_t)vap->va_gid, cr, ZFS_GROUP, &fuidp);
2242 			if (new_kgid != KGID_TO_SGID(ZTOI(zp)->i_gid) &&
2243 			    zfs_id_overquota(zfsvfs, DMU_GROUPUSED_OBJECT,
2244 			    new_kgid)) {
2245 				if (attrzp)
2246 					zrele(attrzp);
2247 				err = SET_ERROR(EDQUOT);
2248 				goto out2;
2249 			}
2250 		}
2251 
2252 		if (projid != ZFS_INVALID_PROJID &&
2253 		    zfs_id_overquota(zfsvfs, DMU_PROJECTUSED_OBJECT, projid)) {
2254 			if (attrzp)
2255 				zrele(attrzp);
2256 			err = EDQUOT;
2257 			goto out2;
2258 		}
2259 	}
2260 	tx = dmu_tx_create(os);
2261 
2262 	if (mask & ATTR_MODE) {
2263 		uint64_t pmode = zp->z_mode;
2264 		uint64_t acl_obj;
2265 		new_mode = (pmode & S_IFMT) | (vap->va_mode & ~S_IFMT);
2266 
2267 		if (ZTOZSB(zp)->z_acl_mode == ZFS_ACL_RESTRICTED &&
2268 		    !(zp->z_pflags & ZFS_ACL_TRIVIAL)) {
2269 			err = EPERM;
2270 			goto out;
2271 		}
2272 
2273 		if ((err = zfs_acl_chmod_setattr(zp, &aclp, new_mode)))
2274 			goto out;
2275 
2276 		mutex_enter(&zp->z_lock);
2277 		if (!zp->z_is_sa && ((acl_obj = zfs_external_acl(zp)) != 0)) {
2278 			/*
2279 			 * Are we upgrading ACL from old V0 format
2280 			 * to V1 format?
2281 			 */
2282 			if (zfsvfs->z_version >= ZPL_VERSION_FUID &&
2283 			    zfs_znode_acl_version(zp) ==
2284 			    ZFS_ACL_VERSION_INITIAL) {
2285 				dmu_tx_hold_free(tx, acl_obj, 0,
2286 				    DMU_OBJECT_END);
2287 				dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
2288 				    0, aclp->z_acl_bytes);
2289 			} else {
2290 				dmu_tx_hold_write(tx, acl_obj, 0,
2291 				    aclp->z_acl_bytes);
2292 			}
2293 		} else if (!zp->z_is_sa && aclp->z_acl_bytes > ZFS_ACE_SPACE) {
2294 			dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
2295 			    0, aclp->z_acl_bytes);
2296 		}
2297 		mutex_exit(&zp->z_lock);
2298 		dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
2299 	} else {
2300 		if (((mask & ATTR_XVATTR) &&
2301 		    XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP)) ||
2302 		    (projid != ZFS_INVALID_PROJID &&
2303 		    !(zp->z_pflags & ZFS_PROJID)))
2304 			dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
2305 		else
2306 			dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
2307 	}
2308 
2309 	if (attrzp) {
2310 		dmu_tx_hold_sa(tx, attrzp->z_sa_hdl, B_FALSE);
2311 	}
2312 
2313 	fuid_dirtied = zfsvfs->z_fuid_dirty;
2314 	if (fuid_dirtied)
2315 		zfs_fuid_txhold(zfsvfs, tx);
2316 
2317 	zfs_sa_upgrade_txholds(tx, zp);
2318 
2319 	err = dmu_tx_assign(tx, TXG_WAIT);
2320 	if (err)
2321 		goto out;
2322 
2323 	count = 0;
2324 	/*
2325 	 * Set each attribute requested.
2326 	 * We group settings according to the locks they need to acquire.
2327 	 *
2328 	 * Note: you cannot set ctime directly, although it will be
2329 	 * updated as a side-effect of calling this function.
2330 	 */
2331 
2332 	if (projid != ZFS_INVALID_PROJID && !(zp->z_pflags & ZFS_PROJID)) {
2333 		/*
2334 		 * For the existed object that is upgraded from old system,
2335 		 * its on-disk layout has no slot for the project ID attribute.
2336 		 * But quota accounting logic needs to access related slots by
2337 		 * offset directly. So we need to adjust old objects' layout
2338 		 * to make the project ID to some unified and fixed offset.
2339 		 */
2340 		if (attrzp)
2341 			err = sa_add_projid(attrzp->z_sa_hdl, tx, projid);
2342 		if (err == 0)
2343 			err = sa_add_projid(zp->z_sa_hdl, tx, projid);
2344 
2345 		if (unlikely(err == EEXIST))
2346 			err = 0;
2347 		else if (err != 0)
2348 			goto out;
2349 		else
2350 			projid = ZFS_INVALID_PROJID;
2351 	}
2352 
2353 	if (mask & (ATTR_UID|ATTR_GID|ATTR_MODE))
2354 		mutex_enter(&zp->z_acl_lock);
2355 	mutex_enter(&zp->z_lock);
2356 
2357 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
2358 	    &zp->z_pflags, sizeof (zp->z_pflags));
2359 
2360 	if (attrzp) {
2361 		if (mask & (ATTR_UID|ATTR_GID|ATTR_MODE))
2362 			mutex_enter(&attrzp->z_acl_lock);
2363 		mutex_enter(&attrzp->z_lock);
2364 		SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
2365 		    SA_ZPL_FLAGS(zfsvfs), NULL, &attrzp->z_pflags,
2366 		    sizeof (attrzp->z_pflags));
2367 		if (projid != ZFS_INVALID_PROJID) {
2368 			attrzp->z_projid = projid;
2369 			SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
2370 			    SA_ZPL_PROJID(zfsvfs), NULL, &attrzp->z_projid,
2371 			    sizeof (attrzp->z_projid));
2372 		}
2373 	}
2374 
2375 	if (mask & (ATTR_UID|ATTR_GID)) {
2376 
2377 		if (mask & ATTR_UID) {
2378 			ZTOI(zp)->i_uid = SUID_TO_KUID(new_kuid);
2379 			new_uid = zfs_uid_read(ZTOI(zp));
2380 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_UID(zfsvfs), NULL,
2381 			    &new_uid, sizeof (new_uid));
2382 			if (attrzp) {
2383 				SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
2384 				    SA_ZPL_UID(zfsvfs), NULL, &new_uid,
2385 				    sizeof (new_uid));
2386 				ZTOI(attrzp)->i_uid = SUID_TO_KUID(new_uid);
2387 			}
2388 		}
2389 
2390 		if (mask & ATTR_GID) {
2391 			ZTOI(zp)->i_gid = SGID_TO_KGID(new_kgid);
2392 			new_gid = zfs_gid_read(ZTOI(zp));
2393 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GID(zfsvfs),
2394 			    NULL, &new_gid, sizeof (new_gid));
2395 			if (attrzp) {
2396 				SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
2397 				    SA_ZPL_GID(zfsvfs), NULL, &new_gid,
2398 				    sizeof (new_gid));
2399 				ZTOI(attrzp)->i_gid = SGID_TO_KGID(new_kgid);
2400 			}
2401 		}
2402 		if (!(mask & ATTR_MODE)) {
2403 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zfsvfs),
2404 			    NULL, &new_mode, sizeof (new_mode));
2405 			new_mode = zp->z_mode;
2406 		}
2407 		err = zfs_acl_chown_setattr(zp);
2408 		ASSERT(err == 0);
2409 		if (attrzp) {
2410 			err = zfs_acl_chown_setattr(attrzp);
2411 			ASSERT(err == 0);
2412 		}
2413 	}
2414 
2415 	if (mask & ATTR_MODE) {
2416 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MODE(zfsvfs), NULL,
2417 		    &new_mode, sizeof (new_mode));
2418 		zp->z_mode = ZTOI(zp)->i_mode = new_mode;
2419 		ASSERT3P(aclp, !=, NULL);
2420 		err = zfs_aclset_common(zp, aclp, cr, tx);
2421 		ASSERT0(err);
2422 		if (zp->z_acl_cached)
2423 			zfs_acl_free(zp->z_acl_cached);
2424 		zp->z_acl_cached = aclp;
2425 		aclp = NULL;
2426 	}
2427 
2428 	if ((mask & ATTR_ATIME) || zp->z_atime_dirty) {
2429 		zp->z_atime_dirty = B_FALSE;
2430 		ZFS_TIME_ENCODE(&ip->i_atime, atime);
2431 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_ATIME(zfsvfs), NULL,
2432 		    &atime, sizeof (atime));
2433 	}
2434 
2435 	if (mask & (ATTR_MTIME | ATTR_SIZE)) {
2436 		ZFS_TIME_ENCODE(&vap->va_mtime, mtime);
2437 		ZTOI(zp)->i_mtime = zpl_inode_timestamp_truncate(
2438 		    vap->va_mtime, ZTOI(zp));
2439 
2440 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL,
2441 		    mtime, sizeof (mtime));
2442 	}
2443 
2444 	if (mask & (ATTR_CTIME | ATTR_SIZE)) {
2445 		ZFS_TIME_ENCODE(&vap->va_ctime, ctime);
2446 		ZTOI(zp)->i_ctime = zpl_inode_timestamp_truncate(vap->va_ctime,
2447 		    ZTOI(zp));
2448 		SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL,
2449 		    ctime, sizeof (ctime));
2450 	}
2451 
2452 	if (projid != ZFS_INVALID_PROJID) {
2453 		zp->z_projid = projid;
2454 		SA_ADD_BULK_ATTR(bulk, count,
2455 		    SA_ZPL_PROJID(zfsvfs), NULL, &zp->z_projid,
2456 		    sizeof (zp->z_projid));
2457 	}
2458 
2459 	if (attrzp && mask) {
2460 		SA_ADD_BULK_ATTR(xattr_bulk, xattr_count,
2461 		    SA_ZPL_CTIME(zfsvfs), NULL, &ctime,
2462 		    sizeof (ctime));
2463 	}
2464 
2465 	/*
2466 	 * Do this after setting timestamps to prevent timestamp
2467 	 * update from toggling bit
2468 	 */
2469 
2470 	if (xoap && (mask & ATTR_XVATTR)) {
2471 
2472 		/*
2473 		 * restore trimmed off masks
2474 		 * so that return masks can be set for caller.
2475 		 */
2476 
2477 		if (XVA_ISSET_REQ(tmpxvattr, XAT_APPENDONLY)) {
2478 			XVA_SET_REQ(xvap, XAT_APPENDONLY);
2479 		}
2480 		if (XVA_ISSET_REQ(tmpxvattr, XAT_NOUNLINK)) {
2481 			XVA_SET_REQ(xvap, XAT_NOUNLINK);
2482 		}
2483 		if (XVA_ISSET_REQ(tmpxvattr, XAT_IMMUTABLE)) {
2484 			XVA_SET_REQ(xvap, XAT_IMMUTABLE);
2485 		}
2486 		if (XVA_ISSET_REQ(tmpxvattr, XAT_NODUMP)) {
2487 			XVA_SET_REQ(xvap, XAT_NODUMP);
2488 		}
2489 		if (XVA_ISSET_REQ(tmpxvattr, XAT_AV_MODIFIED)) {
2490 			XVA_SET_REQ(xvap, XAT_AV_MODIFIED);
2491 		}
2492 		if (XVA_ISSET_REQ(tmpxvattr, XAT_AV_QUARANTINED)) {
2493 			XVA_SET_REQ(xvap, XAT_AV_QUARANTINED);
2494 		}
2495 		if (XVA_ISSET_REQ(tmpxvattr, XAT_PROJINHERIT)) {
2496 			XVA_SET_REQ(xvap, XAT_PROJINHERIT);
2497 		}
2498 
2499 		if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP))
2500 			ASSERT(S_ISREG(ip->i_mode));
2501 
2502 		zfs_xvattr_set(zp, xvap, tx);
2503 	}
2504 
2505 	if (fuid_dirtied)
2506 		zfs_fuid_sync(zfsvfs, tx);
2507 
2508 	if (mask != 0)
2509 		zfs_log_setattr(zilog, tx, TX_SETATTR, zp, vap, mask, fuidp);
2510 
2511 	mutex_exit(&zp->z_lock);
2512 	if (mask & (ATTR_UID|ATTR_GID|ATTR_MODE))
2513 		mutex_exit(&zp->z_acl_lock);
2514 
2515 	if (attrzp) {
2516 		if (mask & (ATTR_UID|ATTR_GID|ATTR_MODE))
2517 			mutex_exit(&attrzp->z_acl_lock);
2518 		mutex_exit(&attrzp->z_lock);
2519 	}
2520 out:
2521 	if (err == 0 && xattr_count > 0) {
2522 		err2 = sa_bulk_update(attrzp->z_sa_hdl, xattr_bulk,
2523 		    xattr_count, tx);
2524 		ASSERT(err2 == 0);
2525 	}
2526 
2527 	if (aclp)
2528 		zfs_acl_free(aclp);
2529 
2530 	if (fuidp) {
2531 		zfs_fuid_info_free(fuidp);
2532 		fuidp = NULL;
2533 	}
2534 
2535 	if (err) {
2536 		dmu_tx_abort(tx);
2537 		if (attrzp)
2538 			zrele(attrzp);
2539 		if (err == ERESTART)
2540 			goto top;
2541 	} else {
2542 		if (count > 0)
2543 			err2 = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
2544 		dmu_tx_commit(tx);
2545 		if (attrzp) {
2546 			if (err2 == 0 && handle_eadir)
2547 				err = zfs_setattr_dir(attrzp);
2548 			zrele(attrzp);
2549 		}
2550 		zfs_znode_update_vfs(zp);
2551 	}
2552 
2553 out2:
2554 	if (os->os_sync == ZFS_SYNC_ALWAYS)
2555 		zil_commit(zilog, 0);
2556 
2557 out3:
2558 	kmem_free(xattr_bulk, sizeof (sa_bulk_attr_t) * bulks);
2559 	kmem_free(bulk, sizeof (sa_bulk_attr_t) * bulks);
2560 	kmem_free(tmpxvattr, sizeof (xvattr_t));
2561 	zfs_exit(zfsvfs, FTAG);
2562 	return (err);
2563 }
2564 
2565 typedef struct zfs_zlock {
2566 	krwlock_t	*zl_rwlock;	/* lock we acquired */
2567 	znode_t		*zl_znode;	/* znode we held */
2568 	struct zfs_zlock *zl_next;	/* next in list */
2569 } zfs_zlock_t;
2570 
2571 /*
2572  * Drop locks and release vnodes that were held by zfs_rename_lock().
2573  */
2574 static void
2575 zfs_rename_unlock(zfs_zlock_t **zlpp)
2576 {
2577 	zfs_zlock_t *zl;
2578 
2579 	while ((zl = *zlpp) != NULL) {
2580 		if (zl->zl_znode != NULL)
2581 			zfs_zrele_async(zl->zl_znode);
2582 		rw_exit(zl->zl_rwlock);
2583 		*zlpp = zl->zl_next;
2584 		kmem_free(zl, sizeof (*zl));
2585 	}
2586 }
2587 
2588 /*
2589  * Search back through the directory tree, using the ".." entries.
2590  * Lock each directory in the chain to prevent concurrent renames.
2591  * Fail any attempt to move a directory into one of its own descendants.
2592  * XXX - z_parent_lock can overlap with map or grow locks
2593  */
2594 static int
2595 zfs_rename_lock(znode_t *szp, znode_t *tdzp, znode_t *sdzp, zfs_zlock_t **zlpp)
2596 {
2597 	zfs_zlock_t	*zl;
2598 	znode_t		*zp = tdzp;
2599 	uint64_t	rootid = ZTOZSB(zp)->z_root;
2600 	uint64_t	oidp = zp->z_id;
2601 	krwlock_t	*rwlp = &szp->z_parent_lock;
2602 	krw_t		rw = RW_WRITER;
2603 
2604 	/*
2605 	 * First pass write-locks szp and compares to zp->z_id.
2606 	 * Later passes read-lock zp and compare to zp->z_parent.
2607 	 */
2608 	do {
2609 		if (!rw_tryenter(rwlp, rw)) {
2610 			/*
2611 			 * Another thread is renaming in this path.
2612 			 * Note that if we are a WRITER, we don't have any
2613 			 * parent_locks held yet.
2614 			 */
2615 			if (rw == RW_READER && zp->z_id > szp->z_id) {
2616 				/*
2617 				 * Drop our locks and restart
2618 				 */
2619 				zfs_rename_unlock(&zl);
2620 				*zlpp = NULL;
2621 				zp = tdzp;
2622 				oidp = zp->z_id;
2623 				rwlp = &szp->z_parent_lock;
2624 				rw = RW_WRITER;
2625 				continue;
2626 			} else {
2627 				/*
2628 				 * Wait for other thread to drop its locks
2629 				 */
2630 				rw_enter(rwlp, rw);
2631 			}
2632 		}
2633 
2634 		zl = kmem_alloc(sizeof (*zl), KM_SLEEP);
2635 		zl->zl_rwlock = rwlp;
2636 		zl->zl_znode = NULL;
2637 		zl->zl_next = *zlpp;
2638 		*zlpp = zl;
2639 
2640 		if (oidp == szp->z_id)		/* We're a descendant of szp */
2641 			return (SET_ERROR(EINVAL));
2642 
2643 		if (oidp == rootid)		/* We've hit the top */
2644 			return (0);
2645 
2646 		if (rw == RW_READER) {		/* i.e. not the first pass */
2647 			int error = zfs_zget(ZTOZSB(zp), oidp, &zp);
2648 			if (error)
2649 				return (error);
2650 			zl->zl_znode = zp;
2651 		}
2652 		(void) sa_lookup(zp->z_sa_hdl, SA_ZPL_PARENT(ZTOZSB(zp)),
2653 		    &oidp, sizeof (oidp));
2654 		rwlp = &zp->z_parent_lock;
2655 		rw = RW_READER;
2656 
2657 	} while (zp->z_id != sdzp->z_id);
2658 
2659 	return (0);
2660 }
2661 
2662 /*
2663  * Move an entry from the provided source directory to the target
2664  * directory.  Change the entry name as indicated.
2665  *
2666  *	IN:	sdzp	- Source directory containing the "old entry".
2667  *		snm	- Old entry name.
2668  *		tdzp	- Target directory to contain the "new entry".
2669  *		tnm	- New entry name.
2670  *		cr	- credentials of caller.
2671  *		flags	- case flags
2672  *		rflags  - RENAME_* flags
2673  *		wa_vap  - attributes for RENAME_WHITEOUT (must be a char 0:0).
2674  *		mnt_ns	- user namespace of the mount
2675  *
2676  *	RETURN:	0 on success, error code on failure.
2677  *
2678  * Timestamps:
2679  *	sdzp,tdzp - ctime|mtime updated
2680  */
2681 int
2682 zfs_rename(znode_t *sdzp, char *snm, znode_t *tdzp, char *tnm,
2683     cred_t *cr, int flags, uint64_t rflags, vattr_t *wo_vap, zuserns_t *mnt_ns)
2684 {
2685 	znode_t		*szp, *tzp;
2686 	zfsvfs_t	*zfsvfs = ZTOZSB(sdzp);
2687 	zilog_t		*zilog;
2688 	zfs_dirlock_t	*sdl, *tdl;
2689 	dmu_tx_t	*tx;
2690 	zfs_zlock_t	*zl;
2691 	int		cmp, serr, terr;
2692 	int		error = 0;
2693 	int		zflg = 0;
2694 	boolean_t	waited = B_FALSE;
2695 	/* Needed for whiteout inode creation. */
2696 	boolean_t	fuid_dirtied;
2697 	zfs_acl_ids_t	acl_ids;
2698 	boolean_t	have_acl = B_FALSE;
2699 	znode_t		*wzp = NULL;
2700 
2701 
2702 	if (snm == NULL || tnm == NULL)
2703 		return (SET_ERROR(EINVAL));
2704 
2705 	if (rflags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
2706 		return (SET_ERROR(EINVAL));
2707 
2708 	/* Already checked by Linux VFS, but just to make sure. */
2709 	if (rflags & RENAME_EXCHANGE &&
2710 	    (rflags & (RENAME_NOREPLACE | RENAME_WHITEOUT)))
2711 		return (SET_ERROR(EINVAL));
2712 
2713 	/*
2714 	 * Make sure we only get wo_vap iff. RENAME_WHITEOUT and that it's the
2715 	 * right kind of vattr_t for the whiteout file. These are set
2716 	 * internally by ZFS so should never be incorrect.
2717 	 */
2718 	VERIFY_EQUIV(rflags & RENAME_WHITEOUT, wo_vap != NULL);
2719 	VERIFY_IMPLY(wo_vap, wo_vap->va_mode == S_IFCHR);
2720 	VERIFY_IMPLY(wo_vap, wo_vap->va_rdev == makedevice(0, 0));
2721 
2722 	if ((error = zfs_enter_verify_zp(zfsvfs, sdzp, FTAG)) != 0)
2723 		return (error);
2724 	zilog = zfsvfs->z_log;
2725 
2726 	if ((error = zfs_verify_zp(tdzp)) != 0) {
2727 		zfs_exit(zfsvfs, FTAG);
2728 		return (error);
2729 	}
2730 
2731 	/*
2732 	 * We check i_sb because snapshots and the ctldir must have different
2733 	 * super blocks.
2734 	 */
2735 	if (ZTOI(tdzp)->i_sb != ZTOI(sdzp)->i_sb ||
2736 	    zfsctl_is_node(ZTOI(tdzp))) {
2737 		zfs_exit(zfsvfs, FTAG);
2738 		return (SET_ERROR(EXDEV));
2739 	}
2740 
2741 	if (zfsvfs->z_utf8 && u8_validate(tnm,
2742 	    strlen(tnm), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
2743 		zfs_exit(zfsvfs, FTAG);
2744 		return (SET_ERROR(EILSEQ));
2745 	}
2746 
2747 	if (flags & FIGNORECASE)
2748 		zflg |= ZCILOOK;
2749 
2750 top:
2751 	szp = NULL;
2752 	tzp = NULL;
2753 	zl = NULL;
2754 
2755 	/*
2756 	 * This is to prevent the creation of links into attribute space
2757 	 * by renaming a linked file into/outof an attribute directory.
2758 	 * See the comment in zfs_link() for why this is considered bad.
2759 	 */
2760 	if ((tdzp->z_pflags & ZFS_XATTR) != (sdzp->z_pflags & ZFS_XATTR)) {
2761 		zfs_exit(zfsvfs, FTAG);
2762 		return (SET_ERROR(EINVAL));
2763 	}
2764 
2765 	/*
2766 	 * Lock source and target directory entries.  To prevent deadlock,
2767 	 * a lock ordering must be defined.  We lock the directory with
2768 	 * the smallest object id first, or if it's a tie, the one with
2769 	 * the lexically first name.
2770 	 */
2771 	if (sdzp->z_id < tdzp->z_id) {
2772 		cmp = -1;
2773 	} else if (sdzp->z_id > tdzp->z_id) {
2774 		cmp = 1;
2775 	} else {
2776 		/*
2777 		 * First compare the two name arguments without
2778 		 * considering any case folding.
2779 		 */
2780 		int nofold = (zfsvfs->z_norm & ~U8_TEXTPREP_TOUPPER);
2781 
2782 		cmp = u8_strcmp(snm, tnm, 0, nofold, U8_UNICODE_LATEST, &error);
2783 		ASSERT(error == 0 || !zfsvfs->z_utf8);
2784 		if (cmp == 0) {
2785 			/*
2786 			 * POSIX: "If the old argument and the new argument
2787 			 * both refer to links to the same existing file,
2788 			 * the rename() function shall return successfully
2789 			 * and perform no other action."
2790 			 */
2791 			zfs_exit(zfsvfs, FTAG);
2792 			return (0);
2793 		}
2794 		/*
2795 		 * If the file system is case-folding, then we may
2796 		 * have some more checking to do.  A case-folding file
2797 		 * system is either supporting mixed case sensitivity
2798 		 * access or is completely case-insensitive.  Note
2799 		 * that the file system is always case preserving.
2800 		 *
2801 		 * In mixed sensitivity mode case sensitive behavior
2802 		 * is the default.  FIGNORECASE must be used to
2803 		 * explicitly request case insensitive behavior.
2804 		 *
2805 		 * If the source and target names provided differ only
2806 		 * by case (e.g., a request to rename 'tim' to 'Tim'),
2807 		 * we will treat this as a special case in the
2808 		 * case-insensitive mode: as long as the source name
2809 		 * is an exact match, we will allow this to proceed as
2810 		 * a name-change request.
2811 		 */
2812 		if ((zfsvfs->z_case == ZFS_CASE_INSENSITIVE ||
2813 		    (zfsvfs->z_case == ZFS_CASE_MIXED &&
2814 		    flags & FIGNORECASE)) &&
2815 		    u8_strcmp(snm, tnm, 0, zfsvfs->z_norm, U8_UNICODE_LATEST,
2816 		    &error) == 0) {
2817 			/*
2818 			 * case preserving rename request, require exact
2819 			 * name matches
2820 			 */
2821 			zflg |= ZCIEXACT;
2822 			zflg &= ~ZCILOOK;
2823 		}
2824 	}
2825 
2826 	/*
2827 	 * If the source and destination directories are the same, we should
2828 	 * grab the z_name_lock of that directory only once.
2829 	 */
2830 	if (sdzp == tdzp) {
2831 		zflg |= ZHAVELOCK;
2832 		rw_enter(&sdzp->z_name_lock, RW_READER);
2833 	}
2834 
2835 	if (cmp < 0) {
2836 		serr = zfs_dirent_lock(&sdl, sdzp, snm, &szp,
2837 		    ZEXISTS | zflg, NULL, NULL);
2838 		terr = zfs_dirent_lock(&tdl,
2839 		    tdzp, tnm, &tzp, ZRENAMING | zflg, NULL, NULL);
2840 	} else {
2841 		terr = zfs_dirent_lock(&tdl,
2842 		    tdzp, tnm, &tzp, zflg, NULL, NULL);
2843 		serr = zfs_dirent_lock(&sdl,
2844 		    sdzp, snm, &szp, ZEXISTS | ZRENAMING | zflg,
2845 		    NULL, NULL);
2846 	}
2847 
2848 	if (serr) {
2849 		/*
2850 		 * Source entry invalid or not there.
2851 		 */
2852 		if (!terr) {
2853 			zfs_dirent_unlock(tdl);
2854 			if (tzp)
2855 				zrele(tzp);
2856 		}
2857 
2858 		if (sdzp == tdzp)
2859 			rw_exit(&sdzp->z_name_lock);
2860 
2861 		if (strcmp(snm, "..") == 0)
2862 			serr = EINVAL;
2863 		zfs_exit(zfsvfs, FTAG);
2864 		return (serr);
2865 	}
2866 	if (terr) {
2867 		zfs_dirent_unlock(sdl);
2868 		zrele(szp);
2869 
2870 		if (sdzp == tdzp)
2871 			rw_exit(&sdzp->z_name_lock);
2872 
2873 		if (strcmp(tnm, "..") == 0)
2874 			terr = EINVAL;
2875 		zfs_exit(zfsvfs, FTAG);
2876 		return (terr);
2877 	}
2878 
2879 	/*
2880 	 * If we are using project inheritance, means if the directory has
2881 	 * ZFS_PROJINHERIT set, then its descendant directories will inherit
2882 	 * not only the project ID, but also the ZFS_PROJINHERIT flag. Under
2883 	 * such case, we only allow renames into our tree when the project
2884 	 * IDs are the same.
2885 	 */
2886 	if (tdzp->z_pflags & ZFS_PROJINHERIT &&
2887 	    tdzp->z_projid != szp->z_projid) {
2888 		error = SET_ERROR(EXDEV);
2889 		goto out;
2890 	}
2891 
2892 	/*
2893 	 * Must have write access at the source to remove the old entry
2894 	 * and write access at the target to create the new entry.
2895 	 * Note that if target and source are the same, this can be
2896 	 * done in a single check.
2897 	 */
2898 	if ((error = zfs_zaccess_rename(sdzp, szp, tdzp, tzp, cr, mnt_ns)))
2899 		goto out;
2900 
2901 	if (S_ISDIR(ZTOI(szp)->i_mode)) {
2902 		/*
2903 		 * Check to make sure rename is valid.
2904 		 * Can't do a move like this: /usr/a/b to /usr/a/b/c/d
2905 		 */
2906 		if ((error = zfs_rename_lock(szp, tdzp, sdzp, &zl)))
2907 			goto out;
2908 	}
2909 
2910 	/*
2911 	 * Does target exist?
2912 	 */
2913 	if (tzp) {
2914 		if (rflags & RENAME_NOREPLACE) {
2915 			error = SET_ERROR(EEXIST);
2916 			goto out;
2917 		}
2918 		/*
2919 		 * Source and target must be the same type (unless exchanging).
2920 		 */
2921 		if (!(rflags & RENAME_EXCHANGE)) {
2922 			boolean_t s_is_dir = S_ISDIR(ZTOI(szp)->i_mode) != 0;
2923 			boolean_t t_is_dir = S_ISDIR(ZTOI(tzp)->i_mode) != 0;
2924 
2925 			if (s_is_dir != t_is_dir) {
2926 				error = SET_ERROR(s_is_dir ? ENOTDIR : EISDIR);
2927 				goto out;
2928 			}
2929 		}
2930 		/*
2931 		 * POSIX dictates that when the source and target
2932 		 * entries refer to the same file object, rename
2933 		 * must do nothing and exit without error.
2934 		 */
2935 		if (szp->z_id == tzp->z_id) {
2936 			error = 0;
2937 			goto out;
2938 		}
2939 	} else if (rflags & RENAME_EXCHANGE) {
2940 		/* Target must exist for RENAME_EXCHANGE. */
2941 		error = SET_ERROR(ENOENT);
2942 		goto out;
2943 	}
2944 
2945 	/* Set up inode creation for RENAME_WHITEOUT. */
2946 	if (rflags & RENAME_WHITEOUT) {
2947 		/*
2948 		 * Whiteout files are not regular files or directories, so to
2949 		 * match zfs_create() we do not inherit the project id.
2950 		 */
2951 		uint64_t wo_projid = ZFS_DEFAULT_PROJID;
2952 
2953 		error = zfs_zaccess(sdzp, ACE_ADD_FILE, 0, B_FALSE, cr, mnt_ns);
2954 		if (error)
2955 			goto out;
2956 
2957 		if (!have_acl) {
2958 			error = zfs_acl_ids_create(sdzp, 0, wo_vap, cr, NULL,
2959 			    &acl_ids, mnt_ns);
2960 			if (error)
2961 				goto out;
2962 			have_acl = B_TRUE;
2963 		}
2964 
2965 		if (zfs_acl_ids_overquota(zfsvfs, &acl_ids, wo_projid)) {
2966 			error = SET_ERROR(EDQUOT);
2967 			goto out;
2968 		}
2969 	}
2970 
2971 	tx = dmu_tx_create(zfsvfs->z_os);
2972 	dmu_tx_hold_sa(tx, szp->z_sa_hdl, B_FALSE);
2973 	dmu_tx_hold_sa(tx, sdzp->z_sa_hdl, B_FALSE);
2974 	dmu_tx_hold_zap(tx, sdzp->z_id,
2975 	    (rflags & RENAME_EXCHANGE) ? TRUE : FALSE, snm);
2976 	dmu_tx_hold_zap(tx, tdzp->z_id, TRUE, tnm);
2977 	if (sdzp != tdzp) {
2978 		dmu_tx_hold_sa(tx, tdzp->z_sa_hdl, B_FALSE);
2979 		zfs_sa_upgrade_txholds(tx, tdzp);
2980 	}
2981 	if (tzp) {
2982 		dmu_tx_hold_sa(tx, tzp->z_sa_hdl, B_FALSE);
2983 		zfs_sa_upgrade_txholds(tx, tzp);
2984 	}
2985 	if (rflags & RENAME_WHITEOUT) {
2986 		dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
2987 		    ZFS_SA_BASE_ATTR_SIZE);
2988 
2989 		dmu_tx_hold_zap(tx, sdzp->z_id, TRUE, snm);
2990 		dmu_tx_hold_sa(tx, sdzp->z_sa_hdl, B_FALSE);
2991 		if (!zfsvfs->z_use_sa &&
2992 		    acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
2993 			dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
2994 			    0, acl_ids.z_aclp->z_acl_bytes);
2995 		}
2996 	}
2997 	fuid_dirtied = zfsvfs->z_fuid_dirty;
2998 	if (fuid_dirtied)
2999 		zfs_fuid_txhold(zfsvfs, tx);
3000 	zfs_sa_upgrade_txholds(tx, szp);
3001 	dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
3002 	error = dmu_tx_assign(tx, (waited ? TXG_NOTHROTTLE : 0) | TXG_NOWAIT);
3003 	if (error) {
3004 		if (zl != NULL)
3005 			zfs_rename_unlock(&zl);
3006 		zfs_dirent_unlock(sdl);
3007 		zfs_dirent_unlock(tdl);
3008 
3009 		if (sdzp == tdzp)
3010 			rw_exit(&sdzp->z_name_lock);
3011 
3012 		if (error == ERESTART) {
3013 			waited = B_TRUE;
3014 			dmu_tx_wait(tx);
3015 			dmu_tx_abort(tx);
3016 			zrele(szp);
3017 			if (tzp)
3018 				zrele(tzp);
3019 			goto top;
3020 		}
3021 		dmu_tx_abort(tx);
3022 		zrele(szp);
3023 		if (tzp)
3024 			zrele(tzp);
3025 		zfs_exit(zfsvfs, FTAG);
3026 		return (error);
3027 	}
3028 
3029 	/*
3030 	 * Unlink the source.
3031 	 */
3032 	szp->z_pflags |= ZFS_AV_MODIFIED;
3033 	if (tdzp->z_pflags & ZFS_PROJINHERIT)
3034 		szp->z_pflags |= ZFS_PROJINHERIT;
3035 
3036 	error = sa_update(szp->z_sa_hdl, SA_ZPL_FLAGS(zfsvfs),
3037 	    (void *)&szp->z_pflags, sizeof (uint64_t), tx);
3038 	VERIFY0(error);
3039 
3040 	error = zfs_link_destroy(sdl, szp, tx, ZRENAMING, NULL);
3041 	if (error)
3042 		goto commit;
3043 
3044 	/*
3045 	 * Unlink the target.
3046 	 */
3047 	if (tzp) {
3048 		int tzflg = zflg;
3049 
3050 		if (rflags & RENAME_EXCHANGE) {
3051 			/* This inode will be re-linked soon. */
3052 			tzflg |= ZRENAMING;
3053 
3054 			tzp->z_pflags |= ZFS_AV_MODIFIED;
3055 			if (sdzp->z_pflags & ZFS_PROJINHERIT)
3056 				tzp->z_pflags |= ZFS_PROJINHERIT;
3057 
3058 			error = sa_update(tzp->z_sa_hdl, SA_ZPL_FLAGS(zfsvfs),
3059 			    (void *)&tzp->z_pflags, sizeof (uint64_t), tx);
3060 			ASSERT0(error);
3061 		}
3062 		error = zfs_link_destroy(tdl, tzp, tx, tzflg, NULL);
3063 		if (error)
3064 			goto commit_link_szp;
3065 	}
3066 
3067 	/*
3068 	 * Create the new target links:
3069 	 *   * We always link the target.
3070 	 *   * RENAME_EXCHANGE: Link the old target to the source.
3071 	 *   * RENAME_WHITEOUT: Create a whiteout inode in-place of the source.
3072 	 */
3073 	error = zfs_link_create(tdl, szp, tx, ZRENAMING);
3074 	if (error) {
3075 		/*
3076 		 * If we have removed the existing target, a subsequent call to
3077 		 * zfs_link_create() to add back the same entry, but with a new
3078 		 * dnode (szp), should not fail.
3079 		 */
3080 		ASSERT3P(tzp, ==, NULL);
3081 		goto commit_link_tzp;
3082 	}
3083 
3084 	switch (rflags & (RENAME_EXCHANGE | RENAME_WHITEOUT)) {
3085 	case RENAME_EXCHANGE:
3086 		error = zfs_link_create(sdl, tzp, tx, ZRENAMING);
3087 		/*
3088 		 * The same argument as zfs_link_create() failing for
3089 		 * szp applies here, since the source directory must
3090 		 * have had an entry we are replacing.
3091 		 */
3092 		ASSERT0(error);
3093 		if (error)
3094 			goto commit_unlink_td_szp;
3095 		break;
3096 	case RENAME_WHITEOUT:
3097 		zfs_mknode(sdzp, wo_vap, tx, cr, 0, &wzp, &acl_ids);
3098 		error = zfs_link_create(sdl, wzp, tx, ZNEW);
3099 		if (error) {
3100 			zfs_znode_delete(wzp, tx);
3101 			remove_inode_hash(ZTOI(wzp));
3102 			goto commit_unlink_td_szp;
3103 		}
3104 		break;
3105 	}
3106 
3107 	if (fuid_dirtied)
3108 		zfs_fuid_sync(zfsvfs, tx);
3109 
3110 	switch (rflags & (RENAME_EXCHANGE | RENAME_WHITEOUT)) {
3111 	case RENAME_EXCHANGE:
3112 		zfs_log_rename_exchange(zilog, tx,
3113 		    (flags & FIGNORECASE ? TX_CI : 0), sdzp, sdl->dl_name,
3114 		    tdzp, tdl->dl_name, szp);
3115 		break;
3116 	case RENAME_WHITEOUT:
3117 		zfs_log_rename_whiteout(zilog, tx,
3118 		    (flags & FIGNORECASE ? TX_CI : 0), sdzp, sdl->dl_name,
3119 		    tdzp, tdl->dl_name, szp, wzp);
3120 		break;
3121 	default:
3122 		ASSERT0(rflags & ~RENAME_NOREPLACE);
3123 		zfs_log_rename(zilog, tx, (flags & FIGNORECASE ? TX_CI : 0),
3124 		    sdzp, sdl->dl_name, tdzp, tdl->dl_name, szp);
3125 		break;
3126 	}
3127 
3128 commit:
3129 	dmu_tx_commit(tx);
3130 out:
3131 	if (have_acl)
3132 		zfs_acl_ids_free(&acl_ids);
3133 
3134 	zfs_znode_update_vfs(sdzp);
3135 	if (sdzp == tdzp)
3136 		rw_exit(&sdzp->z_name_lock);
3137 
3138 	if (sdzp != tdzp)
3139 		zfs_znode_update_vfs(tdzp);
3140 
3141 	zfs_znode_update_vfs(szp);
3142 	zrele(szp);
3143 	if (wzp) {
3144 		zfs_znode_update_vfs(wzp);
3145 		zrele(wzp);
3146 	}
3147 	if (tzp) {
3148 		zfs_znode_update_vfs(tzp);
3149 		zrele(tzp);
3150 	}
3151 
3152 	if (zl != NULL)
3153 		zfs_rename_unlock(&zl);
3154 
3155 	zfs_dirent_unlock(sdl);
3156 	zfs_dirent_unlock(tdl);
3157 
3158 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
3159 		zil_commit(zilog, 0);
3160 
3161 	zfs_exit(zfsvfs, FTAG);
3162 	return (error);
3163 
3164 	/*
3165 	 * Clean-up path for broken link state.
3166 	 *
3167 	 * At this point we are in a (very) bad state, so we need to do our
3168 	 * best to correct the state. In particular, all of the nlinks are
3169 	 * wrong because we were destroying and creating links with ZRENAMING.
3170 	 *
3171 	 * In some form, all of these operations have to resolve the state:
3172 	 *
3173 	 *  * link_destroy() *must* succeed. Fortunately, this is very likely
3174 	 *    since we only just created it.
3175 	 *
3176 	 *  * link_create()s are allowed to fail (though they shouldn't because
3177 	 *    we only just unlinked them and are putting the entries back
3178 	 *    during clean-up). But if they fail, we can just forcefully drop
3179 	 *    the nlink value to (at the very least) avoid broken nlink values
3180 	 *    -- though in the case of non-empty directories we will have to
3181 	 *    panic (otherwise we'd have a leaked directory with a broken ..).
3182 	 */
3183 commit_unlink_td_szp:
3184 	VERIFY0(zfs_link_destroy(tdl, szp, tx, ZRENAMING, NULL));
3185 commit_link_tzp:
3186 	if (tzp) {
3187 		if (zfs_link_create(tdl, tzp, tx, ZRENAMING))
3188 			VERIFY0(zfs_drop_nlink(tzp, tx, NULL));
3189 	}
3190 commit_link_szp:
3191 	if (zfs_link_create(sdl, szp, tx, ZRENAMING))
3192 		VERIFY0(zfs_drop_nlink(szp, tx, NULL));
3193 	goto commit;
3194 }
3195 
3196 /*
3197  * Insert the indicated symbolic reference entry into the directory.
3198  *
3199  *	IN:	dzp	- Directory to contain new symbolic link.
3200  *		name	- Name of directory entry in dip.
3201  *		vap	- Attributes of new entry.
3202  *		link	- Name for new symlink entry.
3203  *		cr	- credentials of caller.
3204  *		flags	- case flags
3205  *		mnt_ns	- user namespace of the mount
3206  *
3207  *	OUT:	zpp	- Znode for new symbolic link.
3208  *
3209  *	RETURN:	0 on success, error code on failure.
3210  *
3211  * Timestamps:
3212  *	dip - ctime|mtime updated
3213  */
3214 int
3215 zfs_symlink(znode_t *dzp, char *name, vattr_t *vap, char *link,
3216     znode_t **zpp, cred_t *cr, int flags, zuserns_t *mnt_ns)
3217 {
3218 	znode_t		*zp;
3219 	zfs_dirlock_t	*dl;
3220 	dmu_tx_t	*tx;
3221 	zfsvfs_t	*zfsvfs = ZTOZSB(dzp);
3222 	zilog_t		*zilog;
3223 	uint64_t	len = strlen(link);
3224 	int		error;
3225 	int		zflg = ZNEW;
3226 	zfs_acl_ids_t	acl_ids;
3227 	boolean_t	fuid_dirtied;
3228 	uint64_t	txtype = TX_SYMLINK;
3229 	boolean_t	waited = B_FALSE;
3230 
3231 	ASSERT(S_ISLNK(vap->va_mode));
3232 
3233 	if (name == NULL)
3234 		return (SET_ERROR(EINVAL));
3235 
3236 	if ((error = zfs_enter_verify_zp(zfsvfs, dzp, FTAG)) != 0)
3237 		return (error);
3238 	zilog = zfsvfs->z_log;
3239 
3240 	if (zfsvfs->z_utf8 && u8_validate(name, strlen(name),
3241 	    NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
3242 		zfs_exit(zfsvfs, FTAG);
3243 		return (SET_ERROR(EILSEQ));
3244 	}
3245 	if (flags & FIGNORECASE)
3246 		zflg |= ZCILOOK;
3247 
3248 	if (len > MAXPATHLEN) {
3249 		zfs_exit(zfsvfs, FTAG);
3250 		return (SET_ERROR(ENAMETOOLONG));
3251 	}
3252 
3253 	if ((error = zfs_acl_ids_create(dzp, 0,
3254 	    vap, cr, NULL, &acl_ids, mnt_ns)) != 0) {
3255 		zfs_exit(zfsvfs, FTAG);
3256 		return (error);
3257 	}
3258 top:
3259 	*zpp = NULL;
3260 
3261 	/*
3262 	 * Attempt to lock directory; fail if entry already exists.
3263 	 */
3264 	error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg, NULL, NULL);
3265 	if (error) {
3266 		zfs_acl_ids_free(&acl_ids);
3267 		zfs_exit(zfsvfs, FTAG);
3268 		return (error);
3269 	}
3270 
3271 	if ((error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr, mnt_ns))) {
3272 		zfs_acl_ids_free(&acl_ids);
3273 		zfs_dirent_unlock(dl);
3274 		zfs_exit(zfsvfs, FTAG);
3275 		return (error);
3276 	}
3277 
3278 	if (zfs_acl_ids_overquota(zfsvfs, &acl_ids, ZFS_DEFAULT_PROJID)) {
3279 		zfs_acl_ids_free(&acl_ids);
3280 		zfs_dirent_unlock(dl);
3281 		zfs_exit(zfsvfs, FTAG);
3282 		return (SET_ERROR(EDQUOT));
3283 	}
3284 	tx = dmu_tx_create(zfsvfs->z_os);
3285 	fuid_dirtied = zfsvfs->z_fuid_dirty;
3286 	dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0, MAX(1, len));
3287 	dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
3288 	dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
3289 	    ZFS_SA_BASE_ATTR_SIZE + len);
3290 	dmu_tx_hold_sa(tx, dzp->z_sa_hdl, B_FALSE);
3291 	if (!zfsvfs->z_use_sa && acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
3292 		dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0,
3293 		    acl_ids.z_aclp->z_acl_bytes);
3294 	}
3295 	if (fuid_dirtied)
3296 		zfs_fuid_txhold(zfsvfs, tx);
3297 	error = dmu_tx_assign(tx, (waited ? TXG_NOTHROTTLE : 0) | TXG_NOWAIT);
3298 	if (error) {
3299 		zfs_dirent_unlock(dl);
3300 		if (error == ERESTART) {
3301 			waited = B_TRUE;
3302 			dmu_tx_wait(tx);
3303 			dmu_tx_abort(tx);
3304 			goto top;
3305 		}
3306 		zfs_acl_ids_free(&acl_ids);
3307 		dmu_tx_abort(tx);
3308 		zfs_exit(zfsvfs, FTAG);
3309 		return (error);
3310 	}
3311 
3312 	/*
3313 	 * Create a new object for the symlink.
3314 	 * for version 4 ZPL datasets the symlink will be an SA attribute
3315 	 */
3316 	zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
3317 
3318 	if (fuid_dirtied)
3319 		zfs_fuid_sync(zfsvfs, tx);
3320 
3321 	mutex_enter(&zp->z_lock);
3322 	if (zp->z_is_sa)
3323 		error = sa_update(zp->z_sa_hdl, SA_ZPL_SYMLINK(zfsvfs),
3324 		    link, len, tx);
3325 	else
3326 		zfs_sa_symlink(zp, link, len, tx);
3327 	mutex_exit(&zp->z_lock);
3328 
3329 	zp->z_size = len;
3330 	(void) sa_update(zp->z_sa_hdl, SA_ZPL_SIZE(zfsvfs),
3331 	    &zp->z_size, sizeof (zp->z_size), tx);
3332 	/*
3333 	 * Insert the new object into the directory.
3334 	 */
3335 	error = zfs_link_create(dl, zp, tx, ZNEW);
3336 	if (error != 0) {
3337 		zfs_znode_delete(zp, tx);
3338 		remove_inode_hash(ZTOI(zp));
3339 	} else {
3340 		if (flags & FIGNORECASE)
3341 			txtype |= TX_CI;
3342 		zfs_log_symlink(zilog, tx, txtype, dzp, zp, name, link);
3343 
3344 		zfs_znode_update_vfs(dzp);
3345 		zfs_znode_update_vfs(zp);
3346 	}
3347 
3348 	zfs_acl_ids_free(&acl_ids);
3349 
3350 	dmu_tx_commit(tx);
3351 
3352 	zfs_dirent_unlock(dl);
3353 
3354 	if (error == 0) {
3355 		*zpp = zp;
3356 
3357 		if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
3358 			zil_commit(zilog, 0);
3359 	} else {
3360 		zrele(zp);
3361 	}
3362 
3363 	zfs_exit(zfsvfs, FTAG);
3364 	return (error);
3365 }
3366 
3367 /*
3368  * Return, in the buffer contained in the provided uio structure,
3369  * the symbolic path referred to by ip.
3370  *
3371  *	IN:	ip	- inode of symbolic link
3372  *		uio	- structure to contain the link path.
3373  *		cr	- credentials of caller.
3374  *
3375  *	RETURN:	0 if success
3376  *		error code if failure
3377  *
3378  * Timestamps:
3379  *	ip - atime updated
3380  */
3381 int
3382 zfs_readlink(struct inode *ip, zfs_uio_t *uio, cred_t *cr)
3383 {
3384 	(void) cr;
3385 	znode_t		*zp = ITOZ(ip);
3386 	zfsvfs_t	*zfsvfs = ITOZSB(ip);
3387 	int		error;
3388 
3389 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
3390 		return (error);
3391 
3392 	mutex_enter(&zp->z_lock);
3393 	if (zp->z_is_sa)
3394 		error = sa_lookup_uio(zp->z_sa_hdl,
3395 		    SA_ZPL_SYMLINK(zfsvfs), uio);
3396 	else
3397 		error = zfs_sa_readlink(zp, uio);
3398 	mutex_exit(&zp->z_lock);
3399 
3400 	zfs_exit(zfsvfs, FTAG);
3401 	return (error);
3402 }
3403 
3404 /*
3405  * Insert a new entry into directory tdzp referencing szp.
3406  *
3407  *	IN:	tdzp	- Directory to contain new entry.
3408  *		szp	- znode of new entry.
3409  *		name	- name of new entry.
3410  *		cr	- credentials of caller.
3411  *		flags	- case flags.
3412  *
3413  *	RETURN:	0 if success
3414  *		error code if failure
3415  *
3416  * Timestamps:
3417  *	tdzp - ctime|mtime updated
3418  *	 szp - ctime updated
3419  */
3420 int
3421 zfs_link(znode_t *tdzp, znode_t *szp, char *name, cred_t *cr,
3422     int flags)
3423 {
3424 	struct inode *sip = ZTOI(szp);
3425 	znode_t		*tzp;
3426 	zfsvfs_t	*zfsvfs = ZTOZSB(tdzp);
3427 	zilog_t		*zilog;
3428 	zfs_dirlock_t	*dl;
3429 	dmu_tx_t	*tx;
3430 	int		error;
3431 	int		zf = ZNEW;
3432 	uint64_t	parent;
3433 	uid_t		owner;
3434 	boolean_t	waited = B_FALSE;
3435 	boolean_t	is_tmpfile = 0;
3436 	uint64_t	txg;
3437 #ifdef HAVE_TMPFILE
3438 	is_tmpfile = (sip->i_nlink == 0 && (sip->i_state & I_LINKABLE));
3439 #endif
3440 	ASSERT(S_ISDIR(ZTOI(tdzp)->i_mode));
3441 
3442 	if (name == NULL)
3443 		return (SET_ERROR(EINVAL));
3444 
3445 	if ((error = zfs_enter_verify_zp(zfsvfs, tdzp, FTAG)) != 0)
3446 		return (error);
3447 	zilog = zfsvfs->z_log;
3448 
3449 	/*
3450 	 * POSIX dictates that we return EPERM here.
3451 	 * Better choices include ENOTSUP or EISDIR.
3452 	 */
3453 	if (S_ISDIR(sip->i_mode)) {
3454 		zfs_exit(zfsvfs, FTAG);
3455 		return (SET_ERROR(EPERM));
3456 	}
3457 
3458 	if ((error = zfs_verify_zp(szp)) != 0) {
3459 		zfs_exit(zfsvfs, FTAG);
3460 		return (error);
3461 	}
3462 
3463 	/*
3464 	 * If we are using project inheritance, means if the directory has
3465 	 * ZFS_PROJINHERIT set, then its descendant directories will inherit
3466 	 * not only the project ID, but also the ZFS_PROJINHERIT flag. Under
3467 	 * such case, we only allow hard link creation in our tree when the
3468 	 * project IDs are the same.
3469 	 */
3470 	if (tdzp->z_pflags & ZFS_PROJINHERIT &&
3471 	    tdzp->z_projid != szp->z_projid) {
3472 		zfs_exit(zfsvfs, FTAG);
3473 		return (SET_ERROR(EXDEV));
3474 	}
3475 
3476 	/*
3477 	 * We check i_sb because snapshots and the ctldir must have different
3478 	 * super blocks.
3479 	 */
3480 	if (sip->i_sb != ZTOI(tdzp)->i_sb || zfsctl_is_node(sip)) {
3481 		zfs_exit(zfsvfs, FTAG);
3482 		return (SET_ERROR(EXDEV));
3483 	}
3484 
3485 	/* Prevent links to .zfs/shares files */
3486 
3487 	if ((error = sa_lookup(szp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs),
3488 	    &parent, sizeof (uint64_t))) != 0) {
3489 		zfs_exit(zfsvfs, FTAG);
3490 		return (error);
3491 	}
3492 	if (parent == zfsvfs->z_shares_dir) {
3493 		zfs_exit(zfsvfs, FTAG);
3494 		return (SET_ERROR(EPERM));
3495 	}
3496 
3497 	if (zfsvfs->z_utf8 && u8_validate(name,
3498 	    strlen(name), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
3499 		zfs_exit(zfsvfs, FTAG);
3500 		return (SET_ERROR(EILSEQ));
3501 	}
3502 	if (flags & FIGNORECASE)
3503 		zf |= ZCILOOK;
3504 
3505 	/*
3506 	 * We do not support links between attributes and non-attributes
3507 	 * because of the potential security risk of creating links
3508 	 * into "normal" file space in order to circumvent restrictions
3509 	 * imposed in attribute space.
3510 	 */
3511 	if ((szp->z_pflags & ZFS_XATTR) != (tdzp->z_pflags & ZFS_XATTR)) {
3512 		zfs_exit(zfsvfs, FTAG);
3513 		return (SET_ERROR(EINVAL));
3514 	}
3515 
3516 	owner = zfs_fuid_map_id(zfsvfs, KUID_TO_SUID(sip->i_uid),
3517 	    cr, ZFS_OWNER);
3518 	if (owner != crgetuid(cr) && secpolicy_basic_link(cr) != 0) {
3519 		zfs_exit(zfsvfs, FTAG);
3520 		return (SET_ERROR(EPERM));
3521 	}
3522 
3523 	if ((error = zfs_zaccess(tdzp, ACE_ADD_FILE, 0, B_FALSE, cr,
3524 	    kcred->user_ns))) {
3525 		zfs_exit(zfsvfs, FTAG);
3526 		return (error);
3527 	}
3528 
3529 top:
3530 	/*
3531 	 * Attempt to lock directory; fail if entry already exists.
3532 	 */
3533 	error = zfs_dirent_lock(&dl, tdzp, name, &tzp, zf, NULL, NULL);
3534 	if (error) {
3535 		zfs_exit(zfsvfs, FTAG);
3536 		return (error);
3537 	}
3538 
3539 	tx = dmu_tx_create(zfsvfs->z_os);
3540 	dmu_tx_hold_sa(tx, szp->z_sa_hdl, B_FALSE);
3541 	dmu_tx_hold_zap(tx, tdzp->z_id, TRUE, name);
3542 	if (is_tmpfile)
3543 		dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
3544 
3545 	zfs_sa_upgrade_txholds(tx, szp);
3546 	zfs_sa_upgrade_txholds(tx, tdzp);
3547 	error = dmu_tx_assign(tx, (waited ? TXG_NOTHROTTLE : 0) | TXG_NOWAIT);
3548 	if (error) {
3549 		zfs_dirent_unlock(dl);
3550 		if (error == ERESTART) {
3551 			waited = B_TRUE;
3552 			dmu_tx_wait(tx);
3553 			dmu_tx_abort(tx);
3554 			goto top;
3555 		}
3556 		dmu_tx_abort(tx);
3557 		zfs_exit(zfsvfs, FTAG);
3558 		return (error);
3559 	}
3560 	/* unmark z_unlinked so zfs_link_create will not reject */
3561 	if (is_tmpfile)
3562 		szp->z_unlinked = B_FALSE;
3563 	error = zfs_link_create(dl, szp, tx, 0);
3564 
3565 	if (error == 0) {
3566 		uint64_t txtype = TX_LINK;
3567 		/*
3568 		 * tmpfile is created to be in z_unlinkedobj, so remove it.
3569 		 * Also, we don't log in ZIL, because all previous file
3570 		 * operation on the tmpfile are ignored by ZIL. Instead we
3571 		 * always wait for txg to sync to make sure all previous
3572 		 * operation are sync safe.
3573 		 */
3574 		if (is_tmpfile) {
3575 			VERIFY(zap_remove_int(zfsvfs->z_os,
3576 			    zfsvfs->z_unlinkedobj, szp->z_id, tx) == 0);
3577 		} else {
3578 			if (flags & FIGNORECASE)
3579 				txtype |= TX_CI;
3580 			zfs_log_link(zilog, tx, txtype, tdzp, szp, name);
3581 		}
3582 	} else if (is_tmpfile) {
3583 		/* restore z_unlinked since when linking failed */
3584 		szp->z_unlinked = B_TRUE;
3585 	}
3586 	txg = dmu_tx_get_txg(tx);
3587 	dmu_tx_commit(tx);
3588 
3589 	zfs_dirent_unlock(dl);
3590 
3591 	if (!is_tmpfile && zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
3592 		zil_commit(zilog, 0);
3593 
3594 	if (is_tmpfile && zfsvfs->z_os->os_sync != ZFS_SYNC_DISABLED)
3595 		txg_wait_synced(dmu_objset_pool(zfsvfs->z_os), txg);
3596 
3597 	zfs_znode_update_vfs(tdzp);
3598 	zfs_znode_update_vfs(szp);
3599 	zfs_exit(zfsvfs, FTAG);
3600 	return (error);
3601 }
3602 
3603 static void
3604 zfs_putpage_sync_commit_cb(void *arg)
3605 {
3606 	struct page *pp = arg;
3607 
3608 	ClearPageError(pp);
3609 	end_page_writeback(pp);
3610 }
3611 
3612 static void
3613 zfs_putpage_async_commit_cb(void *arg)
3614 {
3615 	struct page *pp = arg;
3616 	znode_t *zp = ITOZ(pp->mapping->host);
3617 
3618 	ClearPageError(pp);
3619 	end_page_writeback(pp);
3620 	atomic_dec_32(&zp->z_async_writes_cnt);
3621 }
3622 
3623 /*
3624  * Push a page out to disk, once the page is on stable storage the
3625  * registered commit callback will be run as notification of completion.
3626  *
3627  *	IN:	ip	 - page mapped for inode.
3628  *		pp	 - page to push (page is locked)
3629  *		wbc	 - writeback control data
3630  *		for_sync - does the caller intend to wait synchronously for the
3631  *			   page writeback to complete?
3632  *
3633  *	RETURN:	0 if success
3634  *		error code if failure
3635  *
3636  * Timestamps:
3637  *	ip - ctime|mtime updated
3638  */
3639 int
3640 zfs_putpage(struct inode *ip, struct page *pp, struct writeback_control *wbc,
3641     boolean_t for_sync)
3642 {
3643 	znode_t		*zp = ITOZ(ip);
3644 	zfsvfs_t	*zfsvfs = ITOZSB(ip);
3645 	loff_t		offset;
3646 	loff_t		pgoff;
3647 	unsigned int	pglen;
3648 	dmu_tx_t	*tx;
3649 	caddr_t		va;
3650 	int		err = 0;
3651 	uint64_t	mtime[2], ctime[2];
3652 	sa_bulk_attr_t	bulk[3];
3653 	int		cnt = 0;
3654 	struct address_space *mapping;
3655 
3656 	if ((err = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
3657 		return (err);
3658 
3659 	ASSERT(PageLocked(pp));
3660 
3661 	pgoff = page_offset(pp);	/* Page byte-offset in file */
3662 	offset = i_size_read(ip);	/* File length in bytes */
3663 	pglen = MIN(PAGE_SIZE,		/* Page length in bytes */
3664 	    P2ROUNDUP(offset, PAGE_SIZE)-pgoff);
3665 
3666 	/* Page is beyond end of file */
3667 	if (pgoff >= offset) {
3668 		unlock_page(pp);
3669 		zfs_exit(zfsvfs, FTAG);
3670 		return (0);
3671 	}
3672 
3673 	/* Truncate page length to end of file */
3674 	if (pgoff + pglen > offset)
3675 		pglen = offset - pgoff;
3676 
3677 #if 0
3678 	/*
3679 	 * FIXME: Allow mmap writes past its quota.  The correct fix
3680 	 * is to register a page_mkwrite() handler to count the page
3681 	 * against its quota when it is about to be dirtied.
3682 	 */
3683 	if (zfs_id_overblockquota(zfsvfs, DMU_USERUSED_OBJECT,
3684 	    KUID_TO_SUID(ip->i_uid)) ||
3685 	    zfs_id_overblockquota(zfsvfs, DMU_GROUPUSED_OBJECT,
3686 	    KGID_TO_SGID(ip->i_gid)) ||
3687 	    (zp->z_projid != ZFS_DEFAULT_PROJID &&
3688 	    zfs_id_overblockquota(zfsvfs, DMU_PROJECTUSED_OBJECT,
3689 	    zp->z_projid))) {
3690 		err = EDQUOT;
3691 	}
3692 #endif
3693 
3694 	/*
3695 	 * The ordering here is critical and must adhere to the following
3696 	 * rules in order to avoid deadlocking in either zfs_read() or
3697 	 * zfs_free_range() due to a lock inversion.
3698 	 *
3699 	 * 1) The page must be unlocked prior to acquiring the range lock.
3700 	 *    This is critical because zfs_read() calls find_lock_page()
3701 	 *    which may block on the page lock while holding the range lock.
3702 	 *
3703 	 * 2) Before setting or clearing write back on a page the range lock
3704 	 *    must be held in order to prevent a lock inversion with the
3705 	 *    zfs_free_range() function.
3706 	 *
3707 	 * This presents a problem because upon entering this function the
3708 	 * page lock is already held.  To safely acquire the range lock the
3709 	 * page lock must be dropped.  This creates a window where another
3710 	 * process could truncate, invalidate, dirty, or write out the page.
3711 	 *
3712 	 * Therefore, after successfully reacquiring the range and page locks
3713 	 * the current page state is checked.  In the common case everything
3714 	 * will be as is expected and it can be written out.  However, if
3715 	 * the page state has changed it must be handled accordingly.
3716 	 */
3717 	mapping = pp->mapping;
3718 	redirty_page_for_writepage(wbc, pp);
3719 	unlock_page(pp);
3720 
3721 	zfs_locked_range_t *lr = zfs_rangelock_enter(&zp->z_rangelock,
3722 	    pgoff, pglen, RL_WRITER);
3723 	lock_page(pp);
3724 
3725 	/* Page mapping changed or it was no longer dirty, we're done */
3726 	if (unlikely((mapping != pp->mapping) || !PageDirty(pp))) {
3727 		unlock_page(pp);
3728 		zfs_rangelock_exit(lr);
3729 		zfs_exit(zfsvfs, FTAG);
3730 		return (0);
3731 	}
3732 
3733 	/* Another process started write block if required */
3734 	if (PageWriteback(pp)) {
3735 		unlock_page(pp);
3736 		zfs_rangelock_exit(lr);
3737 
3738 		if (wbc->sync_mode != WB_SYNC_NONE) {
3739 			/*
3740 			 * Speed up any non-sync page writebacks since
3741 			 * they may take several seconds to complete.
3742 			 * Refer to the comment in zpl_fsync() (when
3743 			 * HAVE_FSYNC_RANGE is defined) for details.
3744 			 */
3745 			if (atomic_load_32(&zp->z_async_writes_cnt) > 0) {
3746 				zil_commit(zfsvfs->z_log, zp->z_id);
3747 			}
3748 
3749 			if (PageWriteback(pp))
3750 #ifdef HAVE_PAGEMAP_FOLIO_WAIT_BIT
3751 				folio_wait_bit(page_folio(pp), PG_writeback);
3752 #else
3753 				wait_on_page_bit(pp, PG_writeback);
3754 #endif
3755 		}
3756 
3757 		zfs_exit(zfsvfs, FTAG);
3758 		return (0);
3759 	}
3760 
3761 	/* Clear the dirty flag the required locks are held */
3762 	if (!clear_page_dirty_for_io(pp)) {
3763 		unlock_page(pp);
3764 		zfs_rangelock_exit(lr);
3765 		zfs_exit(zfsvfs, FTAG);
3766 		return (0);
3767 	}
3768 
3769 	/*
3770 	 * Counterpart for redirty_page_for_writepage() above.  This page
3771 	 * was in fact not skipped and should not be counted as if it were.
3772 	 */
3773 	wbc->pages_skipped--;
3774 	if (!for_sync)
3775 		atomic_inc_32(&zp->z_async_writes_cnt);
3776 	set_page_writeback(pp);
3777 	unlock_page(pp);
3778 
3779 	tx = dmu_tx_create(zfsvfs->z_os);
3780 	dmu_tx_hold_write(tx, zp->z_id, pgoff, pglen);
3781 	dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
3782 	zfs_sa_upgrade_txholds(tx, zp);
3783 
3784 	err = dmu_tx_assign(tx, TXG_NOWAIT);
3785 	if (err != 0) {
3786 		if (err == ERESTART)
3787 			dmu_tx_wait(tx);
3788 
3789 		dmu_tx_abort(tx);
3790 #ifdef HAVE_VFS_FILEMAP_DIRTY_FOLIO
3791 		filemap_dirty_folio(page_mapping(pp), page_folio(pp));
3792 #else
3793 		__set_page_dirty_nobuffers(pp);
3794 #endif
3795 		ClearPageError(pp);
3796 		end_page_writeback(pp);
3797 		if (!for_sync)
3798 			atomic_dec_32(&zp->z_async_writes_cnt);
3799 		zfs_rangelock_exit(lr);
3800 		zfs_exit(zfsvfs, FTAG);
3801 		return (err);
3802 	}
3803 
3804 	va = kmap(pp);
3805 	ASSERT3U(pglen, <=, PAGE_SIZE);
3806 	dmu_write(zfsvfs->z_os, zp->z_id, pgoff, pglen, va, tx);
3807 	kunmap(pp);
3808 
3809 	SA_ADD_BULK_ATTR(bulk, cnt, SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16);
3810 	SA_ADD_BULK_ATTR(bulk, cnt, SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16);
3811 	SA_ADD_BULK_ATTR(bulk, cnt, SA_ZPL_FLAGS(zfsvfs), NULL,
3812 	    &zp->z_pflags, 8);
3813 
3814 	/* Preserve the mtime and ctime provided by the inode */
3815 	ZFS_TIME_ENCODE(&ip->i_mtime, mtime);
3816 	ZFS_TIME_ENCODE(&ip->i_ctime, ctime);
3817 	zp->z_atime_dirty = B_FALSE;
3818 	zp->z_seq++;
3819 
3820 	err = sa_bulk_update(zp->z_sa_hdl, bulk, cnt, tx);
3821 
3822 	zfs_log_write(zfsvfs->z_log, tx, TX_WRITE, zp, pgoff, pglen, 0,
3823 	    for_sync ? zfs_putpage_sync_commit_cb :
3824 	    zfs_putpage_async_commit_cb, pp);
3825 
3826 	dmu_tx_commit(tx);
3827 
3828 	zfs_rangelock_exit(lr);
3829 
3830 	if (wbc->sync_mode != WB_SYNC_NONE) {
3831 		/*
3832 		 * Note that this is rarely called under writepages(), because
3833 		 * writepages() normally handles the entire commit for
3834 		 * performance reasons.
3835 		 */
3836 		zil_commit(zfsvfs->z_log, zp->z_id);
3837 	} else if (!for_sync && atomic_load_32(&zp->z_sync_writes_cnt) > 0) {
3838 		/*
3839 		 * If the caller does not intend to wait synchronously
3840 		 * for this page writeback to complete and there are active
3841 		 * synchronous calls on this file, do a commit so that
3842 		 * the latter don't accidentally end up waiting for
3843 		 * our writeback to complete. Refer to the comment in
3844 		 * zpl_fsync() (when HAVE_FSYNC_RANGE is defined) for details.
3845 		 */
3846 		zil_commit(zfsvfs->z_log, zp->z_id);
3847 	}
3848 
3849 	dataset_kstats_update_write_kstats(&zfsvfs->z_kstat, pglen);
3850 
3851 	zfs_exit(zfsvfs, FTAG);
3852 	return (err);
3853 }
3854 
3855 /*
3856  * Update the system attributes when the inode has been dirtied.  For the
3857  * moment we only update the mode, atime, mtime, and ctime.
3858  */
3859 int
3860 zfs_dirty_inode(struct inode *ip, int flags)
3861 {
3862 	znode_t		*zp = ITOZ(ip);
3863 	zfsvfs_t	*zfsvfs = ITOZSB(ip);
3864 	dmu_tx_t	*tx;
3865 	uint64_t	mode, atime[2], mtime[2], ctime[2];
3866 	sa_bulk_attr_t	bulk[4];
3867 	int		error = 0;
3868 	int		cnt = 0;
3869 
3870 	if (zfs_is_readonly(zfsvfs) || dmu_objset_is_snapshot(zfsvfs->z_os))
3871 		return (0);
3872 
3873 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
3874 		return (error);
3875 
3876 #ifdef I_DIRTY_TIME
3877 	/*
3878 	 * This is the lazytime semantic introduced in Linux 4.0
3879 	 * This flag will only be called from update_time when lazytime is set.
3880 	 * (Note, I_DIRTY_SYNC will also set if not lazytime)
3881 	 * Fortunately mtime and ctime are managed within ZFS itself, so we
3882 	 * only need to dirty atime.
3883 	 */
3884 	if (flags == I_DIRTY_TIME) {
3885 		zp->z_atime_dirty = B_TRUE;
3886 		goto out;
3887 	}
3888 #endif
3889 
3890 	tx = dmu_tx_create(zfsvfs->z_os);
3891 
3892 	dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
3893 	zfs_sa_upgrade_txholds(tx, zp);
3894 
3895 	error = dmu_tx_assign(tx, TXG_WAIT);
3896 	if (error) {
3897 		dmu_tx_abort(tx);
3898 		goto out;
3899 	}
3900 
3901 	mutex_enter(&zp->z_lock);
3902 	zp->z_atime_dirty = B_FALSE;
3903 
3904 	SA_ADD_BULK_ATTR(bulk, cnt, SA_ZPL_MODE(zfsvfs), NULL, &mode, 8);
3905 	SA_ADD_BULK_ATTR(bulk, cnt, SA_ZPL_ATIME(zfsvfs), NULL, &atime, 16);
3906 	SA_ADD_BULK_ATTR(bulk, cnt, SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16);
3907 	SA_ADD_BULK_ATTR(bulk, cnt, SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16);
3908 
3909 	/* Preserve the mode, mtime and ctime provided by the inode */
3910 	ZFS_TIME_ENCODE(&ip->i_atime, atime);
3911 	ZFS_TIME_ENCODE(&ip->i_mtime, mtime);
3912 	ZFS_TIME_ENCODE(&ip->i_ctime, ctime);
3913 	mode = ip->i_mode;
3914 
3915 	zp->z_mode = mode;
3916 
3917 	error = sa_bulk_update(zp->z_sa_hdl, bulk, cnt, tx);
3918 	mutex_exit(&zp->z_lock);
3919 
3920 	dmu_tx_commit(tx);
3921 out:
3922 	zfs_exit(zfsvfs, FTAG);
3923 	return (error);
3924 }
3925 
3926 void
3927 zfs_inactive(struct inode *ip)
3928 {
3929 	znode_t	*zp = ITOZ(ip);
3930 	zfsvfs_t *zfsvfs = ITOZSB(ip);
3931 	uint64_t atime[2];
3932 	int error;
3933 	int need_unlock = 0;
3934 
3935 	/* Only read lock if we haven't already write locked, e.g. rollback */
3936 	if (!RW_WRITE_HELD(&zfsvfs->z_teardown_inactive_lock)) {
3937 		need_unlock = 1;
3938 		rw_enter(&zfsvfs->z_teardown_inactive_lock, RW_READER);
3939 	}
3940 	if (zp->z_sa_hdl == NULL) {
3941 		if (need_unlock)
3942 			rw_exit(&zfsvfs->z_teardown_inactive_lock);
3943 		return;
3944 	}
3945 
3946 	if (zp->z_atime_dirty && zp->z_unlinked == B_FALSE) {
3947 		dmu_tx_t *tx = dmu_tx_create(zfsvfs->z_os);
3948 
3949 		dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
3950 		zfs_sa_upgrade_txholds(tx, zp);
3951 		error = dmu_tx_assign(tx, TXG_WAIT);
3952 		if (error) {
3953 			dmu_tx_abort(tx);
3954 		} else {
3955 			ZFS_TIME_ENCODE(&ip->i_atime, atime);
3956 			mutex_enter(&zp->z_lock);
3957 			(void) sa_update(zp->z_sa_hdl, SA_ZPL_ATIME(zfsvfs),
3958 			    (void *)&atime, sizeof (atime), tx);
3959 			zp->z_atime_dirty = B_FALSE;
3960 			mutex_exit(&zp->z_lock);
3961 			dmu_tx_commit(tx);
3962 		}
3963 	}
3964 
3965 	zfs_zinactive(zp);
3966 	if (need_unlock)
3967 		rw_exit(&zfsvfs->z_teardown_inactive_lock);
3968 }
3969 
3970 /*
3971  * Fill pages with data from the disk.
3972  */
3973 static int
3974 zfs_fillpage(struct inode *ip, struct page *pp)
3975 {
3976 	zfsvfs_t *zfsvfs = ITOZSB(ip);
3977 	loff_t i_size = i_size_read(ip);
3978 	u_offset_t io_off = page_offset(pp);
3979 	size_t io_len = PAGE_SIZE;
3980 
3981 	ASSERT3U(io_off, <, i_size);
3982 
3983 	if (io_off + io_len > i_size)
3984 		io_len = i_size - io_off;
3985 
3986 	void *va = kmap(pp);
3987 	int error = dmu_read(zfsvfs->z_os, ITOZ(ip)->z_id, io_off,
3988 	    io_len, va, DMU_READ_PREFETCH);
3989 	if (io_len != PAGE_SIZE)
3990 		memset((char *)va + io_len, 0, PAGE_SIZE - io_len);
3991 	kunmap(pp);
3992 
3993 	if (error) {
3994 		/* convert checksum errors into IO errors */
3995 		if (error == ECKSUM)
3996 			error = SET_ERROR(EIO);
3997 
3998 		SetPageError(pp);
3999 		ClearPageUptodate(pp);
4000 	} else {
4001 		ClearPageError(pp);
4002 		SetPageUptodate(pp);
4003 	}
4004 
4005 	return (error);
4006 }
4007 
4008 /*
4009  * Uses zfs_fillpage to read data from the file and fill the page.
4010  *
4011  *	IN:	ip	 - inode of file to get data from.
4012  *		pp	 - page to read
4013  *
4014  *	RETURN:	0 on success, error code on failure.
4015  *
4016  * Timestamps:
4017  *	vp - atime updated
4018  */
4019 int
4020 zfs_getpage(struct inode *ip, struct page *pp)
4021 {
4022 	zfsvfs_t *zfsvfs = ITOZSB(ip);
4023 	znode_t *zp = ITOZ(ip);
4024 	int error;
4025 
4026 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
4027 		return (error);
4028 
4029 	error = zfs_fillpage(ip, pp);
4030 	if (error == 0)
4031 		dataset_kstats_update_read_kstats(&zfsvfs->z_kstat, PAGE_SIZE);
4032 
4033 	zfs_exit(zfsvfs, FTAG);
4034 
4035 	return (error);
4036 }
4037 
4038 /*
4039  * Check ZFS specific permissions to memory map a section of a file.
4040  *
4041  *	IN:	ip	- inode of the file to mmap
4042  *		off	- file offset
4043  *		addrp	- start address in memory region
4044  *		len	- length of memory region
4045  *		vm_flags- address flags
4046  *
4047  *	RETURN:	0 if success
4048  *		error code if failure
4049  */
4050 int
4051 zfs_map(struct inode *ip, offset_t off, caddr_t *addrp, size_t len,
4052     unsigned long vm_flags)
4053 {
4054 	(void) addrp;
4055 	znode_t  *zp = ITOZ(ip);
4056 	zfsvfs_t *zfsvfs = ITOZSB(ip);
4057 	int error;
4058 
4059 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
4060 		return (error);
4061 
4062 	if ((vm_flags & VM_WRITE) && (zp->z_pflags &
4063 	    (ZFS_IMMUTABLE | ZFS_READONLY | ZFS_APPENDONLY))) {
4064 		zfs_exit(zfsvfs, FTAG);
4065 		return (SET_ERROR(EPERM));
4066 	}
4067 
4068 	if ((vm_flags & (VM_READ | VM_EXEC)) &&
4069 	    (zp->z_pflags & ZFS_AV_QUARANTINED)) {
4070 		zfs_exit(zfsvfs, FTAG);
4071 		return (SET_ERROR(EACCES));
4072 	}
4073 
4074 	if (off < 0 || len > MAXOFFSET_T - off) {
4075 		zfs_exit(zfsvfs, FTAG);
4076 		return (SET_ERROR(ENXIO));
4077 	}
4078 
4079 	zfs_exit(zfsvfs, FTAG);
4080 	return (0);
4081 }
4082 
4083 /*
4084  * Free or allocate space in a file.  Currently, this function only
4085  * supports the `F_FREESP' command.  However, this command is somewhat
4086  * misnamed, as its functionality includes the ability to allocate as
4087  * well as free space.
4088  *
4089  *	IN:	zp	- znode of file to free data in.
4090  *		cmd	- action to take (only F_FREESP supported).
4091  *		bfp	- section of file to free/alloc.
4092  *		flag	- current file open mode flags.
4093  *		offset	- current file offset.
4094  *		cr	- credentials of caller.
4095  *
4096  *	RETURN:	0 on success, error code on failure.
4097  *
4098  * Timestamps:
4099  *	zp - ctime|mtime updated
4100  */
4101 int
4102 zfs_space(znode_t *zp, int cmd, flock64_t *bfp, int flag,
4103     offset_t offset, cred_t *cr)
4104 {
4105 	(void) offset;
4106 	zfsvfs_t	*zfsvfs = ZTOZSB(zp);
4107 	uint64_t	off, len;
4108 	int		error;
4109 
4110 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
4111 		return (error);
4112 
4113 	if (cmd != F_FREESP) {
4114 		zfs_exit(zfsvfs, FTAG);
4115 		return (SET_ERROR(EINVAL));
4116 	}
4117 
4118 	/*
4119 	 * Callers might not be able to detect properly that we are read-only,
4120 	 * so check it explicitly here.
4121 	 */
4122 	if (zfs_is_readonly(zfsvfs)) {
4123 		zfs_exit(zfsvfs, FTAG);
4124 		return (SET_ERROR(EROFS));
4125 	}
4126 
4127 	if (bfp->l_len < 0) {
4128 		zfs_exit(zfsvfs, FTAG);
4129 		return (SET_ERROR(EINVAL));
4130 	}
4131 
4132 	/*
4133 	 * Permissions aren't checked on Solaris because on this OS
4134 	 * zfs_space() can only be called with an opened file handle.
4135 	 * On Linux we can get here through truncate_range() which
4136 	 * operates directly on inodes, so we need to check access rights.
4137 	 */
4138 	if ((error = zfs_zaccess(zp, ACE_WRITE_DATA, 0, B_FALSE, cr,
4139 	    kcred->user_ns))) {
4140 		zfs_exit(zfsvfs, FTAG);
4141 		return (error);
4142 	}
4143 
4144 	off = bfp->l_start;
4145 	len = bfp->l_len; /* 0 means from off to end of file */
4146 
4147 	error = zfs_freesp(zp, off, len, flag, TRUE);
4148 
4149 	zfs_exit(zfsvfs, FTAG);
4150 	return (error);
4151 }
4152 
4153 int
4154 zfs_fid(struct inode *ip, fid_t *fidp)
4155 {
4156 	znode_t		*zp = ITOZ(ip);
4157 	zfsvfs_t	*zfsvfs = ITOZSB(ip);
4158 	uint32_t	gen;
4159 	uint64_t	gen64;
4160 	uint64_t	object = zp->z_id;
4161 	zfid_short_t	*zfid;
4162 	int		size, i, error;
4163 
4164 	if ((error = zfs_enter(zfsvfs, FTAG)) != 0)
4165 		return (error);
4166 
4167 	if (fidp->fid_len < SHORT_FID_LEN) {
4168 		fidp->fid_len = SHORT_FID_LEN;
4169 		zfs_exit(zfsvfs, FTAG);
4170 		return (SET_ERROR(ENOSPC));
4171 	}
4172 
4173 	if ((error = zfs_verify_zp(zp)) != 0) {
4174 		zfs_exit(zfsvfs, FTAG);
4175 		return (error);
4176 	}
4177 
4178 	if ((error = sa_lookup(zp->z_sa_hdl, SA_ZPL_GEN(zfsvfs),
4179 	    &gen64, sizeof (uint64_t))) != 0) {
4180 		zfs_exit(zfsvfs, FTAG);
4181 		return (error);
4182 	}
4183 
4184 	gen = (uint32_t)gen64;
4185 
4186 	size = SHORT_FID_LEN;
4187 
4188 	zfid = (zfid_short_t *)fidp;
4189 
4190 	zfid->zf_len = size;
4191 
4192 	for (i = 0; i < sizeof (zfid->zf_object); i++)
4193 		zfid->zf_object[i] = (uint8_t)(object >> (8 * i));
4194 
4195 	/* Must have a non-zero generation number to distinguish from .zfs */
4196 	if (gen == 0)
4197 		gen = 1;
4198 	for (i = 0; i < sizeof (zfid->zf_gen); i++)
4199 		zfid->zf_gen[i] = (uint8_t)(gen >> (8 * i));
4200 
4201 	zfs_exit(zfsvfs, FTAG);
4202 	return (0);
4203 }
4204 
4205 #if defined(_KERNEL)
4206 EXPORT_SYMBOL(zfs_open);
4207 EXPORT_SYMBOL(zfs_close);
4208 EXPORT_SYMBOL(zfs_lookup);
4209 EXPORT_SYMBOL(zfs_create);
4210 EXPORT_SYMBOL(zfs_tmpfile);
4211 EXPORT_SYMBOL(zfs_remove);
4212 EXPORT_SYMBOL(zfs_mkdir);
4213 EXPORT_SYMBOL(zfs_rmdir);
4214 EXPORT_SYMBOL(zfs_readdir);
4215 EXPORT_SYMBOL(zfs_getattr_fast);
4216 EXPORT_SYMBOL(zfs_setattr);
4217 EXPORT_SYMBOL(zfs_rename);
4218 EXPORT_SYMBOL(zfs_symlink);
4219 EXPORT_SYMBOL(zfs_readlink);
4220 EXPORT_SYMBOL(zfs_link);
4221 EXPORT_SYMBOL(zfs_inactive);
4222 EXPORT_SYMBOL(zfs_space);
4223 EXPORT_SYMBOL(zfs_fid);
4224 EXPORT_SYMBOL(zfs_getpage);
4225 EXPORT_SYMBOL(zfs_putpage);
4226 EXPORT_SYMBOL(zfs_dirty_inode);
4227 EXPORT_SYMBOL(zfs_map);
4228 
4229 /* CSTYLED */
4230 module_param(zfs_delete_blocks, ulong, 0644);
4231 MODULE_PARM_DESC(zfs_delete_blocks, "Delete files larger than N blocks async");
4232 
4233 #endif
4234