xref: /freebsd/sys/contrib/openzfs/module/zfs/zfs_vnops.c (revision 9c474dc51b0b09ff81339caee6772e454dd470e4)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or https://opensource.org/licenses/CDDL-1.0.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2012, 2018 by Delphix. All rights reserved.
25  * Copyright (c) 2015 by Chunwei Chen. All rights reserved.
26  * Copyright 2017 Nexenta Systems, Inc.
27  */
28 
29 /* Portions Copyright 2007 Jeremy Teo */
30 /* Portions Copyright 2010 Robert Milkowski */
31 
32 #include <sys/types.h>
33 #include <sys/param.h>
34 #include <sys/time.h>
35 #include <sys/sysmacros.h>
36 #include <sys/vfs.h>
37 #include <sys/uio_impl.h>
38 #include <sys/file.h>
39 #include <sys/stat.h>
40 #include <sys/kmem.h>
41 #include <sys/cmn_err.h>
42 #include <sys/errno.h>
43 #include <sys/zfs_dir.h>
44 #include <sys/zfs_acl.h>
45 #include <sys/zfs_ioctl.h>
46 #include <sys/fs/zfs.h>
47 #include <sys/dmu.h>
48 #include <sys/dmu_objset.h>
49 #include <sys/spa.h>
50 #include <sys/txg.h>
51 #include <sys/dbuf.h>
52 #include <sys/policy.h>
53 #include <sys/zfs_vnops.h>
54 #include <sys/zfs_quota.h>
55 #include <sys/zfs_vfsops.h>
56 #include <sys/zfs_znode.h>
57 
58 
59 static ulong_t zfs_fsync_sync_cnt = 4;
60 
61 int
62 zfs_fsync(znode_t *zp, int syncflag, cred_t *cr)
63 {
64 	int error = 0;
65 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
66 
67 	(void) tsd_set(zfs_fsyncer_key, (void *)(uintptr_t)zfs_fsync_sync_cnt);
68 
69 	if (zfsvfs->z_os->os_sync != ZFS_SYNC_DISABLED) {
70 		if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
71 			goto out;
72 		atomic_inc_32(&zp->z_sync_writes_cnt);
73 		zil_commit(zfsvfs->z_log, zp->z_id);
74 		atomic_dec_32(&zp->z_sync_writes_cnt);
75 		zfs_exit(zfsvfs, FTAG);
76 	}
77 out:
78 	tsd_set(zfs_fsyncer_key, NULL);
79 
80 	return (error);
81 }
82 
83 
84 #if defined(SEEK_HOLE) && defined(SEEK_DATA)
85 /*
86  * Lseek support for finding holes (cmd == SEEK_HOLE) and
87  * data (cmd == SEEK_DATA). "off" is an in/out parameter.
88  */
89 static int
90 zfs_holey_common(znode_t *zp, ulong_t cmd, loff_t *off)
91 {
92 	zfs_locked_range_t *lr;
93 	uint64_t noff = (uint64_t)*off; /* new offset */
94 	uint64_t file_sz;
95 	int error;
96 	boolean_t hole;
97 
98 	file_sz = zp->z_size;
99 	if (noff >= file_sz)  {
100 		return (SET_ERROR(ENXIO));
101 	}
102 
103 	if (cmd == F_SEEK_HOLE)
104 		hole = B_TRUE;
105 	else
106 		hole = B_FALSE;
107 
108 	/* Flush any mmap()'d data to disk */
109 	if (zn_has_cached_data(zp, 0, file_sz - 1))
110 		zn_flush_cached_data(zp, B_FALSE);
111 
112 	lr = zfs_rangelock_enter(&zp->z_rangelock, 0, file_sz, RL_READER);
113 	error = dmu_offset_next(ZTOZSB(zp)->z_os, zp->z_id, hole, &noff);
114 	zfs_rangelock_exit(lr);
115 
116 	if (error == ESRCH)
117 		return (SET_ERROR(ENXIO));
118 
119 	/* File was dirty, so fall back to using generic logic */
120 	if (error == EBUSY) {
121 		if (hole)
122 			*off = file_sz;
123 
124 		return (0);
125 	}
126 
127 	/*
128 	 * We could find a hole that begins after the logical end-of-file,
129 	 * because dmu_offset_next() only works on whole blocks.  If the
130 	 * EOF falls mid-block, then indicate that the "virtual hole"
131 	 * at the end of the file begins at the logical EOF, rather than
132 	 * at the end of the last block.
133 	 */
134 	if (noff > file_sz) {
135 		ASSERT(hole);
136 		noff = file_sz;
137 	}
138 
139 	if (noff < *off)
140 		return (error);
141 	*off = noff;
142 	return (error);
143 }
144 
145 int
146 zfs_holey(znode_t *zp, ulong_t cmd, loff_t *off)
147 {
148 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
149 	int error;
150 
151 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
152 		return (error);
153 
154 	error = zfs_holey_common(zp, cmd, off);
155 
156 	zfs_exit(zfsvfs, FTAG);
157 	return (error);
158 }
159 #endif /* SEEK_HOLE && SEEK_DATA */
160 
161 int
162 zfs_access(znode_t *zp, int mode, int flag, cred_t *cr)
163 {
164 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
165 	int error;
166 
167 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
168 		return (error);
169 
170 	if (flag & V_ACE_MASK)
171 #if defined(__linux__)
172 		error = zfs_zaccess(zp, mode, flag, B_FALSE, cr,
173 		    kcred->user_ns);
174 #else
175 		error = zfs_zaccess(zp, mode, flag, B_FALSE, cr,
176 		    NULL);
177 #endif
178 	else
179 #if defined(__linux__)
180 		error = zfs_zaccess_rwx(zp, mode, flag, cr, kcred->user_ns);
181 #else
182 		error = zfs_zaccess_rwx(zp, mode, flag, cr, NULL);
183 #endif
184 
185 	zfs_exit(zfsvfs, FTAG);
186 	return (error);
187 }
188 
189 static uint64_t zfs_vnops_read_chunk_size = 1024 * 1024; /* Tunable */
190 
191 /*
192  * Read bytes from specified file into supplied buffer.
193  *
194  *	IN:	zp	- inode of file to be read from.
195  *		uio	- structure supplying read location, range info,
196  *			  and return buffer.
197  *		ioflag	- O_SYNC flags; used to provide FRSYNC semantics.
198  *			  O_DIRECT flag; used to bypass page cache.
199  *		cr	- credentials of caller.
200  *
201  *	OUT:	uio	- updated offset and range, buffer filled.
202  *
203  *	RETURN:	0 on success, error code on failure.
204  *
205  * Side Effects:
206  *	inode - atime updated if byte count > 0
207  */
208 int
209 zfs_read(struct znode *zp, zfs_uio_t *uio, int ioflag, cred_t *cr)
210 {
211 	(void) cr;
212 	int error = 0;
213 	boolean_t frsync = B_FALSE;
214 
215 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
216 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
217 		return (error);
218 
219 	if (zp->z_pflags & ZFS_AV_QUARANTINED) {
220 		zfs_exit(zfsvfs, FTAG);
221 		return (SET_ERROR(EACCES));
222 	}
223 
224 	/* We don't copy out anything useful for directories. */
225 	if (Z_ISDIR(ZTOTYPE(zp))) {
226 		zfs_exit(zfsvfs, FTAG);
227 		return (SET_ERROR(EISDIR));
228 	}
229 
230 	/*
231 	 * Validate file offset
232 	 */
233 	if (zfs_uio_offset(uio) < (offset_t)0) {
234 		zfs_exit(zfsvfs, FTAG);
235 		return (SET_ERROR(EINVAL));
236 	}
237 
238 	/*
239 	 * Fasttrack empty reads
240 	 */
241 	if (zfs_uio_resid(uio) == 0) {
242 		zfs_exit(zfsvfs, FTAG);
243 		return (0);
244 	}
245 
246 #ifdef FRSYNC
247 	/*
248 	 * If we're in FRSYNC mode, sync out this znode before reading it.
249 	 * Only do this for non-snapshots.
250 	 *
251 	 * Some platforms do not support FRSYNC and instead map it
252 	 * to O_SYNC, which results in unnecessary calls to zil_commit. We
253 	 * only honor FRSYNC requests on platforms which support it.
254 	 */
255 	frsync = !!(ioflag & FRSYNC);
256 #endif
257 	if (zfsvfs->z_log &&
258 	    (frsync || zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS))
259 		zil_commit(zfsvfs->z_log, zp->z_id);
260 
261 	/*
262 	 * Lock the range against changes.
263 	 */
264 	zfs_locked_range_t *lr = zfs_rangelock_enter(&zp->z_rangelock,
265 	    zfs_uio_offset(uio), zfs_uio_resid(uio), RL_READER);
266 
267 	/*
268 	 * If we are reading past end-of-file we can skip
269 	 * to the end; but we might still need to set atime.
270 	 */
271 	if (zfs_uio_offset(uio) >= zp->z_size) {
272 		error = 0;
273 		goto out;
274 	}
275 
276 	ASSERT(zfs_uio_offset(uio) < zp->z_size);
277 #if defined(__linux__)
278 	ssize_t start_offset = zfs_uio_offset(uio);
279 #endif
280 	ssize_t n = MIN(zfs_uio_resid(uio), zp->z_size - zfs_uio_offset(uio));
281 	ssize_t start_resid = n;
282 
283 	while (n > 0) {
284 		ssize_t nbytes = MIN(n, zfs_vnops_read_chunk_size -
285 		    P2PHASE(zfs_uio_offset(uio), zfs_vnops_read_chunk_size));
286 #ifdef UIO_NOCOPY
287 		if (zfs_uio_segflg(uio) == UIO_NOCOPY)
288 			error = mappedread_sf(zp, nbytes, uio);
289 		else
290 #endif
291 		if (zn_has_cached_data(zp, zfs_uio_offset(uio),
292 		    zfs_uio_offset(uio) + nbytes - 1) && !(ioflag & O_DIRECT)) {
293 			error = mappedread(zp, nbytes, uio);
294 		} else {
295 			error = dmu_read_uio_dbuf(sa_get_db(zp->z_sa_hdl),
296 			    uio, nbytes);
297 		}
298 
299 		if (error) {
300 			/* convert checksum errors into IO errors */
301 			if (error == ECKSUM)
302 				error = SET_ERROR(EIO);
303 
304 #if defined(__linux__)
305 			/*
306 			 * if we actually read some bytes, bubbling EFAULT
307 			 * up to become EAGAIN isn't what we want here...
308 			 *
309 			 * ...on Linux, at least. On FBSD, doing this breaks.
310 			 */
311 			if (error == EFAULT &&
312 			    (zfs_uio_offset(uio) - start_offset) != 0)
313 				error = 0;
314 #endif
315 			break;
316 		}
317 
318 		n -= nbytes;
319 	}
320 
321 	int64_t nread = start_resid - n;
322 	dataset_kstats_update_read_kstats(&zfsvfs->z_kstat, nread);
323 	task_io_account_read(nread);
324 out:
325 	zfs_rangelock_exit(lr);
326 
327 	ZFS_ACCESSTIME_STAMP(zfsvfs, zp);
328 	zfs_exit(zfsvfs, FTAG);
329 	return (error);
330 }
331 
332 static void
333 zfs_clear_setid_bits_if_necessary(zfsvfs_t *zfsvfs, znode_t *zp, cred_t *cr,
334     uint64_t *clear_setid_bits_txgp, dmu_tx_t *tx)
335 {
336 	zilog_t *zilog = zfsvfs->z_log;
337 	const uint64_t uid = KUID_TO_SUID(ZTOUID(zp));
338 
339 	ASSERT(clear_setid_bits_txgp != NULL);
340 	ASSERT(tx != NULL);
341 
342 	/*
343 	 * Clear Set-UID/Set-GID bits on successful write if not
344 	 * privileged and at least one of the execute bits is set.
345 	 *
346 	 * It would be nice to do this after all writes have
347 	 * been done, but that would still expose the ISUID/ISGID
348 	 * to another app after the partial write is committed.
349 	 *
350 	 * Note: we don't call zfs_fuid_map_id() here because
351 	 * user 0 is not an ephemeral uid.
352 	 */
353 	mutex_enter(&zp->z_acl_lock);
354 	if ((zp->z_mode & (S_IXUSR | (S_IXUSR >> 3) | (S_IXUSR >> 6))) != 0 &&
355 	    (zp->z_mode & (S_ISUID | S_ISGID)) != 0 &&
356 	    secpolicy_vnode_setid_retain(zp, cr,
357 	    ((zp->z_mode & S_ISUID) != 0 && uid == 0)) != 0) {
358 		uint64_t newmode;
359 
360 		zp->z_mode &= ~(S_ISUID | S_ISGID);
361 		newmode = zp->z_mode;
362 		(void) sa_update(zp->z_sa_hdl, SA_ZPL_MODE(zfsvfs),
363 		    (void *)&newmode, sizeof (uint64_t), tx);
364 
365 		mutex_exit(&zp->z_acl_lock);
366 
367 		/*
368 		 * Make sure SUID/SGID bits will be removed when we replay the
369 		 * log. If the setid bits are keep coming back, don't log more
370 		 * than one TX_SETATTR per transaction group.
371 		 */
372 		if (*clear_setid_bits_txgp != dmu_tx_get_txg(tx)) {
373 			vattr_t va = {0};
374 
375 			va.va_mask = ATTR_MODE;
376 			va.va_nodeid = zp->z_id;
377 			va.va_mode = newmode;
378 			zfs_log_setattr(zilog, tx, TX_SETATTR, zp, &va,
379 			    ATTR_MODE, NULL);
380 			*clear_setid_bits_txgp = dmu_tx_get_txg(tx);
381 		}
382 	} else {
383 		mutex_exit(&zp->z_acl_lock);
384 	}
385 }
386 
387 /*
388  * Write the bytes to a file.
389  *
390  *	IN:	zp	- znode of file to be written to.
391  *		uio	- structure supplying write location, range info,
392  *			  and data buffer.
393  *		ioflag	- O_APPEND flag set if in append mode.
394  *			  O_DIRECT flag; used to bypass page cache.
395  *		cr	- credentials of caller.
396  *
397  *	OUT:	uio	- updated offset and range.
398  *
399  *	RETURN:	0 if success
400  *		error code if failure
401  *
402  * Timestamps:
403  *	ip - ctime|mtime updated if byte count > 0
404  */
405 int
406 zfs_write(znode_t *zp, zfs_uio_t *uio, int ioflag, cred_t *cr)
407 {
408 	int error = 0, error1;
409 	ssize_t start_resid = zfs_uio_resid(uio);
410 	uint64_t clear_setid_bits_txg = 0;
411 
412 	/*
413 	 * Fasttrack empty write
414 	 */
415 	ssize_t n = start_resid;
416 	if (n == 0)
417 		return (0);
418 
419 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
420 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
421 		return (error);
422 
423 	sa_bulk_attr_t bulk[4];
424 	int count = 0;
425 	uint64_t mtime[2], ctime[2];
426 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_MTIME(zfsvfs), NULL, &mtime, 16);
427 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_CTIME(zfsvfs), NULL, &ctime, 16);
428 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_SIZE(zfsvfs), NULL,
429 	    &zp->z_size, 8);
430 	SA_ADD_BULK_ATTR(bulk, count, SA_ZPL_FLAGS(zfsvfs), NULL,
431 	    &zp->z_pflags, 8);
432 
433 	/*
434 	 * Callers might not be able to detect properly that we are read-only,
435 	 * so check it explicitly here.
436 	 */
437 	if (zfs_is_readonly(zfsvfs)) {
438 		zfs_exit(zfsvfs, FTAG);
439 		return (SET_ERROR(EROFS));
440 	}
441 
442 	/*
443 	 * If immutable or not appending then return EPERM.
444 	 * Intentionally allow ZFS_READONLY through here.
445 	 * See zfs_zaccess_common()
446 	 */
447 	if ((zp->z_pflags & ZFS_IMMUTABLE) ||
448 	    ((zp->z_pflags & ZFS_APPENDONLY) && !(ioflag & O_APPEND) &&
449 	    (zfs_uio_offset(uio) < zp->z_size))) {
450 		zfs_exit(zfsvfs, FTAG);
451 		return (SET_ERROR(EPERM));
452 	}
453 
454 	/*
455 	 * Validate file offset
456 	 */
457 	offset_t woff = ioflag & O_APPEND ? zp->z_size : zfs_uio_offset(uio);
458 	if (woff < 0) {
459 		zfs_exit(zfsvfs, FTAG);
460 		return (SET_ERROR(EINVAL));
461 	}
462 
463 	const uint64_t max_blksz = zfsvfs->z_max_blksz;
464 
465 	/*
466 	 * Pre-fault the pages to ensure slow (eg NFS) pages
467 	 * don't hold up txg.
468 	 * Skip this if uio contains loaned arc_buf.
469 	 */
470 	if (zfs_uio_prefaultpages(MIN(n, max_blksz), uio)) {
471 		zfs_exit(zfsvfs, FTAG);
472 		return (SET_ERROR(EFAULT));
473 	}
474 
475 	/*
476 	 * If in append mode, set the io offset pointer to eof.
477 	 */
478 	zfs_locked_range_t *lr;
479 	if (ioflag & O_APPEND) {
480 		/*
481 		 * Obtain an appending range lock to guarantee file append
482 		 * semantics.  We reset the write offset once we have the lock.
483 		 */
484 		lr = zfs_rangelock_enter(&zp->z_rangelock, 0, n, RL_APPEND);
485 		woff = lr->lr_offset;
486 		if (lr->lr_length == UINT64_MAX) {
487 			/*
488 			 * We overlocked the file because this write will cause
489 			 * the file block size to increase.
490 			 * Note that zp_size cannot change with this lock held.
491 			 */
492 			woff = zp->z_size;
493 		}
494 		zfs_uio_setoffset(uio, woff);
495 	} else {
496 		/*
497 		 * Note that if the file block size will change as a result of
498 		 * this write, then this range lock will lock the entire file
499 		 * so that we can re-write the block safely.
500 		 */
501 		lr = zfs_rangelock_enter(&zp->z_rangelock, woff, n, RL_WRITER);
502 	}
503 
504 	if (zn_rlimit_fsize(zp, uio)) {
505 		zfs_rangelock_exit(lr);
506 		zfs_exit(zfsvfs, FTAG);
507 		return (SET_ERROR(EFBIG));
508 	}
509 
510 	const rlim64_t limit = MAXOFFSET_T;
511 
512 	if (woff >= limit) {
513 		zfs_rangelock_exit(lr);
514 		zfs_exit(zfsvfs, FTAG);
515 		return (SET_ERROR(EFBIG));
516 	}
517 
518 	if (n > limit - woff)
519 		n = limit - woff;
520 
521 	uint64_t end_size = MAX(zp->z_size, woff + n);
522 	zilog_t *zilog = zfsvfs->z_log;
523 
524 	const uint64_t uid = KUID_TO_SUID(ZTOUID(zp));
525 	const uint64_t gid = KGID_TO_SGID(ZTOGID(zp));
526 	const uint64_t projid = zp->z_projid;
527 
528 	/*
529 	 * Write the file in reasonable size chunks.  Each chunk is written
530 	 * in a separate transaction; this keeps the intent log records small
531 	 * and allows us to do more fine-grained space accounting.
532 	 */
533 	while (n > 0) {
534 		woff = zfs_uio_offset(uio);
535 
536 		if (zfs_id_overblockquota(zfsvfs, DMU_USERUSED_OBJECT, uid) ||
537 		    zfs_id_overblockquota(zfsvfs, DMU_GROUPUSED_OBJECT, gid) ||
538 		    (projid != ZFS_DEFAULT_PROJID &&
539 		    zfs_id_overblockquota(zfsvfs, DMU_PROJECTUSED_OBJECT,
540 		    projid))) {
541 			error = SET_ERROR(EDQUOT);
542 			break;
543 		}
544 
545 		arc_buf_t *abuf = NULL;
546 		if (n >= max_blksz && woff >= zp->z_size &&
547 		    P2PHASE(woff, max_blksz) == 0 &&
548 		    zp->z_blksz == max_blksz) {
549 			/*
550 			 * This write covers a full block.  "Borrow" a buffer
551 			 * from the dmu so that we can fill it before we enter
552 			 * a transaction.  This avoids the possibility of
553 			 * holding up the transaction if the data copy hangs
554 			 * up on a pagefault (e.g., from an NFS server mapping).
555 			 */
556 			size_t cbytes;
557 
558 			abuf = dmu_request_arcbuf(sa_get_db(zp->z_sa_hdl),
559 			    max_blksz);
560 			ASSERT(abuf != NULL);
561 			ASSERT(arc_buf_size(abuf) == max_blksz);
562 			if ((error = zfs_uiocopy(abuf->b_data, max_blksz,
563 			    UIO_WRITE, uio, &cbytes))) {
564 				dmu_return_arcbuf(abuf);
565 				break;
566 			}
567 			ASSERT3S(cbytes, ==, max_blksz);
568 		}
569 
570 		/*
571 		 * Start a transaction.
572 		 */
573 		dmu_tx_t *tx = dmu_tx_create(zfsvfs->z_os);
574 		dmu_tx_hold_sa(tx, zp->z_sa_hdl, B_FALSE);
575 		dmu_buf_impl_t *db = (dmu_buf_impl_t *)sa_get_db(zp->z_sa_hdl);
576 		DB_DNODE_ENTER(db);
577 		dmu_tx_hold_write_by_dnode(tx, DB_DNODE(db), woff,
578 		    MIN(n, max_blksz));
579 		DB_DNODE_EXIT(db);
580 		zfs_sa_upgrade_txholds(tx, zp);
581 		error = dmu_tx_assign(tx, TXG_WAIT);
582 		if (error) {
583 			dmu_tx_abort(tx);
584 			if (abuf != NULL)
585 				dmu_return_arcbuf(abuf);
586 			break;
587 		}
588 
589 		/*
590 		 * NB: We must call zfs_clear_setid_bits_if_necessary before
591 		 * committing the transaction!
592 		 */
593 
594 		/*
595 		 * If rangelock_enter() over-locked we grow the blocksize
596 		 * and then reduce the lock range.  This will only happen
597 		 * on the first iteration since rangelock_reduce() will
598 		 * shrink down lr_length to the appropriate size.
599 		 */
600 		if (lr->lr_length == UINT64_MAX) {
601 			uint64_t new_blksz;
602 
603 			if (zp->z_blksz > max_blksz) {
604 				/*
605 				 * File's blocksize is already larger than the
606 				 * "recordsize" property.  Only let it grow to
607 				 * the next power of 2.
608 				 */
609 				ASSERT(!ISP2(zp->z_blksz));
610 				new_blksz = MIN(end_size,
611 				    1 << highbit64(zp->z_blksz));
612 			} else {
613 				new_blksz = MIN(end_size, max_blksz);
614 			}
615 			zfs_grow_blocksize(zp, new_blksz, tx);
616 			zfs_rangelock_reduce(lr, woff, n);
617 		}
618 
619 		/*
620 		 * XXX - should we really limit each write to z_max_blksz?
621 		 * Perhaps we should use SPA_MAXBLOCKSIZE chunks?
622 		 */
623 		const ssize_t nbytes =
624 		    MIN(n, max_blksz - P2PHASE(woff, max_blksz));
625 
626 		ssize_t tx_bytes;
627 		if (abuf == NULL) {
628 			tx_bytes = zfs_uio_resid(uio);
629 			zfs_uio_fault_disable(uio, B_TRUE);
630 			error = dmu_write_uio_dbuf(sa_get_db(zp->z_sa_hdl),
631 			    uio, nbytes, tx);
632 			zfs_uio_fault_disable(uio, B_FALSE);
633 #ifdef __linux__
634 			if (error == EFAULT) {
635 				zfs_clear_setid_bits_if_necessary(zfsvfs, zp,
636 				    cr, &clear_setid_bits_txg, tx);
637 				dmu_tx_commit(tx);
638 				/*
639 				 * Account for partial writes before
640 				 * continuing the loop.
641 				 * Update needs to occur before the next
642 				 * zfs_uio_prefaultpages, or prefaultpages may
643 				 * error, and we may break the loop early.
644 				 */
645 				if (tx_bytes != zfs_uio_resid(uio))
646 					n -= tx_bytes - zfs_uio_resid(uio);
647 				if (zfs_uio_prefaultpages(MIN(n, max_blksz),
648 				    uio)) {
649 					break;
650 				}
651 				continue;
652 			}
653 #endif
654 			/*
655 			 * On FreeBSD, EFAULT should be propagated back to the
656 			 * VFS, which will handle faulting and will retry.
657 			 */
658 			if (error != 0 && error != EFAULT) {
659 				zfs_clear_setid_bits_if_necessary(zfsvfs, zp,
660 				    cr, &clear_setid_bits_txg, tx);
661 				dmu_tx_commit(tx);
662 				break;
663 			}
664 			tx_bytes -= zfs_uio_resid(uio);
665 		} else {
666 			/* Implied by abuf != NULL: */
667 			ASSERT3S(n, >=, max_blksz);
668 			ASSERT0(P2PHASE(woff, max_blksz));
669 			/*
670 			 * We can simplify nbytes to MIN(n, max_blksz) since
671 			 * P2PHASE(woff, max_blksz) is 0, and knowing
672 			 * n >= max_blksz lets us simplify further:
673 			 */
674 			ASSERT3S(nbytes, ==, max_blksz);
675 			/*
676 			 * Thus, we're writing a full block at a block-aligned
677 			 * offset and extending the file past EOF.
678 			 *
679 			 * dmu_assign_arcbuf_by_dbuf() will directly assign the
680 			 * arc buffer to a dbuf.
681 			 */
682 			error = dmu_assign_arcbuf_by_dbuf(
683 			    sa_get_db(zp->z_sa_hdl), woff, abuf, tx);
684 			if (error != 0) {
685 				/*
686 				 * XXX This might not be necessary if
687 				 * dmu_assign_arcbuf_by_dbuf is guaranteed
688 				 * to be atomic.
689 				 */
690 				zfs_clear_setid_bits_if_necessary(zfsvfs, zp,
691 				    cr, &clear_setid_bits_txg, tx);
692 				dmu_return_arcbuf(abuf);
693 				dmu_tx_commit(tx);
694 				break;
695 			}
696 			ASSERT3S(nbytes, <=, zfs_uio_resid(uio));
697 			zfs_uioskip(uio, nbytes);
698 			tx_bytes = nbytes;
699 		}
700 		if (tx_bytes &&
701 		    zn_has_cached_data(zp, woff, woff + tx_bytes - 1) &&
702 		    !(ioflag & O_DIRECT)) {
703 			update_pages(zp, woff, tx_bytes, zfsvfs->z_os);
704 		}
705 
706 		/*
707 		 * If we made no progress, we're done.  If we made even
708 		 * partial progress, update the znode and ZIL accordingly.
709 		 */
710 		if (tx_bytes == 0) {
711 			(void) sa_update(zp->z_sa_hdl, SA_ZPL_SIZE(zfsvfs),
712 			    (void *)&zp->z_size, sizeof (uint64_t), tx);
713 			dmu_tx_commit(tx);
714 			ASSERT(error != 0);
715 			break;
716 		}
717 
718 		zfs_clear_setid_bits_if_necessary(zfsvfs, zp, cr,
719 		    &clear_setid_bits_txg, tx);
720 
721 		zfs_tstamp_update_setup(zp, CONTENT_MODIFIED, mtime, ctime);
722 
723 		/*
724 		 * Update the file size (zp_size) if it has changed;
725 		 * account for possible concurrent updates.
726 		 */
727 		while ((end_size = zp->z_size) < zfs_uio_offset(uio)) {
728 			(void) atomic_cas_64(&zp->z_size, end_size,
729 			    zfs_uio_offset(uio));
730 			ASSERT(error == 0 || error == EFAULT);
731 		}
732 		/*
733 		 * If we are replaying and eof is non zero then force
734 		 * the file size to the specified eof. Note, there's no
735 		 * concurrency during replay.
736 		 */
737 		if (zfsvfs->z_replay && zfsvfs->z_replay_eof != 0)
738 			zp->z_size = zfsvfs->z_replay_eof;
739 
740 		error1 = sa_bulk_update(zp->z_sa_hdl, bulk, count, tx);
741 		if (error1 != 0)
742 			/* Avoid clobbering EFAULT. */
743 			error = error1;
744 
745 		/*
746 		 * NB: During replay, the TX_SETATTR record logged by
747 		 * zfs_clear_setid_bits_if_necessary must precede any of
748 		 * the TX_WRITE records logged here.
749 		 */
750 		zfs_log_write(zilog, tx, TX_WRITE, zp, woff, tx_bytes, ioflag,
751 		    NULL, NULL);
752 
753 		dmu_tx_commit(tx);
754 
755 		if (error != 0)
756 			break;
757 		ASSERT3S(tx_bytes, ==, nbytes);
758 		n -= nbytes;
759 
760 		if (n > 0) {
761 			if (zfs_uio_prefaultpages(MIN(n, max_blksz), uio)) {
762 				error = SET_ERROR(EFAULT);
763 				break;
764 			}
765 		}
766 	}
767 
768 	zfs_znode_update_vfs(zp);
769 	zfs_rangelock_exit(lr);
770 
771 	/*
772 	 * If we're in replay mode, or we made no progress, or the
773 	 * uio data is inaccessible return an error.  Otherwise, it's
774 	 * at least a partial write, so it's successful.
775 	 */
776 	if (zfsvfs->z_replay || zfs_uio_resid(uio) == start_resid ||
777 	    error == EFAULT) {
778 		zfs_exit(zfsvfs, FTAG);
779 		return (error);
780 	}
781 
782 	if (ioflag & (O_SYNC | O_DSYNC) ||
783 	    zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
784 		zil_commit(zilog, zp->z_id);
785 
786 	const int64_t nwritten = start_resid - zfs_uio_resid(uio);
787 	dataset_kstats_update_write_kstats(&zfsvfs->z_kstat, nwritten);
788 	task_io_account_write(nwritten);
789 
790 	zfs_exit(zfsvfs, FTAG);
791 	return (0);
792 }
793 
794 int
795 zfs_getsecattr(znode_t *zp, vsecattr_t *vsecp, int flag, cred_t *cr)
796 {
797 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
798 	int error;
799 	boolean_t skipaclchk = (flag & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
800 
801 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
802 		return (error);
803 	error = zfs_getacl(zp, vsecp, skipaclchk, cr);
804 	zfs_exit(zfsvfs, FTAG);
805 
806 	return (error);
807 }
808 
809 int
810 zfs_setsecattr(znode_t *zp, vsecattr_t *vsecp, int flag, cred_t *cr)
811 {
812 	zfsvfs_t *zfsvfs = ZTOZSB(zp);
813 	int error;
814 	boolean_t skipaclchk = (flag & ATTR_NOACLCHECK) ? B_TRUE : B_FALSE;
815 	zilog_t	*zilog = zfsvfs->z_log;
816 
817 	if ((error = zfs_enter_verify_zp(zfsvfs, zp, FTAG)) != 0)
818 		return (error);
819 
820 	error = zfs_setacl(zp, vsecp, skipaclchk, cr);
821 
822 	if (zfsvfs->z_os->os_sync == ZFS_SYNC_ALWAYS)
823 		zil_commit(zilog, 0);
824 
825 	zfs_exit(zfsvfs, FTAG);
826 	return (error);
827 }
828 
829 #ifdef ZFS_DEBUG
830 static int zil_fault_io = 0;
831 #endif
832 
833 static void zfs_get_done(zgd_t *zgd, int error);
834 
835 /*
836  * Get data to generate a TX_WRITE intent log record.
837  */
838 int
839 zfs_get_data(void *arg, uint64_t gen, lr_write_t *lr, char *buf,
840     struct lwb *lwb, zio_t *zio)
841 {
842 	zfsvfs_t *zfsvfs = arg;
843 	objset_t *os = zfsvfs->z_os;
844 	znode_t *zp;
845 	uint64_t object = lr->lr_foid;
846 	uint64_t offset = lr->lr_offset;
847 	uint64_t size = lr->lr_length;
848 	dmu_buf_t *db;
849 	zgd_t *zgd;
850 	int error = 0;
851 	uint64_t zp_gen;
852 
853 	ASSERT3P(lwb, !=, NULL);
854 	ASSERT3P(zio, !=, NULL);
855 	ASSERT3U(size, !=, 0);
856 
857 	/*
858 	 * Nothing to do if the file has been removed
859 	 */
860 	if (zfs_zget(zfsvfs, object, &zp) != 0)
861 		return (SET_ERROR(ENOENT));
862 	if (zp->z_unlinked) {
863 		/*
864 		 * Release the vnode asynchronously as we currently have the
865 		 * txg stopped from syncing.
866 		 */
867 		zfs_zrele_async(zp);
868 		return (SET_ERROR(ENOENT));
869 	}
870 	/* check if generation number matches */
871 	if (sa_lookup(zp->z_sa_hdl, SA_ZPL_GEN(zfsvfs), &zp_gen,
872 	    sizeof (zp_gen)) != 0) {
873 		zfs_zrele_async(zp);
874 		return (SET_ERROR(EIO));
875 	}
876 	if (zp_gen != gen) {
877 		zfs_zrele_async(zp);
878 		return (SET_ERROR(ENOENT));
879 	}
880 
881 	zgd = kmem_zalloc(sizeof (zgd_t), KM_SLEEP);
882 	zgd->zgd_lwb = lwb;
883 	zgd->zgd_private = zp;
884 
885 	/*
886 	 * Write records come in two flavors: immediate and indirect.
887 	 * For small writes it's cheaper to store the data with the
888 	 * log record (immediate); for large writes it's cheaper to
889 	 * sync the data and get a pointer to it (indirect) so that
890 	 * we don't have to write the data twice.
891 	 */
892 	if (buf != NULL) { /* immediate write */
893 		zgd->zgd_lr = zfs_rangelock_enter(&zp->z_rangelock,
894 		    offset, size, RL_READER);
895 		/* test for truncation needs to be done while range locked */
896 		if (offset >= zp->z_size) {
897 			error = SET_ERROR(ENOENT);
898 		} else {
899 			error = dmu_read(os, object, offset, size, buf,
900 			    DMU_READ_NO_PREFETCH);
901 		}
902 		ASSERT(error == 0 || error == ENOENT);
903 	} else { /* indirect write */
904 		/*
905 		 * Have to lock the whole block to ensure when it's
906 		 * written out and its checksum is being calculated
907 		 * that no one can change the data. We need to re-check
908 		 * blocksize after we get the lock in case it's changed!
909 		 */
910 		for (;;) {
911 			uint64_t blkoff;
912 			size = zp->z_blksz;
913 			blkoff = ISP2(size) ? P2PHASE(offset, size) : offset;
914 			offset -= blkoff;
915 			zgd->zgd_lr = zfs_rangelock_enter(&zp->z_rangelock,
916 			    offset, size, RL_READER);
917 			if (zp->z_blksz == size)
918 				break;
919 			offset += blkoff;
920 			zfs_rangelock_exit(zgd->zgd_lr);
921 		}
922 		/* test for truncation needs to be done while range locked */
923 		if (lr->lr_offset >= zp->z_size)
924 			error = SET_ERROR(ENOENT);
925 #ifdef ZFS_DEBUG
926 		if (zil_fault_io) {
927 			error = SET_ERROR(EIO);
928 			zil_fault_io = 0;
929 		}
930 #endif
931 		if (error == 0)
932 			error = dmu_buf_hold(os, object, offset, zgd, &db,
933 			    DMU_READ_NO_PREFETCH);
934 
935 		if (error == 0) {
936 			blkptr_t *bp = &lr->lr_blkptr;
937 
938 			zgd->zgd_db = db;
939 			zgd->zgd_bp = bp;
940 
941 			ASSERT(db->db_offset == offset);
942 			ASSERT(db->db_size == size);
943 
944 			error = dmu_sync(zio, lr->lr_common.lrc_txg,
945 			    zfs_get_done, zgd);
946 			ASSERT(error || lr->lr_length <= size);
947 
948 			/*
949 			 * On success, we need to wait for the write I/O
950 			 * initiated by dmu_sync() to complete before we can
951 			 * release this dbuf.  We will finish everything up
952 			 * in the zfs_get_done() callback.
953 			 */
954 			if (error == 0)
955 				return (0);
956 
957 			if (error == EALREADY) {
958 				lr->lr_common.lrc_txtype = TX_WRITE2;
959 				/*
960 				 * TX_WRITE2 relies on the data previously
961 				 * written by the TX_WRITE that caused
962 				 * EALREADY.  We zero out the BP because
963 				 * it is the old, currently-on-disk BP.
964 				 */
965 				zgd->zgd_bp = NULL;
966 				BP_ZERO(bp);
967 				error = 0;
968 			}
969 		}
970 	}
971 
972 	zfs_get_done(zgd, error);
973 
974 	return (error);
975 }
976 
977 
978 static void
979 zfs_get_done(zgd_t *zgd, int error)
980 {
981 	(void) error;
982 	znode_t *zp = zgd->zgd_private;
983 
984 	if (zgd->zgd_db)
985 		dmu_buf_rele(zgd->zgd_db, zgd);
986 
987 	zfs_rangelock_exit(zgd->zgd_lr);
988 
989 	/*
990 	 * Release the vnode asynchronously as we currently have the
991 	 * txg stopped from syncing.
992 	 */
993 	zfs_zrele_async(zp);
994 
995 	kmem_free(zgd, sizeof (zgd_t));
996 }
997 
998 EXPORT_SYMBOL(zfs_access);
999 EXPORT_SYMBOL(zfs_fsync);
1000 EXPORT_SYMBOL(zfs_holey);
1001 EXPORT_SYMBOL(zfs_read);
1002 EXPORT_SYMBOL(zfs_write);
1003 EXPORT_SYMBOL(zfs_getsecattr);
1004 EXPORT_SYMBOL(zfs_setsecattr);
1005 
1006 ZFS_MODULE_PARAM(zfs_vnops, zfs_vnops_, read_chunk_size, U64, ZMOD_RW,
1007 	"Bytes to read per chunk");
1008