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