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