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