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