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