xref: /illumos-gate/usr/src/uts/common/fs/zfs/zfs_vnops.c (revision 9b6c7373)
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, 2017 by Delphix. All rights reserved.
25  * Copyright (c) 2014 Integros [integros.com]
26  * Copyright 2020 Joyent, Inc.
27  * Copyright 2020 Tintri by DDN, Inc. All rights reserved.
28  * Copyright 2015-2023 RackTop Systems, Inc.
29  */
30 
31 /* Portions Copyright 2007 Jeremy Teo */
32 /* Portions Copyright 2010 Robert Milkowski */
33 
34 #include <sys/types.h>
35 #include <sys/param.h>
36 #include <sys/time.h>
37 #include <sys/systm.h>
38 #include <sys/sysmacros.h>
39 #include <sys/resource.h>
40 #include <sys/vfs.h>
41 #include <sys/vfs_opreg.h>
42 #include <sys/vnode.h>
43 #include <sys/file.h>
44 #include <sys/stat.h>
45 #include <sys/kmem.h>
46 #include <sys/taskq.h>
47 #include <sys/uio.h>
48 #include <sys/vmsystm.h>
49 #include <sys/atomic.h>
50 #include <sys/vm.h>
51 #include <vm/seg_vn.h>
52 #include <vm/pvn.h>
53 #include <vm/as.h>
54 #include <vm/kpm.h>
55 #include <vm/seg_kpm.h>
56 #include <sys/mman.h>
57 #include <sys/pathname.h>
58 #include <sys/cmn_err.h>
59 #include <sys/errno.h>
60 #include <sys/unistd.h>
61 #include <sys/zfs_dir.h>
62 #include <sys/zfs_acl.h>
63 #include <sys/zfs_ioctl.h>
64 #include <sys/fs/zfs.h>
65 #include <sys/dmu.h>
66 #include <sys/dmu_objset.h>
67 #include <sys/spa.h>
68 #include <sys/txg.h>
69 #include <sys/dbuf.h>
70 #include <sys/zap.h>
71 #include <sys/sa.h>
72 #include <sys/dirent.h>
73 #include <sys/policy.h>
74 #include <sys/sunddi.h>
75 #include <sys/filio.h>
76 #include <sys/sid.h>
77 #include "fs/fs_subr.h"
78 #include <sys/zfs_ctldir.h>
79 #include <sys/zfs_fuid.h>
80 #include <sys/zfs_sa.h>
81 #include <sys/dnlc.h>
82 #include <sys/zfs_rlock.h>
83 #include <sys/extdirent.h>
84 #include <sys/kidmap.h>
85 #include <sys/cred.h>
86 #include <sys/attr.h>
87 #include <sys/zil.h>
88 #include <sys/sa_impl.h>
89 #include <sys/zfs_project.h>
90 
91 /*
92  * Programming rules.
93  *
94  * Each vnode op performs some logical unit of work.  To do this, the ZPL must
95  * properly lock its in-core state, create a DMU transaction, do the work,
96  * record this work in the intent log (ZIL), commit the DMU transaction,
97  * and wait for the intent log to commit if it is a synchronous operation.
98  * Moreover, the vnode ops must work in both normal and log replay context.
99  * The ordering of events is important to avoid deadlocks and references
100  * to freed memory.  The example below illustrates the following Big Rules:
101  *
102  *  (1)	A check must be made in each zfs thread for a mounted file system.
103  *	This is done avoiding races using ZFS_ENTER(zfsvfs).
104  *	A ZFS_EXIT(zfsvfs) is needed before all returns.  Any znodes
105  *	must be checked with ZFS_VERIFY_ZP(zp).  Both of these macros
106  *	can return EIO from the calling function.
107  *
108  *  (2)	VN_RELE() should always be the last thing except for zil_commit()
109  *	(if necessary) and ZFS_EXIT(). This is for 3 reasons:
110  *	First, if it's the last reference, the vnode/znode
111  *	can be freed, so the zp may point to freed memory.  Second, the last
112  *	reference will call zfs_zinactive(), which may induce a lot of work --
113  *	pushing cached pages (which acquires range locks) and syncing out
114  *	cached atime changes.  Third, zfs_zinactive() may require a new tx,
115  *	which could deadlock the system if you were already holding one.
116  *	If you must call VN_RELE() within a tx then use VN_RELE_ASYNC().
117  *
118  *  (3)	All range locks must be grabbed before calling dmu_tx_assign(),
119  *	as they can span dmu_tx_assign() calls.
120  *
121  *  (4) If ZPL locks are held, pass TXG_NOWAIT as the second argument to
122  *      dmu_tx_assign().  This is critical because we don't want to block
123  *      while holding locks.
124  *
125  *	If no ZPL locks are held (aside from ZFS_ENTER()), use TXG_WAIT.  This
126  *	reduces lock contention and CPU usage when we must wait (note that if
127  *	throughput is constrained by the storage, nearly every transaction
128  *	must wait).
129  *
130  *      Note, in particular, that if a lock is sometimes acquired before
131  *      the tx assigns, and sometimes after (e.g. z_lock), then failing
132  *      to use a non-blocking assign can deadlock the system.  The scenario:
133  *
134  *	Thread A has grabbed a lock before calling dmu_tx_assign().
135  *	Thread B is in an already-assigned tx, and blocks for this lock.
136  *	Thread A calls dmu_tx_assign(TXG_WAIT) and blocks in txg_wait_open()
137  *	forever, because the previous txg can't quiesce until B's tx commits.
138  *
139  *	If dmu_tx_assign() returns ERESTART and zfsvfs->z_assign is TXG_NOWAIT,
140  *	then drop all locks, call dmu_tx_wait(), and try again.  On subsequent
141  *	calls to dmu_tx_assign(), pass TXG_NOTHROTTLE in addition to TXG_NOWAIT,
142  *	to indicate that this operation has already called dmu_tx_wait().
143  *	This will ensure that we don't retry forever, waiting a short bit
144  *	each time.
145  *
146  *  (5)	If the operation succeeded, generate the intent log entry for it
147  *	before dropping locks.  This ensures that the ordering of events
148  *	in the intent log matches the order in which they actually occurred.
149  *	During ZIL replay the zfs_log_* functions will update the sequence
150  *	number to indicate the zil transaction has replayed.
151  *
152  *  (6)	At the end of each vnode op, the DMU tx must always commit,
153  *	regardless of whether there were any errors.
154  *
155  *  (7)	After dropping all locks, invoke zil_commit(zilog, foid)
156  *	to ensure that synchronous semantics are provided when necessary.
157  *
158  * In general, this is how things should be ordered in each vnode op:
159  *
160  *	ZFS_ENTER(zfsvfs);		// exit if unmounted
161  * top:
162  *	zfs_dirent_lock(&dl, ...)	// lock directory entry (may VN_HOLD())
163  *	rw_enter(...);			// grab any other locks you need
164  *	tx = dmu_tx_create(...);	// get DMU tx
165  *	dmu_tx_hold_*();		// hold each object you might modify
166  *	error = dmu_tx_assign(tx, (waited ? TXG_NOTHROTTLE : 0) | TXG_NOWAIT);
167  *	if (error) {
168  *		rw_exit(...);		// drop locks
169  *		zfs_dirent_unlock(dl);	// unlock directory entry
170  *		VN_RELE(...);		// release held vnodes
171  *		if (error == ERESTART) {
172  *			waited = B_TRUE;
173  *			dmu_tx_wait(tx);
174  *			dmu_tx_abort(tx);
175  *			goto top;
176  *		}
177  *		dmu_tx_abort(tx);	// abort DMU tx
178  *		ZFS_EXIT(zfsvfs);	// finished in zfs
179  *		return (error);		// really out of space
180  *	}
181  *	error = do_real_work();		// do whatever this VOP does
182  *	if (error == 0)
183  *		zfs_log_*(...);		// on success, make ZIL entry
184  *	dmu_tx_commit(tx);		// commit DMU tx -- error or not
185  *	rw_exit(...);			// drop locks
186  *	zfs_dirent_unlock(dl);		// unlock directory entry
187  *	VN_RELE(...);			// release held vnodes
188  *	zil_commit(zilog, foid);	// synchronous when necessary
189  *	ZFS_EXIT(zfsvfs);		// finished in zfs
190  *	return (error);			// done, report error
191  */
192 
193 /* ARGSUSED */
194 static int
zfs_open(vnode_t ** vpp,int flag,cred_t * cr,caller_context_t * ct)195 zfs_open(vnode_t **vpp, int flag, cred_t *cr, caller_context_t *ct)
196 {
197 	znode_t	*zp = VTOZ(*vpp);
198 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
199 
200 	ZFS_ENTER(zfsvfs);
201 	ZFS_VERIFY_ZP(zp);
202 
203 	if ((flag & FWRITE) && (zp->z_pflags & ZFS_APPENDONLY) &&
204 	    ((flag & FAPPEND) == 0)) {
205 		ZFS_EXIT(zfsvfs);
206 		return (SET_ERROR(EPERM));
207 	}
208 
209 	if (!zfs_has_ctldir(zp) && zp->z_zfsvfs->z_vscan &&
210 	    ZTOV(zp)->v_type == VREG &&
211 	    !(zp->z_pflags & ZFS_AV_QUARANTINED) && zp->z_size > 0) {
212 		if (fs_vscan(*vpp, cr, 0) != 0) {
213 			ZFS_EXIT(zfsvfs);
214 			return (SET_ERROR(EACCES));
215 		}
216 	}
217 
218 	/* Keep a count of the synchronous opens in the znode */
219 	if (flag & (FSYNC | FDSYNC))
220 		atomic_inc_32(&zp->z_sync_cnt);
221 
222 	ZFS_EXIT(zfsvfs);
223 	return (0);
224 }
225 
226 /* ARGSUSED */
227 static int
zfs_close(vnode_t * vp,int flag,int count,offset_t offset,cred_t * cr,caller_context_t * ct)228 zfs_close(vnode_t *vp, int flag, int count, offset_t offset, cred_t *cr,
229     caller_context_t *ct)
230 {
231 	znode_t	*zp = VTOZ(vp);
232 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
233 
234 	/*
235 	 * Clean up any locks held by this process on the vp.
236 	 */
237 	cleanlocks(vp, ddi_get_pid(), 0);
238 	cleanshares(vp, ddi_get_pid());
239 
240 	ZFS_ENTER(zfsvfs);
241 	ZFS_VERIFY_ZP(zp);
242 
243 	/* Decrement the synchronous opens in the znode */
244 	if ((flag & (FSYNC | FDSYNC)) && (count == 1))
245 		atomic_dec_32(&zp->z_sync_cnt);
246 
247 	if (!zfs_has_ctldir(zp) && zp->z_zfsvfs->z_vscan &&
248 	    ZTOV(zp)->v_type == VREG &&
249 	    !(zp->z_pflags & ZFS_AV_QUARANTINED) && zp->z_size > 0)
250 		VERIFY(fs_vscan(vp, cr, 1) == 0);
251 
252 	ZFS_EXIT(zfsvfs);
253 	return (0);
254 }
255 
256 /*
257  * Lseek support for finding holes (cmd == _FIO_SEEK_HOLE) and
258  * data (cmd == _FIO_SEEK_DATA). "off" is an in/out parameter.
259  */
260 static int
zfs_holey(vnode_t * vp,int cmd,offset_t * off)261 zfs_holey(vnode_t *vp, int cmd, offset_t *off)
262 {
263 	znode_t	*zp = VTOZ(vp);
264 	uint64_t noff = (uint64_t)*off; /* new offset */
265 	uint64_t file_sz;
266 	int error;
267 	boolean_t hole;
268 
269 	file_sz = zp->z_size;
270 	if (noff >= file_sz)  {
271 		return (SET_ERROR(ENXIO));
272 	}
273 
274 	if (cmd == _FIO_SEEK_HOLE)
275 		hole = B_TRUE;
276 	else
277 		hole = B_FALSE;
278 
279 	error = dmu_offset_next(zp->z_zfsvfs->z_os, zp->z_id, hole, &noff);
280 
281 	if (error == ESRCH)
282 		return (SET_ERROR(ENXIO));
283 
284 	/*
285 	 * We could find a hole that begins after the logical end-of-file,
286 	 * because dmu_offset_next() only works on whole blocks.  If the
287 	 * EOF falls mid-block, then indicate that the "virtual hole"
288 	 * at the end of the file begins at the logical EOF, rather than
289 	 * at the end of the last block.
290 	 */
291 	if (noff > file_sz) {
292 		ASSERT(hole);
293 		noff = file_sz;
294 	}
295 
296 	if (noff < *off)
297 		return (error);
298 	*off = noff;
299 	return (error);
300 }
301 
302 static int
zfs_ioctl_getxattr(vnode_t * vp,intptr_t data,int flag,cred_t * cr,caller_context_t * ct)303 zfs_ioctl_getxattr(vnode_t *vp, intptr_t data, int flag, cred_t *cr,
304     caller_context_t *ct)
305 {
306 	zfsxattr_t fsx = { 0 };
307 	znode_t *zp = VTOZ(vp);
308 
309 	if (zp->z_pflags & ZFS_PROJINHERIT)
310 		fsx.fsx_xflags = ZFS_PROJINHERIT_FL;
311 	if (zp->z_pflags & ZFS_PROJID)
312 		fsx.fsx_projid = zp->z_projid;
313 	if (ddi_copyout(&fsx, (void *)data, sizeof (fsx), flag))
314 		return (SET_ERROR(EFAULT));
315 
316 	return (0);
317 }
318 
319 static int zfs_setattr(vnode_t *, vattr_t *, int, cred_t *, caller_context_t *);
320 
321 static int
zfs_ioctl_setxattr(vnode_t * vp,intptr_t data,int flags,cred_t * cr,caller_context_t * ct)322 zfs_ioctl_setxattr(vnode_t *vp, intptr_t data, int flags, cred_t *cr,
323     caller_context_t *ct)
324 {
325 	znode_t *zp = VTOZ(vp);
326 	zfsxattr_t fsx;
327 	xvattr_t xva;
328 	xoptattr_t *xoap;
329 	int err;
330 
331 	if (ddi_copyin((void *)data, &fsx, sizeof (fsx), flags))
332 		return (SET_ERROR(EFAULT));
333 
334 	if (!zpl_is_valid_projid(fsx.fsx_projid))
335 		return (SET_ERROR(EINVAL));
336 
337 	if (fsx.fsx_xflags & ~ZFS_PROJINHERIT_FL)
338 		return (SET_ERROR(EOPNOTSUPP));
339 
340 	xva_init(&xva);
341 	xoap = xva_getxoptattr(&xva);
342 
343 	XVA_SET_REQ(&xva, XAT_PROJINHERIT);
344 	if (fsx.fsx_xflags & ZFS_PROJINHERIT_FL)
345 		xoap->xoa_projinherit = B_TRUE;
346 
347 	XVA_SET_REQ(&xva, XAT_PROJID);
348 	xoap->xoa_projid = fsx.fsx_projid;
349 
350 	return (zfs_setattr(vp, (vattr_t *)&xva, flags, cr, ct));
351 }
352 
353 /* ARGSUSED */
354 static int
zfs_ioctl(vnode_t * vp,int com,intptr_t data,int flag,cred_t * cred,int * rvalp,caller_context_t * ct)355 zfs_ioctl(vnode_t *vp, int com, intptr_t data, int flag, cred_t *cred,
356     int *rvalp, caller_context_t *ct)
357 {
358 	offset_t off;
359 	offset_t ndata;
360 	dmu_object_info_t doi;
361 	int error;
362 	zfsvfs_t *zfsvfs;
363 	znode_t *zp;
364 
365 	switch (com) {
366 	case _FIOFFS:
367 	{
368 		return (zfs_sync(vp->v_vfsp, 0, cred));
369 
370 		/*
371 		 * The following two ioctls are used by bfu.  Faking out,
372 		 * necessary to avoid bfu errors.
373 		 */
374 	}
375 	case _FIOGDIO:
376 	case _FIOSDIO:
377 	{
378 		return (0);
379 	}
380 
381 	case _FIODIRECTIO:
382 	{
383 		/*
384 		 * ZFS inherently provides the basic semantics for directio.
385 		 * This is the summary from the ZFS on Linux support for
386 		 * O_DIRECT, which is the common form of directio, and required
387 		 * no changes to ZFS.
388 		 *
389 		 * 1. Minimize cache effects of the I/O.
390 		 *
391 		 *    By design the ARC is already scan-resistant, which helps
392 		 *    mitigate the need for special O_DIRECT handling.
393 		 *
394 		 * 2. O_DIRECT _MAY_ impose restrictions on IO alignment and
395 		 *    length.
396 		 *
397 		 *    No additional alignment or length restrictions are
398 		 *    imposed by ZFS.
399 		 *
400 		 * 3. O_DIRECT _MAY_ perform unbuffered IO operations directly
401 		 *    between user memory and block device.
402 		 *
403 		 *    No unbuffered IO operations are currently supported. In
404 		 *    order to support features such as compression, encryption,
405 		 *    and checksumming a copy must be made to transform the
406 		 *    data.
407 		 *
408 		 * 4. O_DIRECT _MAY_ imply O_DSYNC (XFS).
409 		 *
410 		 *    O_DIRECT does not imply O_DSYNC for ZFS.
411 		 *
412 		 * 5. O_DIRECT _MAY_ disable file locking that serializes IO
413 		 *    operations.
414 		 *
415 		 *    All I/O in ZFS is locked for correctness and this locking
416 		 *    is not disabled by O_DIRECT.
417 		 */
418 		return (0);
419 	}
420 
421 	case _FIO_SEEK_DATA:
422 	case _FIO_SEEK_HOLE:
423 	{
424 		if (ddi_copyin((void *)data, &off, sizeof (off), flag))
425 			return (SET_ERROR(EFAULT));
426 
427 		zp = VTOZ(vp);
428 		zfsvfs = zp->z_zfsvfs;
429 		ZFS_ENTER(zfsvfs);
430 		ZFS_VERIFY_ZP(zp);
431 
432 		/* offset parameter is in/out */
433 		error = zfs_holey(vp, com, &off);
434 		ZFS_EXIT(zfsvfs);
435 		if (error)
436 			return (error);
437 		if (ddi_copyout(&off, (void *)data, sizeof (off), flag))
438 			return (SET_ERROR(EFAULT));
439 		return (0);
440 	}
441 	case _FIO_COUNT_FILLED:
442 	{
443 		/*
444 		 * _FIO_COUNT_FILLED adds a new ioctl command which
445 		 * exposes the number of filled blocks in a
446 		 * ZFS object.
447 		 */
448 		zp = VTOZ(vp);
449 		zfsvfs = zp->z_zfsvfs;
450 		ZFS_ENTER(zfsvfs);
451 		ZFS_VERIFY_ZP(zp);
452 
453 		/*
454 		 * Wait for all dirty blocks for this object
455 		 * to get synced out to disk, and the DMU info
456 		 * updated.
457 		 */
458 		error = dmu_object_wait_synced(zfsvfs->z_os, zp->z_id);
459 		if (error) {
460 			ZFS_EXIT(zfsvfs);
461 			return (error);
462 		}
463 
464 		/*
465 		 * Retrieve fill count from DMU object.
466 		 */
467 		error = dmu_object_info(zfsvfs->z_os, zp->z_id, &doi);
468 		if (error) {
469 			ZFS_EXIT(zfsvfs);
470 			return (error);
471 		}
472 
473 		ndata = doi.doi_fill_count;
474 
475 		ZFS_EXIT(zfsvfs);
476 		if (ddi_copyout(&ndata, (void *)data, sizeof (ndata), flag))
477 			return (SET_ERROR(EFAULT));
478 		return (0);
479 	}
480 	case ZFS_IOC_FSGETXATTR:
481 		return (zfs_ioctl_getxattr(vp, data, flag, cred, ct));
482 	case ZFS_IOC_FSSETXATTR:
483 		return (zfs_ioctl_setxattr(vp, data, flag, cred, ct));
484 	}
485 	return (SET_ERROR(ENOTTY));
486 }
487 
488 /*
489  * Utility functions to map and unmap a single physical page.  These
490  * are used to manage the mappable copies of ZFS file data, and therefore
491  * do not update ref/mod bits.
492  */
493 caddr_t
zfs_map_page(page_t * pp,enum seg_rw rw)494 zfs_map_page(page_t *pp, enum seg_rw rw)
495 {
496 	if (kpm_enable)
497 		return (hat_kpm_mapin(pp, 0));
498 	ASSERT(rw == S_READ || rw == S_WRITE);
499 	return (ppmapin(pp, PROT_READ | ((rw == S_WRITE) ? PROT_WRITE : 0),
500 	    (caddr_t)-1));
501 }
502 
503 void
zfs_unmap_page(page_t * pp,caddr_t addr)504 zfs_unmap_page(page_t *pp, caddr_t addr)
505 {
506 	if (kpm_enable) {
507 		hat_kpm_mapout(pp, 0, addr);
508 	} else {
509 		ppmapout(addr);
510 	}
511 }
512 
513 /*
514  * When a file is memory mapped, we must keep the IO data synchronized
515  * between the DMU cache and the memory mapped pages.  What this means:
516  *
517  * On Write:	If we find a memory mapped page, we write to *both*
518  *		the page and the dmu buffer.
519  */
520 static void
update_pages(vnode_t * vp,int64_t start,int len,objset_t * os,uint64_t oid)521 update_pages(vnode_t *vp, int64_t start, int len, objset_t *os, uint64_t oid)
522 {
523 	int64_t	off;
524 
525 	off = start & PAGEOFFSET;
526 	for (start &= PAGEMASK; len > 0; start += PAGESIZE) {
527 		page_t *pp;
528 		uint64_t nbytes = MIN(PAGESIZE - off, len);
529 
530 		if (pp = page_lookup(vp, start, SE_SHARED)) {
531 			caddr_t va;
532 
533 			va = zfs_map_page(pp, S_WRITE);
534 			(void) dmu_read(os, oid, start+off, nbytes, va+off,
535 			    DMU_READ_PREFETCH);
536 			zfs_unmap_page(pp, va);
537 			page_unlock(pp);
538 		}
539 		len -= nbytes;
540 		off = 0;
541 	}
542 }
543 
544 /*
545  * When a file is memory mapped, we must keep the IO data synchronized
546  * between the DMU cache and the memory mapped pages.  What this means:
547  *
548  * On Read:	We "read" preferentially from memory mapped pages,
549  *		else we default from the dmu buffer.
550  *
551  * NOTE: We will always "break up" the IO into PAGESIZE uiomoves when
552  *	 the file is memory mapped.
553  */
554 static int
mappedread(vnode_t * vp,int nbytes,uio_t * uio)555 mappedread(vnode_t *vp, int nbytes, uio_t *uio)
556 {
557 	znode_t *zp = VTOZ(vp);
558 	int64_t	start, off;
559 	int len = nbytes;
560 	int error = 0;
561 
562 	start = uio->uio_loffset;
563 	off = start & PAGEOFFSET;
564 	for (start &= PAGEMASK; len > 0; start += PAGESIZE) {
565 		page_t *pp;
566 		uint64_t bytes = MIN(PAGESIZE - off, len);
567 
568 		if (pp = page_lookup(vp, start, SE_SHARED)) {
569 			caddr_t va;
570 
571 			va = zfs_map_page(pp, S_READ);
572 			error = uiomove(va + off, bytes, UIO_READ, uio);
573 			zfs_unmap_page(pp, va);
574 			page_unlock(pp);
575 		} else {
576 			error = dmu_read_uio_dbuf(sa_get_db(zp->z_sa_hdl),
577 			    uio, bytes);
578 		}
579 		len -= bytes;
580 		off = 0;
581 		if (error)
582 			break;
583 	}
584 	return (error);
585 }
586 
587 offset_t zfs_read_chunk_size = 1024 * 1024; /* Tunable */
588 
589 /*
590  * Read bytes from specified file into supplied buffer.
591  *
592  *	IN:	vp	- vnode of file to be read from.
593  *		uio	- structure supplying read location, range info,
594  *			  and return buffer.
595  *		ioflag	- SYNC flags; used to provide FRSYNC semantics.
596  *		cr	- credentials of caller.
597  *		ct	- caller context
598  *
599  *	OUT:	uio	- updated offset and range, buffer filled.
600  *
601  *	RETURN:	0 on success, error code on failure.
602  *
603  * Side Effects:
604  *	vp - atime updated if byte count > 0
605  */
606 /* ARGSUSED */
607 static int
zfs_read(vnode_t * vp,uio_t * uio,int ioflag,cred_t * cr,caller_context_t * ct)608 zfs_read(vnode_t *vp, uio_t *uio, int ioflag, cred_t *cr, caller_context_t *ct)
609 {
610 	znode_t		*zp = VTOZ(vp);
611 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
612 	ssize_t		n, nbytes;
613 	int		error = 0;
614 	boolean_t	frsync = B_FALSE;
615 	xuio_t		*xuio = NULL;
616 
617 	ZFS_ENTER(zfsvfs);
618 	ZFS_VERIFY_ZP(zp);
619 
620 	if (zp->z_pflags & ZFS_AV_QUARANTINED) {
621 		ZFS_EXIT(zfsvfs);
622 		return (SET_ERROR(EACCES));
623 	}
624 
625 	/*
626 	 * Validate file offset
627 	 */
628 	if (uio->uio_loffset < (offset_t)0) {
629 		ZFS_EXIT(zfsvfs);
630 		return (SET_ERROR(EINVAL));
631 	}
632 
633 	/*
634 	 * Fasttrack empty reads
635 	 */
636 	if (uio->uio_resid == 0) {
637 		ZFS_EXIT(zfsvfs);
638 		return (0);
639 	}
640 
641 	/*
642 	 * Check for mandatory locks
643 	 */
644 	if (MANDMODE(zp->z_mode)) {
645 		if (error = chklock(vp, FREAD,
646 		    uio->uio_loffset, uio->uio_resid, uio->uio_fmode, ct)) {
647 			ZFS_EXIT(zfsvfs);
648 			return (error);
649 		}
650 	}
651 
652 #ifdef FRSYNC
653 	/*
654 	 * If we're in FRSYNC mode, sync out this znode before reading it.
655 	 * Only do this for non-snapshots.
656 	 *
657 	 * Some platforms do not support FRSYNC and instead map it
658 	 * to FSYNC, which results in unnecessary calls to zil_commit. We
659 	 * only honor FRSYNC requests on platforms which support it.
660 	 */
661 	frsync = !!(ioflag & FRSYNC);
662 #endif
663 
664 	if (zfsvfs->z_log &&
665 	    (frsync || zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS))
666 		zil_commit(zfsvfs->z_log, zp->z_id);
667 
668 	/*
669 	 * Lock the range against changes.
670 	 */
671 	locked_range_t *lr = rangelock_enter(&zp->z_rangelock,
672 	    uio->uio_loffset, uio->uio_resid, RL_READER);
673 
674 	/*
675 	 * If we are reading past end-of-file we can skip
676 	 * to the end; but we might still need to set atime.
677 	 */
678 	if (uio->uio_loffset >= zp->z_size) {
679 		error = 0;
680 		goto out;
681 	}
682 
683 	ASSERT(uio->uio_loffset < zp->z_size);
684 	n = MIN(uio->uio_resid, zp->z_size - uio->uio_loffset);
685 
686 	if ((uio->uio_extflg == UIO_XUIO) &&
687 	    (((xuio_t *)uio)->xu_type == UIOTYPE_ZEROCOPY)) {
688 		int nblk;
689 		int blksz = zp->z_blksz;
690 		uint64_t offset = uio->uio_loffset;
691 
692 		xuio = (xuio_t *)uio;
693 		if ((ISP2(blksz))) {
694 			nblk = (P2ROUNDUP(offset + n, blksz) - P2ALIGN(offset,
695 			    blksz)) / blksz;
696 		} else {
697 			ASSERT(offset + n <= blksz);
698 			nblk = 1;
699 		}
700 		(void) dmu_xuio_init(xuio, nblk);
701 
702 		if (vn_has_cached_data(vp)) {
703 			/*
704 			 * For simplicity, we always allocate a full buffer
705 			 * even if we only expect to read a portion of a block.
706 			 */
707 			while (--nblk >= 0) {
708 				(void) dmu_xuio_add(xuio,
709 				    dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
710 				    blksz), 0, blksz);
711 			}
712 		}
713 	}
714 
715 	while (n > 0) {
716 		nbytes = MIN(n, zfs_read_chunk_size -
717 		    P2PHASE(uio->uio_loffset, zfs_read_chunk_size));
718 
719 		if (vn_has_cached_data(vp)) {
720 			error = mappedread(vp, nbytes, uio);
721 		} else {
722 			error = dmu_read_uio_dbuf(sa_get_db(zp->z_sa_hdl),
723 			    uio, nbytes);
724 		}
725 		if (error) {
726 			/* convert checksum errors into IO errors */
727 			if (error == ECKSUM)
728 				error = SET_ERROR(EIO);
729 			break;
730 		}
731 
732 		n -= nbytes;
733 	}
734 out:
735 	rangelock_exit(lr);
736 
737 	ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
738 	ZFS_EXIT(zfsvfs);
739 	return (error);
740 }
741 
742 static void
zfs_write_clear_setid_bits_if_necessary(zfsvfs_t * zfsvfs,znode_t * zp,cred_t * cr,boolean_t * did_check,dmu_tx_t * tx)743 zfs_write_clear_setid_bits_if_necessary(zfsvfs_t *zfsvfs, znode_t *zp,
744     cred_t *cr, boolean_t *did_check, dmu_tx_t *tx)
745 {
746 	ASSERT(did_check != NULL);
747 	ASSERT(tx != NULL);
748 
749 	if (*did_check)
750 		return;
751 
752 	zilog_t *zilog = zfsvfs->z_log;
753 
754 	/*
755 	 * Clear Set-UID/Set-GID bits on successful write if not
756 	 * privileged and at least one of the execute bits is set.
757 	 *
758 	 * It would be nice to do this after all writes have
759 	 * been done, but that would still expose the ISUID/ISGID
760 	 * to another app after the partial write is committed.
761 	 *
762 	 * Note: we don't call zfs_fuid_map_id() here because
763 	 * user 0 is not an ephemeral uid.
764 	 */
765 	rw_enter(&zp->z_acl_lock, RW_READER);
766 	if ((zp->z_mode & (S_IXUSR | (S_IXUSR >> 3) | (S_IXUSR >> 6))) != 0 &&
767 	    (zp->z_mode & (S_ISUID | S_ISGID)) != 0 &&
768 	    secpolicy_vnode_setid_retain(cr,
769 	    ((zp->z_mode & S_ISUID) != 0 && zp->z_uid == 0)) != 0) {
770 		/*
771 		 * We need to clear the SUID|SGID bits, but
772 		 * become RW_WRITER before updating z_mode.
773 		 */
774 		rw_exit(&zp->z_acl_lock);
775 		rw_enter(&zp->z_acl_lock, RW_WRITER);
776 
777 		/*
778 		 * If another writer did this, skip it.
779 		 */
780 		if ((zp->z_mode & (S_ISUID | S_ISGID)) != 0) {
781 			uint64_t newmode;
782 			vattr_t va;
783 
784 			zp->z_mode &= ~(S_ISUID | S_ISGID);
785 			newmode = zp->z_mode;
786 			(void) sa_update(zp->z_sa_hdl, SA_ZPL_MODE(zfsvfs),
787 			    (void *)&newmode, sizeof (uint64_t), tx);
788 
789 			/*
790 			 * Make sure SUID/SGID bits will be removed
791 			 * when we replay the log.
792 			 */
793 			bzero(&va, sizeof (va));
794 			va.va_mask = AT_MODE;
795 			va.va_nodeid = zp->z_id;
796 			va.va_mode = newmode;
797 			zfs_log_setattr(zilog, tx, TX_SETATTR,
798 			    zp, &va, AT_MODE, NULL);
799 		}
800 	}
801 	rw_exit(&zp->z_acl_lock);
802 
803 	*did_check = B_TRUE;
804 }
805 
806 /*
807  * Write the bytes to a file.
808  *
809  *	IN:	vp	- vnode of file to be written to.
810  *		uio	- structure supplying write location, range info,
811  *			  and data buffer.
812  *		ioflag	- FAPPEND, FSYNC, and/or FDSYNC.  FAPPEND is
813  *			  set if in append mode.
814  *		cr	- credentials of caller.
815  *		ct	- caller context (NFS/CIFS fem monitor only)
816  *
817  *	OUT:	uio	- updated offset and range.
818  *
819  *	RETURN:	0 on success, error code on failure.
820  *
821  * Timestamps:
822  *	vp - ctime|mtime updated if byte count > 0
823  */
824 
825 /* ARGSUSED */
826 static int
zfs_write(vnode_t * vp,uio_t * uio,int ioflag,cred_t * cr,caller_context_t * ct)827 zfs_write(vnode_t *vp, uio_t *uio, int ioflag, cred_t *cr, caller_context_t *ct)
828 {
829 	znode_t		*zp = VTOZ(vp);
830 	rlim64_t	limit = uio->uio_llimit;
831 	ssize_t		start_resid = uio->uio_resid;
832 	ssize_t		tx_bytes;
833 	uint64_t	end_size;
834 	dmu_tx_t	*tx;
835 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
836 	zilog_t		*zilog;
837 	offset_t	woff;
838 	ssize_t		n, nbytes;
839 	int		max_blksz = zfsvfs->z_max_blksz;
840 	int		error = 0;
841 	int		prev_error;
842 	arc_buf_t	*abuf;
843 	iovec_t		*aiov = NULL;
844 	xuio_t		*xuio = NULL;
845 	int		i_iov = 0;
846 	int		iovcnt = uio->uio_iovcnt;
847 	iovec_t		*iovp = uio->uio_iov;
848 	int		write_eof;
849 	int		count = 0;
850 	sa_bulk_attr_t	bulk[4];
851 	uint64_t	mtime[2], ctime[2];
852 	boolean_t	did_clear_setid_bits = B_FALSE;
853 
854 	/*
855 	 * Fasttrack empty write
856 	 */
857 	n = start_resid;
858 	if (n == 0)
859 		return (0);
860 
861 	if (limit == RLIM64_INFINITY || limit > MAXOFFSET_T)
862 		limit = MAXOFFSET_T;
863 
864 	ZFS_ENTER(zfsvfs);
865 	ZFS_VERIFY_ZP(zp);
866 
867 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16);
868 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16);
869 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs), NULL,
870 	    &zp->z_size, 8);
871 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
872 	    &zp->z_pflags, 8);
873 
874 	/*
875 	 * In a case vp->v_vfsp != zp->z_zfsvfs->z_vfs (e.g. snapshots) our
876 	 * callers might not be able to detect properly that we are read-only,
877 	 * so check it explicitly here.
878 	 */
879 	if (zfsvfs->z_vfs->vfs_flag & VFS_RDONLY) {
880 		ZFS_EXIT(zfsvfs);
881 		return (SET_ERROR(EROFS));
882 	}
883 
884 	/*
885 	 * If immutable or not appending then return EPERM.
886 	 * Intentionally allow ZFS_READONLY through here.
887 	 * See zfs_zaccess_common()
888 	 */
889 	if ((zp->z_pflags & ZFS_IMMUTABLE) ||
890 	    ((zp->z_pflags & ZFS_APPENDONLY) && !(ioflag & FAPPEND) &&
891 	    (uio->uio_loffset < zp->z_size))) {
892 		ZFS_EXIT(zfsvfs);
893 		return (SET_ERROR(EPERM));
894 	}
895 
896 	zilog = zfsvfs->z_log;
897 
898 	/*
899 	 * Validate file offset
900 	 */
901 	woff = ioflag & FAPPEND ? zp->z_size : uio->uio_loffset;
902 	if (woff < 0) {
903 		ZFS_EXIT(zfsvfs);
904 		return (SET_ERROR(EINVAL));
905 	}
906 
907 	/*
908 	 * Check for mandatory locks before calling rangelock_enter()
909 	 * in order to prevent a deadlock with locks set via fcntl().
910 	 */
911 	if (MANDMODE((mode_t)zp->z_mode) &&
912 	    (error = chklock(vp, FWRITE, woff, n, uio->uio_fmode, ct)) != 0) {
913 		ZFS_EXIT(zfsvfs);
914 		return (error);
915 	}
916 
917 	/*
918 	 * Pre-fault the pages to ensure slow (eg NFS) pages
919 	 * don't hold up txg.
920 	 * Skip this if uio contains loaned arc_buf.
921 	 */
922 	if ((uio->uio_extflg == UIO_XUIO) &&
923 	    (((xuio_t *)uio)->xu_type == UIOTYPE_ZEROCOPY))
924 		xuio = (xuio_t *)uio;
925 	else
926 		uio_prefaultpages(MIN(n, max_blksz), uio);
927 
928 	/*
929 	 * If in append mode, set the io offset pointer to eof.
930 	 */
931 	locked_range_t *lr;
932 	if (ioflag & FAPPEND) {
933 		/*
934 		 * Obtain an appending range lock to guarantee file append
935 		 * semantics.  We reset the write offset once we have the lock.
936 		 */
937 		lr = rangelock_enter(&zp->z_rangelock, 0, n, RL_APPEND);
938 		woff = lr->lr_offset;
939 		if (lr->lr_length == UINT64_MAX) {
940 			/*
941 			 * We overlocked the file because this write will cause
942 			 * the file block size to increase.
943 			 * Note that zp_size cannot change with this lock held.
944 			 */
945 			woff = zp->z_size;
946 		}
947 		uio->uio_loffset = woff;
948 	} else {
949 		/*
950 		 * Note that if the file block size will change as a result of
951 		 * this write, then this range lock will lock the entire file
952 		 * so that we can re-write the block safely.
953 		 */
954 		lr = rangelock_enter(&zp->z_rangelock, woff, n, RL_WRITER);
955 	}
956 
957 	if (woff >= limit) {
958 		rangelock_exit(lr);
959 		ZFS_EXIT(zfsvfs);
960 		return (SET_ERROR(EFBIG));
961 	}
962 
963 	if ((woff + n) > limit || woff > (limit - n))
964 		n = limit - woff;
965 
966 	/* Will this write extend the file length? */
967 	write_eof = (woff + n > zp->z_size);
968 
969 	end_size = MAX(zp->z_size, woff + n);
970 
971 	/*
972 	 * Write the file in reasonable size chunks.  Each chunk is written
973 	 * in a separate transaction; this keeps the intent log records small
974 	 * and allows us to do more fine-grained space accounting.
975 	 */
976 	while (n > 0) {
977 		woff = uio->uio_loffset;
978 
979 		if (zfs_id_overblockquota(zfsvfs, DMU_USERUSED_OBJECT,
980 		    zp->z_uid) ||
981 		    zfs_id_overblockquota(zfsvfs, DMU_GROUPUSED_OBJECT,
982 		    zp->z_gid) ||
983 		    (zp->z_projid != ZFS_DEFAULT_PROJID &&
984 		    zfs_id_overblockquota(zfsvfs, DMU_PROJECTUSED_OBJECT,
985 		    zp->z_projid))) {
986 			error = SET_ERROR(EDQUOT);
987 			break;
988 		}
989 
990 		arc_buf_t *abuf = NULL;
991 		if (xuio) {
992 			ASSERT(i_iov < iovcnt);
993 			aiov = &iovp[i_iov];
994 			abuf = dmu_xuio_arcbuf(xuio, i_iov);
995 			dmu_xuio_clear(xuio, i_iov);
996 			DTRACE_PROBE3(zfs_cp_write, int, i_iov,
997 			    iovec_t *, aiov, arc_buf_t *, abuf);
998 			ASSERT((aiov->iov_base == abuf->b_data) ||
999 			    ((char *)aiov->iov_base - (char *)abuf->b_data +
1000 			    aiov->iov_len == arc_buf_size(abuf)));
1001 			i_iov++;
1002 		} else if (n >= max_blksz && woff >= zp->z_size &&
1003 		    P2PHASE(woff, max_blksz) == 0 &&
1004 		    zp->z_blksz == max_blksz) {
1005 			/*
1006 			 * This write covers a full block.  "Borrow" a buffer
1007 			 * from the dmu so that we can fill it before we enter
1008 			 * a transaction.  This avoids the possibility of
1009 			 * holding up the transaction if the data copy hangs
1010 			 * up on a pagefault (e.g., from an NFS server mapping).
1011 			 */
1012 			size_t cbytes;
1013 
1014 			abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
1015 			    max_blksz);
1016 			ASSERT(abuf != NULL);
1017 			ASSERT(arc_buf_size(abuf) == max_blksz);
1018 			if (error = uiocopy(abuf->b_data, max_blksz,
1019 			    UIO_WRITE, uio, &cbytes)) {
1020 				dmu_return_arcbuf(abuf);
1021 				break;
1022 			}
1023 			ASSERT(cbytes == max_blksz);
1024 		}
1025 
1026 		/*
1027 		 * Start a transaction.
1028 		 */
1029 		tx = dmu_tx_create(zfsvfs->z_os);
1030 		dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
1031 		dmu_tx_hold_write(tx, zp->z_id, woff, MIN(n, max_blksz));
1032 		zfs_sa_upgrade_txholds(tx, zp);
1033 		error = dmu_tx_assign(tx, TXG_WAIT);
1034 		if (error) {
1035 			dmu_tx_abort(tx);
1036 			if (abuf != NULL)
1037 				dmu_return_arcbuf(abuf);
1038 			break;
1039 		}
1040 
1041 		/*
1042 		 * NB: We must call zfs_write_clear_setid_bits_if_necessary
1043 		 * before committing the transaction!
1044 		 */
1045 
1046 		/*
1047 		 * If rangelock_enter() over-locked we grow the blocksize
1048 		 * and then reduce the lock range.  This will only happen
1049 		 * on the first iteration since rangelock_reduce() will
1050 		 * shrink down lr_length to the appropriate size.
1051 		 */
1052 		if (lr->lr_length == UINT64_MAX) {
1053 			uint64_t new_blksz;
1054 
1055 			if (zp->z_blksz > max_blksz) {
1056 				/*
1057 				 * File's blocksize is already larger than the
1058 				 * "recordsize" property.  Only let it grow to
1059 				 * the next power of 2.
1060 				 */
1061 				ASSERT(!ISP2(zp->z_blksz));
1062 				new_blksz = MIN(end_size,
1063 				    1 << highbit64(zp->z_blksz));
1064 			} else {
1065 				new_blksz = MIN(end_size, max_blksz);
1066 			}
1067 			zfs_grow_blocksize(zp, new_blksz, tx);
1068 			rangelock_reduce(lr, woff, n);
1069 		}
1070 
1071 		/*
1072 		 * XXX - should we really limit each write to z_max_blksz?
1073 		 * Perhaps we should use SPA_MAXBLOCKSIZE chunks?
1074 		 */
1075 		nbytes = MIN(n, max_blksz - P2PHASE(woff, max_blksz));
1076 
1077 		if (abuf == NULL) {
1078 			tx_bytes = uio->uio_resid;
1079 			error = dmu_write_uio_dbuf(sa_get_db(zp->z_sa_hdl),
1080 			    uio, nbytes, tx);
1081 			tx_bytes -= uio->uio_resid;
1082 		} else {
1083 			tx_bytes = nbytes;
1084 			ASSERT(xuio == NULL || tx_bytes == aiov->iov_len);
1085 			/*
1086 			 * If this is not a full block write, but we are
1087 			 * extending the file past EOF and this data starts
1088 			 * block-aligned, use assign_arcbuf().  Otherwise,
1089 			 * write via dmu_write().
1090 			 */
1091 			if (tx_bytes < max_blksz && (!write_eof ||
1092 			    aiov->iov_base != abuf->b_data)) {
1093 				ASSERT(xuio);
1094 				dmu_write(zfsvfs->z_os, zp->z_id, woff,
1095 				    aiov->iov_len, aiov->iov_base, tx);
1096 				dmu_return_arcbuf(abuf);
1097 				xuio_stat_wbuf_copied();
1098 			} else {
1099 				ASSERT(xuio || tx_bytes == max_blksz);
1100 				dmu_assign_arcbuf_by_dbuf(
1101 				    sa_get_db(zp->z_sa_hdl), woff, abuf, tx);
1102 			}
1103 			ASSERT(tx_bytes <= uio->uio_resid);
1104 			uioskip(uio, tx_bytes);
1105 		}
1106 		if (tx_bytes && vn_has_cached_data(vp)) {
1107 			update_pages(vp, woff,
1108 			    tx_bytes, zfsvfs->z_os, zp->z_id);
1109 		}
1110 
1111 		/*
1112 		 * If we made no progress, we're done.  If we made even
1113 		 * partial progress, update the znode and ZIL accordingly.
1114 		 */
1115 		if (tx_bytes == 0) {
1116 			(void) sa_update(zp->z_sa_hdl, SA_ZPL_SIZE(zfsvfs),
1117 			    (void *)&zp->z_size, sizeof (uint64_t), tx);
1118 			dmu_tx_commit(tx);
1119 			ASSERT(error != 0);
1120 			break;
1121 		}
1122 
1123 		zfs_write_clear_setid_bits_if_necessary(zfsvfs, zp, cr,
1124 		    &did_clear_setid_bits, tx);
1125 
1126 		zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime,
1127 		    B_TRUE);
1128 
1129 		/*
1130 		 * Update the file size (zp_size) if it has changed;
1131 		 * account for possible concurrent updates.
1132 		 */
1133 		while ((end_size = zp->z_size) < uio->uio_loffset) {
1134 			(void) atomic_cas_64(&zp->z_size, end_size,
1135 			    uio->uio_loffset);
1136 		}
1137 		/*
1138 		 * If we are replaying and eof is non zero then force
1139 		 * the file size to the specified eof. Note, there's no
1140 		 * concurrency during replay.
1141 		 */
1142 		if (zfsvfs->z_replay && zfsvfs->z_replay_eof != 0)
1143 			zp->z_size = zfsvfs->z_replay_eof;
1144 
1145 		/*
1146 		 * Keep track of a possible pre-existing error from a partial
1147 		 * write via dmu_write_uio_dbuf above.
1148 		 */
1149 		prev_error = error;
1150 		error = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
1151 
1152 		/*
1153 		 * NB: During replay, the TX_SETATTR record logged by
1154 		 * zfs_write_clear_setid_bits_if_necessary must precede
1155 		 * any of the TX_WRITE records logged here.
1156 		 */
1157 		zfs_log_write(zilog, tx, TX_WRITE, zp, woff, tx_bytes, ioflag);
1158 		dmu_tx_commit(tx);
1159 
1160 		if (prev_error != 0 || error != 0)
1161 			break;
1162 		ASSERT(tx_bytes == nbytes);
1163 		n -= nbytes;
1164 
1165 		if (!xuio && n > 0)
1166 			uio_prefaultpages(MIN(n, max_blksz), uio);
1167 	}
1168 
1169 	rangelock_exit(lr);
1170 
1171 	/*
1172 	 * If we're in replay mode, or we made no progress, return error.
1173 	 * Otherwise, it's at least a partial write, so it's successful.
1174 	 */
1175 	if (zfsvfs->z_replay || uio->uio_resid == start_resid) {
1176 		ZFS_EXIT(zfsvfs);
1177 		return (error);
1178 	}
1179 
1180 	if (ioflag & (FSYNC | FDSYNC) ||
1181 	    zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1182 		zil_commit(zilog, zp->z_id);
1183 
1184 	ZFS_EXIT(zfsvfs);
1185 	return (0);
1186 }
1187 
1188 /* ARGSUSED */
1189 void
zfs_get_done(zgd_t * zgd,int error)1190 zfs_get_done(zgd_t *zgd, int error)
1191 {
1192 	znode_t *zp = zgd->zgd_private;
1193 	objset_t *os = zp->z_zfsvfs->z_os;
1194 
1195 	if (zgd->zgd_db)
1196 		dmu_buf_rele(zgd->zgd_db, zgd);
1197 
1198 	rangelock_exit(zgd->zgd_lr);
1199 
1200 	/*
1201 	 * Release the vnode asynchronously as we currently have the
1202 	 * txg stopped from syncing.
1203 	 */
1204 	VN_RELE_ASYNC(ZTOV(zp), dsl_pool_vnrele_taskq(dmu_objset_pool(os)));
1205 
1206 	kmem_free(zgd, sizeof (zgd_t));
1207 }
1208 
1209 #ifdef DEBUG
1210 static int zil_fault_io = 0;
1211 #endif
1212 
1213 /*
1214  * Get data to generate a TX_WRITE intent log record.
1215  */
1216 int
zfs_get_data(void * arg,lr_write_t * lr,char * buf,struct lwb * lwb,zio_t * zio)1217 zfs_get_data(void *arg, lr_write_t *lr, char *buf, struct lwb *lwb, zio_t *zio)
1218 {
1219 	zfsvfs_t *zfsvfs = arg;
1220 	objset_t *os = zfsvfs->z_os;
1221 	znode_t *zp;
1222 	uint64_t object = lr->lr_foid;
1223 	uint64_t offset = lr->lr_offset;
1224 	uint64_t size = lr->lr_length;
1225 	dmu_buf_t *db;
1226 	zgd_t *zgd;
1227 	int error = 0;
1228 
1229 	ASSERT3P(lwb, !=, NULL);
1230 	ASSERT3P(zio, !=, NULL);
1231 	ASSERT3U(size, !=, 0);
1232 
1233 	/*
1234 	 * Nothing to do if the file has been removed
1235 	 */
1236 	if (zfs_zget(zfsvfs, object, &zp) != 0)
1237 		return (SET_ERROR(ENOENT));
1238 	if (zp->z_unlinked) {
1239 		/*
1240 		 * Release the vnode asynchronously as we currently have the
1241 		 * txg stopped from syncing.
1242 		 */
1243 		VN_RELE_ASYNC(ZTOV(zp),
1244 		    dsl_pool_vnrele_taskq(dmu_objset_pool(os)));
1245 		return (SET_ERROR(ENOENT));
1246 	}
1247 
1248 	zgd = (zgd_t *)kmem_zalloc(sizeof (zgd_t), KM_SLEEP);
1249 	zgd->zgd_lwb = lwb;
1250 	zgd->zgd_private = zp;
1251 
1252 	/*
1253 	 * Write records come in two flavors: immediate and indirect.
1254 	 * For small writes it's cheaper to store the data with the
1255 	 * log record (immediate); for large writes it's cheaper to
1256 	 * sync the data and get a pointer to it (indirect) so that
1257 	 * we don't have to write the data twice.
1258 	 */
1259 	if (buf != NULL) { /* immediate write */
1260 		zgd->zgd_lr = rangelock_enter(&zp->z_rangelock,
1261 		    offset, size, RL_READER);
1262 		/* test for truncation needs to be done while range locked */
1263 		if (offset >= zp->z_size) {
1264 			error = SET_ERROR(ENOENT);
1265 		} else {
1266 			error = dmu_read(os, object, offset, size, buf,
1267 			    DMU_READ_NO_PREFETCH);
1268 		}
1269 		ASSERT(error == 0 || error == ENOENT);
1270 	} else { /* indirect write */
1271 		/*
1272 		 * Have to lock the whole block to ensure when it's
1273 		 * written out and its checksum is being calculated
1274 		 * that no one can change the data. We need to re-check
1275 		 * blocksize after we get the lock in case it's changed!
1276 		 */
1277 		for (;;) {
1278 			uint64_t blkoff;
1279 			size = zp->z_blksz;
1280 			blkoff = ISP2(size) ? P2PHASE(offset, size) : offset;
1281 			offset -= blkoff;
1282 			zgd->zgd_lr = rangelock_enter(&zp->z_rangelock,
1283 			    offset, size, RL_READER);
1284 			if (zp->z_blksz == size)
1285 				break;
1286 			offset += blkoff;
1287 			rangelock_exit(zgd->zgd_lr);
1288 		}
1289 		/* test for truncation needs to be done while range locked */
1290 		if (lr->lr_offset >= zp->z_size)
1291 			error = SET_ERROR(ENOENT);
1292 #ifdef DEBUG
1293 		if (zil_fault_io) {
1294 			error = SET_ERROR(EIO);
1295 			zil_fault_io = 0;
1296 		}
1297 #endif
1298 		if (error == 0)
1299 			error = dmu_buf_hold(os, object, offset, zgd, &db,
1300 			    DMU_READ_NO_PREFETCH);
1301 
1302 		if (error == 0) {
1303 			blkptr_t *bp = &lr->lr_blkptr;
1304 
1305 			zgd->zgd_db = db;
1306 			zgd->zgd_bp = bp;
1307 
1308 			ASSERT(db->db_offset == offset);
1309 			ASSERT(db->db_size == size);
1310 
1311 			error = dmu_sync(zio, lr->lr_common.lrc_txg,
1312 			    zfs_get_done, zgd);
1313 			ASSERT(error || lr->lr_length <= size);
1314 
1315 			/*
1316 			 * On success, we need to wait for the write I/O
1317 			 * initiated by dmu_sync() to complete before we can
1318 			 * release this dbuf.  We will finish everything up
1319 			 * in the zfs_get_done() callback.
1320 			 */
1321 			if (error == 0)
1322 				return (0);
1323 
1324 			if (error == EALREADY) {
1325 				lr->lr_common.lrc_txtype = TX_WRITE2;
1326 				/*
1327 				 * TX_WRITE2 relies on the data previously
1328 				 * written by the TX_WRITE that caused
1329 				 * EALREADY.  We zero out the BP because
1330 				 * it is the old, currently-on-disk BP.
1331 				 */
1332 				zgd->zgd_bp = NULL;
1333 				BP_ZERO(bp);
1334 				error = 0;
1335 			}
1336 		}
1337 	}
1338 
1339 	zfs_get_done(zgd, error);
1340 
1341 	return (error);
1342 }
1343 
1344 /*ARGSUSED*/
1345 static int
zfs_access(vnode_t * vp,int mode,int flag,cred_t * cr,caller_context_t * ct)1346 zfs_access(vnode_t *vp, int mode, int flag, cred_t *cr,
1347     caller_context_t *ct)
1348 {
1349 	znode_t *zp = VTOZ(vp);
1350 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
1351 	int error;
1352 
1353 	ZFS_ENTER(zfsvfs);
1354 	ZFS_VERIFY_ZP(zp);
1355 
1356 	if (flag & V_ACE_MASK)
1357 		error = zfs_zaccess(zp, mode, flag, B_FALSE, cr);
1358 	else
1359 		error = zfs_zaccess_rwx(zp, mode, flag, cr);
1360 
1361 	ZFS_EXIT(zfsvfs);
1362 	return (error);
1363 }
1364 
1365 /*
1366  * If vnode is for a device return a specfs vnode instead.
1367  */
1368 static int
specvp_check(vnode_t ** vpp,cred_t * cr)1369 specvp_check(vnode_t **vpp, cred_t *cr)
1370 {
1371 	int error = 0;
1372 
1373 	if (IS_DEVVP(*vpp)) {
1374 		struct vnode *svp;
1375 
1376 		svp = specvp(*vpp, (*vpp)->v_rdev, (*vpp)->v_type, cr);
1377 		VN_RELE(*vpp);
1378 		if (svp == NULL)
1379 			error = SET_ERROR(ENOSYS);
1380 		*vpp = svp;
1381 	}
1382 	return (error);
1383 }
1384 
1385 
1386 /*
1387  * Lookup an entry in a directory, or an extended attribute directory.
1388  * If it exists, return a held vnode reference for it.
1389  *
1390  *	IN:	dvp	- vnode of directory to search.
1391  *		nm	- name of entry to lookup.
1392  *		pnp	- full pathname to lookup [UNUSED].
1393  *		flags	- LOOKUP_XATTR set if looking for an attribute.
1394  *		rdir	- root directory vnode [UNUSED].
1395  *		cr	- credentials of caller.
1396  *		ct	- caller context
1397  *		direntflags - directory lookup flags
1398  *		realpnp - returned pathname.
1399  *
1400  *	OUT:	vpp	- vnode of located entry, NULL if not found.
1401  *
1402  *	RETURN:	0 on success, error code on failure.
1403  *
1404  * Timestamps:
1405  *	NA
1406  */
1407 /* ARGSUSED */
1408 static int
zfs_lookup(vnode_t * dvp,char * nm,vnode_t ** vpp,struct pathname * pnp,int flags,vnode_t * rdir,cred_t * cr,caller_context_t * ct,int * direntflags,pathname_t * realpnp)1409 zfs_lookup(vnode_t *dvp, char *nm, vnode_t **vpp, struct pathname *pnp,
1410     int flags, vnode_t *rdir, cred_t *cr,  caller_context_t *ct,
1411     int *direntflags, pathname_t *realpnp)
1412 {
1413 	znode_t *zdp = VTOZ(dvp);
1414 	zfsvfs_t *zfsvfs = zdp->z_zfsvfs;
1415 	int	error = 0;
1416 	boolean_t skipaclchk = ((flags & LOOKUP_NOACLCHECK) != 0);
1417 
1418 	/*
1419 	 * LOOKUP_NOACLCHECK is specified to skip EXECUTE checks for
1420 	 * consumers (like SMB) that bypass traverse checking.
1421 	 * Turn it off here so it can't accidentally be used
1422 	 * for other checks.
1423 	 */
1424 	flags &= ~LOOKUP_NOACLCHECK;
1425 
1426 	/*
1427 	 * Fast path lookup, however we must skip DNLC lookup
1428 	 * for case folding or normalizing lookups because the
1429 	 * DNLC code only stores the passed in name.  This means
1430 	 * creating 'a' and removing 'A' on a case insensitive
1431 	 * file system would work, but DNLC still thinks 'a'
1432 	 * exists and won't let you create it again on the next
1433 	 * pass through fast path.
1434 	 */
1435 	if (!(flags & (LOOKUP_XATTR | FIGNORECASE))) {
1436 
1437 		if (dvp->v_type != VDIR) {
1438 			return (SET_ERROR(ENOTDIR));
1439 		} else if (zdp->z_sa_hdl == NULL) {
1440 			return (SET_ERROR(EIO));
1441 		}
1442 
1443 		if (nm[0] == 0 || (nm[0] == '.' && nm[1] == '\0')) {
1444 			error = zfs_fastaccesschk_execute(zdp, cr, skipaclchk);
1445 			if (!error) {
1446 				*vpp = dvp;
1447 				VN_HOLD(*vpp);
1448 				return (0);
1449 			}
1450 			return (error);
1451 		} else if (!zdp->z_zfsvfs->z_norm &&
1452 		    (zdp->z_zfsvfs->z_case == ZFS_CASE_SENSITIVE)) {
1453 
1454 			vnode_t *tvp = dnlc_lookup(dvp, nm);
1455 
1456 			if (tvp) {
1457 				error = zfs_fastaccesschk_execute(zdp, cr,
1458 				    skipaclchk);
1459 				if (error) {
1460 					VN_RELE(tvp);
1461 					return (error);
1462 				}
1463 				if (tvp == DNLC_NO_VNODE) {
1464 					VN_RELE(tvp);
1465 					return (SET_ERROR(ENOENT));
1466 				} else {
1467 					*vpp = tvp;
1468 					return (specvp_check(vpp, cr));
1469 				}
1470 			}
1471 		}
1472 	}
1473 
1474 	DTRACE_PROBE2(zfs__fastpath__lookup__miss, vnode_t *, dvp, char *, nm);
1475 
1476 	ZFS_ENTER(zfsvfs);
1477 	ZFS_VERIFY_ZP(zdp);
1478 
1479 	*vpp = NULL;
1480 
1481 	if (flags & LOOKUP_XATTR) {
1482 		/*
1483 		 * If the xattr property is off, refuse the lookup request.
1484 		 */
1485 		if (!(zfsvfs->z_vfs->vfs_flag & VFS_XATTR)) {
1486 			ZFS_EXIT(zfsvfs);
1487 			return (SET_ERROR(EINVAL));
1488 		}
1489 
1490 		/*
1491 		 * We don't allow recursive attributes..
1492 		 * Maybe someday we will.
1493 		 */
1494 		if (zdp->z_pflags & ZFS_XATTR) {
1495 			ZFS_EXIT(zfsvfs);
1496 			return (SET_ERROR(EINVAL));
1497 		}
1498 
1499 		if (error = zfs_get_xattrdir(VTOZ(dvp), vpp, cr, flags)) {
1500 			ZFS_EXIT(zfsvfs);
1501 			return (error);
1502 		}
1503 
1504 		/*
1505 		 * Do we have permission to get into attribute directory?
1506 		 */
1507 
1508 		if (error = zfs_zaccess(VTOZ(*vpp), ACE_EXECUTE, 0,
1509 		    skipaclchk, cr)) {
1510 			VN_RELE(*vpp);
1511 			*vpp = NULL;
1512 		}
1513 
1514 		ZFS_EXIT(zfsvfs);
1515 		return (error);
1516 	}
1517 
1518 	if (dvp->v_type != VDIR) {
1519 		ZFS_EXIT(zfsvfs);
1520 		return (SET_ERROR(ENOTDIR));
1521 	}
1522 
1523 	/*
1524 	 * Check accessibility of directory.
1525 	 */
1526 
1527 	if (error = zfs_zaccess(zdp, ACE_EXECUTE, 0, skipaclchk, cr)) {
1528 		ZFS_EXIT(zfsvfs);
1529 		return (error);
1530 	}
1531 
1532 	if (zfsvfs->z_utf8 && u8_validate(nm, strlen(nm),
1533 	    NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
1534 		ZFS_EXIT(zfsvfs);
1535 		return (SET_ERROR(EILSEQ));
1536 	}
1537 
1538 	error = zfs_dirlook(zdp, nm, vpp, flags, direntflags, realpnp);
1539 	if (error == 0)
1540 		error = specvp_check(vpp, cr);
1541 
1542 	ZFS_EXIT(zfsvfs);
1543 	return (error);
1544 }
1545 
1546 /*
1547  * Attempt to create a new entry in a directory.  If the entry
1548  * already exists, truncate the file if permissible, else return
1549  * an error.  Return the vp of the created or trunc'd file.
1550  *
1551  *	IN:	dvp	- vnode of directory to put new file entry in.
1552  *		name	- name of new file entry.
1553  *		vap	- attributes of new file.
1554  *		excl	- flag indicating exclusive or non-exclusive mode.
1555  *		mode	- mode to open file with.
1556  *		cr	- credentials of caller.
1557  *		flag	- large file flag [UNUSED].
1558  *		ct	- caller context
1559  *		vsecp	- ACL to be set
1560  *
1561  *	OUT:	vpp	- vnode of created or trunc'd entry.
1562  *
1563  *	RETURN:	0 on success, error code on failure.
1564  *
1565  * Timestamps:
1566  *	dvp - ctime|mtime updated if new entry created
1567  *	 vp - ctime|mtime always, atime if new
1568  */
1569 
1570 /* ARGSUSED */
1571 static int
zfs_create(vnode_t * dvp,char * name,vattr_t * vap,vcexcl_t excl,int mode,vnode_t ** vpp,cred_t * cr,int flag,caller_context_t * ct,vsecattr_t * vsecp)1572 zfs_create(vnode_t *dvp, char *name, vattr_t *vap, vcexcl_t excl,
1573     int mode, vnode_t **vpp, cred_t *cr, int flag, caller_context_t *ct,
1574     vsecattr_t *vsecp)
1575 {
1576 	znode_t		*zp, *dzp = VTOZ(dvp);
1577 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1578 	zilog_t		*zilog;
1579 	objset_t	*os;
1580 	zfs_dirlock_t	*dl;
1581 	dmu_tx_t	*tx;
1582 	int		error;
1583 	ksid_t		*ksid;
1584 	uid_t		uid;
1585 	gid_t		gid = crgetgid(cr);
1586 	zfs_acl_ids_t   acl_ids;
1587 	boolean_t	fuid_dirtied;
1588 	boolean_t	have_acl = B_FALSE;
1589 	boolean_t	waited = B_FALSE;
1590 
1591 	/*
1592 	 * If we have an ephemeral id, ACL, or XVATTR then
1593 	 * make sure file system is at proper version
1594 	 */
1595 
1596 	ksid = crgetsid(cr, KSID_OWNER);
1597 	if (ksid)
1598 		uid = ksid_getid(ksid);
1599 	else
1600 		uid = crgetuid(cr);
1601 
1602 	if (zfsvfs->z_use_fuids == B_FALSE &&
1603 	    (vsecp || (vap->va_mask & AT_XVATTR) ||
1604 	    IS_EPHEMERAL(uid) || IS_EPHEMERAL(gid)))
1605 		return (SET_ERROR(EINVAL));
1606 
1607 	ZFS_ENTER(zfsvfs);
1608 	ZFS_VERIFY_ZP(dzp);
1609 	os = zfsvfs->z_os;
1610 	zilog = zfsvfs->z_log;
1611 
1612 	if (zfsvfs->z_utf8 && u8_validate(name, strlen(name),
1613 	    NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
1614 		ZFS_EXIT(zfsvfs);
1615 		return (SET_ERROR(EILSEQ));
1616 	}
1617 
1618 	if (vap->va_mask & AT_XVATTR) {
1619 		if ((error = secpolicy_xvattr((xvattr_t *)vap,
1620 		    crgetuid(cr), cr, vap->va_type)) != 0) {
1621 			ZFS_EXIT(zfsvfs);
1622 			return (error);
1623 		}
1624 	}
1625 top:
1626 	*vpp = NULL;
1627 
1628 	if ((vap->va_mode & VSVTX) && secpolicy_vnode_stky_modify(cr))
1629 		vap->va_mode &= ~VSVTX;
1630 
1631 	if (*name == '\0') {
1632 		/*
1633 		 * Null component name refers to the directory itself.
1634 		 */
1635 		VN_HOLD(dvp);
1636 		zp = dzp;
1637 		dl = NULL;
1638 		error = 0;
1639 	} else {
1640 		/* possible VN_HOLD(zp) */
1641 		int zflg = 0;
1642 
1643 		if (flag & FIGNORECASE)
1644 			zflg |= ZCILOOK;
1645 
1646 		error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg,
1647 		    NULL, NULL);
1648 		if (error) {
1649 			if (have_acl)
1650 				zfs_acl_ids_free(&acl_ids);
1651 			if (strcmp(name, "..") == 0)
1652 				error = SET_ERROR(EISDIR);
1653 			ZFS_EXIT(zfsvfs);
1654 			return (error);
1655 		}
1656 	}
1657 
1658 	if (zp == NULL) {
1659 		uint64_t txtype;
1660 		uint64_t projid = ZFS_DEFAULT_PROJID;
1661 
1662 		/*
1663 		 * Create a new file object and update the directory
1664 		 * to reference it.
1665 		 */
1666 		if (error = zfs_zaccess(dzp, ACE_ADD_FILE, 0, B_FALSE, cr)) {
1667 			if (have_acl)
1668 				zfs_acl_ids_free(&acl_ids);
1669 			goto out;
1670 		}
1671 
1672 		/*
1673 		 * We only support the creation of regular files in
1674 		 * extended attribute directories.
1675 		 */
1676 
1677 		if ((dzp->z_pflags & ZFS_XATTR) &&
1678 		    (vap->va_type != VREG)) {
1679 			if (have_acl)
1680 				zfs_acl_ids_free(&acl_ids);
1681 			error = SET_ERROR(EINVAL);
1682 			goto out;
1683 		}
1684 
1685 		if (!have_acl && (error = zfs_acl_ids_create(dzp, 0, vap,
1686 		    cr, vsecp, &acl_ids)) != 0)
1687 			goto out;
1688 		have_acl = B_TRUE;
1689 
1690 		if (vap->va_type == VREG || vap->va_type == VDIR)
1691 			projid = zfs_inherit_projid(dzp);
1692 		if (zfs_acl_ids_overquota(zfsvfs, &acl_ids, projid)) {
1693 			zfs_acl_ids_free(&acl_ids);
1694 			error = SET_ERROR(EDQUOT);
1695 			goto out;
1696 		}
1697 
1698 		tx = dmu_tx_create(os);
1699 
1700 		dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
1701 		    ZFS_SA_BASE_ATTR_SIZE);
1702 
1703 		fuid_dirtied = zfsvfs->z_fuid_dirty;
1704 		if (fuid_dirtied)
1705 			zfs_fuid_txhold(zfsvfs, tx);
1706 		dmu_tx_hold_zap(tx, dzp->z_id, TRUE, name);
1707 		dmu_tx_hold_sa(tx, dzp->z_sa_hdl, B_FALSE);
1708 		if (!zfsvfs->z_use_sa &&
1709 		    acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
1710 			dmu_tx_hold_write(tx, DMU_NEW_OBJECT,
1711 			    0, acl_ids.z_aclp->z_acl_bytes);
1712 		}
1713 		error = dmu_tx_assign(tx,
1714 		    (waited ? TXG_NOTHROTTLE : 0) | TXG_NOWAIT);
1715 		if (error) {
1716 			zfs_dirent_unlock(dl);
1717 			if (error == ERESTART) {
1718 				waited = B_TRUE;
1719 				dmu_tx_wait(tx);
1720 				dmu_tx_abort(tx);
1721 				goto top;
1722 			}
1723 			zfs_acl_ids_free(&acl_ids);
1724 			dmu_tx_abort(tx);
1725 			ZFS_EXIT(zfsvfs);
1726 			return (error);
1727 		}
1728 		zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
1729 
1730 		if (fuid_dirtied)
1731 			zfs_fuid_sync(zfsvfs, tx);
1732 
1733 		(void) zfs_link_create(dl, zp, tx, ZNEW);
1734 		txtype = zfs_log_create_txtype(Z_FILE, vsecp, vap);
1735 		if (flag & FIGNORECASE)
1736 			txtype |= TX_CI;
1737 		zfs_log_create(zilog, tx, txtype, dzp, zp, name,
1738 		    vsecp, acl_ids.z_fuidp, vap);
1739 		zfs_acl_ids_free(&acl_ids);
1740 		dmu_tx_commit(tx);
1741 	} else {
1742 		int aflags = (flag & FAPPEND) ? V_APPEND : 0;
1743 
1744 		if (have_acl)
1745 			zfs_acl_ids_free(&acl_ids);
1746 		have_acl = B_FALSE;
1747 
1748 		/*
1749 		 * A directory entry already exists for this name.
1750 		 */
1751 		/*
1752 		 * Can't truncate an existing file if in exclusive mode.
1753 		 */
1754 		if (excl == EXCL) {
1755 			error = SET_ERROR(EEXIST);
1756 			goto out;
1757 		}
1758 		/*
1759 		 * Can't open a directory for writing.
1760 		 */
1761 		if ((ZTOV(zp)->v_type == VDIR) && (mode & S_IWRITE)) {
1762 			error = SET_ERROR(EISDIR);
1763 			goto out;
1764 		}
1765 		/*
1766 		 * Verify requested access to file.
1767 		 */
1768 		if (mode && (error = zfs_zaccess_rwx(zp, mode, aflags, cr))) {
1769 			goto out;
1770 		}
1771 
1772 		mutex_enter(&dzp->z_lock);
1773 		dzp->z_seq++;
1774 		mutex_exit(&dzp->z_lock);
1775 
1776 		/*
1777 		 * Truncate regular files if requested.
1778 		 */
1779 		if ((ZTOV(zp)->v_type == VREG) &&
1780 		    (vap->va_mask & AT_SIZE) && (vap->va_size == 0)) {
1781 			/* we can't hold any locks when calling zfs_freesp() */
1782 			zfs_dirent_unlock(dl);
1783 			dl = NULL;
1784 			error = zfs_freesp(zp, 0, 0, mode, TRUE);
1785 			if (error == 0) {
1786 				vnevent_create(ZTOV(zp), ct);
1787 			}
1788 		}
1789 	}
1790 out:
1791 
1792 	if (dl)
1793 		zfs_dirent_unlock(dl);
1794 
1795 	if (error) {
1796 		if (zp)
1797 			VN_RELE(ZTOV(zp));
1798 	} else {
1799 		*vpp = ZTOV(zp);
1800 		error = specvp_check(vpp, cr);
1801 	}
1802 
1803 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
1804 		zil_commit(zilog, 0);
1805 
1806 	ZFS_EXIT(zfsvfs);
1807 	return (error);
1808 }
1809 
1810 /*
1811  * Remove an entry from a directory.
1812  *
1813  *	IN:	dvp	- vnode of directory to remove entry from.
1814  *		name	- name of entry to remove.
1815  *		cr	- credentials of caller.
1816  *		ct	- caller context
1817  *		flags	- case flags
1818  *
1819  *	RETURN:	0 on success, error code on failure.
1820  *
1821  * Timestamps:
1822  *	dvp - ctime|mtime
1823  *	 vp - ctime (if nlink > 0)
1824  */
1825 
1826 uint64_t null_xattr = 0;
1827 
1828 /*ARGSUSED*/
1829 static int
zfs_remove(vnode_t * dvp,char * name,cred_t * cr,caller_context_t * ct,int flags)1830 zfs_remove(vnode_t *dvp, char *name, cred_t *cr, caller_context_t *ct,
1831     int flags)
1832 {
1833 	znode_t		*zp, *dzp = VTOZ(dvp);
1834 	znode_t		*xzp;
1835 	vnode_t		*vp;
1836 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
1837 	zilog_t		*zilog;
1838 	uint64_t	acl_obj, xattr_obj;
1839 	uint64_t	xattr_obj_unlinked = 0;
1840 	uint64_t	obj = 0;
1841 	zfs_dirlock_t	*dl;
1842 	dmu_tx_t	*tx;
1843 	boolean_t	may_delete_now, delete_now = FALSE;
1844 	boolean_t	unlinked, toobig = FALSE;
1845 	uint64_t	txtype;
1846 	pathname_t	*realnmp = NULL;
1847 	pathname_t	realnm;
1848 	int		error;
1849 	int		zflg = ZEXISTS;
1850 	boolean_t	waited = B_FALSE;
1851 
1852 	ZFS_ENTER(zfsvfs);
1853 	ZFS_VERIFY_ZP(dzp);
1854 	zilog = zfsvfs->z_log;
1855 
1856 	if (flags & FIGNORECASE) {
1857 		zflg |= ZCILOOK;
1858 		pn_alloc(&realnm);
1859 		realnmp = &realnm;
1860 	}
1861 
1862 top:
1863 	xattr_obj = 0;
1864 	xzp = NULL;
1865 	/*
1866 	 * Attempt to lock directory; fail if entry doesn't exist.
1867 	 */
1868 	if (error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg,
1869 	    NULL, realnmp)) {
1870 		if (realnmp)
1871 			pn_free(realnmp);
1872 		ZFS_EXIT(zfsvfs);
1873 		return (error);
1874 	}
1875 
1876 	vp = ZTOV(zp);
1877 
1878 	if (error = zfs_zaccess_delete(dzp, zp, cr)) {
1879 		goto out;
1880 	}
1881 
1882 	/*
1883 	 * Need to use rmdir for removing directories.
1884 	 */
1885 	if (vp->v_type == VDIR) {
1886 		error = SET_ERROR(EPERM);
1887 		goto out;
1888 	}
1889 
1890 	vnevent_remove(vp, dvp, name, ct);
1891 
1892 	if (realnmp)
1893 		dnlc_remove(dvp, realnmp->pn_buf);
1894 	else
1895 		dnlc_remove(dvp, name);
1896 
1897 	mutex_enter(&vp->v_lock);
1898 	may_delete_now = vp->v_count == 1 && !vn_has_cached_data(vp);
1899 	mutex_exit(&vp->v_lock);
1900 
1901 	/*
1902 	 * We may delete the znode now, or we may put it in the unlinked set;
1903 	 * it depends on whether we're the last link, and on whether there are
1904 	 * other holds on the vnode.  So we dmu_tx_hold() the right things to
1905 	 * allow for either case.
1906 	 */
1907 	obj = zp->z_id;
1908 	tx = dmu_tx_create(zfsvfs->z_os);
1909 	dmu_tx_hold_zap(tx, dzp->z_id, FALSE, name);
1910 	dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
1911 	zfs_sa_upgrade_txholds(tx, zp);
1912 	zfs_sa_upgrade_txholds(tx, dzp);
1913 	if (may_delete_now) {
1914 		toobig =
1915 		    zp->z_size > zp->z_blksz * DMU_MAX_DELETEBLKCNT;
1916 		/* if the file is too big, only hold_free a token amount */
1917 		dmu_tx_hold_free(tx, zp->z_id, 0,
1918 		    (toobig ? DMU_MAX_ACCESS : DMU_OBJECT_END));
1919 	}
1920 
1921 	/* are there any extended attributes? */
1922 	error = sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
1923 	    &xattr_obj, sizeof (xattr_obj));
1924 	if (error == 0 && xattr_obj) {
1925 		error = zfs_zget(zfsvfs, xattr_obj, &xzp);
1926 		ASSERT0(error);
1927 		dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
1928 		dmu_tx_hold_sa(tx, xzp->z_sa_hdl, B_FALSE);
1929 	}
1930 
1931 	mutex_enter(&zp->z_lock);
1932 	if ((acl_obj = zfs_external_acl(zp)) != 0 && may_delete_now)
1933 		dmu_tx_hold_free(tx, acl_obj, 0, DMU_OBJECT_END);
1934 	mutex_exit(&zp->z_lock);
1935 
1936 	/* charge as an update -- would be nice not to charge at all */
1937 	dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
1938 
1939 	/*
1940 	 * Mark this transaction as typically resulting in a net free of space
1941 	 */
1942 	dmu_tx_mark_netfree(tx);
1943 
1944 	error = dmu_tx_assign(tx, (waited ? TXG_NOTHROTTLE : 0) | TXG_NOWAIT);
1945 	if (error) {
1946 		zfs_dirent_unlock(dl);
1947 		VN_RELE(vp);
1948 		if (xzp)
1949 			VN_RELE(ZTOV(xzp));
1950 		if (error == ERESTART) {
1951 			waited = B_TRUE;
1952 			dmu_tx_wait(tx);
1953 			dmu_tx_abort(tx);
1954 			goto top;
1955 		}
1956 		if (realnmp)
1957 			pn_free(realnmp);
1958 		dmu_tx_abort(tx);
1959 		ZFS_EXIT(zfsvfs);
1960 		return (error);
1961 	}
1962 
1963 	/*
1964 	 * Remove the directory entry.
1965 	 */
1966 	error = zfs_link_destroy(dl, zp, tx, zflg, &unlinked);
1967 
1968 	if (error) {
1969 		dmu_tx_commit(tx);
1970 		goto out;
1971 	}
1972 
1973 	if (unlinked) {
1974 		/*
1975 		 * Hold z_lock so that we can make sure that the ACL obj
1976 		 * hasn't changed.  Could have been deleted due to
1977 		 * zfs_sa_upgrade().
1978 		 */
1979 		mutex_enter(&zp->z_lock);
1980 		mutex_enter(&vp->v_lock);
1981 		(void) sa_lookup(zp->z_sa_hdl, SA_ZPL_XATTR(zfsvfs),
1982 		    &xattr_obj_unlinked, sizeof (xattr_obj_unlinked));
1983 		delete_now = may_delete_now && !toobig &&
1984 		    vp->v_count == 1 && !vn_has_cached_data(vp) &&
1985 		    xattr_obj == xattr_obj_unlinked && zfs_external_acl(zp) ==
1986 		    acl_obj;
1987 		mutex_exit(&vp->v_lock);
1988 	}
1989 
1990 	if (delete_now) {
1991 		if (xattr_obj_unlinked) {
1992 			ASSERT3U(xzp->z_links, ==, 2);
1993 			mutex_enter(&xzp->z_lock);
1994 			xzp->z_unlinked = 1;
1995 			xzp->z_links = 0;
1996 			error = sa_update(xzp->z_sa_hdl, SA_ZPL_LINKS(zfsvfs),
1997 			    &xzp->z_links, sizeof (xzp->z_links), tx);
1998 			ASSERT3U(error,  ==,  0);
1999 			mutex_exit(&xzp->z_lock);
2000 			zfs_unlinked_add(xzp, tx);
2001 
2002 			if (zp->z_is_sa)
2003 				error = sa_remove(zp->z_sa_hdl,
2004 				    SA_ZPL_XATTR(zfsvfs), tx);
2005 			else
2006 				error = sa_update(zp->z_sa_hdl,
2007 				    SA_ZPL_XATTR(zfsvfs), &null_xattr,
2008 				    sizeof (uint64_t), tx);
2009 			ASSERT0(error);
2010 		}
2011 		mutex_enter(&vp->v_lock);
2012 		VN_RELE_LOCKED(vp);
2013 		ASSERT0(vp->v_count);
2014 		mutex_exit(&vp->v_lock);
2015 		mutex_exit(&zp->z_lock);
2016 		zfs_znode_delete(zp, tx);
2017 	} else if (unlinked) {
2018 		mutex_exit(&zp->z_lock);
2019 		zfs_unlinked_add(zp, tx);
2020 	}
2021 
2022 	txtype = TX_REMOVE;
2023 	if (flags & FIGNORECASE)
2024 		txtype |= TX_CI;
2025 	zfs_log_remove(zilog, tx, txtype, dzp, name, obj, unlinked);
2026 
2027 	dmu_tx_commit(tx);
2028 out:
2029 	if (realnmp)
2030 		pn_free(realnmp);
2031 
2032 	zfs_dirent_unlock(dl);
2033 
2034 	if (!delete_now)
2035 		VN_RELE(vp);
2036 	if (xzp)
2037 		VN_RELE(ZTOV(xzp));
2038 
2039 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
2040 		zil_commit(zilog, 0);
2041 
2042 	ZFS_EXIT(zfsvfs);
2043 	return (error);
2044 }
2045 
2046 /*
2047  * Create a new directory and insert it into dvp using the name
2048  * provided.  Return a pointer to the inserted directory.
2049  *
2050  *	IN:	dvp	- vnode of directory to add subdir to.
2051  *		dirname	- name of new directory.
2052  *		vap	- attributes of new directory.
2053  *		cr	- credentials of caller.
2054  *		ct	- caller context
2055  *		flags	- case flags
2056  *		vsecp	- ACL to be set
2057  *
2058  *	OUT:	vpp	- vnode of created directory.
2059  *
2060  *	RETURN:	0 on success, error code on failure.
2061  *
2062  * Timestamps:
2063  *	dvp - ctime|mtime updated
2064  *	 vp - ctime|mtime|atime updated
2065  */
2066 /*ARGSUSED*/
2067 static int
zfs_mkdir(vnode_t * dvp,char * dirname,vattr_t * vap,vnode_t ** vpp,cred_t * cr,caller_context_t * ct,int flags,vsecattr_t * vsecp)2068 zfs_mkdir(vnode_t *dvp, char *dirname, vattr_t *vap, vnode_t **vpp, cred_t *cr,
2069     caller_context_t *ct, int flags, vsecattr_t *vsecp)
2070 {
2071 	znode_t		*zp, *dzp = VTOZ(dvp);
2072 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
2073 	zilog_t		*zilog;
2074 	zfs_dirlock_t	*dl;
2075 	uint64_t	txtype;
2076 	dmu_tx_t	*tx;
2077 	int		error;
2078 	int		zf = ZNEW;
2079 	ksid_t		*ksid;
2080 	uid_t		uid;
2081 	gid_t		gid = crgetgid(cr);
2082 	zfs_acl_ids_t   acl_ids;
2083 	boolean_t	fuid_dirtied;
2084 	boolean_t	waited = B_FALSE;
2085 
2086 	ASSERT(vap->va_type == VDIR);
2087 
2088 	/*
2089 	 * If we have an ephemeral id, ACL, or XVATTR then
2090 	 * make sure file system is at proper version
2091 	 */
2092 
2093 	ksid = crgetsid(cr, KSID_OWNER);
2094 	if (ksid)
2095 		uid = ksid_getid(ksid);
2096 	else
2097 		uid = crgetuid(cr);
2098 	if (zfsvfs->z_use_fuids == B_FALSE &&
2099 	    (vsecp || (vap->va_mask & AT_XVATTR) ||
2100 	    IS_EPHEMERAL(uid) || IS_EPHEMERAL(gid)))
2101 		return (SET_ERROR(EINVAL));
2102 
2103 	ZFS_ENTER(zfsvfs);
2104 	ZFS_VERIFY_ZP(dzp);
2105 	zilog = zfsvfs->z_log;
2106 
2107 	if (dzp->z_pflags & ZFS_XATTR) {
2108 		ZFS_EXIT(zfsvfs);
2109 		return (SET_ERROR(EINVAL));
2110 	}
2111 
2112 	if (zfsvfs->z_utf8 && u8_validate(dirname,
2113 	    strlen(dirname), NULL, U8_VALIDATE_ENTIRE, &error) < 0) {
2114 		ZFS_EXIT(zfsvfs);
2115 		return (SET_ERROR(EILSEQ));
2116 	}
2117 	if (flags & FIGNORECASE)
2118 		zf |= ZCILOOK;
2119 
2120 	if (vap->va_mask & AT_XVATTR) {
2121 		if ((error = secpolicy_xvattr((xvattr_t *)vap,
2122 		    crgetuid(cr), cr, vap->va_type)) != 0) {
2123 			ZFS_EXIT(zfsvfs);
2124 			return (error);
2125 		}
2126 	}
2127 
2128 	if ((error = zfs_acl_ids_create(dzp, 0, vap, cr,
2129 	    vsecp, &acl_ids)) != 0) {
2130 		ZFS_EXIT(zfsvfs);
2131 		return (error);
2132 	}
2133 	/*
2134 	 * First make sure the new directory doesn't exist.
2135 	 *
2136 	 * Existence is checked first to make sure we don't return
2137 	 * EACCES instead of EEXIST which can cause some applications
2138 	 * to fail.
2139 	 */
2140 top:
2141 	*vpp = NULL;
2142 
2143 	if (error = zfs_dirent_lock(&dl, dzp, dirname, &zp, zf,
2144 	    NULL, NULL)) {
2145 		zfs_acl_ids_free(&acl_ids);
2146 		ZFS_EXIT(zfsvfs);
2147 		return (error);
2148 	}
2149 
2150 	if (error = zfs_zaccess(dzp, ACE_ADD_SUBDIRECTORY, 0, B_FALSE, cr)) {
2151 		zfs_acl_ids_free(&acl_ids);
2152 		zfs_dirent_unlock(dl);
2153 		ZFS_EXIT(zfsvfs);
2154 		return (error);
2155 	}
2156 
2157 	if (zfs_acl_ids_overquota(zfsvfs, &acl_ids, zfs_inherit_projid(dzp))) {
2158 		zfs_acl_ids_free(&acl_ids);
2159 		zfs_dirent_unlock(dl);
2160 		ZFS_EXIT(zfsvfs);
2161 		return (SET_ERROR(EDQUOT));
2162 	}
2163 
2164 	/*
2165 	 * Add a new entry to the directory.
2166 	 */
2167 	tx = dmu_tx_create(zfsvfs->z_os);
2168 	dmu_tx_hold_zap(tx, dzp->z_id, TRUE, dirname);
2169 	dmu_tx_hold_zap(tx, DMU_NEW_OBJECT, FALSE, NULL);
2170 	fuid_dirtied = zfsvfs->z_fuid_dirty;
2171 	if (fuid_dirtied)
2172 		zfs_fuid_txhold(zfsvfs, tx);
2173 	if (!zfsvfs->z_use_sa && acl_ids.z_aclp->z_acl_bytes > ZFS_ACE_SPACE) {
2174 		dmu_tx_hold_write(tx, DMU_NEW_OBJECT, 0,
2175 		    acl_ids.z_aclp->z_acl_bytes);
2176 	}
2177 
2178 	dmu_tx_hold_sa_create(tx, acl_ids.z_aclp->z_acl_bytes +
2179 	    ZFS_SA_BASE_ATTR_SIZE);
2180 
2181 	error = dmu_tx_assign(tx, (waited ? TXG_NOTHROTTLE : 0) | TXG_NOWAIT);
2182 	if (error) {
2183 		zfs_dirent_unlock(dl);
2184 		if (error == ERESTART) {
2185 			waited = B_TRUE;
2186 			dmu_tx_wait(tx);
2187 			dmu_tx_abort(tx);
2188 			goto top;
2189 		}
2190 		zfs_acl_ids_free(&acl_ids);
2191 		dmu_tx_abort(tx);
2192 		ZFS_EXIT(zfsvfs);
2193 		return (error);
2194 	}
2195 
2196 	/*
2197 	 * Create new node.
2198 	 */
2199 	zfs_mknode(dzp, vap, tx, cr, 0, &zp, &acl_ids);
2200 
2201 	if (fuid_dirtied)
2202 		zfs_fuid_sync(zfsvfs, tx);
2203 
2204 	/*
2205 	 * Now put new name in parent dir.
2206 	 */
2207 	(void) zfs_link_create(dl, zp, tx, ZNEW);
2208 
2209 	*vpp = ZTOV(zp);
2210 
2211 	txtype = zfs_log_create_txtype(Z_DIR, vsecp, vap);
2212 	if (flags & FIGNORECASE)
2213 		txtype |= TX_CI;
2214 	zfs_log_create(zilog, tx, txtype, dzp, zp, dirname, vsecp,
2215 	    acl_ids.z_fuidp, vap);
2216 
2217 	zfs_acl_ids_free(&acl_ids);
2218 
2219 	dmu_tx_commit(tx);
2220 
2221 	zfs_dirent_unlock(dl);
2222 
2223 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
2224 		zil_commit(zilog, 0);
2225 
2226 	ZFS_EXIT(zfsvfs);
2227 	return (0);
2228 }
2229 
2230 /*
2231  * Remove a directory subdir entry.  If the current working
2232  * directory is the same as the subdir to be removed, the
2233  * remove will fail.
2234  *
2235  *	IN:	dvp	- vnode of directory to remove from.
2236  *		name	- name of directory to be removed.
2237  *		cwd	- vnode of current working directory.
2238  *		cr	- credentials of caller.
2239  *		ct	- caller context
2240  *		flags	- case flags
2241  *
2242  *	RETURN:	0 on success, error code on failure.
2243  *
2244  * Timestamps:
2245  *	dvp - ctime|mtime updated
2246  */
2247 /*ARGSUSED*/
2248 static int
zfs_rmdir(vnode_t * dvp,char * name,vnode_t * cwd,cred_t * cr,caller_context_t * ct,int flags)2249 zfs_rmdir(vnode_t *dvp, char *name, vnode_t *cwd, cred_t *cr,
2250     caller_context_t *ct, int flags)
2251 {
2252 	znode_t		*dzp = VTOZ(dvp);
2253 	znode_t		*zp;
2254 	vnode_t		*vp;
2255 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
2256 	zilog_t		*zilog;
2257 	zfs_dirlock_t	*dl;
2258 	dmu_tx_t	*tx;
2259 	int		error;
2260 	int		zflg = ZEXISTS;
2261 	boolean_t	waited = B_FALSE;
2262 
2263 	ZFS_ENTER(zfsvfs);
2264 	ZFS_VERIFY_ZP(dzp);
2265 	zilog = zfsvfs->z_log;
2266 
2267 	if (flags & FIGNORECASE)
2268 		zflg |= ZCILOOK;
2269 top:
2270 	zp = NULL;
2271 
2272 	/*
2273 	 * Attempt to lock directory; fail if entry doesn't exist.
2274 	 */
2275 	if (error = zfs_dirent_lock(&dl, dzp, name, &zp, zflg,
2276 	    NULL, NULL)) {
2277 		ZFS_EXIT(zfsvfs);
2278 		return (error);
2279 	}
2280 
2281 	vp = ZTOV(zp);
2282 
2283 	if (error = zfs_zaccess_delete(dzp, zp, cr)) {
2284 		goto out;
2285 	}
2286 
2287 	if (vp->v_type != VDIR) {
2288 		error = SET_ERROR(ENOTDIR);
2289 		goto out;
2290 	}
2291 
2292 	if (vp == cwd) {
2293 		error = SET_ERROR(EINVAL);
2294 		goto out;
2295 	}
2296 
2297 	vnevent_rmdir(vp, dvp, name, ct);
2298 
2299 	/*
2300 	 * Grab a lock on the directory to make sure that noone is
2301 	 * trying to add (or lookup) entries while we are removing it.
2302 	 */
2303 	rw_enter(&zp->z_name_lock, RW_WRITER);
2304 
2305 	/*
2306 	 * Grab a lock on the parent pointer to make sure we play well
2307 	 * with the treewalk and directory rename code.
2308 	 */
2309 	rw_enter(&zp->z_parent_lock, RW_WRITER);
2310 
2311 	tx = dmu_tx_create(zfsvfs->z_os);
2312 	dmu_tx_hold_zap(tx, dzp->z_id, FALSE, name);
2313 	dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
2314 	dmu_tx_hold_zap(tx, zfsvfs->z_unlinkedobj, FALSE, NULL);
2315 	zfs_sa_upgrade_txholds(tx, zp);
2316 	zfs_sa_upgrade_txholds(tx, dzp);
2317 	dmu_tx_mark_netfree(tx);
2318 	error = dmu_tx_assign(tx, (waited ? TXG_NOTHROTTLE : 0) | TXG_NOWAIT);
2319 	if (error) {
2320 		rw_exit(&zp->z_parent_lock);
2321 		rw_exit(&zp->z_name_lock);
2322 		zfs_dirent_unlock(dl);
2323 		VN_RELE(vp);
2324 		if (error == ERESTART) {
2325 			waited = B_TRUE;
2326 			dmu_tx_wait(tx);
2327 			dmu_tx_abort(tx);
2328 			goto top;
2329 		}
2330 		dmu_tx_abort(tx);
2331 		ZFS_EXIT(zfsvfs);
2332 		return (error);
2333 	}
2334 
2335 	error = zfs_link_destroy(dl, zp, tx, zflg, NULL);
2336 
2337 	if (error == 0) {
2338 		uint64_t txtype = TX_RMDIR;
2339 		if (flags & FIGNORECASE)
2340 			txtype |= TX_CI;
2341 		zfs_log_remove(zilog, tx, txtype, dzp, name, ZFS_NO_OBJECT,
2342 		    B_FALSE);
2343 	}
2344 
2345 	dmu_tx_commit(tx);
2346 
2347 	rw_exit(&zp->z_parent_lock);
2348 	rw_exit(&zp->z_name_lock);
2349 out:
2350 	zfs_dirent_unlock(dl);
2351 
2352 	VN_RELE(vp);
2353 
2354 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
2355 		zil_commit(zilog, 0);
2356 
2357 	ZFS_EXIT(zfsvfs);
2358 	return (error);
2359 }
2360 
2361 /*
2362  * Read as many directory entries as will fit into the provided
2363  * buffer from the given directory cursor position (specified in
2364  * the uio structure).
2365  *
2366  *	IN:	vp	- vnode of directory to read.
2367  *		uio	- structure supplying read location, range info,
2368  *			  and return buffer.
2369  *		cr	- credentials of caller.
2370  *		ct	- caller context
2371  *		flags	- case flags
2372  *
2373  *	OUT:	uio	- updated offset and range, buffer filled.
2374  *		eofp	- set to true if end-of-file detected.
2375  *
2376  *	RETURN:	0 on success, error code on failure.
2377  *
2378  * Timestamps:
2379  *	vp - atime updated
2380  *
2381  * Note that the low 4 bits of the cookie returned by zap is always zero.
2382  * This allows us to use the low range for "special" directory entries:
2383  * We use 0 for '.', and 1 for '..'.  If this is the root of the filesystem,
2384  * we use the offset 2 for the '.zfs' directory.
2385  */
2386 /* ARGSUSED */
2387 static int
zfs_readdir(vnode_t * vp,uio_t * uio,cred_t * cr,int * eofp,caller_context_t * ct,int flags)2388 zfs_readdir(vnode_t *vp, uio_t *uio, cred_t *cr, int *eofp,
2389     caller_context_t *ct, int flags)
2390 {
2391 	znode_t		*zp = VTOZ(vp);
2392 	iovec_t		*iovp;
2393 	edirent_t	*eodp;
2394 	dirent64_t	*odp;
2395 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
2396 	objset_t	*os;
2397 	caddr_t		outbuf;
2398 	size_t		bufsize;
2399 	zap_cursor_t	zc;
2400 	zap_attribute_t	zap;
2401 	uint_t		bytes_wanted;
2402 	uint64_t	offset; /* must be unsigned; checks for < 1 */
2403 	uint64_t	parent;
2404 	int		local_eof;
2405 	int		outcount;
2406 	int		error;
2407 	uint8_t		prefetch;
2408 	boolean_t	check_sysattrs;
2409 
2410 	ZFS_ENTER(zfsvfs);
2411 	ZFS_VERIFY_ZP(zp);
2412 
2413 	if ((error = sa_lookup(zp->z_sa_hdl, SA_ZPL_PARENT(zfsvfs),
2414 	    &parent, sizeof (parent))) != 0) {
2415 		ZFS_EXIT(zfsvfs);
2416 		return (error);
2417 	}
2418 
2419 	/*
2420 	 * If we are not given an eof variable,
2421 	 * use a local one.
2422 	 */
2423 	if (eofp == NULL)
2424 		eofp = &local_eof;
2425 
2426 	/*
2427 	 * Check for valid iov_len.
2428 	 */
2429 	if (uio->uio_iov->iov_len <= 0) {
2430 		ZFS_EXIT(zfsvfs);
2431 		return (SET_ERROR(EINVAL));
2432 	}
2433 
2434 	/*
2435 	 * Quit if directory has been removed (posix)
2436 	 */
2437 	if ((*eofp = zp->z_unlinked) != 0) {
2438 		ZFS_EXIT(zfsvfs);
2439 		return (0);
2440 	}
2441 
2442 	error = 0;
2443 	os = zfsvfs->z_os;
2444 	offset = uio->uio_loffset;
2445 	prefetch = zp->z_zn_prefetch;
2446 
2447 	/*
2448 	 * Initialize the iterator cursor.
2449 	 */
2450 	if (offset <= 3) {
2451 		/*
2452 		 * Start iteration from the beginning of the directory.
2453 		 */
2454 		zap_cursor_init(&zc, os, zp->z_id);
2455 	} else {
2456 		/*
2457 		 * The offset is a serialized cursor.
2458 		 */
2459 		zap_cursor_init_serialized(&zc, os, zp->z_id, offset);
2460 	}
2461 
2462 	/*
2463 	 * Get space to change directory entries into fs independent format.
2464 	 */
2465 	iovp = uio->uio_iov;
2466 	bytes_wanted = iovp->iov_len;
2467 	if (uio->uio_segflg != UIO_SYSSPACE || uio->uio_iovcnt != 1) {
2468 		bufsize = bytes_wanted;
2469 		outbuf = kmem_alloc(bufsize, KM_SLEEP);
2470 		odp = (struct dirent64 *)outbuf;
2471 	} else {
2472 		bufsize = bytes_wanted;
2473 		outbuf = NULL;
2474 		odp = (struct dirent64 *)iovp->iov_base;
2475 	}
2476 	eodp = (struct edirent *)odp;
2477 
2478 	/*
2479 	 * If this VFS supports the system attribute view interface; and
2480 	 * we're looking at an extended attribute directory; and we care
2481 	 * about normalization conflicts on this vfs; then we must check
2482 	 * for normalization conflicts with the sysattr name space.
2483 	 */
2484 	check_sysattrs = vfs_has_feature(vp->v_vfsp, VFSFT_SYSATTR_VIEWS) &&
2485 	    (vp->v_flag & V_XATTRDIR) && zfsvfs->z_norm &&
2486 	    (flags & V_RDDIR_ENTFLAGS);
2487 
2488 	/*
2489 	 * Transform to file-system independent format
2490 	 */
2491 	outcount = 0;
2492 	while (outcount < bytes_wanted) {
2493 		ino64_t objnum;
2494 		ushort_t reclen;
2495 		off64_t *next = NULL;
2496 
2497 		/*
2498 		 * Special case `.', `..', and `.zfs'.
2499 		 */
2500 		if (offset == 0) {
2501 			(void) strcpy(zap.za_name, ".");
2502 			zap.za_normalization_conflict = 0;
2503 			objnum = zp->z_id;
2504 		} else if (offset == 1) {
2505 			(void) strcpy(zap.za_name, "..");
2506 			zap.za_normalization_conflict = 0;
2507 			objnum = parent;
2508 		} else if (offset == 2 && zfs_show_ctldir(zp)) {
2509 			(void) strcpy(zap.za_name, ZFS_CTLDIR_NAME);
2510 			zap.za_normalization_conflict = 0;
2511 			objnum = ZFSCTL_INO_ROOT;
2512 		} else {
2513 			/*
2514 			 * Grab next entry.
2515 			 */
2516 			if (error = zap_cursor_retrieve(&zc, &zap)) {
2517 				if ((*eofp = (error == ENOENT)) != 0)
2518 					break;
2519 				else
2520 					goto update;
2521 			}
2522 
2523 			if (zap.za_integer_length != 8 ||
2524 			    zap.za_num_integers != 1) {
2525 				cmn_err(CE_WARN, "zap_readdir: bad directory "
2526 				    "entry, obj = %lld, offset = %lld\n",
2527 				    (u_longlong_t)zp->z_id,
2528 				    (u_longlong_t)offset);
2529 				error = SET_ERROR(ENXIO);
2530 				goto update;
2531 			}
2532 
2533 			objnum = ZFS_DIRENT_OBJ(zap.za_first_integer);
2534 			/*
2535 			 * MacOS X can extract the object type here such as:
2536 			 * uint8_t type = ZFS_DIRENT_TYPE(zap.za_first_integer);
2537 			 */
2538 
2539 			if (check_sysattrs && !zap.za_normalization_conflict) {
2540 				zap.za_normalization_conflict =
2541 				    xattr_sysattr_casechk(zap.za_name);
2542 			}
2543 		}
2544 
2545 		if (flags & V_RDDIR_ACCFILTER) {
2546 			/*
2547 			 * If we have no access at all, don't include
2548 			 * this entry in the returned information
2549 			 */
2550 			znode_t	*ezp;
2551 			if (zfs_zget(zp->z_zfsvfs, objnum, &ezp) != 0)
2552 				goto skip_entry;
2553 			if (!zfs_has_access(ezp, cr)) {
2554 				VN_RELE(ZTOV(ezp));
2555 				goto skip_entry;
2556 			}
2557 			VN_RELE(ZTOV(ezp));
2558 		}
2559 
2560 		if (flags & V_RDDIR_ENTFLAGS)
2561 			reclen = EDIRENT_RECLEN(strlen(zap.za_name));
2562 		else
2563 			reclen = DIRENT64_RECLEN(strlen(zap.za_name));
2564 
2565 		/*
2566 		 * Will this entry fit in the buffer?
2567 		 */
2568 		if (outcount + reclen > bufsize) {
2569 			/*
2570 			 * Did we manage to fit anything in the buffer?
2571 			 */
2572 			if (!outcount) {
2573 				error = SET_ERROR(EINVAL);
2574 				goto update;
2575 			}
2576 			break;
2577 		}
2578 		if (flags & V_RDDIR_ENTFLAGS) {
2579 			/*
2580 			 * Add extended flag entry:
2581 			 */
2582 			eodp->ed_ino = objnum;
2583 			eodp->ed_reclen = reclen;
2584 			/* NOTE: ed_off is the offset for the *next* entry */
2585 			next = &(eodp->ed_off);
2586 			eodp->ed_eflags = zap.za_normalization_conflict ?
2587 			    ED_CASE_CONFLICT : 0;
2588 			(void) strncpy(eodp->ed_name, zap.za_name,
2589 			    EDIRENT_NAMELEN(reclen));
2590 			eodp = (edirent_t *)((intptr_t)eodp + reclen);
2591 		} else {
2592 			/*
2593 			 * Add normal entry:
2594 			 */
2595 			odp->d_ino = objnum;
2596 			odp->d_reclen = reclen;
2597 			/* NOTE: d_off is the offset for the *next* entry */
2598 			next = &(odp->d_off);
2599 			(void) strncpy(odp->d_name, zap.za_name,
2600 			    DIRENT64_NAMELEN(reclen));
2601 			odp = (dirent64_t *)((intptr_t)odp + reclen);
2602 		}
2603 		outcount += reclen;
2604 
2605 		ASSERT(outcount <= bufsize);
2606 
2607 		/* Prefetch znode */
2608 		if (prefetch)
2609 			dmu_prefetch(os, objnum, 0, 0, 0,
2610 			    ZIO_PRIORITY_SYNC_READ);
2611 
2612 	skip_entry:
2613 		/*
2614 		 * Move to the next entry, fill in the previous offset.
2615 		 */
2616 		if (offset > 2 || (offset == 2 && !zfs_show_ctldir(zp))) {
2617 			zap_cursor_advance(&zc);
2618 			offset = zap_cursor_serialize(&zc);
2619 		} else {
2620 			offset += 1;
2621 		}
2622 		if (next)
2623 			*next = offset;
2624 	}
2625 	zp->z_zn_prefetch = B_FALSE; /* a lookup will re-enable pre-fetching */
2626 
2627 	if (uio->uio_segflg == UIO_SYSSPACE && uio->uio_iovcnt == 1) {
2628 		iovp->iov_base += outcount;
2629 		iovp->iov_len -= outcount;
2630 		uio->uio_resid -= outcount;
2631 	} else if (error = uiomove(outbuf, (long)outcount, UIO_READ, uio)) {
2632 		/*
2633 		 * Reset the pointer.
2634 		 */
2635 		offset = uio->uio_loffset;
2636 	}
2637 
2638 update:
2639 	zap_cursor_fini(&zc);
2640 	if (uio->uio_segflg != UIO_SYSSPACE || uio->uio_iovcnt != 1)
2641 		kmem_free(outbuf, bufsize);
2642 
2643 	if (error == ENOENT)
2644 		error = 0;
2645 
2646 	ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
2647 
2648 	uio->uio_loffset = offset;
2649 	ZFS_EXIT(zfsvfs);
2650 	return (error);
2651 }
2652 
2653 ulong_t zfs_fsync_sync_cnt = 4;
2654 
2655 static int
zfs_fsync(vnode_t * vp,int syncflag,cred_t * cr,caller_context_t * ct)2656 zfs_fsync(vnode_t *vp, int syncflag, cred_t *cr, caller_context_t *ct)
2657 {
2658 	znode_t	*zp = VTOZ(vp);
2659 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
2660 
2661 	/*
2662 	 * Regardless of whether this is required for standards conformance,
2663 	 * this is the logical behavior when fsync() is called on a file with
2664 	 * dirty pages.  We use B_ASYNC since the ZIL transactions are already
2665 	 * going to be pushed out as part of the zil_commit().
2666 	 */
2667 	if (vn_has_cached_data(vp) && !(syncflag & FNODSYNC) &&
2668 	    (vp->v_type == VREG) && !(IS_SWAPVP(vp)))
2669 		(void) VOP_PUTPAGE(vp, (offset_t)0, (size_t)0, B_ASYNC, cr, ct);
2670 
2671 	(void) tsd_set(zfs_fsyncer_key, (void *)zfs_fsync_sync_cnt);
2672 
2673 	if (zfsvfs->z_os->os_sync != ZFS_SYNC_DISABLED) {
2674 		ZFS_ENTER(zfsvfs);
2675 		ZFS_VERIFY_ZP(zp);
2676 		zil_commit(zfsvfs->z_log, zp->z_id);
2677 		ZFS_EXIT(zfsvfs);
2678 	}
2679 	return (0);
2680 }
2681 
2682 
2683 /*
2684  * Get the requested file attributes and place them in the provided
2685  * vattr structure.
2686  *
2687  *	IN:	vp	- vnode of file.
2688  *		vap	- va_mask identifies requested attributes.
2689  *			  If AT_XVATTR set, then optional attrs are requested
2690  *		flags	- ATTR_NOACLCHECK (CIFS server context)
2691  *		cr	- credentials of caller.
2692  *		ct	- caller context
2693  *
2694  *	OUT:	vap	- attribute values.
2695  *
2696  *	RETURN:	0 (always succeeds).
2697  */
2698 /* ARGSUSED */
2699 static int
zfs_getattr(vnode_t * vp,vattr_t * vap,int flags,cred_t * cr,caller_context_t * ct)2700 zfs_getattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr,
2701     caller_context_t *ct)
2702 {
2703 	znode_t *zp = VTOZ(vp);
2704 	zfsvfs_t *zfsvfs = zp->z_zfsvfs;
2705 	int	error = 0;
2706 	uint64_t links;
2707 	uint64_t mtime[2], ctime[2];
2708 	xvattr_t *xvap = (xvattr_t *)vap;	/* vap may be an xvattr_t * */
2709 	xoptattr_t *xoap = NULL;
2710 	boolean_t skipaclchk = (flags & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
2711 	sa_bulk_attr_t bulk[2];
2712 	int count = 0;
2713 
2714 	ZFS_ENTER(zfsvfs);
2715 	ZFS_VERIFY_ZP(zp);
2716 
2717 	zfs_fuid_map_ids(zp, cr, &vap->va_uid, &vap->va_gid);
2718 
2719 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16);
2720 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16);
2721 
2722 	if ((error = sa_bulk_lookup(zp->z_sa_hdl, bulk, count)) != 0) {
2723 		ZFS_EXIT(zfsvfs);
2724 		return (error);
2725 	}
2726 
2727 	/*
2728 	 * If ACL is trivial don't bother looking for ACE_READ_ATTRIBUTES.
2729 	 * Also, if we are the owner don't bother, since owner should
2730 	 * always be allowed to read basic attributes of file.
2731 	 */
2732 	if (!(zp->z_pflags & ZFS_ACL_TRIVIAL) &&
2733 	    (vap->va_uid != crgetuid(cr))) {
2734 		if (error = zfs_zaccess(zp, ACE_READ_ATTRIBUTES, 0,
2735 		    skipaclchk, cr)) {
2736 			ZFS_EXIT(zfsvfs);
2737 			return (error);
2738 		}
2739 	}
2740 
2741 	/*
2742 	 * Return all attributes.  It's cheaper to provide the answer
2743 	 * than to determine whether we were asked the question.
2744 	 */
2745 
2746 	mutex_enter(&zp->z_lock);
2747 	vap->va_type = vp->v_type;
2748 	vap->va_mode = zp->z_mode & MODEMASK;
2749 	vap->va_fsid = zp->z_zfsvfs->z_vfs->vfs_dev;
2750 	vap->va_nodeid = zp->z_id;
2751 	if ((vp->v_flag & VROOT) && zfs_show_ctldir(zp))
2752 		links = zp->z_links + 1;
2753 	else
2754 		links = zp->z_links;
2755 	vap->va_nlink = MIN(links, UINT32_MAX);	/* nlink_t limit! */
2756 	vap->va_size = zp->z_size;
2757 	vap->va_rdev = vp->v_rdev;
2758 	vap->va_seq = zp->z_seq;
2759 
2760 	/*
2761 	 * Add in any requested optional attributes and the create time.
2762 	 * Also set the corresponding bits in the returned attribute bitmap.
2763 	 */
2764 	if ((xoap = xva_getxoptattr(xvap)) != NULL && zfsvfs->z_use_fuids) {
2765 		if (XVA_ISSET_REQ(xvap, XAT_ARCHIVE)) {
2766 			xoap->xoa_archive =
2767 			    ((zp->z_pflags & ZFS_ARCHIVE) != 0);
2768 			XVA_SET_RTN(xvap, XAT_ARCHIVE);
2769 		}
2770 
2771 		if (XVA_ISSET_REQ(xvap, XAT_READONLY)) {
2772 			xoap->xoa_readonly =
2773 			    ((zp->z_pflags & ZFS_READONLY) != 0);
2774 			XVA_SET_RTN(xvap, XAT_READONLY);
2775 		}
2776 
2777 		if (XVA_ISSET_REQ(xvap, XAT_SYSTEM)) {
2778 			xoap->xoa_system =
2779 			    ((zp->z_pflags & ZFS_SYSTEM) != 0);
2780 			XVA_SET_RTN(xvap, XAT_SYSTEM);
2781 		}
2782 
2783 		if (XVA_ISSET_REQ(xvap, XAT_HIDDEN)) {
2784 			xoap->xoa_hidden =
2785 			    ((zp->z_pflags & ZFS_HIDDEN) != 0);
2786 			XVA_SET_RTN(xvap, XAT_HIDDEN);
2787 		}
2788 
2789 		if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
2790 			xoap->xoa_nounlink =
2791 			    ((zp->z_pflags & ZFS_NOUNLINK) != 0);
2792 			XVA_SET_RTN(xvap, XAT_NOUNLINK);
2793 		}
2794 
2795 		if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
2796 			xoap->xoa_immutable =
2797 			    ((zp->z_pflags & ZFS_IMMUTABLE) != 0);
2798 			XVA_SET_RTN(xvap, XAT_IMMUTABLE);
2799 		}
2800 
2801 		if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
2802 			xoap->xoa_appendonly =
2803 			    ((zp->z_pflags & ZFS_APPENDONLY) != 0);
2804 			XVA_SET_RTN(xvap, XAT_APPENDONLY);
2805 		}
2806 
2807 		if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
2808 			xoap->xoa_nodump =
2809 			    ((zp->z_pflags & ZFS_NODUMP) != 0);
2810 			XVA_SET_RTN(xvap, XAT_NODUMP);
2811 		}
2812 
2813 		if (XVA_ISSET_REQ(xvap, XAT_OPAQUE)) {
2814 			xoap->xoa_opaque =
2815 			    ((zp->z_pflags & ZFS_OPAQUE) != 0);
2816 			XVA_SET_RTN(xvap, XAT_OPAQUE);
2817 		}
2818 
2819 		if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
2820 			xoap->xoa_av_quarantined =
2821 			    ((zp->z_pflags & ZFS_AV_QUARANTINED) != 0);
2822 			XVA_SET_RTN(xvap, XAT_AV_QUARANTINED);
2823 		}
2824 
2825 		if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
2826 			xoap->xoa_av_modified =
2827 			    ((zp->z_pflags & ZFS_AV_MODIFIED) != 0);
2828 			XVA_SET_RTN(xvap, XAT_AV_MODIFIED);
2829 		}
2830 
2831 		if (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP) &&
2832 		    vp->v_type == VREG) {
2833 			zfs_sa_get_scanstamp(zp, xvap);
2834 		}
2835 
2836 		if (XVA_ISSET_REQ(xvap, XAT_CREATETIME)) {
2837 			uint64_t times[2];
2838 
2839 			(void) sa_lookup(zp->z_sa_hdl, SA_ZPL_CRTIME(zfsvfs),
2840 			    times, sizeof (times));
2841 			ZFS_TIME_DECODE(&xoap->xoa_createtime, times);
2842 			XVA_SET_RTN(xvap, XAT_CREATETIME);
2843 		}
2844 
2845 		if (XVA_ISSET_REQ(xvap, XAT_REPARSE)) {
2846 			xoap->xoa_reparse = ((zp->z_pflags & ZFS_REPARSE) != 0);
2847 			XVA_SET_RTN(xvap, XAT_REPARSE);
2848 		}
2849 		if (XVA_ISSET_REQ(xvap, XAT_GEN)) {
2850 			xoap->xoa_generation = zp->z_gen;
2851 			XVA_SET_RTN(xvap, XAT_GEN);
2852 		}
2853 
2854 		if (XVA_ISSET_REQ(xvap, XAT_OFFLINE)) {
2855 			xoap->xoa_offline =
2856 			    ((zp->z_pflags & ZFS_OFFLINE) != 0);
2857 			XVA_SET_RTN(xvap, XAT_OFFLINE);
2858 		}
2859 
2860 		if (XVA_ISSET_REQ(xvap, XAT_SPARSE)) {
2861 			xoap->xoa_sparse =
2862 			    ((zp->z_pflags & ZFS_SPARSE) != 0);
2863 			XVA_SET_RTN(xvap, XAT_SPARSE);
2864 		}
2865 
2866 		if (XVA_ISSET_REQ(xvap, XAT_PROJINHERIT)) {
2867 			xoap->xoa_projinherit =
2868 			    ((zp->z_pflags & ZFS_PROJINHERIT) != 0);
2869 			XVA_SET_RTN(xvap, XAT_PROJINHERIT);
2870 		}
2871 
2872 		if (XVA_ISSET_REQ(xvap, XAT_PROJID)) {
2873 			xoap->xoa_projid = zp->z_projid;
2874 			XVA_SET_RTN(xvap, XAT_PROJID);
2875 		}
2876 	}
2877 
2878 	ZFS_TIME_DECODE(&vap->va_atime, zp->z_atime);
2879 	ZFS_TIME_DECODE(&vap->va_mtime, mtime);
2880 	ZFS_TIME_DECODE(&vap->va_ctime, ctime);
2881 
2882 	mutex_exit(&zp->z_lock);
2883 
2884 	sa_object_size(zp->z_sa_hdl, &vap->va_blksize, &vap->va_nblocks);
2885 
2886 	if (zp->z_blksz == 0) {
2887 		/*
2888 		 * Block size hasn't been set; suggest maximal I/O transfers.
2889 		 */
2890 		vap->va_blksize = zfsvfs->z_max_blksz;
2891 	}
2892 
2893 	ZFS_EXIT(zfsvfs);
2894 	return (0);
2895 }
2896 
2897 /*
2898  * For the operation of changing file's user/group/project, we need to
2899  * handle not only the main object that is assigned to the file directly,
2900  * but also the ones that are used by the file via hidden xattr directory.
2901  *
2902  * Because the xattr directory may contain many EA entries, it may be
2903  * impossible to change all of them in the same transaction as changing the
2904  * main object's user/group/project attributes. If so, we have to change them
2905  * via other multiple independent transactions one by one. It may be not a good
2906  * solution, but we have no better idea yet.
2907  */
2908 static int
zfs_setattr_dir(znode_t * dzp)2909 zfs_setattr_dir(znode_t *dzp)
2910 {
2911 	zfsvfs_t	*zfsvfs = dzp->z_zfsvfs;
2912 	objset_t	*os = zfsvfs->z_os;
2913 	zap_cursor_t	zc;
2914 	zap_attribute_t	zap;
2915 	zfs_dirlock_t	*dl;
2916 	znode_t		*zp = NULL;
2917 	dmu_tx_t	*tx = NULL;
2918 	sa_bulk_attr_t	bulk[4];
2919 	int		count;
2920 	int		err;
2921 
2922 	zap_cursor_init(&zc, os, dzp->z_id);
2923 	while ((err = zap_cursor_retrieve(&zc, &zap)) == 0) {
2924 		count = 0;
2925 		if (zap.za_integer_length != 8 || zap.za_num_integers != 1) {
2926 			err = ENXIO;
2927 			break;
2928 		}
2929 
2930 		err = zfs_dirent_lock(&dl, dzp, (char *)zap.za_name, &zp,
2931 		    ZEXISTS, NULL, NULL);
2932 		if (err == ENOENT)
2933 			goto next;
2934 		if (err)
2935 			break;
2936 
2937 		if (zp->z_uid == dzp->z_uid &&
2938 		    zp->z_gid == dzp->z_gid &&
2939 		    zp->z_projid == dzp->z_projid)
2940 			goto next;
2941 
2942 		tx = dmu_tx_create(os);
2943 		if (!(zp->z_pflags & ZFS_PROJID))
2944 			dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_TRUE);
2945 		else
2946 			dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
2947 
2948 		err = dmu_tx_assign(tx, TXG_WAIT);
2949 		if (err)
2950 			break;
2951 
2952 		mutex_enter(&dzp->z_lock);
2953 
2954 		if (zp->z_uid != dzp->z_uid) {
2955 			zp->z_uid = dzp->z_uid;
2956 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_UID(zfsvfs), NULL,
2957 			    &dzp->z_uid, sizeof (dzp->z_uid));
2958 		}
2959 
2960 		if (zp->z_gid != dzp->z_gid) {
2961 			zp->z_gid = dzp->z_gid;
2962 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_GID(zfsvfs), NULL,
2963 			    &dzp->z_gid, sizeof (dzp->z_gid));
2964 		}
2965 
2966 		if (zp->z_projid != dzp->z_projid) {
2967 			if (!(zp->z_pflags & ZFS_PROJID)) {
2968 				zp->z_pflags |= ZFS_PROJID;
2969 				SA_ADD_BULK_ATTR(bulk, count,
2970 				    SA_ZPL_FLAGS(zfsvfs), NULL, &zp->z_pflags,
2971 				    sizeof (zp->z_pflags));
2972 			}
2973 
2974 			zp->z_projid = dzp->z_projid;
2975 			SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_PROJID(zfsvfs),
2976 			    NULL, &zp->z_projid, sizeof (zp->z_projid));
2977 		}
2978 
2979 		mutex_exit(&dzp->z_lock);
2980 
2981 		if (likely(count > 0)) {
2982 			err = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
2983 			dmu_tx_commit(tx);
2984 		} else {
2985 			dmu_tx_abort(tx);
2986 		}
2987 		tx = NULL;
2988 		if (err != 0 && err != ENOENT)
2989 			break;
2990 
2991 next:
2992 		if (zp) {
2993 			VN_RELE(ZTOV(zp));
2994 			zp = NULL;
2995 			zfs_dirent_unlock(dl);
2996 		}
2997 		zap_cursor_advance(&zc);
2998 	}
2999 
3000 	if (tx)
3001 		dmu_tx_abort(tx);
3002 	if (zp) {
3003 		VN_RELE(ZTOV(zp));
3004 		zfs_dirent_unlock(dl);
3005 	}
3006 	zap_cursor_fini(&zc);
3007 
3008 	return (err == ENOENT ? 0 : err);
3009 }
3010 
3011 /*
3012  * Set the file attributes to the values contained in the
3013  * vattr structure.
3014  *
3015  *	IN:	vp	- vnode of file to be modified.
3016  *		vap	- new attribute values.
3017  *			  If AT_XVATTR set, then optional attrs are being set
3018  *		flags	- ATTR_UTIME set if non-default time values provided.
3019  *			- ATTR_NOACLCHECK (CIFS context only).
3020  *		cr	- credentials of caller.
3021  *		ct	- caller context
3022  *
3023  *	RETURN:	0 on success, error code on failure.
3024  *
3025  * Timestamps:
3026  *	vp - ctime updated, mtime updated if size changed.
3027  */
3028 /* ARGSUSED */
3029 static int
zfs_setattr(vnode_t * vp,vattr_t * vap,int flags,cred_t * cr,caller_context_t * ct)3030 zfs_setattr(vnode_t *vp, vattr_t *vap, int flags, cred_t *cr,
3031     caller_context_t *ct)
3032 {
3033 	znode_t		*zp = VTOZ(vp);
3034 	zfsvfs_t	*zfsvfs = zp->z_zfsvfs;
3035 	objset_t	*os = zfsvfs->z_os;
3036 	zilog_t		*zilog;
3037 	dmu_tx_t	*tx;
3038 	vattr_t		oldva;
3039 	xvattr_t	tmpxvattr;
3040 	uint_t		mask = vap->va_mask;
3041 	uint_t		saved_mask = 0;
3042 	int		trim_mask = 0;
3043 	uint64_t	new_mode;
3044 	uint64_t	new_uid, new_gid;
3045 	uint64_t	xattr_obj;
3046 	uint64_t	mtime[2], ctime[2];
3047 	uint64_t	projid = ZFS_INVALID_PROJID;
3048 	znode_t		*attrzp;
3049 	int		need_policy = FALSE;
3050 	int		err, err2 = 0;
3051 	zfs_fuid_info_t *fuidp = NULL;
3052 	xvattr_t *xvap = (xvattr_t *)vap;	/* vap may be an xvattr_t * */
3053 	xoptattr_t	*xoap;
3054 	zfs_acl_t	*aclp;
3055 	boolean_t skipaclchk = (flags & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
3056 	boolean_t	fuid_dirtied = B_FALSE;
3057 	boolean_t	handle_eadir = B_FALSE;
3058 	boolean_t	zp_acl_entered = B_FALSE;
3059 	boolean_t	attr_acl_entered = B_FALSE;
3060 	sa_bulk_attr_t	bulk[8], xattr_bulk[8];
3061 	int		count = 0, xattr_count = 0;
3062 
3063 	if (mask == 0)
3064 		return (0);
3065 
3066 	if (mask & AT_NOSET)
3067 		return (SET_ERROR(EINVAL));
3068 
3069 	ZFS_ENTER(zfsvfs);
3070 	ZFS_VERIFY_ZP(zp);
3071 
3072 	/*
3073 	 * If this is a xvattr_t, then get a pointer to the structure of
3074 	 * optional attributes.  If this is NULL, then we have a vattr_t.
3075 	 */
3076 	xoap = xva_getxoptattr(xvap);
3077 	if (xoap != NULL && (mask & AT_XVATTR)) {
3078 		if (XVA_ISSET_REQ(xvap, XAT_PROJID)) {
3079 			if (!dmu_objset_projectquota_enabled(os) ||
3080 			    (vp->v_type != VREG && vp->v_type != VDIR)) {
3081 				ZFS_EXIT(zfsvfs);
3082 				return (SET_ERROR(ENOTSUP));
3083 			}
3084 
3085 			projid = xoap->xoa_projid;
3086 			if (unlikely(projid == ZFS_INVALID_PROJID)) {
3087 				ZFS_EXIT(zfsvfs);
3088 				return (SET_ERROR(EINVAL));
3089 			}
3090 
3091 			if (projid == zp->z_projid && zp->z_pflags & ZFS_PROJID)
3092 				projid = ZFS_INVALID_PROJID;
3093 			else
3094 				need_policy = TRUE;
3095 		}
3096 
3097 		if (XVA_ISSET_REQ(xvap, XAT_PROJINHERIT) &&
3098 		    (!dmu_objset_projectquota_enabled(os) ||
3099 		    (vp->v_type != VREG && vp->v_type != VDIR))) {
3100 				ZFS_EXIT(zfsvfs);
3101 				return (SET_ERROR(ENOTSUP));
3102 		}
3103 	}
3104 
3105 	zilog = zfsvfs->z_log;
3106 
3107 	/*
3108 	 * Make sure that if we have ephemeral uid/gid or xvattr specified
3109 	 * that file system is at proper version level
3110 	 */
3111 
3112 	if (zfsvfs->z_use_fuids == B_FALSE &&
3113 	    (((mask & AT_UID) && IS_EPHEMERAL(vap->va_uid)) ||
3114 	    ((mask & AT_GID) && IS_EPHEMERAL(vap->va_gid)) ||
3115 	    (mask & AT_XVATTR))) {
3116 		ZFS_EXIT(zfsvfs);
3117 		return (SET_ERROR(EINVAL));
3118 	}
3119 
3120 	if (mask & AT_SIZE && vp->v_type == VDIR) {
3121 		ZFS_EXIT(zfsvfs);
3122 		return (SET_ERROR(EISDIR));
3123 	}
3124 
3125 	if (mask & AT_SIZE && vp->v_type != VREG && vp->v_type != VFIFO) {
3126 		ZFS_EXIT(zfsvfs);
3127 		return (SET_ERROR(EINVAL));
3128 	}
3129 
3130 	xva_init(&tmpxvattr);
3131 
3132 	/*
3133 	 * Immutable files can only alter immutable bit and atime
3134 	 */
3135 	if ((zp->z_pflags & ZFS_IMMUTABLE) &&
3136 	    ((mask & (AT_SIZE|AT_UID|AT_GID|AT_MTIME|AT_MODE)) ||
3137 	    ((mask & AT_XVATTR) && XVA_ISSET_REQ(xvap, XAT_CREATETIME)))) {
3138 		ZFS_EXIT(zfsvfs);
3139 		return (SET_ERROR(EPERM));
3140 	}
3141 
3142 	/*
3143 	 * Note: ZFS_READONLY is handled in zfs_zaccess_common.
3144 	 */
3145 
3146 	/*
3147 	 * Verify timestamps doesn't overflow 32 bits.
3148 	 * ZFS can handle large timestamps, but 32bit syscalls can't
3149 	 * handle times greater than 2039.  This check should be removed
3150 	 * once large timestamps are fully supported.
3151 	 */
3152 	if (mask & (AT_ATIME | AT_MTIME)) {
3153 		if (((mask & AT_ATIME) && TIMESPEC_OVERFLOW(&vap->va_atime)) ||
3154 		    ((mask & AT_MTIME) && TIMESPEC_OVERFLOW(&vap->va_mtime))) {
3155 			ZFS_EXIT(zfsvfs);
3156 			return (SET_ERROR(EOVERFLOW));
3157 		}
3158 	}
3159 
3160 top:
3161 	attrzp = NULL;
3162 	aclp = NULL;
3163 
3164 	/* Can this be moved to before the top label? */
3165 	if (zfsvfs->z_vfs->vfs_flag & VFS_RDONLY) {
3166 		ZFS_EXIT(zfsvfs);
3167 		return (SET_ERROR(EROFS));
3168 	}
3169 
3170 	/*
3171 	 * First validate permissions
3172 	 */
3173 
3174 	if (mask & AT_SIZE) {
3175 		err = zfs_zaccess(zp, ACE_WRITE_DATA, 0, skipaclchk, cr);
3176 		if (err) {
3177 			ZFS_EXIT(zfsvfs);
3178 			return (err);
3179 		}
3180 		/*
3181 		 * XXX - Note, we are not providing any open
3182 		 * mode flags here (like FNDELAY), so we may
3183 		 * block if there are locks present... this
3184 		 * should be addressed in openat().
3185 		 */
3186 		/* XXX - would it be OK to generate a log record here? */
3187 		err = zfs_freesp(zp, vap->va_size, 0, 0, FALSE);
3188 		if (err) {
3189 			ZFS_EXIT(zfsvfs);
3190 			return (err);
3191 		}
3192 
3193 		if (vap->va_size == 0)
3194 			vnevent_truncate(ZTOV(zp), ct);
3195 	}
3196 
3197 	if (mask & (AT_ATIME|AT_MTIME) ||
3198 	    ((mask & AT_XVATTR) && (XVA_ISSET_REQ(xvap, XAT_HIDDEN) ||
3199 	    XVA_ISSET_REQ(xvap, XAT_READONLY) ||
3200 	    XVA_ISSET_REQ(xvap, XAT_ARCHIVE) ||
3201 	    XVA_ISSET_REQ(xvap, XAT_OFFLINE) ||
3202 	    XVA_ISSET_REQ(xvap, XAT_SPARSE) ||
3203 	    XVA_ISSET_REQ(xvap, XAT_CREATETIME) ||
3204 	    XVA_ISSET_REQ(xvap, XAT_SYSTEM)))) {
3205 		need_policy = zfs_zaccess(zp, ACE_WRITE_ATTRIBUTES, 0,
3206 		    skipaclchk, cr);
3207 	}
3208 
3209 	if (mask & (AT_UID|AT_GID)) {
3210 		int	idmask = (mask & (AT_UID|AT_GID));
3211 		int	take_owner;
3212 		int	take_group;
3213 
3214 		/*
3215 		 * NOTE: even if a new mode is being set,
3216 		 * we may clear S_ISUID/S_ISGID bits.
3217 		 */
3218 
3219 		if (!(mask & AT_MODE))
3220 			vap->va_mode = zp->z_mode;
3221 
3222 		/*
3223 		 * Take ownership or chgrp to group we are a member of
3224 		 */
3225 
3226 		take_owner = (mask & AT_UID) && (vap->va_uid == crgetuid(cr));
3227 		take_group = (mask & AT_GID) &&
3228 		    zfs_groupmember(zfsvfs, vap->va_gid, cr);
3229 
3230 		/*
3231 		 * If both AT_UID and AT_GID are set then take_owner and
3232 		 * take_group must both be set in order to allow taking
3233 		 * ownership.
3234 		 *
3235 		 * Otherwise, send the check through secpolicy_vnode_setattr()
3236 		 *
3237 		 */
3238 
3239 		if (((idmask == (AT_UID|AT_GID)) && take_owner && take_group) ||
3240 		    ((idmask == AT_UID) && take_owner) ||
3241 		    ((idmask == AT_GID) && take_group)) {
3242 			if (zfs_zaccess(zp, ACE_WRITE_OWNER, 0,
3243 			    skipaclchk, cr) == 0) {
3244 				/*
3245 				 * Remove setuid/setgid for non-privileged users
3246 				 */
3247 				secpolicy_setid_clear(vap, cr);
3248 				trim_mask = (mask & (AT_UID|AT_GID));
3249 			} else {
3250 				need_policy =  TRUE;
3251 			}
3252 		} else {
3253 			need_policy =  TRUE;
3254 		}
3255 	}
3256 
3257 	mutex_enter(&zp->z_lock);
3258 	oldva.va_mode = zp->z_mode;
3259 	zfs_fuid_map_ids(zp, cr, &oldva.va_uid, &oldva.va_gid);
3260 	if (mask & AT_XVATTR) {
3261 		/*
3262 		 * Update xvattr mask to include only those attributes
3263 		 * that are actually changing.
3264 		 *
3265 		 * the bits will be restored prior to actually setting
3266 		 * the attributes so the caller thinks they were set.
3267 		 */
3268 		if (XVA_ISSET_REQ(xvap, XAT_APPENDONLY)) {
3269 			if (xoap->xoa_appendonly !=
3270 			    ((zp->z_pflags & ZFS_APPENDONLY) != 0)) {
3271 				need_policy = TRUE;
3272 			} else {
3273 				XVA_CLR_REQ(xvap, XAT_APPENDONLY);
3274 				XVA_SET_REQ(&tmpxvattr, XAT_APPENDONLY);
3275 			}
3276 		}
3277 
3278 		if (XVA_ISSET_REQ(xvap, XAT_PROJINHERIT)) {
3279 			if (xoap->xoa_projinherit !=
3280 			    ((zp->z_pflags & ZFS_PROJINHERIT) != 0)) {
3281 				need_policy = TRUE;
3282 			} else {
3283 				XVA_CLR_REQ(xvap, XAT_PROJINHERIT);
3284 				XVA_SET_REQ(&tmpxvattr, XAT_PROJINHERIT);
3285 			}
3286 		}
3287 
3288 		if (XVA_ISSET_REQ(xvap, XAT_NOUNLINK)) {
3289 			if (xoap->xoa_nounlink !=
3290 			    ((zp->z_pflags & ZFS_NOUNLINK) != 0)) {
3291 				need_policy = TRUE;
3292 			} else {
3293 				XVA_CLR_REQ(xvap, XAT_NOUNLINK);
3294 				XVA_SET_REQ(&tmpxvattr, XAT_NOUNLINK);
3295 			}
3296 		}
3297 
3298 		if (XVA_ISSET_REQ(xvap, XAT_IMMUTABLE)) {
3299 			if (xoap->xoa_immutable !=
3300 			    ((zp->z_pflags & ZFS_IMMUTABLE) != 0)) {
3301 				need_policy = TRUE;
3302 			} else {
3303 				XVA_CLR_REQ(xvap, XAT_IMMUTABLE);
3304 				XVA_SET_REQ(&tmpxvattr, XAT_IMMUTABLE);
3305 			}
3306 		}
3307 
3308 		if (XVA_ISSET_REQ(xvap, XAT_NODUMP)) {
3309 			if (xoap->xoa_nodump !=
3310 			    ((zp->z_pflags & ZFS_NODUMP) != 0)) {
3311 				need_policy = TRUE;
3312 			} else {
3313 				XVA_CLR_REQ(xvap, XAT_NODUMP);
3314 				XVA_SET_REQ(&tmpxvattr, XAT_NODUMP);
3315 			}
3316 		}
3317 
3318 		if (XVA_ISSET_REQ(xvap, XAT_AV_MODIFIED)) {
3319 			if (xoap->xoa_av_modified !=
3320 			    ((zp->z_pflags & ZFS_AV_MODIFIED) != 0)) {
3321 				need_policy = TRUE;
3322 			} else {
3323 				XVA_CLR_REQ(xvap, XAT_AV_MODIFIED);
3324 				XVA_SET_REQ(&tmpxvattr, XAT_AV_MODIFIED);
3325 			}
3326 		}
3327 
3328 		if (XVA_ISSET_REQ(xvap, XAT_AV_QUARANTINED)) {
3329 			if ((vp->v_type != VREG &&
3330 			    xoap->xoa_av_quarantined) ||
3331 			    xoap->xoa_av_quarantined !=
3332 			    ((zp->z_pflags & ZFS_AV_QUARANTINED) != 0)) {
3333 				need_policy = TRUE;
3334 			} else {
3335 				XVA_CLR_REQ(xvap, XAT_AV_QUARANTINED);
3336 				XVA_SET_REQ(&tmpxvattr, XAT_AV_QUARANTINED);
3337 			}
3338 		}
3339 
3340 		if (XVA_ISSET_REQ(xvap, XAT_REPARSE)) {
3341 			mutex_exit(&zp->z_lock);
3342 			ZFS_EXIT(zfsvfs);
3343 			return (SET_ERROR(EPERM));
3344 		}
3345 
3346 		if (need_policy == FALSE &&
3347 		    (XVA_ISSET_REQ(xvap, XAT_AV_SCANSTAMP) ||
3348 		    XVA_ISSET_REQ(xvap, XAT_OPAQUE))) {
3349 			need_policy = TRUE;
3350 		}
3351 	}
3352 
3353 	mutex_exit(&zp->z_lock);
3354 
3355 	if (mask & AT_MODE) {
3356 		if (zfs_zaccess(zp, ACE_WRITE_ACL, 0, skipaclchk, cr) == 0) {
3357 			err = secpolicy_setid_setsticky_clear(vp, vap,
3358 			    &oldva, cr);
3359 			if (err) {
3360 				ZFS_EXIT(zfsvfs);
3361 				return (err);
3362 			}
3363 			trim_mask |= AT_MODE;
3364 		} else {
3365 			need_policy = TRUE;
3366 		}
3367 	}
3368 
3369 	if (need_policy) {
3370 		/*
3371 		 * If trim_mask is set then take ownership
3372 		 * has been granted or write_acl is present and user
3373 		 * has the ability to modify mode.  In that case remove
3374 		 * UID|GID and or MODE from mask so that
3375 		 * secpolicy_vnode_setattr() doesn't revoke it.
3376 		 * If acl_implicit (implicit owner rights) is false,
3377 		 * tell secpolicy about that via the flags.
3378 		 */
3379 
3380 		if (zfsvfs->z_acl_implicit == B_FALSE)
3381 			flags |= ATTR_NOIMPLICIT;
3382 		if (trim_mask) {
3383 			saved_mask = vap->va_mask;
3384 			vap->va_mask &= ~trim_mask;
3385