xref: /freebsd/sys/kern/vfs_vnops.c (revision 6597ea4481bb29b6ac72b9c55038b1e98634bf92)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1989, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  * (c) UNIX System Laboratories, Inc.
7  * All or some portions of this file are derived from material licensed
8  * to the University of California by American Telephone and Telegraph
9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10  * the permission of UNIX System Laboratories, Inc.
11  *
12  * Copyright (c) 2012 Konstantin Belousov <kib@FreeBSD.org>
13  * Copyright (c) 2013, 2014 The FreeBSD Foundation
14  *
15  * Portions of this software were developed by Konstantin Belousov
16  * under sponsorship from the FreeBSD Foundation.
17  *
18  * Redistribution and use in source and binary forms, with or without
19  * modification, are permitted provided that the following conditions
20  * are met:
21  * 1. Redistributions of source code must retain the above copyright
22  *    notice, this list of conditions and the following disclaimer.
23  * 2. Redistributions in binary form must reproduce the above copyright
24  *    notice, this list of conditions and the following disclaimer in the
25  *    documentation and/or other materials provided with the distribution.
26  * 3. Neither the name of the University nor the names of its contributors
27  *    may be used to endorse or promote products derived from this software
28  *    without specific prior written permission.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
31  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
34  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40  * SUCH DAMAGE.
41  */
42 
43 #include <sys/cdefs.h>
44 #include "opt_hwpmc_hooks.h"
45 
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/disk.h>
49 #include <sys/fail.h>
50 #include <sys/fcntl.h>
51 #include <sys/file.h>
52 #include <sys/kdb.h>
53 #include <sys/ktr.h>
54 #include <sys/stat.h>
55 #include <sys/priv.h>
56 #include <sys/proc.h>
57 #include <sys/limits.h>
58 #include <sys/lock.h>
59 #include <sys/mman.h>
60 #include <sys/mount.h>
61 #include <sys/mutex.h>
62 #include <sys/namei.h>
63 #include <sys/vnode.h>
64 #include <sys/dirent.h>
65 #include <sys/bio.h>
66 #include <sys/buf.h>
67 #include <sys/filio.h>
68 #include <sys/resourcevar.h>
69 #include <sys/rwlock.h>
70 #include <sys/prng.h>
71 #include <sys/sx.h>
72 #include <sys/sleepqueue.h>
73 #include <sys/sysctl.h>
74 #include <sys/ttycom.h>
75 #include <sys/conf.h>
76 #include <sys/syslog.h>
77 #include <sys/unistd.h>
78 #include <sys/user.h>
79 #include <sys/ktrace.h>
80 
81 #include <security/audit/audit.h>
82 #include <security/mac/mac_framework.h>
83 
84 #include <vm/vm.h>
85 #include <vm/vm_extern.h>
86 #include <vm/pmap.h>
87 #include <vm/vm_map.h>
88 #include <vm/vm_object.h>
89 #include <vm/vm_page.h>
90 #include <vm/vm_pager.h>
91 #include <vm/vnode_pager.h>
92 
93 #ifdef HWPMC_HOOKS
94 #include <sys/pmckern.h>
95 #endif
96 
97 static fo_rdwr_t	vn_read;
98 static fo_rdwr_t	vn_write;
99 static fo_rdwr_t	vn_io_fault;
100 static fo_truncate_t	vn_truncate;
101 static fo_ioctl_t	vn_ioctl;
102 static fo_poll_t	vn_poll;
103 static fo_kqfilter_t	vn_kqfilter;
104 static fo_close_t	vn_closefile;
105 static fo_mmap_t	vn_mmap;
106 static fo_fallocate_t	vn_fallocate;
107 static fo_fspacectl_t	vn_fspacectl;
108 
109 struct 	fileops vnops = {
110 	.fo_read = vn_io_fault,
111 	.fo_write = vn_io_fault,
112 	.fo_truncate = vn_truncate,
113 	.fo_ioctl = vn_ioctl,
114 	.fo_poll = vn_poll,
115 	.fo_kqfilter = vn_kqfilter,
116 	.fo_stat = vn_statfile,
117 	.fo_close = vn_closefile,
118 	.fo_chmod = vn_chmod,
119 	.fo_chown = vn_chown,
120 	.fo_sendfile = vn_sendfile,
121 	.fo_seek = vn_seek,
122 	.fo_fill_kinfo = vn_fill_kinfo,
123 	.fo_mmap = vn_mmap,
124 	.fo_fallocate = vn_fallocate,
125 	.fo_fspacectl = vn_fspacectl,
126 	.fo_flags = DFLAG_PASSABLE | DFLAG_SEEKABLE
127 };
128 
129 const u_int io_hold_cnt = 16;
130 static int vn_io_fault_enable = 1;
131 SYSCTL_INT(_debug, OID_AUTO, vn_io_fault_enable, CTLFLAG_RWTUN,
132     &vn_io_fault_enable, 0, "Enable vn_io_fault lock avoidance");
133 static int vn_io_fault_prefault = 0;
134 SYSCTL_INT(_debug, OID_AUTO, vn_io_fault_prefault, CTLFLAG_RWTUN,
135     &vn_io_fault_prefault, 0, "Enable vn_io_fault prefaulting");
136 static int vn_io_pgcache_read_enable = 1;
137 SYSCTL_INT(_debug, OID_AUTO, vn_io_pgcache_read_enable, CTLFLAG_RWTUN,
138     &vn_io_pgcache_read_enable, 0,
139     "Enable copying from page cache for reads, avoiding fs");
140 static u_long vn_io_faults_cnt;
141 SYSCTL_ULONG(_debug, OID_AUTO, vn_io_faults, CTLFLAG_RD,
142     &vn_io_faults_cnt, 0, "Count of vn_io_fault lock avoidance triggers");
143 
144 static int vfs_allow_read_dir = 0;
145 SYSCTL_INT(_security_bsd, OID_AUTO, allow_read_dir, CTLFLAG_RW,
146     &vfs_allow_read_dir, 0,
147     "Enable read(2) of directory by root for filesystems that support it");
148 
149 /*
150  * Returns true if vn_io_fault mode of handling the i/o request should
151  * be used.
152  */
153 static bool
154 do_vn_io_fault(struct vnode *vp, struct uio *uio)
155 {
156 	struct mount *mp;
157 
158 	return (uio->uio_segflg == UIO_USERSPACE && vp->v_type == VREG &&
159 	    (mp = vp->v_mount) != NULL &&
160 	    (mp->mnt_kern_flag & MNTK_NO_IOPF) != 0 && vn_io_fault_enable);
161 }
162 
163 /*
164  * Structure used to pass arguments to vn_io_fault1(), to do either
165  * file- or vnode-based I/O calls.
166  */
167 struct vn_io_fault_args {
168 	enum {
169 		VN_IO_FAULT_FOP,
170 		VN_IO_FAULT_VOP
171 	} kind;
172 	struct ucred *cred;
173 	int flags;
174 	union {
175 		struct fop_args_tag {
176 			struct file *fp;
177 			fo_rdwr_t *doio;
178 		} fop_args;
179 		struct vop_args_tag {
180 			struct vnode *vp;
181 		} vop_args;
182 	} args;
183 };
184 
185 static int vn_io_fault1(struct vnode *vp, struct uio *uio,
186     struct vn_io_fault_args *args, struct thread *td);
187 
188 int
189 vn_open(struct nameidata *ndp, int *flagp, int cmode, struct file *fp)
190 {
191 	struct thread *td = curthread;
192 
193 	return (vn_open_cred(ndp, flagp, cmode, 0, td->td_ucred, fp));
194 }
195 
196 static uint64_t
197 open2nameif(int fmode, u_int vn_open_flags)
198 {
199 	uint64_t res;
200 
201 	res = ISOPEN | LOCKLEAF;
202 	if ((fmode & O_RESOLVE_BENEATH) != 0)
203 		res |= RBENEATH;
204 	if ((fmode & O_EMPTY_PATH) != 0)
205 		res |= EMPTYPATH;
206 	if ((fmode & FREAD) != 0)
207 		res |= OPENREAD;
208 	if ((fmode & FWRITE) != 0)
209 		res |= OPENWRITE;
210 	if ((vn_open_flags & VN_OPEN_NOAUDIT) == 0)
211 		res |= AUDITVNODE1;
212 	if ((vn_open_flags & VN_OPEN_NOCAPCHECK) != 0)
213 		res |= NOCAPCHECK;
214 	if ((vn_open_flags & VN_OPEN_WANTIOCTLCAPS) != 0)
215 		res |= WANTIOCTLCAPS;
216 	return (res);
217 }
218 
219 /*
220  * Common code for vnode open operations via a name lookup.
221  * Lookup the vnode and invoke VOP_CREATE if needed.
222  * Check permissions, and call the VOP_OPEN or VOP_CREATE routine.
223  *
224  * Note that this does NOT free nameidata for the successful case,
225  * due to the NDINIT being done elsewhere.
226  */
227 int
228 vn_open_cred(struct nameidata *ndp, int *flagp, int cmode, u_int vn_open_flags,
229     struct ucred *cred, struct file *fp)
230 {
231 	struct vnode *vp;
232 	struct mount *mp;
233 	struct vattr vat;
234 	struct vattr *vap = &vat;
235 	int fmode, error;
236 	bool first_open;
237 
238 restart:
239 	first_open = false;
240 	fmode = *flagp;
241 	if ((fmode & (O_CREAT | O_EXCL | O_DIRECTORY)) == (O_CREAT |
242 	    O_EXCL | O_DIRECTORY) ||
243 	    (fmode & (O_CREAT | O_EMPTY_PATH)) == (O_CREAT | O_EMPTY_PATH))
244 		return (EINVAL);
245 	else if ((fmode & (O_CREAT | O_DIRECTORY)) == O_CREAT) {
246 		ndp->ni_cnd.cn_nameiop = CREATE;
247 		ndp->ni_cnd.cn_flags = open2nameif(fmode, vn_open_flags);
248 		/*
249 		 * Set NOCACHE to avoid flushing the cache when
250 		 * rolling in many files at once.
251 		 *
252 		 * Set NC_KEEPPOSENTRY to keep positive entries if they already
253 		 * exist despite NOCACHE.
254 		 */
255 		ndp->ni_cnd.cn_flags |= LOCKPARENT | NOCACHE | NC_KEEPPOSENTRY;
256 		if ((fmode & O_EXCL) == 0 && (fmode & O_NOFOLLOW) == 0)
257 			ndp->ni_cnd.cn_flags |= FOLLOW;
258 		if ((vn_open_flags & VN_OPEN_INVFS) == 0)
259 			bwillwrite();
260 		if ((error = namei(ndp)) != 0)
261 			return (error);
262 		if (ndp->ni_vp == NULL) {
263 			VATTR_NULL(vap);
264 			vap->va_type = VREG;
265 			vap->va_mode = cmode;
266 			if (fmode & O_EXCL)
267 				vap->va_vaflags |= VA_EXCLUSIVE;
268 			if (vn_start_write(ndp->ni_dvp, &mp, V_NOWAIT) != 0) {
269 				NDFREE_PNBUF(ndp);
270 				vput(ndp->ni_dvp);
271 				if ((error = vn_start_write(NULL, &mp,
272 				    V_XSLEEP | V_PCATCH)) != 0)
273 					return (error);
274 				NDREINIT(ndp);
275 				goto restart;
276 			}
277 			if ((vn_open_flags & VN_OPEN_NAMECACHE) != 0)
278 				ndp->ni_cnd.cn_flags |= MAKEENTRY;
279 #ifdef MAC
280 			error = mac_vnode_check_create(cred, ndp->ni_dvp,
281 			    &ndp->ni_cnd, vap);
282 			if (error == 0)
283 #endif
284 				error = VOP_CREATE(ndp->ni_dvp, &ndp->ni_vp,
285 				    &ndp->ni_cnd, vap);
286 			vp = ndp->ni_vp;
287 			if (error == 0 && (fmode & O_EXCL) != 0 &&
288 			    (fmode & (O_EXLOCK | O_SHLOCK)) != 0) {
289 				VI_LOCK(vp);
290 				vp->v_iflag |= VI_FOPENING;
291 				VI_UNLOCK(vp);
292 				first_open = true;
293 			}
294 			VOP_VPUT_PAIR(ndp->ni_dvp, error == 0 ? &vp : NULL,
295 			    false);
296 			vn_finished_write(mp);
297 			if (error) {
298 				NDFREE_PNBUF(ndp);
299 				if (error == ERELOOKUP) {
300 					NDREINIT(ndp);
301 					goto restart;
302 				}
303 				return (error);
304 			}
305 			fmode &= ~O_TRUNC;
306 		} else {
307 			if (ndp->ni_dvp == ndp->ni_vp)
308 				vrele(ndp->ni_dvp);
309 			else
310 				vput(ndp->ni_dvp);
311 			ndp->ni_dvp = NULL;
312 			vp = ndp->ni_vp;
313 			if (fmode & O_EXCL) {
314 				error = EEXIST;
315 				goto bad;
316 			}
317 			if (vp->v_type == VDIR) {
318 				error = EISDIR;
319 				goto bad;
320 			}
321 			fmode &= ~O_CREAT;
322 		}
323 	} else {
324 		ndp->ni_cnd.cn_nameiop = LOOKUP;
325 		ndp->ni_cnd.cn_flags = open2nameif(fmode, vn_open_flags);
326 		ndp->ni_cnd.cn_flags |= (fmode & O_NOFOLLOW) != 0 ? NOFOLLOW :
327 		    FOLLOW;
328 		if ((fmode & FWRITE) == 0)
329 			ndp->ni_cnd.cn_flags |= LOCKSHARED;
330 		if ((error = namei(ndp)) != 0)
331 			return (error);
332 		vp = ndp->ni_vp;
333 	}
334 	error = vn_open_vnode(vp, fmode, cred, curthread, fp);
335 	if (first_open) {
336 		VI_LOCK(vp);
337 		vp->v_iflag &= ~VI_FOPENING;
338 		wakeup(vp);
339 		VI_UNLOCK(vp);
340 	}
341 	if (error)
342 		goto bad;
343 	*flagp = fmode;
344 	return (0);
345 bad:
346 	NDFREE_PNBUF(ndp);
347 	vput(vp);
348 	*flagp = fmode;
349 	ndp->ni_vp = NULL;
350 	return (error);
351 }
352 
353 static int
354 vn_open_vnode_advlock(struct vnode *vp, int fmode, struct file *fp)
355 {
356 	struct flock lf;
357 	int error, lock_flags, type;
358 
359 	ASSERT_VOP_LOCKED(vp, "vn_open_vnode_advlock");
360 	if ((fmode & (O_EXLOCK | O_SHLOCK)) == 0)
361 		return (0);
362 	KASSERT(fp != NULL, ("open with flock requires fp"));
363 	if (fp->f_type != DTYPE_NONE && fp->f_type != DTYPE_VNODE)
364 		return (EOPNOTSUPP);
365 
366 	lock_flags = VOP_ISLOCKED(vp);
367 	VOP_UNLOCK(vp);
368 
369 	lf.l_whence = SEEK_SET;
370 	lf.l_start = 0;
371 	lf.l_len = 0;
372 	lf.l_type = (fmode & O_EXLOCK) != 0 ? F_WRLCK : F_RDLCK;
373 	type = F_FLOCK;
374 	if ((fmode & FNONBLOCK) == 0)
375 		type |= F_WAIT;
376 	if ((fmode & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL))
377 		type |= F_FIRSTOPEN;
378 	error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, type);
379 	if (error == 0)
380 		fp->f_flag |= FHASLOCK;
381 
382 	vn_lock(vp, lock_flags | LK_RETRY);
383 	return (error);
384 }
385 
386 /*
387  * Common code for vnode open operations once a vnode is located.
388  * Check permissions, and call the VOP_OPEN routine.
389  */
390 int
391 vn_open_vnode(struct vnode *vp, int fmode, struct ucred *cred,
392     struct thread *td, struct file *fp)
393 {
394 	accmode_t accmode;
395 	int error;
396 
397 	if (vp->v_type == VLNK) {
398 		if ((fmode & O_PATH) == 0 || (fmode & FEXEC) != 0)
399 			return (EMLINK);
400 	}
401 	if (vp->v_type != VDIR && fmode & O_DIRECTORY)
402 		return (ENOTDIR);
403 
404 	accmode = 0;
405 	if ((fmode & O_PATH) == 0) {
406 		if (vp->v_type == VSOCK)
407 			return (EOPNOTSUPP);
408 		if ((fmode & (FWRITE | O_TRUNC)) != 0) {
409 			if (vp->v_type == VDIR)
410 				return (EISDIR);
411 			accmode |= VWRITE;
412 		}
413 		if ((fmode & FREAD) != 0)
414 			accmode |= VREAD;
415 		if ((fmode & O_APPEND) && (fmode & FWRITE))
416 			accmode |= VAPPEND;
417 #ifdef MAC
418 		if ((fmode & O_CREAT) != 0)
419 			accmode |= VCREAT;
420 #endif
421 	}
422 	if ((fmode & FEXEC) != 0)
423 		accmode |= VEXEC;
424 #ifdef MAC
425 	if ((fmode & O_VERIFY) != 0)
426 		accmode |= VVERIFY;
427 	error = mac_vnode_check_open(cred, vp, accmode);
428 	if (error != 0)
429 		return (error);
430 
431 	accmode &= ~(VCREAT | VVERIFY);
432 #endif
433 	if ((fmode & O_CREAT) == 0 && accmode != 0) {
434 		error = VOP_ACCESS(vp, accmode, cred, td);
435 		if (error != 0)
436 			return (error);
437 	}
438 	if ((fmode & O_PATH) != 0) {
439 		if (vp->v_type != VFIFO && vp->v_type != VSOCK &&
440 		    VOP_ACCESS(vp, VREAD, cred, td) == 0)
441 			fp->f_flag |= FKQALLOWED;
442 		return (0);
443 	}
444 
445 	if (vp->v_type == VFIFO && VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
446 		vn_lock(vp, LK_UPGRADE | LK_RETRY);
447 	error = VOP_OPEN(vp, fmode, cred, td, fp);
448 	if (error != 0)
449 		return (error);
450 
451 	error = vn_open_vnode_advlock(vp, fmode, fp);
452 	if (error == 0 && (fmode & FWRITE) != 0) {
453 		error = VOP_ADD_WRITECOUNT(vp, 1);
454 		if (error == 0) {
455 			CTR3(KTR_VFS, "%s: vp %p v_writecount increased to %d",
456 			     __func__, vp, vp->v_writecount);
457 		}
458 	}
459 
460 	/*
461 	 * Error from advlock or VOP_ADD_WRITECOUNT() still requires
462 	 * calling VOP_CLOSE() to pair with earlier VOP_OPEN().
463 	 */
464 	if (error != 0) {
465 		if (fp != NULL) {
466 			/*
467 			 * Arrange the call by having fdrop() to use
468 			 * vn_closefile().  This is to satisfy
469 			 * filesystems like devfs or tmpfs, which
470 			 * override fo_close().
471 			 */
472 			fp->f_flag |= FOPENFAILED;
473 			fp->f_vnode = vp;
474 			if (fp->f_ops == &badfileops) {
475 				fp->f_type = DTYPE_VNODE;
476 				fp->f_ops = &vnops;
477 			}
478 			vref(vp);
479 		} else {
480 			/*
481 			 * If there is no fp, due to kernel-mode open,
482 			 * we can call VOP_CLOSE() now.
483 			 */
484 			if ((vp->v_type == VFIFO ||
485 			    !MNT_EXTENDED_SHARED(vp->v_mount)) &&
486 			    VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
487 				vn_lock(vp, LK_UPGRADE | LK_RETRY);
488 			(void)VOP_CLOSE(vp, fmode & (FREAD | FWRITE | FEXEC),
489 			    cred, td);
490 		}
491 	}
492 
493 	ASSERT_VOP_LOCKED(vp, "vn_open_vnode");
494 	return (error);
495 
496 }
497 
498 /*
499  * Check for write permissions on the specified vnode.
500  * Prototype text segments cannot be written.
501  * It is racy.
502  */
503 int
504 vn_writechk(struct vnode *vp)
505 {
506 
507 	ASSERT_VOP_LOCKED(vp, "vn_writechk");
508 	/*
509 	 * If there's shared text associated with
510 	 * the vnode, try to free it up once.  If
511 	 * we fail, we can't allow writing.
512 	 */
513 	if (VOP_IS_TEXT(vp))
514 		return (ETXTBSY);
515 
516 	return (0);
517 }
518 
519 /*
520  * Vnode close call
521  */
522 static int
523 vn_close1(struct vnode *vp, int flags, struct ucred *file_cred,
524     struct thread *td, bool keep_ref)
525 {
526 	struct mount *mp;
527 	int error, lock_flags;
528 
529 	lock_flags = vp->v_type != VFIFO && MNT_EXTENDED_SHARED(vp->v_mount) ?
530 	    LK_SHARED : LK_EXCLUSIVE;
531 
532 	vn_start_write(vp, &mp, V_WAIT);
533 	vn_lock(vp, lock_flags | LK_RETRY);
534 	AUDIT_ARG_VNODE1(vp);
535 	if ((flags & (FWRITE | FOPENFAILED)) == FWRITE) {
536 		VOP_ADD_WRITECOUNT_CHECKED(vp, -1);
537 		CTR3(KTR_VFS, "%s: vp %p v_writecount decreased to %d",
538 		    __func__, vp, vp->v_writecount);
539 	}
540 	error = VOP_CLOSE(vp, flags, file_cred, td);
541 	if (keep_ref)
542 		VOP_UNLOCK(vp);
543 	else
544 		vput(vp);
545 	vn_finished_write(mp);
546 	return (error);
547 }
548 
549 int
550 vn_close(struct vnode *vp, int flags, struct ucred *file_cred,
551     struct thread *td)
552 {
553 
554 	return (vn_close1(vp, flags, file_cred, td, false));
555 }
556 
557 /*
558  * Heuristic to detect sequential operation.
559  */
560 static int
561 sequential_heuristic(struct uio *uio, struct file *fp)
562 {
563 	enum uio_rw rw;
564 
565 	ASSERT_VOP_LOCKED(fp->f_vnode, __func__);
566 
567 	rw = uio->uio_rw;
568 	if (fp->f_flag & FRDAHEAD)
569 		return (fp->f_seqcount[rw] << IO_SEQSHIFT);
570 
571 	/*
572 	 * Offset 0 is handled specially.  open() sets f_seqcount to 1 so
573 	 * that the first I/O is normally considered to be slightly
574 	 * sequential.  Seeking to offset 0 doesn't change sequentiality
575 	 * unless previous seeks have reduced f_seqcount to 0, in which
576 	 * case offset 0 is not special.
577 	 */
578 	if ((uio->uio_offset == 0 && fp->f_seqcount[rw] > 0) ||
579 	    uio->uio_offset == fp->f_nextoff[rw]) {
580 		/*
581 		 * f_seqcount is in units of fixed-size blocks so that it
582 		 * depends mainly on the amount of sequential I/O and not
583 		 * much on the number of sequential I/O's.  The fixed size
584 		 * of 16384 is hard-coded here since it is (not quite) just
585 		 * a magic size that works well here.  This size is more
586 		 * closely related to the best I/O size for real disks than
587 		 * to any block size used by software.
588 		 */
589 		if (uio->uio_resid >= IO_SEQMAX * 16384)
590 			fp->f_seqcount[rw] = IO_SEQMAX;
591 		else {
592 			fp->f_seqcount[rw] += howmany(uio->uio_resid, 16384);
593 			if (fp->f_seqcount[rw] > IO_SEQMAX)
594 				fp->f_seqcount[rw] = IO_SEQMAX;
595 		}
596 		return (fp->f_seqcount[rw] << IO_SEQSHIFT);
597 	}
598 
599 	/* Not sequential.  Quickly draw-down sequentiality. */
600 	if (fp->f_seqcount[rw] > 1)
601 		fp->f_seqcount[rw] = 1;
602 	else
603 		fp->f_seqcount[rw] = 0;
604 	return (0);
605 }
606 
607 /*
608  * Package up an I/O request on a vnode into a uio and do it.
609  */
610 int
611 vn_rdwr(enum uio_rw rw, struct vnode *vp, void *base, int len, off_t offset,
612     enum uio_seg segflg, int ioflg, struct ucred *active_cred,
613     struct ucred *file_cred, ssize_t *aresid, struct thread *td)
614 {
615 	struct uio auio;
616 	struct iovec aiov;
617 	struct mount *mp;
618 	struct ucred *cred;
619 	void *rl_cookie;
620 	struct vn_io_fault_args args;
621 	int error, lock_flags;
622 
623 	if (offset < 0 && vp->v_type != VCHR)
624 		return (EINVAL);
625 	auio.uio_iov = &aiov;
626 	auio.uio_iovcnt = 1;
627 	aiov.iov_base = base;
628 	aiov.iov_len = len;
629 	auio.uio_resid = len;
630 	auio.uio_offset = offset;
631 	auio.uio_segflg = segflg;
632 	auio.uio_rw = rw;
633 	auio.uio_td = td;
634 	error = 0;
635 
636 	if ((ioflg & IO_NODELOCKED) == 0) {
637 		if ((ioflg & IO_RANGELOCKED) == 0) {
638 			if (rw == UIO_READ) {
639 				rl_cookie = vn_rangelock_rlock(vp, offset,
640 				    offset + len);
641 			} else if ((ioflg & IO_APPEND) != 0) {
642 				rl_cookie = vn_rangelock_wlock(vp, 0, OFF_MAX);
643 			} else {
644 				rl_cookie = vn_rangelock_wlock(vp, offset,
645 				    offset + len);
646 			}
647 		} else
648 			rl_cookie = NULL;
649 		mp = NULL;
650 		if (rw == UIO_WRITE) {
651 			if (vp->v_type != VCHR &&
652 			    (error = vn_start_write(vp, &mp, V_WAIT | V_PCATCH))
653 			    != 0)
654 				goto out;
655 			lock_flags = vn_lktype_write(mp, vp);
656 		} else
657 			lock_flags = LK_SHARED;
658 		vn_lock(vp, lock_flags | LK_RETRY);
659 	} else
660 		rl_cookie = NULL;
661 
662 	ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
663 #ifdef MAC
664 	if ((ioflg & IO_NOMACCHECK) == 0) {
665 		if (rw == UIO_READ)
666 			error = mac_vnode_check_read(active_cred, file_cred,
667 			    vp);
668 		else
669 			error = mac_vnode_check_write(active_cred, file_cred,
670 			    vp);
671 	}
672 #endif
673 	if (error == 0) {
674 		if (file_cred != NULL)
675 			cred = file_cred;
676 		else
677 			cred = active_cred;
678 		if (do_vn_io_fault(vp, &auio)) {
679 			args.kind = VN_IO_FAULT_VOP;
680 			args.cred = cred;
681 			args.flags = ioflg;
682 			args.args.vop_args.vp = vp;
683 			error = vn_io_fault1(vp, &auio, &args, td);
684 		} else if (rw == UIO_READ) {
685 			error = VOP_READ(vp, &auio, ioflg, cred);
686 		} else /* if (rw == UIO_WRITE) */ {
687 			error = VOP_WRITE(vp, &auio, ioflg, cred);
688 		}
689 	}
690 	if (aresid)
691 		*aresid = auio.uio_resid;
692 	else
693 		if (auio.uio_resid && error == 0)
694 			error = EIO;
695 	if ((ioflg & IO_NODELOCKED) == 0) {
696 		VOP_UNLOCK(vp);
697 		if (mp != NULL)
698 			vn_finished_write(mp);
699 	}
700  out:
701 	if (rl_cookie != NULL)
702 		vn_rangelock_unlock(vp, rl_cookie);
703 	return (error);
704 }
705 
706 /*
707  * Package up an I/O request on a vnode into a uio and do it.  The I/O
708  * request is split up into smaller chunks and we try to avoid saturating
709  * the buffer cache while potentially holding a vnode locked, so we
710  * check bwillwrite() before calling vn_rdwr().  We also call kern_yield()
711  * to give other processes a chance to lock the vnode (either other processes
712  * core'ing the same binary, or unrelated processes scanning the directory).
713  */
714 int
715 vn_rdwr_inchunks(enum uio_rw rw, struct vnode *vp, void *base, size_t len,
716     off_t offset, enum uio_seg segflg, int ioflg, struct ucred *active_cred,
717     struct ucred *file_cred, size_t *aresid, struct thread *td)
718 {
719 	int error = 0;
720 	ssize_t iaresid;
721 
722 	do {
723 		int chunk;
724 
725 		/*
726 		 * Force `offset' to a multiple of MAXBSIZE except possibly
727 		 * for the first chunk, so that filesystems only need to
728 		 * write full blocks except possibly for the first and last
729 		 * chunks.
730 		 */
731 		chunk = MAXBSIZE - (uoff_t)offset % MAXBSIZE;
732 
733 		if (chunk > len)
734 			chunk = len;
735 		if (rw != UIO_READ && vp->v_type == VREG)
736 			bwillwrite();
737 		iaresid = 0;
738 		error = vn_rdwr(rw, vp, base, chunk, offset, segflg,
739 		    ioflg, active_cred, file_cred, &iaresid, td);
740 		len -= chunk;	/* aresid calc already includes length */
741 		if (error)
742 			break;
743 		offset += chunk;
744 		base = (char *)base + chunk;
745 		kern_yield(PRI_USER);
746 	} while (len);
747 	if (aresid)
748 		*aresid = len + iaresid;
749 	return (error);
750 }
751 
752 #if OFF_MAX <= LONG_MAX
753 off_t
754 foffset_lock(struct file *fp, int flags)
755 {
756 	volatile short *flagsp;
757 	off_t res;
758 	short state;
759 
760 	KASSERT((flags & FOF_OFFSET) == 0, ("FOF_OFFSET passed"));
761 
762 	if ((flags & FOF_NOLOCK) != 0)
763 		return (atomic_load_long(&fp->f_offset));
764 
765 	/*
766 	 * According to McKusick the vn lock was protecting f_offset here.
767 	 * It is now protected by the FOFFSET_LOCKED flag.
768 	 */
769 	flagsp = &fp->f_vnread_flags;
770 	if (atomic_cmpset_acq_16(flagsp, 0, FOFFSET_LOCKED))
771 		return (atomic_load_long(&fp->f_offset));
772 
773 	sleepq_lock(&fp->f_vnread_flags);
774 	state = atomic_load_16(flagsp);
775 	for (;;) {
776 		if ((state & FOFFSET_LOCKED) == 0) {
777 			if (!atomic_fcmpset_acq_16(flagsp, &state,
778 			    FOFFSET_LOCKED))
779 				continue;
780 			break;
781 		}
782 		if ((state & FOFFSET_LOCK_WAITING) == 0) {
783 			if (!atomic_fcmpset_acq_16(flagsp, &state,
784 			    state | FOFFSET_LOCK_WAITING))
785 				continue;
786 		}
787 		DROP_GIANT();
788 		sleepq_add(&fp->f_vnread_flags, NULL, "vofflock", 0, 0);
789 		sleepq_wait(&fp->f_vnread_flags, PUSER -1);
790 		PICKUP_GIANT();
791 		sleepq_lock(&fp->f_vnread_flags);
792 		state = atomic_load_16(flagsp);
793 	}
794 	res = atomic_load_long(&fp->f_offset);
795 	sleepq_release(&fp->f_vnread_flags);
796 	return (res);
797 }
798 
799 void
800 foffset_unlock(struct file *fp, off_t val, int flags)
801 {
802 	volatile short *flagsp;
803 	short state;
804 
805 	KASSERT((flags & FOF_OFFSET) == 0, ("FOF_OFFSET passed"));
806 
807 	if ((flags & FOF_NOUPDATE) == 0)
808 		atomic_store_long(&fp->f_offset, val);
809 	if ((flags & FOF_NEXTOFF_R) != 0)
810 		fp->f_nextoff[UIO_READ] = val;
811 	if ((flags & FOF_NEXTOFF_W) != 0)
812 		fp->f_nextoff[UIO_WRITE] = val;
813 
814 	if ((flags & FOF_NOLOCK) != 0)
815 		return;
816 
817 	flagsp = &fp->f_vnread_flags;
818 	state = atomic_load_16(flagsp);
819 	if ((state & FOFFSET_LOCK_WAITING) == 0 &&
820 	    atomic_cmpset_rel_16(flagsp, state, 0))
821 		return;
822 
823 	sleepq_lock(&fp->f_vnread_flags);
824 	MPASS((fp->f_vnread_flags & FOFFSET_LOCKED) != 0);
825 	MPASS((fp->f_vnread_flags & FOFFSET_LOCK_WAITING) != 0);
826 	fp->f_vnread_flags = 0;
827 	sleepq_broadcast(&fp->f_vnread_flags, SLEEPQ_SLEEP, 0, 0);
828 	sleepq_release(&fp->f_vnread_flags);
829 }
830 
831 static off_t
832 foffset_read(struct file *fp)
833 {
834 
835 	return (atomic_load_long(&fp->f_offset));
836 }
837 #else
838 off_t
839 foffset_lock(struct file *fp, int flags)
840 {
841 	struct mtx *mtxp;
842 	off_t res;
843 
844 	KASSERT((flags & FOF_OFFSET) == 0, ("FOF_OFFSET passed"));
845 
846 	mtxp = mtx_pool_find(mtxpool_sleep, fp);
847 	mtx_lock(mtxp);
848 	if ((flags & FOF_NOLOCK) == 0) {
849 		while (fp->f_vnread_flags & FOFFSET_LOCKED) {
850 			fp->f_vnread_flags |= FOFFSET_LOCK_WAITING;
851 			msleep(&fp->f_vnread_flags, mtxp, PUSER -1,
852 			    "vofflock", 0);
853 		}
854 		fp->f_vnread_flags |= FOFFSET_LOCKED;
855 	}
856 	res = fp->f_offset;
857 	mtx_unlock(mtxp);
858 	return (res);
859 }
860 
861 void
862 foffset_unlock(struct file *fp, off_t val, int flags)
863 {
864 	struct mtx *mtxp;
865 
866 	KASSERT((flags & FOF_OFFSET) == 0, ("FOF_OFFSET passed"));
867 
868 	mtxp = mtx_pool_find(mtxpool_sleep, fp);
869 	mtx_lock(mtxp);
870 	if ((flags & FOF_NOUPDATE) == 0)
871 		fp->f_offset = val;
872 	if ((flags & FOF_NEXTOFF_R) != 0)
873 		fp->f_nextoff[UIO_READ] = val;
874 	if ((flags & FOF_NEXTOFF_W) != 0)
875 		fp->f_nextoff[UIO_WRITE] = val;
876 	if ((flags & FOF_NOLOCK) == 0) {
877 		KASSERT((fp->f_vnread_flags & FOFFSET_LOCKED) != 0,
878 		    ("Lost FOFFSET_LOCKED"));
879 		if (fp->f_vnread_flags & FOFFSET_LOCK_WAITING)
880 			wakeup(&fp->f_vnread_flags);
881 		fp->f_vnread_flags = 0;
882 	}
883 	mtx_unlock(mtxp);
884 }
885 
886 static off_t
887 foffset_read(struct file *fp)
888 {
889 
890 	return (foffset_lock(fp, FOF_NOLOCK));
891 }
892 #endif
893 
894 void
895 foffset_lock_uio(struct file *fp, struct uio *uio, int flags)
896 {
897 
898 	if ((flags & FOF_OFFSET) == 0)
899 		uio->uio_offset = foffset_lock(fp, flags);
900 }
901 
902 void
903 foffset_unlock_uio(struct file *fp, struct uio *uio, int flags)
904 {
905 
906 	if ((flags & FOF_OFFSET) == 0)
907 		foffset_unlock(fp, uio->uio_offset, flags);
908 }
909 
910 static int
911 get_advice(struct file *fp, struct uio *uio)
912 {
913 	struct mtx *mtxp;
914 	int ret;
915 
916 	ret = POSIX_FADV_NORMAL;
917 	if (fp->f_advice == NULL || fp->f_vnode->v_type != VREG)
918 		return (ret);
919 
920 	mtxp = mtx_pool_find(mtxpool_sleep, fp);
921 	mtx_lock(mtxp);
922 	if (fp->f_advice != NULL &&
923 	    uio->uio_offset >= fp->f_advice->fa_start &&
924 	    uio->uio_offset + uio->uio_resid <= fp->f_advice->fa_end)
925 		ret = fp->f_advice->fa_advice;
926 	mtx_unlock(mtxp);
927 	return (ret);
928 }
929 
930 static int
931 get_write_ioflag(struct file *fp)
932 {
933 	int ioflag;
934 	struct mount *mp;
935 	struct vnode *vp;
936 
937 	ioflag = 0;
938 	vp = fp->f_vnode;
939 	mp = atomic_load_ptr(&vp->v_mount);
940 
941 	if ((fp->f_flag & O_DIRECT) != 0)
942 		ioflag |= IO_DIRECT;
943 
944 	if ((fp->f_flag & O_FSYNC) != 0 ||
945 	    (mp != NULL && (mp->mnt_flag & MNT_SYNCHRONOUS) != 0))
946 		ioflag |= IO_SYNC;
947 
948 	/*
949 	 * For O_DSYNC we set both IO_SYNC and IO_DATASYNC, so that VOP_WRITE()
950 	 * or VOP_DEALLOCATE() implementations that don't understand IO_DATASYNC
951 	 * fall back to full O_SYNC behavior.
952 	 */
953 	if ((fp->f_flag & O_DSYNC) != 0)
954 		ioflag |= IO_SYNC | IO_DATASYNC;
955 
956 	return (ioflag);
957 }
958 
959 int
960 vn_read_from_obj(struct vnode *vp, struct uio *uio)
961 {
962 	vm_object_t obj;
963 	vm_page_t ma[io_hold_cnt + 2];
964 	off_t off, vsz;
965 	ssize_t resid;
966 	int error, i, j;
967 
968 	MPASS(uio->uio_resid <= ptoa(io_hold_cnt + 2));
969 	obj = atomic_load_ptr(&vp->v_object);
970 	if (obj == NULL)
971 		return (EJUSTRETURN);
972 
973 	/*
974 	 * Depends on type stability of vm_objects.
975 	 */
976 	vm_object_pip_add(obj, 1);
977 	if ((obj->flags & OBJ_DEAD) != 0) {
978 		/*
979 		 * Note that object might be already reused from the
980 		 * vnode, and the OBJ_DEAD flag cleared.  This is fine,
981 		 * we recheck for DOOMED vnode state after all pages
982 		 * are busied, and retract then.
983 		 *
984 		 * But we check for OBJ_DEAD to ensure that we do not
985 		 * busy pages while vm_object_terminate_pages()
986 		 * processes the queue.
987 		 */
988 		error = EJUSTRETURN;
989 		goto out_pip;
990 	}
991 
992 	resid = uio->uio_resid;
993 	off = uio->uio_offset;
994 	for (i = 0; resid > 0; i++) {
995 		MPASS(i < io_hold_cnt + 2);
996 		ma[i] = vm_page_grab_unlocked(obj, atop(off),
997 		    VM_ALLOC_NOCREAT | VM_ALLOC_SBUSY | VM_ALLOC_IGN_SBUSY |
998 		    VM_ALLOC_NOWAIT);
999 		if (ma[i] == NULL)
1000 			break;
1001 
1002 		/*
1003 		 * Skip invalid pages.  Valid mask can be partial only
1004 		 * at EOF, and we clip later.
1005 		 */
1006 		if (vm_page_none_valid(ma[i])) {
1007 			vm_page_sunbusy(ma[i]);
1008 			break;
1009 		}
1010 
1011 		resid -= PAGE_SIZE;
1012 		off += PAGE_SIZE;
1013 	}
1014 	if (i == 0) {
1015 		error = EJUSTRETURN;
1016 		goto out_pip;
1017 	}
1018 
1019 	/*
1020 	 * Check VIRF_DOOMED after we busied our pages.  Since
1021 	 * vgonel() terminates the vnode' vm_object, it cannot
1022 	 * process past pages busied by us.
1023 	 */
1024 	if (VN_IS_DOOMED(vp)) {
1025 		error = EJUSTRETURN;
1026 		goto out;
1027 	}
1028 
1029 	resid = PAGE_SIZE - (uio->uio_offset & PAGE_MASK) + ptoa(i - 1);
1030 	if (resid > uio->uio_resid)
1031 		resid = uio->uio_resid;
1032 
1033 	/*
1034 	 * Unlocked read of vnp_size is safe because truncation cannot
1035 	 * pass busied page.  But we load vnp_size into a local
1036 	 * variable so that possible concurrent extension does not
1037 	 * break calculation.
1038 	 */
1039 #if defined(__powerpc__) && !defined(__powerpc64__)
1040 	vsz = obj->un_pager.vnp.vnp_size;
1041 #else
1042 	vsz = atomic_load_64(&obj->un_pager.vnp.vnp_size);
1043 #endif
1044 	if (uio->uio_offset >= vsz) {
1045 		error = EJUSTRETURN;
1046 		goto out;
1047 	}
1048 	if (uio->uio_offset + resid > vsz)
1049 		resid = vsz - uio->uio_offset;
1050 
1051 	error = vn_io_fault_pgmove(ma, uio->uio_offset & PAGE_MASK, resid, uio);
1052 
1053 out:
1054 	for (j = 0; j < i; j++) {
1055 		if (error == 0)
1056 			vm_page_reference(ma[j]);
1057 		vm_page_sunbusy(ma[j]);
1058 	}
1059 out_pip:
1060 	vm_object_pip_wakeup(obj);
1061 	if (error != 0)
1062 		return (error);
1063 	return (uio->uio_resid == 0 ? 0 : EJUSTRETURN);
1064 }
1065 
1066 /*
1067  * File table vnode read routine.
1068  */
1069 static int
1070 vn_read(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags,
1071     struct thread *td)
1072 {
1073 	struct vnode *vp;
1074 	off_t orig_offset;
1075 	int error, ioflag;
1076 	int advice;
1077 
1078 	KASSERT(uio->uio_td == td, ("uio_td %p is not td %p",
1079 	    uio->uio_td, td));
1080 	KASSERT(flags & FOF_OFFSET, ("No FOF_OFFSET"));
1081 	vp = fp->f_vnode;
1082 	ioflag = 0;
1083 	if (fp->f_flag & FNONBLOCK)
1084 		ioflag |= IO_NDELAY;
1085 	if (fp->f_flag & O_DIRECT)
1086 		ioflag |= IO_DIRECT;
1087 
1088 	/*
1089 	 * Try to read from page cache.  VIRF_DOOMED check is racy but
1090 	 * allows us to avoid unneeded work outright.
1091 	 */
1092 	if (vn_io_pgcache_read_enable && !mac_vnode_check_read_enabled() &&
1093 	    (vn_irflag_read(vp) & (VIRF_DOOMED | VIRF_PGREAD)) == VIRF_PGREAD) {
1094 		error = VOP_READ_PGCACHE(vp, uio, ioflag, fp->f_cred);
1095 		if (error == 0) {
1096 			fp->f_nextoff[UIO_READ] = uio->uio_offset;
1097 			return (0);
1098 		}
1099 		if (error != EJUSTRETURN)
1100 			return (error);
1101 	}
1102 
1103 	advice = get_advice(fp, uio);
1104 	vn_lock(vp, LK_SHARED | LK_RETRY);
1105 
1106 	switch (advice) {
1107 	case POSIX_FADV_NORMAL:
1108 	case POSIX_FADV_SEQUENTIAL:
1109 	case POSIX_FADV_NOREUSE:
1110 		ioflag |= sequential_heuristic(uio, fp);
1111 		break;
1112 	case POSIX_FADV_RANDOM:
1113 		/* Disable read-ahead for random I/O. */
1114 		break;
1115 	}
1116 	orig_offset = uio->uio_offset;
1117 
1118 #ifdef MAC
1119 	error = mac_vnode_check_read(active_cred, fp->f_cred, vp);
1120 	if (error == 0)
1121 #endif
1122 		error = VOP_READ(vp, uio, ioflag, fp->f_cred);
1123 	fp->f_nextoff[UIO_READ] = uio->uio_offset;
1124 	VOP_UNLOCK(vp);
1125 	if (error == 0 && advice == POSIX_FADV_NOREUSE &&
1126 	    orig_offset != uio->uio_offset)
1127 		/*
1128 		 * Use POSIX_FADV_DONTNEED to flush pages and buffers
1129 		 * for the backing file after a POSIX_FADV_NOREUSE
1130 		 * read(2).
1131 		 */
1132 		error = VOP_ADVISE(vp, orig_offset, uio->uio_offset - 1,
1133 		    POSIX_FADV_DONTNEED);
1134 	return (error);
1135 }
1136 
1137 /*
1138  * File table vnode write routine.
1139  */
1140 static int
1141 vn_write(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags,
1142     struct thread *td)
1143 {
1144 	struct vnode *vp;
1145 	struct mount *mp;
1146 	off_t orig_offset;
1147 	int error, ioflag;
1148 	int advice;
1149 	bool need_finished_write;
1150 
1151 	KASSERT(uio->uio_td == td, ("uio_td %p is not td %p",
1152 	    uio->uio_td, td));
1153 	KASSERT(flags & FOF_OFFSET, ("No FOF_OFFSET"));
1154 	vp = fp->f_vnode;
1155 	if (vp->v_type == VREG)
1156 		bwillwrite();
1157 	ioflag = IO_UNIT;
1158 	if (vp->v_type == VREG && (fp->f_flag & O_APPEND) != 0)
1159 		ioflag |= IO_APPEND;
1160 	if ((fp->f_flag & FNONBLOCK) != 0)
1161 		ioflag |= IO_NDELAY;
1162 	ioflag |= get_write_ioflag(fp);
1163 
1164 	mp = NULL;
1165 	need_finished_write = false;
1166 	if (vp->v_type != VCHR) {
1167 		error = vn_start_write(vp, &mp, V_WAIT | V_PCATCH);
1168 		if (error != 0)
1169 			goto unlock;
1170 		need_finished_write = true;
1171 	}
1172 
1173 	advice = get_advice(fp, uio);
1174 
1175 	vn_lock(vp, vn_lktype_write(mp, vp) | LK_RETRY);
1176 	switch (advice) {
1177 	case POSIX_FADV_NORMAL:
1178 	case POSIX_FADV_SEQUENTIAL:
1179 	case POSIX_FADV_NOREUSE:
1180 		ioflag |= sequential_heuristic(uio, fp);
1181 		break;
1182 	case POSIX_FADV_RANDOM:
1183 		/* XXX: Is this correct? */
1184 		break;
1185 	}
1186 	orig_offset = uio->uio_offset;
1187 
1188 #ifdef MAC
1189 	error = mac_vnode_check_write(active_cred, fp->f_cred, vp);
1190 	if (error == 0)
1191 #endif
1192 		error = VOP_WRITE(vp, uio, ioflag, fp->f_cred);
1193 	fp->f_nextoff[UIO_WRITE] = uio->uio_offset;
1194 	VOP_UNLOCK(vp);
1195 	if (need_finished_write)
1196 		vn_finished_write(mp);
1197 	if (error == 0 && advice == POSIX_FADV_NOREUSE &&
1198 	    orig_offset != uio->uio_offset)
1199 		/*
1200 		 * Use POSIX_FADV_DONTNEED to flush pages and buffers
1201 		 * for the backing file after a POSIX_FADV_NOREUSE
1202 		 * write(2).
1203 		 */
1204 		error = VOP_ADVISE(vp, orig_offset, uio->uio_offset - 1,
1205 		    POSIX_FADV_DONTNEED);
1206 unlock:
1207 	return (error);
1208 }
1209 
1210 /*
1211  * The vn_io_fault() is a wrapper around vn_read() and vn_write() to
1212  * prevent the following deadlock:
1213  *
1214  * Assume that the thread A reads from the vnode vp1 into userspace
1215  * buffer buf1 backed by the pages of vnode vp2.  If a page in buf1 is
1216  * currently not resident, then system ends up with the call chain
1217  *   vn_read() -> VOP_READ(vp1) -> uiomove() -> [Page Fault] ->
1218  *     vm_fault(buf1) -> vnode_pager_getpages(vp2) -> VOP_GETPAGES(vp2)
1219  * which establishes lock order vp1->vn_lock, then vp2->vn_lock.
1220  * If, at the same time, thread B reads from vnode vp2 into buffer buf2
1221  * backed by the pages of vnode vp1, and some page in buf2 is not
1222  * resident, we get a reversed order vp2->vn_lock, then vp1->vn_lock.
1223  *
1224  * To prevent the lock order reversal and deadlock, vn_io_fault() does
1225  * not allow page faults to happen during VOP_READ() or VOP_WRITE().
1226  * Instead, it first tries to do the whole range i/o with pagefaults
1227  * disabled. If all pages in the i/o buffer are resident and mapped,
1228  * VOP will succeed (ignoring the genuine filesystem errors).
1229  * Otherwise, we get back EFAULT, and vn_io_fault() falls back to do
1230  * i/o in chunks, with all pages in the chunk prefaulted and held
1231  * using vm_fault_quick_hold_pages().
1232  *
1233  * Filesystems using this deadlock avoidance scheme should use the
1234  * array of the held pages from uio, saved in the curthread->td_ma,
1235  * instead of doing uiomove().  A helper function
1236  * vn_io_fault_uiomove() converts uiomove request into
1237  * uiomove_fromphys() over td_ma array.
1238  *
1239  * Since vnode locks do not cover the whole i/o anymore, rangelocks
1240  * make the current i/o request atomic with respect to other i/os and
1241  * truncations.
1242  */
1243 
1244 /*
1245  * Decode vn_io_fault_args and perform the corresponding i/o.
1246  */
1247 static int
1248 vn_io_fault_doio(struct vn_io_fault_args *args, struct uio *uio,
1249     struct thread *td)
1250 {
1251 	int error, save;
1252 
1253 	error = 0;
1254 	save = vm_fault_disable_pagefaults();
1255 	switch (args->kind) {
1256 	case VN_IO_FAULT_FOP:
1257 		error = (args->args.fop_args.doio)(args->args.fop_args.fp,
1258 		    uio, args->cred, args->flags, td);
1259 		break;
1260 	case VN_IO_FAULT_VOP:
1261 		if (uio->uio_rw == UIO_READ) {
1262 			error = VOP_READ(args->args.vop_args.vp, uio,
1263 			    args->flags, args->cred);
1264 		} else if (uio->uio_rw == UIO_WRITE) {
1265 			error = VOP_WRITE(args->args.vop_args.vp, uio,
1266 			    args->flags, args->cred);
1267 		}
1268 		break;
1269 	default:
1270 		panic("vn_io_fault_doio: unknown kind of io %d %d",
1271 		    args->kind, uio->uio_rw);
1272 	}
1273 	vm_fault_enable_pagefaults(save);
1274 	return (error);
1275 }
1276 
1277 static int
1278 vn_io_fault_touch(char *base, const struct uio *uio)
1279 {
1280 	int r;
1281 
1282 	r = fubyte(base);
1283 	if (r == -1 || (uio->uio_rw == UIO_READ && subyte(base, r) == -1))
1284 		return (EFAULT);
1285 	return (0);
1286 }
1287 
1288 static int
1289 vn_io_fault_prefault_user(const struct uio *uio)
1290 {
1291 	char *base;
1292 	const struct iovec *iov;
1293 	size_t len;
1294 	ssize_t resid;
1295 	int error, i;
1296 
1297 	KASSERT(uio->uio_segflg == UIO_USERSPACE,
1298 	    ("vn_io_fault_prefault userspace"));
1299 
1300 	error = i = 0;
1301 	iov = uio->uio_iov;
1302 	resid = uio->uio_resid;
1303 	base = iov->iov_base;
1304 	len = iov->iov_len;
1305 	while (resid > 0) {
1306 		error = vn_io_fault_touch(base, uio);
1307 		if (error != 0)
1308 			break;
1309 		if (len < PAGE_SIZE) {
1310 			if (len != 0) {
1311 				error = vn_io_fault_touch(base + len - 1, uio);
1312 				if (error != 0)
1313 					break;
1314 				resid -= len;
1315 			}
1316 			if (++i >= uio->uio_iovcnt)
1317 				break;
1318 			iov = uio->uio_iov + i;
1319 			base = iov->iov_base;
1320 			len = iov->iov_len;
1321 		} else {
1322 			len -= PAGE_SIZE;
1323 			base += PAGE_SIZE;
1324 			resid -= PAGE_SIZE;
1325 		}
1326 	}
1327 	return (error);
1328 }
1329 
1330 /*
1331  * Common code for vn_io_fault(), agnostic to the kind of i/o request.
1332  * Uses vn_io_fault_doio() to make the call to an actual i/o function.
1333  * Used from vn_rdwr() and vn_io_fault(), which encode the i/o request
1334  * into args and call vn_io_fault1() to handle faults during the user
1335  * mode buffer accesses.
1336  */
1337 static int
1338 vn_io_fault1(struct vnode *vp, struct uio *uio, struct vn_io_fault_args *args,
1339     struct thread *td)
1340 {
1341 	vm_page_t ma[io_hold_cnt + 2];
1342 	struct uio *uio_clone, short_uio;
1343 	struct iovec short_iovec[1];
1344 	vm_page_t *prev_td_ma;
1345 	vm_prot_t prot;
1346 	vm_offset_t addr, end;
1347 	size_t len, resid;
1348 	ssize_t adv;
1349 	int error, cnt, saveheld, prev_td_ma_cnt;
1350 
1351 	if (vn_io_fault_prefault) {
1352 		error = vn_io_fault_prefault_user(uio);
1353 		if (error != 0)
1354 			return (error); /* Or ignore ? */
1355 	}
1356 
1357 	prot = uio->uio_rw == UIO_READ ? VM_PROT_WRITE : VM_PROT_READ;
1358 
1359 	/*
1360 	 * The UFS follows IO_UNIT directive and replays back both
1361 	 * uio_offset and uio_resid if an error is encountered during the
1362 	 * operation.  But, since the iovec may be already advanced,
1363 	 * uio is still in an inconsistent state.
1364 	 *
1365 	 * Cache a copy of the original uio, which is advanced to the redo
1366 	 * point using UIO_NOCOPY below.
1367 	 */
1368 	uio_clone = cloneuio(uio);
1369 	resid = uio->uio_resid;
1370 
1371 	short_uio.uio_segflg = UIO_USERSPACE;
1372 	short_uio.uio_rw = uio->uio_rw;
1373 	short_uio.uio_td = uio->uio_td;
1374 
1375 	error = vn_io_fault_doio(args, uio, td);
1376 	if (error != EFAULT)
1377 		goto out;
1378 
1379 	atomic_add_long(&vn_io_faults_cnt, 1);
1380 	uio_clone->uio_segflg = UIO_NOCOPY;
1381 	uiomove(NULL, resid - uio->uio_resid, uio_clone);
1382 	uio_clone->uio_segflg = uio->uio_segflg;
1383 
1384 	saveheld = curthread_pflags_set(TDP_UIOHELD);
1385 	prev_td_ma = td->td_ma;
1386 	prev_td_ma_cnt = td->td_ma_cnt;
1387 
1388 	while (uio_clone->uio_resid != 0) {
1389 		len = uio_clone->uio_iov->iov_len;
1390 		if (len == 0) {
1391 			KASSERT(uio_clone->uio_iovcnt >= 1,
1392 			    ("iovcnt underflow"));
1393 			uio_clone->uio_iov++;
1394 			uio_clone->uio_iovcnt--;
1395 			continue;
1396 		}
1397 		if (len > ptoa(io_hold_cnt))
1398 			len = ptoa(io_hold_cnt);
1399 		addr = (uintptr_t)uio_clone->uio_iov->iov_base;
1400 		end = round_page(addr + len);
1401 		if (end < addr) {
1402 			error = EFAULT;
1403 			break;
1404 		}
1405 		/*
1406 		 * A perfectly misaligned address and length could cause
1407 		 * both the start and the end of the chunk to use partial
1408 		 * page.  +2 accounts for such a situation.
1409 		 */
1410 		cnt = vm_fault_quick_hold_pages(&td->td_proc->p_vmspace->vm_map,
1411 		    addr, len, prot, ma, io_hold_cnt + 2);
1412 		if (cnt == -1) {
1413 			error = EFAULT;
1414 			break;
1415 		}
1416 		short_uio.uio_iov = &short_iovec[0];
1417 		short_iovec[0].iov_base = (void *)addr;
1418 		short_uio.uio_iovcnt = 1;
1419 		short_uio.uio_resid = short_iovec[0].iov_len = len;
1420 		short_uio.uio_offset = uio_clone->uio_offset;
1421 		td->td_ma = ma;
1422 		td->td_ma_cnt = cnt;
1423 
1424 		error = vn_io_fault_doio(args, &short_uio, td);
1425 		vm_page_unhold_pages(ma, cnt);
1426 		adv = len - short_uio.uio_resid;
1427 
1428 		uio_clone->uio_iov->iov_base =
1429 		    (char *)uio_clone->uio_iov->iov_base + adv;
1430 		uio_clone->uio_iov->iov_len -= adv;
1431 		uio_clone->uio_resid -= adv;
1432 		uio_clone->uio_offset += adv;
1433 
1434 		uio->uio_resid -= adv;
1435 		uio->uio_offset += adv;
1436 
1437 		if (error != 0 || adv == 0)
1438 			break;
1439 	}
1440 	td->td_ma = prev_td_ma;
1441 	td->td_ma_cnt = prev_td_ma_cnt;
1442 	curthread_pflags_restore(saveheld);
1443 out:
1444 	free(uio_clone, M_IOV);
1445 	return (error);
1446 }
1447 
1448 static int
1449 vn_io_fault(struct file *fp, struct uio *uio, struct ucred *active_cred,
1450     int flags, struct thread *td)
1451 {
1452 	fo_rdwr_t *doio;
1453 	struct vnode *vp;
1454 	void *rl_cookie;
1455 	struct vn_io_fault_args args;
1456 	int error;
1457 	bool do_io_fault, do_rangelock;
1458 
1459 	doio = uio->uio_rw == UIO_READ ? vn_read : vn_write;
1460 	vp = fp->f_vnode;
1461 
1462 	/*
1463 	 * The ability to read(2) on a directory has historically been
1464 	 * allowed for all users, but this can and has been the source of
1465 	 * at least one security issue in the past.  As such, it is now hidden
1466 	 * away behind a sysctl for those that actually need it to use it, and
1467 	 * restricted to root when it's turned on to make it relatively safe to
1468 	 * leave on for longer sessions of need.
1469 	 */
1470 	if (vp->v_type == VDIR) {
1471 		KASSERT(uio->uio_rw == UIO_READ,
1472 		    ("illegal write attempted on a directory"));
1473 		if (!vfs_allow_read_dir)
1474 			return (EISDIR);
1475 		if ((error = priv_check(td, PRIV_VFS_READ_DIR)) != 0)
1476 			return (EISDIR);
1477 	}
1478 
1479 	do_io_fault = do_vn_io_fault(vp, uio);
1480 	do_rangelock = do_io_fault || (vn_irflag_read(vp) & VIRF_PGREAD) != 0;
1481 	foffset_lock_uio(fp, uio, flags);
1482 	if (do_rangelock) {
1483 		if (uio->uio_rw == UIO_READ) {
1484 			rl_cookie = vn_rangelock_rlock(vp, uio->uio_offset,
1485 			    uio->uio_offset + uio->uio_resid);
1486 		} else if ((fp->f_flag & O_APPEND) != 0 ||
1487 		    (flags & FOF_OFFSET) == 0) {
1488 			/* For appenders, punt and lock the whole range. */
1489 			rl_cookie = vn_rangelock_wlock(vp, 0, OFF_MAX);
1490 		} else {
1491 			rl_cookie = vn_rangelock_wlock(vp, uio->uio_offset,
1492 			    uio->uio_offset + uio->uio_resid);
1493 		}
1494 	}
1495 	if (do_io_fault) {
1496 		args.kind = VN_IO_FAULT_FOP;
1497 		args.args.fop_args.fp = fp;
1498 		args.args.fop_args.doio = doio;
1499 		args.cred = active_cred;
1500 		args.flags = flags | FOF_OFFSET;
1501 		error = vn_io_fault1(vp, uio, &args, td);
1502 	} else {
1503 		error = doio(fp, uio, active_cred, flags | FOF_OFFSET, td);
1504 	}
1505 	if (do_rangelock)
1506 		vn_rangelock_unlock(vp, rl_cookie);
1507 	foffset_unlock_uio(fp, uio, flags);
1508 	return (error);
1509 }
1510 
1511 /*
1512  * Helper function to perform the requested uiomove operation using
1513  * the held pages for io->uio_iov[0].iov_base buffer instead of
1514  * copyin/copyout.  Access to the pages with uiomove_fromphys()
1515  * instead of iov_base prevents page faults that could occur due to
1516  * pmap_collect() invalidating the mapping created by
1517  * vm_fault_quick_hold_pages(), or pageout daemon, page laundry or
1518  * object cleanup revoking the write access from page mappings.
1519  *
1520  * Filesystems specified MNTK_NO_IOPF shall use vn_io_fault_uiomove()
1521  * instead of plain uiomove().
1522  */
1523 int
1524 vn_io_fault_uiomove(char *data, int xfersize, struct uio *uio)
1525 {
1526 	struct uio transp_uio;
1527 	struct iovec transp_iov[1];
1528 	struct thread *td;
1529 	size_t adv;
1530 	int error, pgadv;
1531 
1532 	td = curthread;
1533 	if ((td->td_pflags & TDP_UIOHELD) == 0 ||
1534 	    uio->uio_segflg != UIO_USERSPACE)
1535 		return (uiomove(data, xfersize, uio));
1536 
1537 	KASSERT(uio->uio_iovcnt == 1, ("uio_iovcnt %d", uio->uio_iovcnt));
1538 	transp_iov[0].iov_base = data;
1539 	transp_uio.uio_iov = &transp_iov[0];
1540 	transp_uio.uio_iovcnt = 1;
1541 	if (xfersize > uio->uio_resid)
1542 		xfersize = uio->uio_resid;
1543 	transp_uio.uio_resid = transp_iov[0].iov_len = xfersize;
1544 	transp_uio.uio_offset = 0;
1545 	transp_uio.uio_segflg = UIO_SYSSPACE;
1546 	/*
1547 	 * Since transp_iov points to data, and td_ma page array
1548 	 * corresponds to original uio->uio_iov, we need to invert the
1549 	 * direction of the i/o operation as passed to
1550 	 * uiomove_fromphys().
1551 	 */
1552 	switch (uio->uio_rw) {
1553 	case UIO_WRITE:
1554 		transp_uio.uio_rw = UIO_READ;
1555 		break;
1556 	case UIO_READ:
1557 		transp_uio.uio_rw = UIO_WRITE;
1558 		break;
1559 	}
1560 	transp_uio.uio_td = uio->uio_td;
1561 	error = uiomove_fromphys(td->td_ma,
1562 	    ((vm_offset_t)uio->uio_iov->iov_base) & PAGE_MASK,
1563 	    xfersize, &transp_uio);
1564 	adv = xfersize - transp_uio.uio_resid;
1565 	pgadv =
1566 	    (((vm_offset_t)uio->uio_iov->iov_base + adv) >> PAGE_SHIFT) -
1567 	    (((vm_offset_t)uio->uio_iov->iov_base) >> PAGE_SHIFT);
1568 	td->td_ma += pgadv;
1569 	KASSERT(td->td_ma_cnt >= pgadv, ("consumed pages %d %d", td->td_ma_cnt,
1570 	    pgadv));
1571 	td->td_ma_cnt -= pgadv;
1572 	uio->uio_iov->iov_base = (char *)uio->uio_iov->iov_base + adv;
1573 	uio->uio_iov->iov_len -= adv;
1574 	uio->uio_resid -= adv;
1575 	uio->uio_offset += adv;
1576 	return (error);
1577 }
1578 
1579 int
1580 vn_io_fault_pgmove(vm_page_t ma[], vm_offset_t offset, int xfersize,
1581     struct uio *uio)
1582 {
1583 	struct thread *td;
1584 	vm_offset_t iov_base;
1585 	int cnt, pgadv;
1586 
1587 	td = curthread;
1588 	if ((td->td_pflags & TDP_UIOHELD) == 0 ||
1589 	    uio->uio_segflg != UIO_USERSPACE)
1590 		return (uiomove_fromphys(ma, offset, xfersize, uio));
1591 
1592 	KASSERT(uio->uio_iovcnt == 1, ("uio_iovcnt %d", uio->uio_iovcnt));
1593 	cnt = xfersize > uio->uio_resid ? uio->uio_resid : xfersize;
1594 	iov_base = (vm_offset_t)uio->uio_iov->iov_base;
1595 	switch (uio->uio_rw) {
1596 	case UIO_WRITE:
1597 		pmap_copy_pages(td->td_ma, iov_base & PAGE_MASK, ma,
1598 		    offset, cnt);
1599 		break;
1600 	case UIO_READ:
1601 		pmap_copy_pages(ma, offset, td->td_ma, iov_base & PAGE_MASK,
1602 		    cnt);
1603 		break;
1604 	}
1605 	pgadv = ((iov_base + cnt) >> PAGE_SHIFT) - (iov_base >> PAGE_SHIFT);
1606 	td->td_ma += pgadv;
1607 	KASSERT(td->td_ma_cnt >= pgadv, ("consumed pages %d %d", td->td_ma_cnt,
1608 	    pgadv));
1609 	td->td_ma_cnt -= pgadv;
1610 	uio->uio_iov->iov_base = (char *)(iov_base + cnt);
1611 	uio->uio_iov->iov_len -= cnt;
1612 	uio->uio_resid -= cnt;
1613 	uio->uio_offset += cnt;
1614 	return (0);
1615 }
1616 
1617 /*
1618  * File table truncate routine.
1619  */
1620 static int
1621 vn_truncate(struct file *fp, off_t length, struct ucred *active_cred,
1622     struct thread *td)
1623 {
1624 	struct mount *mp;
1625 	struct vnode *vp;
1626 	void *rl_cookie;
1627 	int error;
1628 
1629 	vp = fp->f_vnode;
1630 
1631 retry:
1632 	/*
1633 	 * Lock the whole range for truncation.  Otherwise split i/o
1634 	 * might happen partly before and partly after the truncation.
1635 	 */
1636 	rl_cookie = vn_rangelock_wlock(vp, 0, OFF_MAX);
1637 	error = vn_start_write(vp, &mp, V_WAIT | V_PCATCH);
1638 	if (error)
1639 		goto out1;
1640 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1641 	AUDIT_ARG_VNODE1(vp);
1642 	if (vp->v_type == VDIR) {
1643 		error = EISDIR;
1644 		goto out;
1645 	}
1646 #ifdef MAC
1647 	error = mac_vnode_check_write(active_cred, fp->f_cred, vp);
1648 	if (error)
1649 		goto out;
1650 #endif
1651 	error = vn_truncate_locked(vp, length, (fp->f_flag & O_FSYNC) != 0,
1652 	    fp->f_cred);
1653 out:
1654 	VOP_UNLOCK(vp);
1655 	vn_finished_write(mp);
1656 out1:
1657 	vn_rangelock_unlock(vp, rl_cookie);
1658 	if (error == ERELOOKUP)
1659 		goto retry;
1660 	return (error);
1661 }
1662 
1663 /*
1664  * Truncate a file that is already locked.
1665  */
1666 int
1667 vn_truncate_locked(struct vnode *vp, off_t length, bool sync,
1668     struct ucred *cred)
1669 {
1670 	struct vattr vattr;
1671 	int error;
1672 
1673 	error = VOP_ADD_WRITECOUNT(vp, 1);
1674 	if (error == 0) {
1675 		VATTR_NULL(&vattr);
1676 		vattr.va_size = length;
1677 		if (sync)
1678 			vattr.va_vaflags |= VA_SYNC;
1679 		error = VOP_SETATTR(vp, &vattr, cred);
1680 		VOP_ADD_WRITECOUNT_CHECKED(vp, -1);
1681 	}
1682 	return (error);
1683 }
1684 
1685 /*
1686  * File table vnode stat routine.
1687  */
1688 int
1689 vn_statfile(struct file *fp, struct stat *sb, struct ucred *active_cred)
1690 {
1691 	struct vnode *vp = fp->f_vnode;
1692 	int error;
1693 
1694 	vn_lock(vp, LK_SHARED | LK_RETRY);
1695 	error = VOP_STAT(vp, sb, active_cred, fp->f_cred);
1696 	VOP_UNLOCK(vp);
1697 
1698 	return (error);
1699 }
1700 
1701 /*
1702  * File table vnode ioctl routine.
1703  */
1704 static int
1705 vn_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
1706     struct thread *td)
1707 {
1708 	struct vnode *vp;
1709 	struct fiobmap2_arg *bmarg;
1710 	off_t size;
1711 	int error;
1712 
1713 	vp = fp->f_vnode;
1714 	switch (vp->v_type) {
1715 	case VDIR:
1716 	case VREG:
1717 		switch (com) {
1718 		case FIONREAD:
1719 			error = vn_getsize(vp, &size, active_cred);
1720 			if (error == 0)
1721 				*(int *)data = size - fp->f_offset;
1722 			return (error);
1723 		case FIOBMAP2:
1724 			bmarg = (struct fiobmap2_arg *)data;
1725 			vn_lock(vp, LK_SHARED | LK_RETRY);
1726 #ifdef MAC
1727 			error = mac_vnode_check_read(active_cred, fp->f_cred,
1728 			    vp);
1729 			if (error == 0)
1730 #endif
1731 				error = VOP_BMAP(vp, bmarg->bn, NULL,
1732 				    &bmarg->bn, &bmarg->runp, &bmarg->runb);
1733 			VOP_UNLOCK(vp);
1734 			return (error);
1735 		case FIONBIO:
1736 		case FIOASYNC:
1737 			return (0);
1738 		default:
1739 			return (VOP_IOCTL(vp, com, data, fp->f_flag,
1740 			    active_cred, td));
1741 		}
1742 		break;
1743 	case VCHR:
1744 		return (VOP_IOCTL(vp, com, data, fp->f_flag,
1745 		    active_cred, td));
1746 	default:
1747 		return (ENOTTY);
1748 	}
1749 }
1750 
1751 /*
1752  * File table vnode poll routine.
1753  */
1754 static int
1755 vn_poll(struct file *fp, int events, struct ucred *active_cred,
1756     struct thread *td)
1757 {
1758 	struct vnode *vp;
1759 	int error;
1760 
1761 	vp = fp->f_vnode;
1762 #if defined(MAC) || defined(AUDIT)
1763 	if (AUDITING_TD(td) || mac_vnode_check_poll_enabled()) {
1764 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1765 		AUDIT_ARG_VNODE1(vp);
1766 		error = mac_vnode_check_poll(active_cred, fp->f_cred, vp);
1767 		VOP_UNLOCK(vp);
1768 		if (error != 0)
1769 			return (error);
1770 	}
1771 #endif
1772 	error = VOP_POLL(vp, events, fp->f_cred, td);
1773 	return (error);
1774 }
1775 
1776 /*
1777  * Acquire the requested lock and then check for validity.  LK_RETRY
1778  * permits vn_lock to return doomed vnodes.
1779  */
1780 static int __noinline
1781 _vn_lock_fallback(struct vnode *vp, int flags, const char *file, int line,
1782     int error)
1783 {
1784 
1785 	KASSERT((flags & LK_RETRY) == 0 || error == 0,
1786 	    ("vn_lock: error %d incompatible with flags %#x", error, flags));
1787 
1788 	if (error == 0)
1789 		VNASSERT(VN_IS_DOOMED(vp), vp, ("vnode not doomed"));
1790 
1791 	if ((flags & LK_RETRY) == 0) {
1792 		if (error == 0) {
1793 			VOP_UNLOCK(vp);
1794 			error = ENOENT;
1795 		}
1796 		return (error);
1797 	}
1798 
1799 	/*
1800 	 * LK_RETRY case.
1801 	 *
1802 	 * Nothing to do if we got the lock.
1803 	 */
1804 	if (error == 0)
1805 		return (0);
1806 
1807 	/*
1808 	 * Interlock was dropped by the call in _vn_lock.
1809 	 */
1810 	flags &= ~LK_INTERLOCK;
1811 	do {
1812 		error = VOP_LOCK1(vp, flags, file, line);
1813 	} while (error != 0);
1814 	return (0);
1815 }
1816 
1817 int
1818 _vn_lock(struct vnode *vp, int flags, const char *file, int line)
1819 {
1820 	int error;
1821 
1822 	VNASSERT((flags & LK_TYPE_MASK) != 0, vp,
1823 	    ("vn_lock: no locktype (%d passed)", flags));
1824 	VNPASS(vp->v_holdcnt > 0, vp);
1825 	error = VOP_LOCK1(vp, flags, file, line);
1826 	if (__predict_false(error != 0 || VN_IS_DOOMED(vp)))
1827 		return (_vn_lock_fallback(vp, flags, file, line, error));
1828 	return (0);
1829 }
1830 
1831 /*
1832  * File table vnode close routine.
1833  */
1834 static int
1835 vn_closefile(struct file *fp, struct thread *td)
1836 {
1837 	struct vnode *vp;
1838 	struct flock lf;
1839 	int error;
1840 	bool ref;
1841 
1842 	vp = fp->f_vnode;
1843 	fp->f_ops = &badfileops;
1844 	ref = (fp->f_flag & FHASLOCK) != 0;
1845 
1846 	error = vn_close1(vp, fp->f_flag, fp->f_cred, td, ref);
1847 
1848 	if (__predict_false(ref)) {
1849 		lf.l_whence = SEEK_SET;
1850 		lf.l_start = 0;
1851 		lf.l_len = 0;
1852 		lf.l_type = F_UNLCK;
1853 		(void) VOP_ADVLOCK(vp, fp, F_UNLCK, &lf, F_FLOCK);
1854 		vrele(vp);
1855 	}
1856 	return (error);
1857 }
1858 
1859 /*
1860  * Preparing to start a filesystem write operation. If the operation is
1861  * permitted, then we bump the count of operations in progress and
1862  * proceed. If a suspend request is in progress, we wait until the
1863  * suspension is over, and then proceed.
1864  */
1865 static int
1866 vn_start_write_refed(struct mount *mp, int flags, bool mplocked)
1867 {
1868 	struct mount_pcpu *mpcpu;
1869 	int error, mflags;
1870 
1871 	if (__predict_true(!mplocked) && (flags & V_XSLEEP) == 0 &&
1872 	    vfs_op_thread_enter(mp, mpcpu)) {
1873 		MPASS((mp->mnt_kern_flag & MNTK_SUSPEND) == 0);
1874 		vfs_mp_count_add_pcpu(mpcpu, writeopcount, 1);
1875 		vfs_op_thread_exit(mp, mpcpu);
1876 		return (0);
1877 	}
1878 
1879 	if (mplocked)
1880 		mtx_assert(MNT_MTX(mp), MA_OWNED);
1881 	else
1882 		MNT_ILOCK(mp);
1883 
1884 	error = 0;
1885 
1886 	/*
1887 	 * Check on status of suspension.
1888 	 */
1889 	if ((curthread->td_pflags & TDP_IGNSUSP) == 0 ||
1890 	    mp->mnt_susp_owner != curthread) {
1891 		mflags = 0;
1892 		if ((mp->mnt_vfc->vfc_flags & VFCF_SBDRY) != 0) {
1893 			if (flags & V_PCATCH)
1894 				mflags |= PCATCH;
1895 		}
1896 		mflags |= (PUSER - 1);
1897 		while ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0) {
1898 			if ((flags & V_NOWAIT) != 0) {
1899 				error = EWOULDBLOCK;
1900 				goto unlock;
1901 			}
1902 			error = msleep(&mp->mnt_flag, MNT_MTX(mp), mflags,
1903 			    "suspfs", 0);
1904 			if (error != 0)
1905 				goto unlock;
1906 		}
1907 	}
1908 	if ((flags & V_XSLEEP) != 0)
1909 		goto unlock;
1910 	mp->mnt_writeopcount++;
1911 unlock:
1912 	if (error != 0 || (flags & V_XSLEEP) != 0)
1913 		MNT_REL(mp);
1914 	MNT_IUNLOCK(mp);
1915 	return (error);
1916 }
1917 
1918 int
1919 vn_start_write(struct vnode *vp, struct mount **mpp, int flags)
1920 {
1921 	struct mount *mp;
1922 	int error;
1923 
1924 	KASSERT((flags & ~V_VALID_FLAGS) == 0,
1925 	    ("%s: invalid flags passed %d\n", __func__, flags));
1926 
1927 	error = 0;
1928 	/*
1929 	 * If a vnode is provided, get and return the mount point that
1930 	 * to which it will write.
1931 	 */
1932 	if (vp != NULL) {
1933 		if ((error = VOP_GETWRITEMOUNT(vp, mpp)) != 0) {
1934 			*mpp = NULL;
1935 			if (error != EOPNOTSUPP)
1936 				return (error);
1937 			return (0);
1938 		}
1939 	}
1940 	if ((mp = *mpp) == NULL)
1941 		return (0);
1942 
1943 	/*
1944 	 * VOP_GETWRITEMOUNT() returns with the mp refcount held through
1945 	 * a vfs_ref().
1946 	 * As long as a vnode is not provided we need to acquire a
1947 	 * refcount for the provided mountpoint too, in order to
1948 	 * emulate a vfs_ref().
1949 	 */
1950 	if (vp == NULL)
1951 		vfs_ref(mp);
1952 
1953 	error = vn_start_write_refed(mp, flags, false);
1954 	if (error != 0 && (flags & V_NOWAIT) == 0)
1955 		*mpp = NULL;
1956 	return (error);
1957 }
1958 
1959 /*
1960  * Secondary suspension. Used by operations such as vop_inactive
1961  * routines that are needed by the higher level functions. These
1962  * are allowed to proceed until all the higher level functions have
1963  * completed (indicated by mnt_writeopcount dropping to zero). At that
1964  * time, these operations are halted until the suspension is over.
1965  */
1966 int
1967 vn_start_secondary_write(struct vnode *vp, struct mount **mpp, int flags)
1968 {
1969 	struct mount *mp;
1970 	int error, mflags;
1971 
1972 	KASSERT((flags & (~V_VALID_FLAGS | V_XSLEEP)) == 0,
1973 	    ("%s: invalid flags passed %d\n", __func__, flags));
1974 
1975  retry:
1976 	if (vp != NULL) {
1977 		if ((error = VOP_GETWRITEMOUNT(vp, mpp)) != 0) {
1978 			*mpp = NULL;
1979 			if (error != EOPNOTSUPP)
1980 				return (error);
1981 			return (0);
1982 		}
1983 	}
1984 	/*
1985 	 * If we are not suspended or have not yet reached suspended
1986 	 * mode, then let the operation proceed.
1987 	 */
1988 	if ((mp = *mpp) == NULL)
1989 		return (0);
1990 
1991 	/*
1992 	 * VOP_GETWRITEMOUNT() returns with the mp refcount held through
1993 	 * a vfs_ref().
1994 	 * As long as a vnode is not provided we need to acquire a
1995 	 * refcount for the provided mountpoint too, in order to
1996 	 * emulate a vfs_ref().
1997 	 */
1998 	MNT_ILOCK(mp);
1999 	if (vp == NULL)
2000 		MNT_REF(mp);
2001 	if ((mp->mnt_kern_flag & (MNTK_SUSPENDED | MNTK_SUSPEND2)) == 0) {
2002 		mp->mnt_secondary_writes++;
2003 		mp->mnt_secondary_accwrites++;
2004 		MNT_IUNLOCK(mp);
2005 		return (0);
2006 	}
2007 	if ((flags & V_NOWAIT) != 0) {
2008 		MNT_REL(mp);
2009 		MNT_IUNLOCK(mp);
2010 		*mpp = NULL;
2011 		return (EWOULDBLOCK);
2012 	}
2013 	/*
2014 	 * Wait for the suspension to finish.
2015 	 */
2016 	mflags = 0;
2017 	if ((mp->mnt_vfc->vfc_flags & VFCF_SBDRY) != 0) {
2018 		if ((flags & V_PCATCH) != 0)
2019 			mflags |= PCATCH;
2020 	}
2021 	mflags |= (PUSER - 1) | PDROP;
2022 	error = msleep(&mp->mnt_flag, MNT_MTX(mp), mflags, "suspfs", 0);
2023 	vfs_rel(mp);
2024 	if (error == 0)
2025 		goto retry;
2026 	*mpp = NULL;
2027 	return (error);
2028 }
2029 
2030 /*
2031  * Filesystem write operation has completed. If we are suspending and this
2032  * operation is the last one, notify the suspender that the suspension is
2033  * now in effect.
2034  */
2035 void
2036 vn_finished_write(struct mount *mp)
2037 {
2038 	struct mount_pcpu *mpcpu;
2039 	int c;
2040 
2041 	if (mp == NULL)
2042 		return;
2043 
2044 	if (vfs_op_thread_enter(mp, mpcpu)) {
2045 		vfs_mp_count_sub_pcpu(mpcpu, writeopcount, 1);
2046 		vfs_mp_count_sub_pcpu(mpcpu, ref, 1);
2047 		vfs_op_thread_exit(mp, mpcpu);
2048 		return;
2049 	}
2050 
2051 	MNT_ILOCK(mp);
2052 	vfs_assert_mount_counters(mp);
2053 	MNT_REL(mp);
2054 	c = --mp->mnt_writeopcount;
2055 	if (mp->mnt_vfs_ops == 0) {
2056 		MPASS((mp->mnt_kern_flag & MNTK_SUSPEND) == 0);
2057 		MNT_IUNLOCK(mp);
2058 		return;
2059 	}
2060 	if (c < 0)
2061 		vfs_dump_mount_counters(mp);
2062 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0 && c == 0)
2063 		wakeup(&mp->mnt_writeopcount);
2064 	MNT_IUNLOCK(mp);
2065 }
2066 
2067 /*
2068  * Filesystem secondary write operation has completed. If we are
2069  * suspending and this operation is the last one, notify the suspender
2070  * that the suspension is now in effect.
2071  */
2072 void
2073 vn_finished_secondary_write(struct mount *mp)
2074 {
2075 	if (mp == NULL)
2076 		return;
2077 	MNT_ILOCK(mp);
2078 	MNT_REL(mp);
2079 	mp->mnt_secondary_writes--;
2080 	if (mp->mnt_secondary_writes < 0)
2081 		panic("vn_finished_secondary_write: neg cnt");
2082 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0 &&
2083 	    mp->mnt_secondary_writes <= 0)
2084 		wakeup(&mp->mnt_secondary_writes);
2085 	MNT_IUNLOCK(mp);
2086 }
2087 
2088 /*
2089  * Request a filesystem to suspend write operations.
2090  */
2091 int
2092 vfs_write_suspend(struct mount *mp, int flags)
2093 {
2094 	int error;
2095 
2096 	vfs_op_enter(mp);
2097 
2098 	MNT_ILOCK(mp);
2099 	vfs_assert_mount_counters(mp);
2100 	if (mp->mnt_susp_owner == curthread) {
2101 		vfs_op_exit_locked(mp);
2102 		MNT_IUNLOCK(mp);
2103 		return (EALREADY);
2104 	}
2105 	while (mp->mnt_kern_flag & MNTK_SUSPEND)
2106 		msleep(&mp->mnt_flag, MNT_MTX(mp), PUSER - 1, "wsuspfs", 0);
2107 
2108 	/*
2109 	 * Unmount holds a write reference on the mount point.  If we
2110 	 * own busy reference and drain for writers, we deadlock with
2111 	 * the reference draining in the unmount path.  Callers of
2112 	 * vfs_write_suspend() must specify VS_SKIP_UNMOUNT if
2113 	 * vfs_busy() reference is owned and caller is not in the
2114 	 * unmount context.
2115 	 */
2116 	if ((flags & VS_SKIP_UNMOUNT) != 0 &&
2117 	    (mp->mnt_kern_flag & MNTK_UNMOUNT) != 0) {
2118 		vfs_op_exit_locked(mp);
2119 		MNT_IUNLOCK(mp);
2120 		return (EBUSY);
2121 	}
2122 
2123 	mp->mnt_kern_flag |= MNTK_SUSPEND;
2124 	mp->mnt_susp_owner = curthread;
2125 	if (mp->mnt_writeopcount > 0)
2126 		(void) msleep(&mp->mnt_writeopcount,
2127 		    MNT_MTX(mp), (PUSER - 1)|PDROP, "suspwt", 0);
2128 	else
2129 		MNT_IUNLOCK(mp);
2130 	if ((error = VFS_SYNC(mp, MNT_SUSPEND)) != 0) {
2131 		vfs_write_resume(mp, 0);
2132 		/* vfs_write_resume does vfs_op_exit() for us */
2133 	}
2134 	return (error);
2135 }
2136 
2137 /*
2138  * Request a filesystem to resume write operations.
2139  */
2140 void
2141 vfs_write_resume(struct mount *mp, int flags)
2142 {
2143 
2144 	MNT_ILOCK(mp);
2145 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0) {
2146 		KASSERT(mp->mnt_susp_owner == curthread, ("mnt_susp_owner"));
2147 		mp->mnt_kern_flag &= ~(MNTK_SUSPEND | MNTK_SUSPEND2 |
2148 				       MNTK_SUSPENDED);
2149 		mp->mnt_susp_owner = NULL;
2150 		wakeup(&mp->mnt_writeopcount);
2151 		wakeup(&mp->mnt_flag);
2152 		curthread->td_pflags &= ~TDP_IGNSUSP;
2153 		if ((flags & VR_START_WRITE) != 0) {
2154 			MNT_REF(mp);
2155 			mp->mnt_writeopcount++;
2156 		}
2157 		MNT_IUNLOCK(mp);
2158 		if ((flags & VR_NO_SUSPCLR) == 0)
2159 			VFS_SUSP_CLEAN(mp);
2160 		vfs_op_exit(mp);
2161 	} else if ((flags & VR_START_WRITE) != 0) {
2162 		MNT_REF(mp);
2163 		vn_start_write_refed(mp, 0, true);
2164 	} else {
2165 		MNT_IUNLOCK(mp);
2166 	}
2167 }
2168 
2169 /*
2170  * Helper loop around vfs_write_suspend() for filesystem unmount VFS
2171  * methods.
2172  */
2173 int
2174 vfs_write_suspend_umnt(struct mount *mp)
2175 {
2176 	int error;
2177 
2178 	KASSERT((curthread->td_pflags & TDP_IGNSUSP) == 0,
2179 	    ("vfs_write_suspend_umnt: recursed"));
2180 
2181 	/* dounmount() already called vn_start_write(). */
2182 	for (;;) {
2183 		vn_finished_write(mp);
2184 		error = vfs_write_suspend(mp, 0);
2185 		if (error != 0) {
2186 			vn_start_write(NULL, &mp, V_WAIT);
2187 			return (error);
2188 		}
2189 		MNT_ILOCK(mp);
2190 		if ((mp->mnt_kern_flag & MNTK_SUSPENDED) != 0)
2191 			break;
2192 		MNT_IUNLOCK(mp);
2193 		vn_start_write(NULL, &mp, V_WAIT);
2194 	}
2195 	mp->mnt_kern_flag &= ~(MNTK_SUSPENDED | MNTK_SUSPEND2);
2196 	wakeup(&mp->mnt_flag);
2197 	MNT_IUNLOCK(mp);
2198 	curthread->td_pflags |= TDP_IGNSUSP;
2199 	return (0);
2200 }
2201 
2202 /*
2203  * Implement kqueues for files by translating it to vnode operation.
2204  */
2205 static int
2206 vn_kqfilter(struct file *fp, struct knote *kn)
2207 {
2208 
2209 	return (VOP_KQFILTER(fp->f_vnode, kn));
2210 }
2211 
2212 int
2213 vn_kqfilter_opath(struct file *fp, struct knote *kn)
2214 {
2215 	if ((fp->f_flag & FKQALLOWED) == 0)
2216 		return (EBADF);
2217 	return (vn_kqfilter(fp, kn));
2218 }
2219 
2220 /*
2221  * Simplified in-kernel wrapper calls for extended attribute access.
2222  * Both calls pass in a NULL credential, authorizing as "kernel" access.
2223  * Set IO_NODELOCKED in ioflg if the vnode is already locked.
2224  */
2225 int
2226 vn_extattr_get(struct vnode *vp, int ioflg, int attrnamespace,
2227     const char *attrname, int *buflen, char *buf, struct thread *td)
2228 {
2229 	struct uio	auio;
2230 	struct iovec	iov;
2231 	int	error;
2232 
2233 	iov.iov_len = *buflen;
2234 	iov.iov_base = buf;
2235 
2236 	auio.uio_iov = &iov;
2237 	auio.uio_iovcnt = 1;
2238 	auio.uio_rw = UIO_READ;
2239 	auio.uio_segflg = UIO_SYSSPACE;
2240 	auio.uio_td = td;
2241 	auio.uio_offset = 0;
2242 	auio.uio_resid = *buflen;
2243 
2244 	if ((ioflg & IO_NODELOCKED) == 0)
2245 		vn_lock(vp, LK_SHARED | LK_RETRY);
2246 
2247 	ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
2248 
2249 	/* authorize attribute retrieval as kernel */
2250 	error = VOP_GETEXTATTR(vp, attrnamespace, attrname, &auio, NULL, NULL,
2251 	    td);
2252 
2253 	if ((ioflg & IO_NODELOCKED) == 0)
2254 		VOP_UNLOCK(vp);
2255 
2256 	if (error == 0) {
2257 		*buflen = *buflen - auio.uio_resid;
2258 	}
2259 
2260 	return (error);
2261 }
2262 
2263 /*
2264  * XXX failure mode if partially written?
2265  */
2266 int
2267 vn_extattr_set(struct vnode *vp, int ioflg, int attrnamespace,
2268     const char *attrname, int buflen, char *buf, struct thread *td)
2269 {
2270 	struct uio	auio;
2271 	struct iovec	iov;
2272 	struct mount	*mp;
2273 	int	error;
2274 
2275 	iov.iov_len = buflen;
2276 	iov.iov_base = buf;
2277 
2278 	auio.uio_iov = &iov;
2279 	auio.uio_iovcnt = 1;
2280 	auio.uio_rw = UIO_WRITE;
2281 	auio.uio_segflg = UIO_SYSSPACE;
2282 	auio.uio_td = td;
2283 	auio.uio_offset = 0;
2284 	auio.uio_resid = buflen;
2285 
2286 	if ((ioflg & IO_NODELOCKED) == 0) {
2287 		if ((error = vn_start_write(vp, &mp, V_WAIT)) != 0)
2288 			return (error);
2289 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2290 	}
2291 
2292 	ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
2293 
2294 	/* authorize attribute setting as kernel */
2295 	error = VOP_SETEXTATTR(vp, attrnamespace, attrname, &auio, NULL, td);
2296 
2297 	if ((ioflg & IO_NODELOCKED) == 0) {
2298 		vn_finished_write(mp);
2299 		VOP_UNLOCK(vp);
2300 	}
2301 
2302 	return (error);
2303 }
2304 
2305 int
2306 vn_extattr_rm(struct vnode *vp, int ioflg, int attrnamespace,
2307     const char *attrname, struct thread *td)
2308 {
2309 	struct mount	*mp;
2310 	int	error;
2311 
2312 	if ((ioflg & IO_NODELOCKED) == 0) {
2313 		if ((error = vn_start_write(vp, &mp, V_WAIT)) != 0)
2314 			return (error);
2315 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2316 	}
2317 
2318 	ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
2319 
2320 	/* authorize attribute removal as kernel */
2321 	error = VOP_DELETEEXTATTR(vp, attrnamespace, attrname, NULL, td);
2322 	if (error == EOPNOTSUPP)
2323 		error = VOP_SETEXTATTR(vp, attrnamespace, attrname, NULL,
2324 		    NULL, td);
2325 
2326 	if ((ioflg & IO_NODELOCKED) == 0) {
2327 		vn_finished_write(mp);
2328 		VOP_UNLOCK(vp);
2329 	}
2330 
2331 	return (error);
2332 }
2333 
2334 static int
2335 vn_get_ino_alloc_vget(struct mount *mp, void *arg, int lkflags,
2336     struct vnode **rvp)
2337 {
2338 
2339 	return (VFS_VGET(mp, *(ino_t *)arg, lkflags, rvp));
2340 }
2341 
2342 int
2343 vn_vget_ino(struct vnode *vp, ino_t ino, int lkflags, struct vnode **rvp)
2344 {
2345 
2346 	return (vn_vget_ino_gen(vp, vn_get_ino_alloc_vget, &ino,
2347 	    lkflags, rvp));
2348 }
2349 
2350 int
2351 vn_vget_ino_gen(struct vnode *vp, vn_get_ino_t alloc, void *alloc_arg,
2352     int lkflags, struct vnode **rvp)
2353 {
2354 	struct mount *mp;
2355 	int ltype, error;
2356 
2357 	ASSERT_VOP_LOCKED(vp, "vn_vget_ino_get");
2358 	mp = vp->v_mount;
2359 	ltype = VOP_ISLOCKED(vp);
2360 	KASSERT(ltype == LK_EXCLUSIVE || ltype == LK_SHARED,
2361 	    ("vn_vget_ino: vp not locked"));
2362 	error = vfs_busy(mp, MBF_NOWAIT);
2363 	if (error != 0) {
2364 		vfs_ref(mp);
2365 		VOP_UNLOCK(vp);
2366 		error = vfs_busy(mp, 0);
2367 		vn_lock(vp, ltype | LK_RETRY);
2368 		vfs_rel(mp);
2369 		if (error != 0)
2370 			return (ENOENT);
2371 		if (VN_IS_DOOMED(vp)) {
2372 			vfs_unbusy(mp);
2373 			return (ENOENT);
2374 		}
2375 	}
2376 	VOP_UNLOCK(vp);
2377 	error = alloc(mp, alloc_arg, lkflags, rvp);
2378 	vfs_unbusy(mp);
2379 	if (error != 0 || *rvp != vp)
2380 		vn_lock(vp, ltype | LK_RETRY);
2381 	if (VN_IS_DOOMED(vp)) {
2382 		if (error == 0) {
2383 			if (*rvp == vp)
2384 				vunref(vp);
2385 			else
2386 				vput(*rvp);
2387 		}
2388 		error = ENOENT;
2389 	}
2390 	return (error);
2391 }
2392 
2393 static void
2394 vn_send_sigxfsz(struct proc *p)
2395 {
2396 	PROC_LOCK(p);
2397 	kern_psignal(p, SIGXFSZ);
2398 	PROC_UNLOCK(p);
2399 }
2400 
2401 int
2402 vn_rlimit_trunc(u_quad_t size, struct thread *td)
2403 {
2404 	if (size <= lim_cur(td, RLIMIT_FSIZE))
2405 		return (0);
2406 	vn_send_sigxfsz(td->td_proc);
2407 	return (EFBIG);
2408 }
2409 
2410 static int
2411 vn_rlimit_fsizex1(const struct vnode *vp, struct uio *uio, off_t maxfsz,
2412     bool adj, struct thread *td)
2413 {
2414 	off_t lim;
2415 	bool ktr_write;
2416 
2417 	if (vp->v_type != VREG)
2418 		return (0);
2419 
2420 	/*
2421 	 * Handle file system maximum file size.
2422 	 */
2423 	if (maxfsz != 0 && uio->uio_offset + uio->uio_resid > maxfsz) {
2424 		if (!adj || uio->uio_offset >= maxfsz)
2425 			return (EFBIG);
2426 		uio->uio_resid = maxfsz - uio->uio_offset;
2427 	}
2428 
2429 	/*
2430 	 * This is kernel write (e.g. vnode_pager) or accounting
2431 	 * write, ignore limit.
2432 	 */
2433 	if (td == NULL || (td->td_pflags2 & TDP2_ACCT) != 0)
2434 		return (0);
2435 
2436 	/*
2437 	 * Calculate file size limit.
2438 	 */
2439 	ktr_write = (td->td_pflags & TDP_INKTRACE) != 0;
2440 	lim = __predict_false(ktr_write) ? td->td_ktr_io_lim :
2441 	    lim_cur(td, RLIMIT_FSIZE);
2442 
2443 	/*
2444 	 * Is the limit reached?
2445 	 */
2446 	if (__predict_true((uoff_t)uio->uio_offset + uio->uio_resid <= lim))
2447 		return (0);
2448 
2449 	/*
2450 	 * Prepared filesystems can handle writes truncated to the
2451 	 * file size limit.
2452 	 */
2453 	if (adj && (uoff_t)uio->uio_offset < lim) {
2454 		uio->uio_resid = lim - (uoff_t)uio->uio_offset;
2455 		return (0);
2456 	}
2457 
2458 	if (!ktr_write || ktr_filesize_limit_signal)
2459 		vn_send_sigxfsz(td->td_proc);
2460 	return (EFBIG);
2461 }
2462 
2463 /*
2464  * Helper for VOP_WRITE() implementations, the common code to
2465  * handle maximum supported file size on the filesystem, and
2466  * RLIMIT_FSIZE, except for special writes from accounting subsystem
2467  * and ktrace.
2468  *
2469  * For maximum file size (maxfsz argument):
2470  * - return EFBIG if uio_offset is beyond it
2471  * - otherwise, clamp uio_resid if write would extend file beyond maxfsz.
2472  *
2473  * For RLIMIT_FSIZE:
2474  * - return EFBIG and send SIGXFSZ if uio_offset is beyond the limit
2475  * - otherwise, clamp uio_resid if write would extend file beyond limit.
2476  *
2477  * If clamping occured, the adjustment for uio_resid is stored in
2478  * *resid_adj, to be re-applied by vn_rlimit_fsizex_res() on return
2479  * from the VOP.
2480  */
2481 int
2482 vn_rlimit_fsizex(const struct vnode *vp, struct uio *uio, off_t maxfsz,
2483     ssize_t *resid_adj, struct thread *td)
2484 {
2485 	ssize_t resid_orig;
2486 	int error;
2487 	bool adj;
2488 
2489 	resid_orig = uio->uio_resid;
2490 	adj = resid_adj != NULL;
2491 	error = vn_rlimit_fsizex1(vp, uio, maxfsz, adj, td);
2492 	if (adj)
2493 		*resid_adj = resid_orig - uio->uio_resid;
2494 	return (error);
2495 }
2496 
2497 void
2498 vn_rlimit_fsizex_res(struct uio *uio, ssize_t resid_adj)
2499 {
2500 	uio->uio_resid += resid_adj;
2501 }
2502 
2503 int
2504 vn_rlimit_fsize(const struct vnode *vp, const struct uio *uio,
2505     struct thread *td)
2506 {
2507 	return (vn_rlimit_fsizex(vp, __DECONST(struct uio *, uio), 0, NULL,
2508 	    td));
2509 }
2510 
2511 int
2512 vn_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
2513     struct thread *td)
2514 {
2515 	struct vnode *vp;
2516 
2517 	vp = fp->f_vnode;
2518 #ifdef AUDIT
2519 	vn_lock(vp, LK_SHARED | LK_RETRY);
2520 	AUDIT_ARG_VNODE1(vp);
2521 	VOP_UNLOCK(vp);
2522 #endif
2523 	return (setfmode(td, active_cred, vp, mode));
2524 }
2525 
2526 int
2527 vn_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
2528     struct thread *td)
2529 {
2530 	struct vnode *vp;
2531 
2532 	vp = fp->f_vnode;
2533 #ifdef AUDIT
2534 	vn_lock(vp, LK_SHARED | LK_RETRY);
2535 	AUDIT_ARG_VNODE1(vp);
2536 	VOP_UNLOCK(vp);
2537 #endif
2538 	return (setfown(td, active_cred, vp, uid, gid));
2539 }
2540 
2541 /*
2542  * Remove pages in the range ["start", "end") from the vnode's VM object.  If
2543  * "end" is 0, then the range extends to the end of the object.
2544  */
2545 void
2546 vn_pages_remove(struct vnode *vp, vm_pindex_t start, vm_pindex_t end)
2547 {
2548 	vm_object_t object;
2549 
2550 	if ((object = vp->v_object) == NULL)
2551 		return;
2552 	VM_OBJECT_WLOCK(object);
2553 	vm_object_page_remove(object, start, end, 0);
2554 	VM_OBJECT_WUNLOCK(object);
2555 }
2556 
2557 /*
2558  * Like vn_pages_remove(), but skips invalid pages, which by definition are not
2559  * mapped into any process' address space.  Filesystems may use this in
2560  * preference to vn_pages_remove() to avoid blocking on pages busied in
2561  * preparation for a VOP_GETPAGES.
2562  */
2563 void
2564 vn_pages_remove_valid(struct vnode *vp, vm_pindex_t start, vm_pindex_t end)
2565 {
2566 	vm_object_t object;
2567 
2568 	if ((object = vp->v_object) == NULL)
2569 		return;
2570 	VM_OBJECT_WLOCK(object);
2571 	vm_object_page_remove(object, start, end, OBJPR_VALIDONLY);
2572 	VM_OBJECT_WUNLOCK(object);
2573 }
2574 
2575 int
2576 vn_bmap_seekhole_locked(struct vnode *vp, u_long cmd, off_t *off,
2577     struct ucred *cred)
2578 {
2579 	off_t size;
2580 	daddr_t bn, bnp;
2581 	uint64_t bsize;
2582 	off_t noff;
2583 	int error;
2584 
2585 	KASSERT(cmd == FIOSEEKHOLE || cmd == FIOSEEKDATA,
2586 	    ("%s: Wrong command %lu", __func__, cmd));
2587 	ASSERT_VOP_ELOCKED(vp, "vn_bmap_seekhole_locked");
2588 
2589 	if (vp->v_type != VREG) {
2590 		error = ENOTTY;
2591 		goto out;
2592 	}
2593 	error = vn_getsize_locked(vp, &size, cred);
2594 	if (error != 0)
2595 		goto out;
2596 	noff = *off;
2597 	if (noff < 0 || noff >= size) {
2598 		error = ENXIO;
2599 		goto out;
2600 	}
2601 
2602 	/* See the comment in ufs_bmap_seekdata(). */
2603 	vnode_pager_clean_sync(vp);
2604 
2605 	bsize = vp->v_mount->mnt_stat.f_iosize;
2606 	for (bn = noff / bsize; noff < size; bn++, noff += bsize -
2607 	    noff % bsize) {
2608 		error = VOP_BMAP(vp, bn, NULL, &bnp, NULL, NULL);
2609 		if (error == EOPNOTSUPP) {
2610 			error = ENOTTY;
2611 			goto out;
2612 		}
2613 		if ((bnp == -1 && cmd == FIOSEEKHOLE) ||
2614 		    (bnp != -1 && cmd == FIOSEEKDATA)) {
2615 			noff = bn * bsize;
2616 			if (noff < *off)
2617 				noff = *off;
2618 			goto out;
2619 		}
2620 	}
2621 	if (noff > size)
2622 		noff = size;
2623 	/* noff == size. There is an implicit hole at the end of file. */
2624 	if (cmd == FIOSEEKDATA)
2625 		error = ENXIO;
2626 out:
2627 	if (error == 0)
2628 		*off = noff;
2629 	return (error);
2630 }
2631 
2632 int
2633 vn_bmap_seekhole(struct vnode *vp, u_long cmd, off_t *off, struct ucred *cred)
2634 {
2635 	int error;
2636 
2637 	KASSERT(cmd == FIOSEEKHOLE || cmd == FIOSEEKDATA,
2638 	    ("%s: Wrong command %lu", __func__, cmd));
2639 
2640 	if (vn_lock(vp, LK_EXCLUSIVE) != 0)
2641 		return (EBADF);
2642 	error = vn_bmap_seekhole_locked(vp, cmd, off, cred);
2643 	VOP_UNLOCK(vp);
2644 	return (error);
2645 }
2646 
2647 int
2648 vn_seek(struct file *fp, off_t offset, int whence, struct thread *td)
2649 {
2650 	struct ucred *cred;
2651 	struct vnode *vp;
2652 	off_t foffset, fsize, size;
2653 	int error, noneg;
2654 
2655 	cred = td->td_ucred;
2656 	vp = fp->f_vnode;
2657 	noneg = (vp->v_type != VCHR);
2658 	/*
2659 	 * Try to dodge locking for common case of querying the offset.
2660 	 */
2661 	if (whence == L_INCR && offset == 0) {
2662 		foffset = foffset_read(fp);
2663 		if (__predict_false(foffset < 0 && noneg)) {
2664 			return (EOVERFLOW);
2665 		}
2666 		td->td_uretoff.tdu_off = foffset;
2667 		return (0);
2668 	}
2669 	foffset = foffset_lock(fp, 0);
2670 	error = 0;
2671 	switch (whence) {
2672 	case L_INCR:
2673 		if (noneg &&
2674 		    (foffset < 0 ||
2675 		    (offset > 0 && foffset > OFF_MAX - offset))) {
2676 			error = EOVERFLOW;
2677 			break;
2678 		}
2679 		offset += foffset;
2680 		break;
2681 	case L_XTND:
2682 		error = vn_getsize(vp, &fsize, cred);
2683 		if (error != 0)
2684 			break;
2685 
2686 		/*
2687 		 * If the file references a disk device, then fetch
2688 		 * the media size and use that to determine the ending
2689 		 * offset.
2690 		 */
2691 		if (fsize == 0 && vp->v_type == VCHR &&
2692 		    fo_ioctl(fp, DIOCGMEDIASIZE, &size, cred, td) == 0)
2693 			fsize = size;
2694 		if (noneg && offset > 0 && fsize > OFF_MAX - offset) {
2695 			error = EOVERFLOW;
2696 			break;
2697 		}
2698 		offset += fsize;
2699 		break;
2700 	case L_SET:
2701 		break;
2702 	case SEEK_DATA:
2703 		error = fo_ioctl(fp, FIOSEEKDATA, &offset, cred, td);
2704 		if (error == ENOTTY)
2705 			error = EINVAL;
2706 		break;
2707 	case SEEK_HOLE:
2708 		error = fo_ioctl(fp, FIOSEEKHOLE, &offset, cred, td);
2709 		if (error == ENOTTY)
2710 			error = EINVAL;
2711 		break;
2712 	default:
2713 		error = EINVAL;
2714 	}
2715 	if (error == 0 && noneg && offset < 0)
2716 		error = EINVAL;
2717 	if (error != 0)
2718 		goto drop;
2719 	VFS_KNOTE_UNLOCKED(vp, 0);
2720 	td->td_uretoff.tdu_off = offset;
2721 drop:
2722 	foffset_unlock(fp, offset, error != 0 ? FOF_NOUPDATE : 0);
2723 	return (error);
2724 }
2725 
2726 int
2727 vn_utimes_perm(struct vnode *vp, struct vattr *vap, struct ucred *cred,
2728     struct thread *td)
2729 {
2730 	int error;
2731 
2732 	/*
2733 	 * Grant permission if the caller is the owner of the file, or
2734 	 * the super-user, or has ACL_WRITE_ATTRIBUTES permission on
2735 	 * on the file.  If the time pointer is null, then write
2736 	 * permission on the file is also sufficient.
2737 	 *
2738 	 * From NFSv4.1, draft 21, 6.2.1.3.1, Discussion of Mask Attributes:
2739 	 * A user having ACL_WRITE_DATA or ACL_WRITE_ATTRIBUTES
2740 	 * will be allowed to set the times [..] to the current
2741 	 * server time.
2742 	 */
2743 	error = VOP_ACCESSX(vp, VWRITE_ATTRIBUTES, cred, td);
2744 	if (error != 0 && (vap->va_vaflags & VA_UTIMES_NULL) != 0)
2745 		error = VOP_ACCESS(vp, VWRITE, cred, td);
2746 	return (error);
2747 }
2748 
2749 int
2750 vn_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
2751 {
2752 	struct vnode *vp;
2753 	int error;
2754 
2755 	if (fp->f_type == DTYPE_FIFO)
2756 		kif->kf_type = KF_TYPE_FIFO;
2757 	else
2758 		kif->kf_type = KF_TYPE_VNODE;
2759 	vp = fp->f_vnode;
2760 	vref(vp);
2761 	FILEDESC_SUNLOCK(fdp);
2762 	error = vn_fill_kinfo_vnode(vp, kif);
2763 	vrele(vp);
2764 	FILEDESC_SLOCK(fdp);
2765 	return (error);
2766 }
2767 
2768 static inline void
2769 vn_fill_junk(struct kinfo_file *kif)
2770 {
2771 	size_t len, olen;
2772 
2773 	/*
2774 	 * Simulate vn_fullpath returning changing values for a given
2775 	 * vp during e.g. coredump.
2776 	 */
2777 	len = (arc4random() % (sizeof(kif->kf_path) - 2)) + 1;
2778 	olen = strlen(kif->kf_path);
2779 	if (len < olen)
2780 		strcpy(&kif->kf_path[len - 1], "$");
2781 	else
2782 		for (; olen < len; olen++)
2783 			strcpy(&kif->kf_path[olen], "A");
2784 }
2785 
2786 int
2787 vn_fill_kinfo_vnode(struct vnode *vp, struct kinfo_file *kif)
2788 {
2789 	struct vattr va;
2790 	char *fullpath, *freepath;
2791 	int error;
2792 
2793 	kif->kf_un.kf_file.kf_file_type = vntype_to_kinfo(vp->v_type);
2794 	freepath = NULL;
2795 	fullpath = "-";
2796 	error = vn_fullpath(vp, &fullpath, &freepath);
2797 	if (error == 0) {
2798 		strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2799 	}
2800 	if (freepath != NULL)
2801 		free(freepath, M_TEMP);
2802 
2803 	KFAIL_POINT_CODE(DEBUG_FP, fill_kinfo_vnode__random_path,
2804 		vn_fill_junk(kif);
2805 	);
2806 
2807 	/*
2808 	 * Retrieve vnode attributes.
2809 	 */
2810 	va.va_fsid = VNOVAL;
2811 	va.va_rdev = NODEV;
2812 	vn_lock(vp, LK_SHARED | LK_RETRY);
2813 	error = VOP_GETATTR(vp, &va, curthread->td_ucred);
2814 	VOP_UNLOCK(vp);
2815 	if (error != 0)
2816 		return (error);
2817 	if (va.va_fsid != VNOVAL)
2818 		kif->kf_un.kf_file.kf_file_fsid = va.va_fsid;
2819 	else
2820 		kif->kf_un.kf_file.kf_file_fsid =
2821 		    vp->v_mount->mnt_stat.f_fsid.val[0];
2822 	kif->kf_un.kf_file.kf_file_fsid_freebsd11 =
2823 	    kif->kf_un.kf_file.kf_file_fsid; /* truncate */
2824 	kif->kf_un.kf_file.kf_file_fileid = va.va_fileid;
2825 	kif->kf_un.kf_file.kf_file_mode = MAKEIMODE(va.va_type, va.va_mode);
2826 	kif->kf_un.kf_file.kf_file_size = va.va_size;
2827 	kif->kf_un.kf_file.kf_file_rdev = va.va_rdev;
2828 	kif->kf_un.kf_file.kf_file_rdev_freebsd11 =
2829 	    kif->kf_un.kf_file.kf_file_rdev; /* truncate */
2830 	kif->kf_un.kf_file.kf_file_nlink = va.va_nlink;
2831 	return (0);
2832 }
2833 
2834 int
2835 vn_mmap(struct file *fp, vm_map_t map, vm_offset_t *addr, vm_size_t size,
2836     vm_prot_t prot, vm_prot_t cap_maxprot, int flags, vm_ooffset_t foff,
2837     struct thread *td)
2838 {
2839 #ifdef HWPMC_HOOKS
2840 	struct pmckern_map_in pkm;
2841 #endif
2842 	struct mount *mp;
2843 	struct vnode *vp;
2844 	vm_object_t object;
2845 	vm_prot_t maxprot;
2846 	boolean_t writecounted;
2847 	int error;
2848 
2849 #if defined(COMPAT_FREEBSD7) || defined(COMPAT_FREEBSD6) || \
2850     defined(COMPAT_FREEBSD5) || defined(COMPAT_FREEBSD4)
2851 	/*
2852 	 * POSIX shared-memory objects are defined to have
2853 	 * kernel persistence, and are not defined to support
2854 	 * read(2)/write(2) -- or even open(2).  Thus, we can
2855 	 * use MAP_ASYNC to trade on-disk coherence for speed.
2856 	 * The shm_open(3) library routine turns on the FPOSIXSHM
2857 	 * flag to request this behavior.
2858 	 */
2859 	if ((fp->f_flag & FPOSIXSHM) != 0)
2860 		flags |= MAP_NOSYNC;
2861 #endif
2862 	vp = fp->f_vnode;
2863 
2864 	/*
2865 	 * Ensure that file and memory protections are
2866 	 * compatible.  Note that we only worry about
2867 	 * writability if mapping is shared; in this case,
2868 	 * current and max prot are dictated by the open file.
2869 	 * XXX use the vnode instead?  Problem is: what
2870 	 * credentials do we use for determination? What if
2871 	 * proc does a setuid?
2872 	 */
2873 	mp = vp->v_mount;
2874 	if (mp != NULL && (mp->mnt_flag & MNT_NOEXEC) != 0) {
2875 		maxprot = VM_PROT_NONE;
2876 		if ((prot & VM_PROT_EXECUTE) != 0)
2877 			return (EACCES);
2878 	} else
2879 		maxprot = VM_PROT_EXECUTE;
2880 	if ((fp->f_flag & FREAD) != 0)
2881 		maxprot |= VM_PROT_READ;
2882 	else if ((prot & VM_PROT_READ) != 0)
2883 		return (EACCES);
2884 
2885 	/*
2886 	 * If we are sharing potential changes via MAP_SHARED and we
2887 	 * are trying to get write permission although we opened it
2888 	 * without asking for it, bail out.
2889 	 */
2890 	if ((flags & MAP_SHARED) != 0) {
2891 		if ((fp->f_flag & FWRITE) != 0)
2892 			maxprot |= VM_PROT_WRITE;
2893 		else if ((prot & VM_PROT_WRITE) != 0)
2894 			return (EACCES);
2895 	} else {
2896 		maxprot |= VM_PROT_WRITE;
2897 		cap_maxprot |= VM_PROT_WRITE;
2898 	}
2899 	maxprot &= cap_maxprot;
2900 
2901 	/*
2902 	 * For regular files and shared memory, POSIX requires that
2903 	 * the value of foff be a legitimate offset within the data
2904 	 * object.  In particular, negative offsets are invalid.
2905 	 * Blocking negative offsets and overflows here avoids
2906 	 * possible wraparound or user-level access into reserved
2907 	 * ranges of the data object later.  In contrast, POSIX does
2908 	 * not dictate how offsets are used by device drivers, so in
2909 	 * the case of a device mapping a negative offset is passed
2910 	 * on.
2911 	 */
2912 	if (
2913 #ifdef _LP64
2914 	    size > OFF_MAX ||
2915 #endif
2916 	    foff > OFF_MAX - size)
2917 		return (EINVAL);
2918 
2919 	writecounted = FALSE;
2920 	error = vm_mmap_vnode(td, size, prot, &maxprot, &flags, vp,
2921 	    &foff, &object, &writecounted);
2922 	if (error != 0)
2923 		return (error);
2924 	error = vm_mmap_object(map, addr, size, prot, maxprot, flags, object,
2925 	    foff, writecounted, td);
2926 	if (error != 0) {
2927 		/*
2928 		 * If this mapping was accounted for in the vnode's
2929 		 * writecount, then undo that now.
2930 		 */
2931 		if (writecounted)
2932 			vm_pager_release_writecount(object, 0, size);
2933 		vm_object_deallocate(object);
2934 	}
2935 #ifdef HWPMC_HOOKS
2936 	/* Inform hwpmc(4) if an executable is being mapped. */
2937 	if (PMC_HOOK_INSTALLED(PMC_FN_MMAP)) {
2938 		if ((prot & VM_PROT_EXECUTE) != 0 && error == 0) {
2939 			pkm.pm_file = vp;
2940 			pkm.pm_address = (uintptr_t) *addr;
2941 			PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_MMAP, (void *) &pkm);
2942 		}
2943 	}
2944 #endif
2945 	return (error);
2946 }
2947 
2948 void
2949 vn_fsid(struct vnode *vp, struct vattr *va)
2950 {
2951 	fsid_t *f;
2952 
2953 	f = &vp->v_mount->mnt_stat.f_fsid;
2954 	va->va_fsid = (uint32_t)f->val[1];
2955 	va->va_fsid <<= sizeof(f->val[1]) * NBBY;
2956 	va->va_fsid += (uint32_t)f->val[0];
2957 }
2958 
2959 int
2960 vn_fsync_buf(struct vnode *vp, int waitfor)
2961 {
2962 	struct buf *bp, *nbp;
2963 	struct bufobj *bo;
2964 	struct mount *mp;
2965 	int error, maxretry;
2966 
2967 	error = 0;
2968 	maxretry = 10000;     /* large, arbitrarily chosen */
2969 	mp = NULL;
2970 	if (vp->v_type == VCHR) {
2971 		VI_LOCK(vp);
2972 		mp = vp->v_rdev->si_mountpt;
2973 		VI_UNLOCK(vp);
2974 	}
2975 	bo = &vp->v_bufobj;
2976 	BO_LOCK(bo);
2977 loop1:
2978 	/*
2979 	 * MARK/SCAN initialization to avoid infinite loops.
2980 	 */
2981         TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
2982 		bp->b_vflags &= ~BV_SCANNED;
2983 		bp->b_error = 0;
2984 	}
2985 
2986 	/*
2987 	 * Flush all dirty buffers associated with a vnode.
2988 	 */
2989 loop2:
2990 	TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2991 		if ((bp->b_vflags & BV_SCANNED) != 0)
2992 			continue;
2993 		bp->b_vflags |= BV_SCANNED;
2994 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL)) {
2995 			if (waitfor != MNT_WAIT)
2996 				continue;
2997 			if (BUF_LOCK(bp,
2998 			    LK_EXCLUSIVE | LK_INTERLOCK | LK_SLEEPFAIL,
2999 			    BO_LOCKPTR(bo)) != 0) {
3000 				BO_LOCK(bo);
3001 				goto loop1;
3002 			}
3003 			BO_LOCK(bo);
3004 		}
3005 		BO_UNLOCK(bo);
3006 		KASSERT(bp->b_bufobj == bo,
3007 		    ("bp %p wrong b_bufobj %p should be %p",
3008 		    bp, bp->b_bufobj, bo));
3009 		if ((bp->b_flags & B_DELWRI) == 0)
3010 			panic("fsync: not dirty");
3011 		if ((vp->v_object != NULL) && (bp->b_flags & B_CLUSTEROK)) {
3012 			vfs_bio_awrite(bp);
3013 		} else {
3014 			bremfree(bp);
3015 			bawrite(bp);
3016 		}
3017 		if (maxretry < 1000)
3018 			pause("dirty", hz < 1000 ? 1 : hz / 1000);
3019 		BO_LOCK(bo);
3020 		goto loop2;
3021 	}
3022 
3023 	/*
3024 	 * If synchronous the caller expects us to completely resolve all
3025 	 * dirty buffers in the system.  Wait for in-progress I/O to
3026 	 * complete (which could include background bitmap writes), then
3027 	 * retry if dirty blocks still exist.
3028 	 */
3029 	if (waitfor == MNT_WAIT) {
3030 		bufobj_wwait(bo, 0, 0);
3031 		if (bo->bo_dirty.bv_cnt > 0) {
3032 			/*
3033 			 * If we are unable to write any of these buffers
3034 			 * then we fail now rather than trying endlessly
3035 			 * to write them out.
3036 			 */
3037 			TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
3038 				if ((error = bp->b_error) != 0)
3039 					break;
3040 			if ((mp != NULL && mp->mnt_secondary_writes > 0) ||
3041 			    (error == 0 && --maxretry >= 0))
3042 				goto loop1;
3043 			if (error == 0)
3044 				error = EAGAIN;
3045 		}
3046 	}
3047 	BO_UNLOCK(bo);
3048 	if (error != 0)
3049 		vn_printf(vp, "fsync: giving up on dirty (error = %d) ", error);
3050 
3051 	return (error);
3052 }
3053 
3054 /*
3055  * Copies a byte range from invp to outvp.  Calls VOP_COPY_FILE_RANGE()
3056  * or vn_generic_copy_file_range() after rangelocking the byte ranges,
3057  * to do the actual copy.
3058  * vn_generic_copy_file_range() is factored out, so it can be called
3059  * from a VOP_COPY_FILE_RANGE() call as well, but handles vnodes from
3060  * different file systems.
3061  */
3062 int
3063 vn_copy_file_range(struct vnode *invp, off_t *inoffp, struct vnode *outvp,
3064     off_t *outoffp, size_t *lenp, unsigned int flags, struct ucred *incred,
3065     struct ucred *outcred, struct thread *fsize_td)
3066 {
3067 	struct mount *inmp, *outmp;
3068 	struct vnode *invpl, *outvpl;
3069 	int error;
3070 	size_t len;
3071 	uint64_t uval;
3072 
3073 	invpl = outvpl = NULL;
3074 	len = *lenp;
3075 	*lenp = 0;		/* For error returns. */
3076 	error = 0;
3077 
3078 	/* Do some sanity checks on the arguments. */
3079 	if (invp->v_type == VDIR || outvp->v_type == VDIR)
3080 		error = EISDIR;
3081 	else if (*inoffp < 0 || *outoffp < 0 ||
3082 	    invp->v_type != VREG || outvp->v_type != VREG)
3083 		error = EINVAL;
3084 	if (error != 0)
3085 		goto out;
3086 
3087 	/* Ensure offset + len does not wrap around. */
3088 	uval = *inoffp;
3089 	uval += len;
3090 	if (uval > INT64_MAX)
3091 		len = INT64_MAX - *inoffp;
3092 	uval = *outoffp;
3093 	uval += len;
3094 	if (uval > INT64_MAX)
3095 		len = INT64_MAX - *outoffp;
3096 	if (len == 0)
3097 		goto out;
3098 
3099 	error = VOP_GETLOWVNODE(invp, &invpl, FREAD);
3100 	if (error != 0)
3101 		goto out;
3102 	error = VOP_GETLOWVNODE(outvp, &outvpl, FWRITE);
3103 	if (error != 0)
3104 		goto out1;
3105 
3106 	inmp = invpl->v_mount;
3107 	outmp = outvpl->v_mount;
3108 	if (inmp == NULL || outmp == NULL)
3109 		goto out2;
3110 
3111 	for (;;) {
3112 		error = vfs_busy(inmp, 0);
3113 		if (error != 0)
3114 			goto out2;
3115 		if (inmp == outmp)
3116 			break;
3117 		error = vfs_busy(outmp, MBF_NOWAIT);
3118 		if (error != 0) {
3119 			vfs_unbusy(inmp);
3120 			error = vfs_busy(outmp, 0);
3121 			if (error == 0) {
3122 				vfs_unbusy(outmp);
3123 				continue;
3124 			}
3125 			goto out2;
3126 		}
3127 		break;
3128 	}
3129 
3130 	/*
3131 	 * If the two vnodes are for the same file system type, call
3132 	 * VOP_COPY_FILE_RANGE(), otherwise call vn_generic_copy_file_range()
3133 	 * which can handle copies across multiple file system types.
3134 	 */
3135 	*lenp = len;
3136 	if (inmp == outmp || inmp->mnt_vfc == outmp->mnt_vfc)
3137 		error = VOP_COPY_FILE_RANGE(invpl, inoffp, outvpl, outoffp,
3138 		    lenp, flags, incred, outcred, fsize_td);
3139 	else
3140 		error = ENOSYS;
3141 	if (error == ENOSYS)
3142 		error = vn_generic_copy_file_range(invpl, inoffp, outvpl,
3143 		    outoffp, lenp, flags, incred, outcred, fsize_td);
3144 	vfs_unbusy(outmp);
3145 	if (inmp != outmp)
3146 		vfs_unbusy(inmp);
3147 out2:
3148 	if (outvpl != NULL)
3149 		vrele(outvpl);
3150 out1:
3151 	if (invpl != NULL)
3152 		vrele(invpl);
3153 out:
3154 	return (error);
3155 }
3156 
3157 /*
3158  * Test len bytes of data starting at dat for all bytes == 0.
3159  * Return true if all bytes are zero, false otherwise.
3160  * Expects dat to be well aligned.
3161  */
3162 static bool
3163 mem_iszero(void *dat, int len)
3164 {
3165 	int i;
3166 	const u_int *p;
3167 	const char *cp;
3168 
3169 	for (p = dat; len > 0; len -= sizeof(*p), p++) {
3170 		if (len >= sizeof(*p)) {
3171 			if (*p != 0)
3172 				return (false);
3173 		} else {
3174 			cp = (const char *)p;
3175 			for (i = 0; i < len; i++, cp++)
3176 				if (*cp != '\0')
3177 					return (false);
3178 		}
3179 	}
3180 	return (true);
3181 }
3182 
3183 /*
3184  * Look for a hole in the output file and, if found, adjust *outoffp
3185  * and *xferp to skip past the hole.
3186  * *xferp is the entire hole length to be written and xfer2 is how many bytes
3187  * to be written as 0's upon return.
3188  */
3189 static off_t
3190 vn_skip_hole(struct vnode *outvp, off_t xfer2, off_t *outoffp, off_t *xferp,
3191     off_t *dataoffp, off_t *holeoffp, struct ucred *cred)
3192 {
3193 	int error;
3194 	off_t delta;
3195 
3196 	if (*holeoffp == 0 || *holeoffp <= *outoffp) {
3197 		*dataoffp = *outoffp;
3198 		error = VOP_IOCTL(outvp, FIOSEEKDATA, dataoffp, 0, cred,
3199 		    curthread);
3200 		if (error == 0) {
3201 			*holeoffp = *dataoffp;
3202 			error = VOP_IOCTL(outvp, FIOSEEKHOLE, holeoffp, 0, cred,
3203 			    curthread);
3204 		}
3205 		if (error != 0 || *holeoffp == *dataoffp) {
3206 			/*
3207 			 * Since outvp is unlocked, it may be possible for
3208 			 * another thread to do a truncate(), lseek(), write()
3209 			 * creating a hole at startoff between the above
3210 			 * VOP_IOCTL() calls, if the other thread does not do
3211 			 * rangelocking.
3212 			 * If that happens, *holeoffp == *dataoffp and finding
3213 			 * the hole has failed, so disable vn_skip_hole().
3214 			 */
3215 			*holeoffp = -1;	/* Disable use of vn_skip_hole(). */
3216 			return (xfer2);
3217 		}
3218 		KASSERT(*dataoffp >= *outoffp,
3219 		    ("vn_skip_hole: dataoff=%jd < outoff=%jd",
3220 		    (intmax_t)*dataoffp, (intmax_t)*outoffp));
3221 		KASSERT(*holeoffp > *dataoffp,
3222 		    ("vn_skip_hole: holeoff=%jd <= dataoff=%jd",
3223 		    (intmax_t)*holeoffp, (intmax_t)*dataoffp));
3224 	}
3225 
3226 	/*
3227 	 * If there is a hole before the data starts, advance *outoffp and
3228 	 * *xferp past the hole.
3229 	 */
3230 	if (*dataoffp > *outoffp) {
3231 		delta = *dataoffp - *outoffp;
3232 		if (delta >= *xferp) {
3233 			/* Entire *xferp is a hole. */
3234 			*outoffp += *xferp;
3235 			*xferp = 0;
3236 			return (0);
3237 		}
3238 		*xferp -= delta;
3239 		*outoffp += delta;
3240 		xfer2 = MIN(xfer2, *xferp);
3241 	}
3242 
3243 	/*
3244 	 * If a hole starts before the end of this xfer2, reduce this xfer2 so
3245 	 * that the write ends at the start of the hole.
3246 	 * *holeoffp should always be greater than *outoffp, but for the
3247 	 * non-INVARIANTS case, check this to make sure xfer2 remains a sane
3248 	 * value.
3249 	 */
3250 	if (*holeoffp > *outoffp && *holeoffp < *outoffp + xfer2)
3251 		xfer2 = *holeoffp - *outoffp;
3252 	return (xfer2);
3253 }
3254 
3255 /*
3256  * Write an xfer sized chunk to outvp in blksize blocks from dat.
3257  * dat is a maximum of blksize in length and can be written repeatedly in
3258  * the chunk.
3259  * If growfile == true, just grow the file via vn_truncate_locked() instead
3260  * of doing actual writes.
3261  * If checkhole == true, a hole is being punched, so skip over any hole
3262  * already in the output file.
3263  */
3264 static int
3265 vn_write_outvp(struct vnode *outvp, char *dat, off_t outoff, off_t xfer,
3266     u_long blksize, bool growfile, bool checkhole, struct ucred *cred)
3267 {
3268 	struct mount *mp;
3269 	off_t dataoff, holeoff, xfer2;
3270 	int error;
3271 
3272 	/*
3273 	 * Loop around doing writes of blksize until write has been completed.
3274 	 * Lock/unlock on each loop iteration so that a bwillwrite() can be
3275 	 * done for each iteration, since the xfer argument can be very
3276 	 * large if there is a large hole to punch in the output file.
3277 	 */
3278 	error = 0;
3279 	holeoff = 0;
3280 	do {
3281 		xfer2 = MIN(xfer, blksize);
3282 		if (checkhole) {
3283 			/*
3284 			 * Punching a hole.  Skip writing if there is
3285 			 * already a hole in the output file.
3286 			 */
3287 			xfer2 = vn_skip_hole(outvp, xfer2, &outoff, &xfer,
3288 			    &dataoff, &holeoff, cred);
3289 			if (xfer == 0)
3290 				break;
3291 			if (holeoff < 0)
3292 				checkhole = false;
3293 			KASSERT(xfer2 > 0, ("vn_write_outvp: xfer2=%jd",
3294 			    (intmax_t)xfer2));
3295 		}
3296 		bwillwrite();
3297 		mp = NULL;
3298 		error = vn_start_write(outvp, &mp, V_WAIT);
3299 		if (error != 0)
3300 			break;
3301 		if (growfile) {
3302 			error = vn_lock(outvp, LK_EXCLUSIVE);
3303 			if (error == 0) {
3304 				error = vn_truncate_locked(outvp, outoff + xfer,
3305 				    false, cred);
3306 				VOP_UNLOCK(outvp);
3307 			}
3308 		} else {
3309 			error = vn_lock(outvp, vn_lktype_write(mp, outvp));
3310 			if (error == 0) {
3311 				error = vn_rdwr(UIO_WRITE, outvp, dat, xfer2,
3312 				    outoff, UIO_SYSSPACE, IO_NODELOCKED,
3313 				    curthread->td_ucred, cred, NULL, curthread);
3314 				outoff += xfer2;
3315 				xfer -= xfer2;
3316 				VOP_UNLOCK(outvp);
3317 			}
3318 		}
3319 		if (mp != NULL)
3320 			vn_finished_write(mp);
3321 	} while (!growfile && xfer > 0 && error == 0);
3322 	return (error);
3323 }
3324 
3325 /*
3326  * Copy a byte range of one file to another.  This function can handle the
3327  * case where invp and outvp are on different file systems.
3328  * It can also be called by a VOP_COPY_FILE_RANGE() to do the work, if there
3329  * is no better file system specific way to do it.
3330  */
3331 int
3332 vn_generic_copy_file_range(struct vnode *invp, off_t *inoffp,
3333     struct vnode *outvp, off_t *outoffp, size_t *lenp, unsigned int flags,
3334     struct ucred *incred, struct ucred *outcred, struct thread *fsize_td)
3335 {
3336 	struct mount *mp;
3337 	off_t startoff, endoff, xfer, xfer2;
3338 	u_long blksize;
3339 	int error, interrupted;
3340 	bool cantseek, readzeros, eof, lastblock, holetoeof;
3341 	ssize_t aresid, r = 0;
3342 	size_t copylen, len, savlen;
3343 	off_t insize, outsize;
3344 	char *dat;
3345 	long holein, holeout;
3346 	struct timespec curts, endts;
3347 
3348 	holein = holeout = 0;
3349 	savlen = len = *lenp;
3350 	error = 0;
3351 	interrupted = 0;
3352 	dat = NULL;
3353 
3354 	error = vn_lock(invp, LK_SHARED);
3355 	if (error != 0)
3356 		goto out;
3357 	if (VOP_PATHCONF(invp, _PC_MIN_HOLE_SIZE, &holein) != 0)
3358 		holein = 0;
3359 	error = vn_getsize_locked(invp, &insize, incred);
3360 	VOP_UNLOCK(invp);
3361 	if (error != 0)
3362 		goto out;
3363 
3364 	mp = NULL;
3365 	error = vn_start_write(outvp, &mp, V_WAIT);
3366 	if (error == 0)
3367 		error = vn_lock(outvp, LK_EXCLUSIVE);
3368 	if (error == 0) {
3369 		/*
3370 		 * If fsize_td != NULL, do a vn_rlimit_fsizex() call,
3371 		 * now that outvp is locked.
3372 		 */
3373 		if (fsize_td != NULL) {
3374 			struct uio io;
3375 
3376 			io.uio_offset = *outoffp;
3377 			io.uio_resid = len;
3378 			error = vn_rlimit_fsizex(outvp, &io, 0, &r, fsize_td);
3379 			len = savlen = io.uio_resid;
3380 			/*
3381 			 * No need to call vn_rlimit_fsizex_res before return,
3382 			 * since the uio is local.
3383 			 */
3384 		}
3385 		if (VOP_PATHCONF(outvp, _PC_MIN_HOLE_SIZE, &holeout) != 0)
3386 			holeout = 0;
3387 		/*
3388 		 * Holes that are past EOF do not need to be written as a block
3389 		 * of zero bytes.  So, truncate the output file as far as
3390 		 * possible and then use size to decide if writing 0
3391 		 * bytes is necessary in the loop below.
3392 		 */
3393 		if (error == 0)
3394 			error = vn_getsize_locked(outvp, &outsize, outcred);
3395 		if (error == 0 && outsize > *outoffp &&
3396 		    *outoffp <= OFF_MAX - len && outsize <= *outoffp + len &&
3397 		    *inoffp < insize &&
3398 		    *outoffp <= OFF_MAX - (insize - *inoffp) &&
3399 		    outsize <= *outoffp + (insize - *inoffp)) {
3400 #ifdef MAC
3401 			error = mac_vnode_check_write(curthread->td_ucred,
3402 			    outcred, outvp);
3403 			if (error == 0)
3404 #endif
3405 				error = vn_truncate_locked(outvp, *outoffp,
3406 				    false, outcred);
3407 			if (error == 0)
3408 				outsize = *outoffp;
3409 		}
3410 		VOP_UNLOCK(outvp);
3411 	}
3412 	if (mp != NULL)
3413 		vn_finished_write(mp);
3414 	if (error != 0)
3415 		goto out;
3416 
3417 	if (holein == 0 && holeout > 0) {
3418 		/*
3419 		 * For this special case, the input data will be scanned
3420 		 * for blocks of all 0 bytes.  For these blocks, the
3421 		 * write can be skipped for the output file to create
3422 		 * an unallocated region.
3423 		 * Therefore, use the appropriate size for the output file.
3424 		 */
3425 		blksize = holeout;
3426 		if (blksize <= 512) {
3427 			/*
3428 			 * Use f_iosize, since ZFS reports a _PC_MIN_HOLE_SIZE
3429 			 * of 512, although it actually only creates
3430 			 * unallocated regions for blocks >= f_iosize.
3431 			 */
3432 			blksize = outvp->v_mount->mnt_stat.f_iosize;
3433 		}
3434 	} else {
3435 		/*
3436 		 * Use the larger of the two f_iosize values.  If they are
3437 		 * not the same size, one will normally be an exact multiple of
3438 		 * the other, since they are both likely to be a power of 2.
3439 		 */
3440 		blksize = MAX(invp->v_mount->mnt_stat.f_iosize,
3441 		    outvp->v_mount->mnt_stat.f_iosize);
3442 	}
3443 
3444 	/* Clip to sane limits. */
3445 	if (blksize < 4096)
3446 		blksize = 4096;
3447 	else if (blksize > maxphys)
3448 		blksize = maxphys;
3449 	dat = malloc(blksize, M_TEMP, M_WAITOK);
3450 
3451 	/*
3452 	 * If VOP_IOCTL(FIOSEEKHOLE) works for invp, use it and FIOSEEKDATA
3453 	 * to find holes.  Otherwise, just scan the read block for all 0s
3454 	 * in the inner loop where the data copying is done.
3455 	 * Note that some file systems such as NFSv3, NFSv4.0 and NFSv4.1 may
3456 	 * support holes on the server, but do not support FIOSEEKHOLE.
3457 	 * The kernel flag COPY_FILE_RANGE_TIMEO1SEC is used to indicate
3458 	 * that this function should return after 1second with a partial
3459 	 * completion.
3460 	 */
3461 	if ((flags & COPY_FILE_RANGE_TIMEO1SEC) != 0) {
3462 		getnanouptime(&endts);
3463 		endts.tv_sec++;
3464 	} else
3465 		timespecclear(&endts);
3466 	holetoeof = eof = false;
3467 	while (len > 0 && error == 0 && !eof && interrupted == 0) {
3468 		endoff = 0;			/* To shut up compilers. */
3469 		cantseek = true;
3470 		startoff = *inoffp;
3471 		copylen = len;
3472 
3473 		/*
3474 		 * Find the next data area.  If there is just a hole to EOF,
3475 		 * FIOSEEKDATA should fail with ENXIO.
3476 		 * (I do not know if any file system will report a hole to
3477 		 *  EOF via FIOSEEKHOLE, but I am pretty sure FIOSEEKDATA
3478 		 *  will fail for those file systems.)
3479 		 *
3480 		 * For input files that don't support FIOSEEKDATA/FIOSEEKHOLE,
3481 		 * the code just falls through to the inner copy loop.
3482 		 */
3483 		error = EINVAL;
3484 		if (holein > 0) {
3485 			error = VOP_IOCTL(invp, FIOSEEKDATA, &startoff, 0,
3486 			    incred, curthread);
3487 			if (error == ENXIO) {
3488 				startoff = endoff = insize;
3489 				eof = holetoeof = true;
3490 				error = 0;
3491 			}
3492 		}
3493 		if (error == 0 && !holetoeof) {
3494 			endoff = startoff;
3495 			error = VOP_IOCTL(invp, FIOSEEKHOLE, &endoff, 0,
3496 			    incred, curthread);
3497 			/*
3498 			 * Since invp is unlocked, it may be possible for
3499 			 * another thread to do a truncate(), lseek(), write()
3500 			 * creating a hole at startoff between the above
3501 			 * VOP_IOCTL() calls, if the other thread does not do
3502 			 * rangelocking.
3503 			 * If that happens, startoff == endoff and finding
3504 			 * the hole has failed, so set an error.
3505 			 */
3506 			if (error == 0 && startoff == endoff)
3507 				error = EINVAL; /* Any error. Reset to 0. */
3508 		}
3509 		if (error == 0) {
3510 			if (startoff > *inoffp) {
3511 				/* Found hole before data block. */
3512 				xfer = MIN(startoff - *inoffp, len);
3513 				if (*outoffp < outsize) {
3514 					/* Must write 0s to punch hole. */
3515 					xfer2 = MIN(outsize - *outoffp,
3516 					    xfer);
3517 					memset(dat, 0, MIN(xfer2, blksize));
3518 					error = vn_write_outvp(outvp, dat,
3519 					    *outoffp, xfer2, blksize, false,
3520 					    holeout > 0, outcred);
3521 				}
3522 
3523 				if (error == 0 && *outoffp + xfer >
3524 				    outsize && (xfer == len || holetoeof)) {
3525 					/* Grow output file (hole at end). */
3526 					error = vn_write_outvp(outvp, dat,
3527 					    *outoffp, xfer, blksize, true,
3528 					    false, outcred);
3529 				}
3530 				if (error == 0) {
3531 					*inoffp += xfer;
3532 					*outoffp += xfer;
3533 					len -= xfer;
3534 					if (len < savlen) {
3535 						interrupted = sig_intr();
3536 						if (timespecisset(&endts) &&
3537 						    interrupted == 0) {
3538 							getnanouptime(&curts);
3539 							if (timespeccmp(&curts,
3540 							    &endts, >=))
3541 								interrupted =
3542 								    EINTR;
3543 						}
3544 					}
3545 				}
3546 			}
3547 			copylen = MIN(len, endoff - startoff);
3548 			cantseek = false;
3549 		} else {
3550 			cantseek = true;
3551 			startoff = *inoffp;
3552 			copylen = len;
3553 			error = 0;
3554 		}
3555 
3556 		xfer = blksize;
3557 		if (cantseek) {
3558 			/*
3559 			 * Set first xfer to end at a block boundary, so that
3560 			 * holes are more likely detected in the loop below via
3561 			 * the for all bytes 0 method.
3562 			 */
3563 			xfer -= (*inoffp % blksize);
3564 		}
3565 		/* Loop copying the data block. */
3566 		while (copylen > 0 && error == 0 && !eof && interrupted == 0) {
3567 			if (copylen < xfer)
3568 				xfer = copylen;
3569 			error = vn_lock(invp, LK_SHARED);
3570 			if (error != 0)
3571 				goto out;
3572 			error = vn_rdwr(UIO_READ, invp, dat, xfer,
3573 			    startoff, UIO_SYSSPACE, IO_NODELOCKED,
3574 			    curthread->td_ucred, incred, &aresid,
3575 			    curthread);
3576 			VOP_UNLOCK(invp);
3577 			lastblock = false;
3578 			if (error == 0 && aresid > 0) {
3579 				/* Stop the copy at EOF on the input file. */
3580 				xfer -= aresid;
3581 				eof = true;
3582 				lastblock = true;
3583 			}
3584 			if (error == 0) {
3585 				/*
3586 				 * Skip the write for holes past the initial EOF
3587 				 * of the output file, unless this is the last
3588 				 * write of the output file at EOF.
3589 				 */
3590 				readzeros = cantseek ? mem_iszero(dat, xfer) :
3591 				    false;
3592 				if (xfer == len)
3593 					lastblock = true;
3594 				if (!cantseek || *outoffp < outsize ||
3595 				    lastblock || !readzeros)
3596 					error = vn_write_outvp(outvp, dat,
3597 					    *outoffp, xfer, blksize,
3598 					    readzeros && lastblock &&
3599 					    *outoffp >= outsize, false,
3600 					    outcred);
3601 				if (error == 0) {
3602 					*inoffp += xfer;
3603 					startoff += xfer;
3604 					*outoffp += xfer;
3605 					copylen -= xfer;
3606 					len -= xfer;
3607 					if (len < savlen) {
3608 						interrupted = sig_intr();
3609 						if (timespecisset(&endts) &&
3610 						    interrupted == 0) {
3611 							getnanouptime(&curts);
3612 							if (timespeccmp(&curts,
3613 							    &endts, >=))
3614 								interrupted =
3615 								    EINTR;
3616 						}
3617 					}
3618 				}
3619 			}
3620 			xfer = blksize;
3621 		}
3622 	}
3623 out:
3624 	*lenp = savlen - len;
3625 	free(dat, M_TEMP);
3626 	return (error);
3627 }
3628 
3629 static int
3630 vn_fallocate(struct file *fp, off_t offset, off_t len, struct thread *td)
3631 {
3632 	struct mount *mp;
3633 	struct vnode *vp;
3634 	off_t olen, ooffset;
3635 	int error;
3636 #ifdef AUDIT
3637 	int audited_vnode1 = 0;
3638 #endif
3639 
3640 	vp = fp->f_vnode;
3641 	if (vp->v_type != VREG)
3642 		return (ENODEV);
3643 
3644 	/* Allocating blocks may take a long time, so iterate. */
3645 	for (;;) {
3646 		olen = len;
3647 		ooffset = offset;
3648 
3649 		bwillwrite();
3650 		mp = NULL;
3651 		error = vn_start_write(vp, &mp, V_WAIT | V_PCATCH);
3652 		if (error != 0)
3653 			break;
3654 		error = vn_lock(vp, LK_EXCLUSIVE);
3655 		if (error != 0) {
3656 			vn_finished_write(mp);
3657 			break;
3658 		}
3659 #ifdef AUDIT
3660 		if (!audited_vnode1) {
3661 			AUDIT_ARG_VNODE1(vp);
3662 			audited_vnode1 = 1;
3663 		}
3664 #endif
3665 #ifdef MAC
3666 		error = mac_vnode_check_write(td->td_ucred, fp->f_cred, vp);
3667 		if (error == 0)
3668 #endif
3669 			error = VOP_ALLOCATE(vp, &offset, &len, 0,
3670 			    td->td_ucred);
3671 		VOP_UNLOCK(vp);
3672 		vn_finished_write(mp);
3673 
3674 		if (olen + ooffset != offset + len) {
3675 			panic("offset + len changed from %jx/%jx to %jx/%jx",
3676 			    ooffset, olen, offset, len);
3677 		}
3678 		if (error != 0 || len == 0)
3679 			break;
3680 		KASSERT(olen > len, ("Iteration did not make progress?"));
3681 		maybe_yield();
3682 	}
3683 
3684 	return (error);
3685 }
3686 
3687 static int
3688 vn_deallocate_impl(struct vnode *vp, off_t *offset, off_t *length, int flags,
3689     int ioflag, struct ucred *cred, struct ucred *active_cred,
3690     struct ucred *file_cred)
3691 {
3692 	struct mount *mp;
3693 	void *rl_cookie;
3694 	off_t off, len;
3695 	int error;
3696 #ifdef AUDIT
3697 	bool audited_vnode1 = false;
3698 #endif
3699 
3700 	rl_cookie = NULL;
3701 	error = 0;
3702 	mp = NULL;
3703 	off = *offset;
3704 	len = *length;
3705 
3706 	if ((ioflag & (IO_NODELOCKED | IO_RANGELOCKED)) == 0)
3707 		rl_cookie = vn_rangelock_wlock(vp, off, off + len);
3708 	while (len > 0 && error == 0) {
3709 		/*
3710 		 * Try to deallocate the longest range in one pass.
3711 		 * In case a pass takes too long to be executed, it returns
3712 		 * partial result. The residue will be proceeded in the next
3713 		 * pass.
3714 		 */
3715 
3716 		if ((ioflag & IO_NODELOCKED) == 0) {
3717 			bwillwrite();
3718 			if ((error = vn_start_write(vp, &mp,
3719 			    V_WAIT | V_PCATCH)) != 0)
3720 				goto out;
3721 			vn_lock(vp, vn_lktype_write(mp, vp) | LK_RETRY);
3722 		}
3723 #ifdef AUDIT
3724 		if (!audited_vnode1) {
3725 			AUDIT_ARG_VNODE1(vp);
3726 			audited_vnode1 = true;
3727 		}
3728 #endif
3729 
3730 #ifdef MAC
3731 		if ((ioflag & IO_NOMACCHECK) == 0)
3732 			error = mac_vnode_check_write(active_cred, file_cred,
3733 			    vp);
3734 #endif
3735 		if (error == 0)
3736 			error = VOP_DEALLOCATE(vp, &off, &len, flags, ioflag,
3737 			    cred);
3738 
3739 		if ((ioflag & IO_NODELOCKED) == 0) {
3740 			VOP_UNLOCK(vp);
3741 			if (mp != NULL) {
3742 				vn_finished_write(mp);
3743 				mp = NULL;
3744 			}
3745 		}
3746 		if (error == 0 && len != 0)
3747 			maybe_yield();
3748 	}
3749 out:
3750 	if (rl_cookie != NULL)
3751 		vn_rangelock_unlock(vp, rl_cookie);
3752 	*offset = off;
3753 	*length = len;
3754 	return (error);
3755 }
3756 
3757 /*
3758  * This function is supposed to be used in the situations where the deallocation
3759  * is not triggered by a user request.
3760  */
3761 int
3762 vn_deallocate(struct vnode *vp, off_t *offset, off_t *length, int flags,
3763     int ioflag, struct ucred *active_cred, struct ucred *file_cred)
3764 {
3765 	struct ucred *cred;
3766 
3767 	if (*offset < 0 || *length <= 0 || *length > OFF_MAX - *offset ||
3768 	    flags != 0)
3769 		return (EINVAL);
3770 	if (vp->v_type != VREG)
3771 		return (ENODEV);
3772 
3773 	cred = file_cred != NOCRED ? file_cred : active_cred;
3774 	return (vn_deallocate_impl(vp, offset, length, flags, ioflag, cred,
3775 	    active_cred, file_cred));
3776 }
3777 
3778 static int
3779 vn_fspacectl(struct file *fp, int cmd, off_t *offset, off_t *length, int flags,
3780     struct ucred *active_cred, struct thread *td)
3781 {
3782 	int error;
3783 	struct vnode *vp;
3784 	int ioflag;
3785 
3786 	KASSERT(cmd == SPACECTL_DEALLOC, ("vn_fspacectl: Invalid cmd"));
3787 	KASSERT((flags & ~SPACECTL_F_SUPPORTED) == 0,
3788 	    ("vn_fspacectl: non-zero flags"));
3789 	KASSERT(*offset >= 0 && *length > 0 && *length <= OFF_MAX - *offset,
3790 	    ("vn_fspacectl: offset/length overflow or underflow"));
3791 	vp = fp->f_vnode;
3792 
3793 	if (vp->v_type != VREG)
3794 		return (ENODEV);
3795 
3796 	ioflag = get_write_ioflag(fp);
3797 
3798 	switch (cmd) {
3799 	case SPACECTL_DEALLOC:
3800 		error = vn_deallocate_impl(vp, offset, length, flags, ioflag,
3801 		    active_cred, active_cred, fp->f_cred);
3802 		break;
3803 	default:
3804 		panic("vn_fspacectl: unknown cmd %d", cmd);
3805 	}
3806 
3807 	return (error);
3808 }
3809 
3810 /*
3811  * Keep this assert as long as sizeof(struct dirent) is used as the maximum
3812  * entry size.
3813  */
3814 _Static_assert(_GENERIC_MAXDIRSIZ == sizeof(struct dirent),
3815     "'struct dirent' size must be a multiple of its alignment "
3816     "(see _GENERIC_DIRLEN())");
3817 
3818 /*
3819  * Returns successive directory entries through some caller's provided buffer.
3820  *
3821  * This function automatically refills the provided buffer with calls to
3822  * VOP_READDIR() (after MAC permission checks).
3823  *
3824  * 'td' is used for credentials and passed to uiomove().  'dirbuf' is the
3825  * caller's buffer to fill and 'dirbuflen' its allocated size.  'dirbuf' must
3826  * be properly aligned to access 'struct dirent' structures and 'dirbuflen'
3827  * must be greater than GENERIC_MAXDIRSIZ to avoid VOP_READDIR() returning
3828  * EINVAL (the latter is not a strong guarantee (yet); but EINVAL will always
3829  * be returned if this requirement is not verified).  '*dpp' points to the
3830  * current directory entry in the buffer and '*len' contains the remaining
3831  * valid bytes in 'dirbuf' after 'dpp' (including the pointed entry).
3832  *
3833  * At first call (or when restarting the read), '*len' must have been set to 0,
3834  * '*off' to 0 (or any valid start offset) and '*eofflag' to 0.  There are no
3835  * more entries as soon as '*len' is 0 after a call that returned 0.  Calling
3836  * again this function after such a condition is considered an error and EINVAL
3837  * will be returned.  Other possible error codes are those of VOP_READDIR(),
3838  * EINTEGRITY if the returned entries do not pass coherency tests, or EINVAL
3839  * (bad call).  All errors are unrecoverable, i.e., the state ('*len', '*off'
3840  * and '*eofflag') must be re-initialized before a subsequent call.  On error
3841  * or at end of directory, '*dpp' is reset to NULL.
3842  *
3843  * '*len', '*off' and '*eofflag' are internal state the caller should not
3844  * tamper with except as explained above.  '*off' is the next directory offset
3845  * to read from to refill the buffer.  '*eofflag' is set to 0 or 1 by the last
3846  * internal call to VOP_READDIR() that returned without error, indicating
3847  * whether it reached the end of the directory, and to 2 by this function after
3848  * all entries have been read.
3849  */
3850 int
3851 vn_dir_next_dirent(struct vnode *vp, struct thread *td,
3852     char *dirbuf, size_t dirbuflen,
3853     struct dirent **dpp, size_t *len, off_t *off, int *eofflag)
3854 {
3855 	struct dirent *dp = NULL;
3856 	int reclen;
3857 	int error;
3858 	struct uio uio;
3859 	struct iovec iov;
3860 
3861 	ASSERT_VOP_LOCKED(vp, "vnode not locked");
3862 	VNASSERT(vp->v_type == VDIR, vp, ("vnode is not a directory"));
3863 	MPASS2((uintptr_t)dirbuf < (uintptr_t)dirbuf + dirbuflen,
3864 	    "Address space overflow");
3865 
3866 	if (__predict_false(dirbuflen < GENERIC_MAXDIRSIZ)) {
3867 		/* Don't take any chances in this case */
3868 		error = EINVAL;
3869 		goto out;
3870 	}
3871 
3872 	if (*len != 0) {
3873 		dp = *dpp;
3874 
3875 		/*
3876 		 * The caller continued to call us after an error (we set dp to
3877 		 * NULL in a previous iteration).  Bail out right now.
3878 		 */
3879 		if (__predict_false(dp == NULL))
3880 			return (EINVAL);
3881 
3882 		MPASS(*len <= dirbuflen);
3883 		MPASS2((uintptr_t)dirbuf <= (uintptr_t)dp &&
3884 		    (uintptr_t)dp + *len <= (uintptr_t)dirbuf + dirbuflen,
3885 		    "Filled range not inside buffer");
3886 
3887 		reclen = dp->d_reclen;
3888 		if (reclen >= *len) {
3889 			/* End of buffer reached */
3890 			*len = 0;
3891 		} else {
3892 			dp = (struct dirent *)((char *)dp + reclen);
3893 			*len -= reclen;
3894 		}
3895 	}
3896 
3897 	if (*len == 0) {
3898 		dp = NULL;
3899 
3900 		/* Have to refill. */
3901 		switch (*eofflag) {
3902 		case 0:
3903 			break;
3904 
3905 		case 1:
3906 			/* Nothing more to read. */
3907 			*eofflag = 2; /* Remember the caller reached EOF. */
3908 			goto success;
3909 
3910 		default:
3911 			/* The caller didn't test for EOF. */
3912 			error = EINVAL;
3913 			goto out;
3914 		}
3915 
3916 		iov.iov_base = dirbuf;
3917 		iov.iov_len = dirbuflen;
3918 
3919 		uio.uio_iov = &iov;
3920 		uio.uio_iovcnt = 1;
3921 		uio.uio_offset = *off;
3922 		uio.uio_resid = dirbuflen;
3923 		uio.uio_segflg = UIO_SYSSPACE;
3924 		uio.uio_rw = UIO_READ;
3925 		uio.uio_td = td;
3926 
3927 #ifdef MAC
3928 		error = mac_vnode_check_readdir(td->td_ucred, vp);
3929 		if (error == 0)
3930 #endif
3931 			error = VOP_READDIR(vp, &uio, td->td_ucred, eofflag,
3932 			    NULL, NULL);
3933 		if (error != 0)
3934 			goto out;
3935 
3936 		*len = dirbuflen - uio.uio_resid;
3937 		*off = uio.uio_offset;
3938 
3939 		if (*len == 0) {
3940 			/* Sanity check on INVARIANTS. */
3941 			MPASS(*eofflag != 0);
3942 			*eofflag = 1;
3943 			goto success;
3944 		}
3945 
3946 		/*
3947 		 * Normalize the flag returned by VOP_READDIR(), since we use 2
3948 		 * as a sentinel value.
3949 		 */
3950 		if (*eofflag != 0)
3951 			*eofflag = 1;
3952 
3953 		dp = (struct dirent *)dirbuf;
3954 	}
3955 
3956 	if (__predict_false(*len < GENERIC_MINDIRSIZ ||
3957 	    dp->d_reclen < GENERIC_MINDIRSIZ)) {
3958 		error = EINTEGRITY;
3959 		dp = NULL;
3960 		goto out;
3961 	}
3962 
3963 success:
3964 	error = 0;
3965 out:
3966 	*dpp = dp;
3967 	return (error);
3968 }
3969 
3970 /*
3971  * Checks whether a directory is empty or not.
3972  *
3973  * If the directory is empty, returns 0, and if it is not, ENOTEMPTY.  Other
3974  * values are genuine errors preventing the check.
3975  */
3976 int
3977 vn_dir_check_empty(struct vnode *vp)
3978 {
3979 	struct thread *const td = curthread;
3980 	char *dirbuf;
3981 	size_t dirbuflen, len;
3982 	off_t off;
3983 	int eofflag, error;
3984 	struct dirent *dp;
3985 	struct vattr va;
3986 
3987 	ASSERT_VOP_LOCKED(vp, "vfs_emptydir");
3988 	VNPASS(vp->v_type == VDIR, vp);
3989 
3990 	error = VOP_GETATTR(vp, &va, td->td_ucred);
3991 	if (error != 0)
3992 		return (error);
3993 
3994 	dirbuflen = max(DEV_BSIZE, GENERIC_MAXDIRSIZ);
3995 	if (dirbuflen < va.va_blocksize)
3996 		dirbuflen = va.va_blocksize;
3997 	dirbuf = malloc(dirbuflen, M_TEMP, M_WAITOK);
3998 
3999 	len = 0;
4000 	off = 0;
4001 	eofflag = 0;
4002 
4003 	for (;;) {
4004 		error = vn_dir_next_dirent(vp, td, dirbuf, dirbuflen,
4005 		    &dp, &len, &off, &eofflag);
4006 		if (error != 0)
4007 			goto end;
4008 
4009 		if (len == 0) {
4010 			/* EOF */
4011 			error = 0;
4012 			goto end;
4013 		}
4014 
4015 		/*
4016 		 * Skip whiteouts.  Unionfs operates on filesystems only and
4017 		 * not on hierarchies, so these whiteouts would be shadowed on
4018 		 * the system hierarchy but not for a union using the
4019 		 * filesystem of their directories as the upper layer.
4020 		 * Additionally, unionfs currently transparently exposes
4021 		 * union-specific metadata of its upper layer, meaning that
4022 		 * whiteouts can be seen through the union view in empty
4023 		 * directories.  Taking into account these whiteouts would then
4024 		 * prevent mounting another filesystem on such effectively
4025 		 * empty directories.
4026 		 */
4027 		if (dp->d_type == DT_WHT)
4028 			continue;
4029 
4030 		/*
4031 		 * Any file in the directory which is not '.' or '..' indicates
4032 		 * the directory is not empty.
4033 		 */
4034 		switch (dp->d_namlen) {
4035 		case 2:
4036 			if (dp->d_name[1] != '.') {
4037 				/* Can't be '..' (nor '.') */
4038 				error = ENOTEMPTY;
4039 				goto end;
4040 			}
4041 			/* FALLTHROUGH */
4042 		case 1:
4043 			if (dp->d_name[0] != '.') {
4044 				/* Can't be '..' nor '.' */
4045 				error = ENOTEMPTY;
4046 				goto end;
4047 			}
4048 			break;
4049 
4050 		default:
4051 			error = ENOTEMPTY;
4052 			goto end;
4053 		}
4054 	}
4055 
4056 end:
4057 	free(dirbuf, M_TEMP);
4058 	return (error);
4059 }
4060 
4061 
4062 static u_long vn_lock_pair_pause_cnt;
4063 SYSCTL_ULONG(_debug, OID_AUTO, vn_lock_pair_pause, CTLFLAG_RD,
4064     &vn_lock_pair_pause_cnt, 0,
4065     "Count of vn_lock_pair deadlocks");
4066 
4067 u_int vn_lock_pair_pause_max;
4068 SYSCTL_UINT(_debug, OID_AUTO, vn_lock_pair_pause_max, CTLFLAG_RW,
4069     &vn_lock_pair_pause_max, 0,
4070     "Max ticks for vn_lock_pair deadlock avoidance sleep");
4071 
4072 static void
4073 vn_lock_pair_pause(const char *wmesg)
4074 {
4075 	atomic_add_long(&vn_lock_pair_pause_cnt, 1);
4076 	pause(wmesg, prng32_bounded(vn_lock_pair_pause_max));
4077 }
4078 
4079 /*
4080  * Lock pair of (possibly same) vnodes vp1, vp2, avoiding lock order
4081  * reversal.  vp1_locked indicates whether vp1 is locked; if not, vp1
4082  * must be unlocked.  Same for vp2 and vp2_locked.  One of the vnodes
4083  * can be NULL.
4084  *
4085  * The function returns with both vnodes exclusively or shared locked,
4086  * according to corresponding lkflags, and guarantees that it does not
4087  * create lock order reversal with other threads during its execution.
4088  * Both vnodes could be unlocked temporary (and reclaimed).
4089  *
4090  * If requesting shared locking, locked vnode lock must not be recursed.
4091  *
4092  * Only one of LK_SHARED and LK_EXCLUSIVE must be specified.
4093  * LK_NODDLKTREAT can be optionally passed.
4094  *
4095  * If vp1 == vp2, only one, most exclusive, lock is obtained on it.
4096  */
4097 void
4098 vn_lock_pair(struct vnode *vp1, bool vp1_locked, int lkflags1,
4099     struct vnode *vp2, bool vp2_locked, int lkflags2)
4100 {
4101 	int error, locked1;
4102 
4103 	MPASS(((lkflags1 & LK_SHARED) != 0) ^ ((lkflags1 & LK_EXCLUSIVE) != 0));
4104 	MPASS((lkflags1 & ~(LK_SHARED | LK_EXCLUSIVE | LK_NODDLKTREAT)) == 0);
4105 	MPASS(((lkflags2 & LK_SHARED) != 0) ^ ((lkflags2 & LK_EXCLUSIVE) != 0));
4106 	MPASS((lkflags2 & ~(LK_SHARED | LK_EXCLUSIVE | LK_NODDLKTREAT)) == 0);
4107 
4108 	if (vp1 == NULL && vp2 == NULL)
4109 		return;
4110 
4111 	if (vp1 == vp2) {
4112 		MPASS(vp1_locked == vp2_locked);
4113 
4114 		/* Select the most exclusive mode for lock. */
4115 		if ((lkflags1 & LK_TYPE_MASK) != (lkflags2 & LK_TYPE_MASK))
4116 			lkflags1 = (lkflags1 & ~LK_SHARED) | LK_EXCLUSIVE;
4117 
4118 		if (vp1_locked) {
4119 			ASSERT_VOP_LOCKED(vp1, "vp1");
4120 
4121 			/* No need to relock if any lock is exclusive. */
4122 			if ((vp1->v_vnlock->lock_object.lo_flags &
4123 			    LK_NOSHARE) != 0)
4124 				return;
4125 
4126 			locked1 = VOP_ISLOCKED(vp1);
4127 			if (((lkflags1 & LK_SHARED) != 0 &&
4128 			    locked1 != LK_EXCLUSIVE) ||
4129 			    ((lkflags1 & LK_EXCLUSIVE) != 0 &&
4130 			    locked1 == LK_EXCLUSIVE))
4131 				return;
4132 			VOP_UNLOCK(vp1);
4133 		}
4134 
4135 		ASSERT_VOP_UNLOCKED(vp1, "vp1");
4136 		vn_lock(vp1, lkflags1 | LK_RETRY);
4137 		return;
4138 	}
4139 
4140 	if (vp1 != NULL) {
4141 		if ((lkflags1 & LK_SHARED) != 0 &&
4142 		    (vp1->v_vnlock->lock_object.lo_flags & LK_NOSHARE) != 0)
4143 			lkflags1 = (lkflags1 & ~LK_SHARED) | LK_EXCLUSIVE;
4144 		if (vp1_locked && VOP_ISLOCKED(vp1) != LK_EXCLUSIVE) {
4145 			ASSERT_VOP_LOCKED(vp1, "vp1");
4146 			if ((lkflags1 & LK_EXCLUSIVE) != 0) {
4147 				VOP_UNLOCK(vp1);
4148 				ASSERT_VOP_UNLOCKED(vp1,
4149 				    "vp1 shared recursed");
4150 				vp1_locked = false;
4151 			}
4152 		} else if (!vp1_locked)
4153 			ASSERT_VOP_UNLOCKED(vp1, "vp1");
4154 	} else {
4155 		vp1_locked = true;
4156 	}
4157 
4158 	if (vp2 != NULL) {
4159 		if ((lkflags2 & LK_SHARED) != 0 &&
4160 		    (vp2->v_vnlock->lock_object.lo_flags & LK_NOSHARE) != 0)
4161 			lkflags2 = (lkflags2 & ~LK_SHARED) | LK_EXCLUSIVE;
4162 		if (vp2_locked && VOP_ISLOCKED(vp2) != LK_EXCLUSIVE) {
4163 			ASSERT_VOP_LOCKED(vp2, "vp2");
4164 			if ((lkflags2 & LK_EXCLUSIVE) != 0) {
4165 				VOP_UNLOCK(vp2);
4166 				ASSERT_VOP_UNLOCKED(vp2,
4167 				    "vp2 shared recursed");
4168 				vp2_locked = false;
4169 			}
4170 		} else if (!vp2_locked)
4171 			ASSERT_VOP_UNLOCKED(vp2, "vp2");
4172 	} else {
4173 		vp2_locked = true;
4174 	}
4175 
4176 	if (!vp1_locked && !vp2_locked) {
4177 		vn_lock(vp1, lkflags1 | LK_RETRY);
4178 		vp1_locked = true;
4179 	}
4180 
4181 	while (!vp1_locked || !vp2_locked) {
4182 		if (vp1_locked && vp2 != NULL) {
4183 			if (vp1 != NULL) {
4184 				error = VOP_LOCK1(vp2, lkflags2 | LK_NOWAIT,
4185 				    __FILE__, __LINE__);
4186 				if (error == 0)
4187 					break;
4188 				VOP_UNLOCK(vp1);
4189 				vp1_locked = false;
4190 				vn_lock_pair_pause("vlp1");
4191 			}
4192 			vn_lock(vp2, lkflags2 | LK_RETRY);
4193 			vp2_locked = true;
4194 		}
4195 		if (vp2_locked && vp1 != NULL) {
4196 			if (vp2 != NULL) {
4197 				error = VOP_LOCK1(vp1, lkflags1 | LK_NOWAIT,
4198 				    __FILE__, __LINE__);
4199 				if (error == 0)
4200 					break;
4201 				VOP_UNLOCK(vp2);
4202 				vp2_locked = false;
4203 				vn_lock_pair_pause("vlp2");
4204 			}
4205 			vn_lock(vp1, lkflags1 | LK_RETRY);
4206 			vp1_locked = true;
4207 		}
4208 	}
4209 	if (vp1 != NULL) {
4210 		if (lkflags1 == LK_EXCLUSIVE)
4211 			ASSERT_VOP_ELOCKED(vp1, "vp1 ret");
4212 		else
4213 			ASSERT_VOP_LOCKED(vp1, "vp1 ret");
4214 	}
4215 	if (vp2 != NULL) {
4216 		if (lkflags2 == LK_EXCLUSIVE)
4217 			ASSERT_VOP_ELOCKED(vp2, "vp2 ret");
4218 		else
4219 			ASSERT_VOP_LOCKED(vp2, "vp2 ret");
4220 	}
4221 }
4222 
4223 int
4224 vn_lktype_write(struct mount *mp, struct vnode *vp)
4225 {
4226 	if (MNT_SHARED_WRITES(mp) ||
4227 	    (mp == NULL && MNT_SHARED_WRITES(vp->v_mount)))
4228 		return (LK_SHARED);
4229 	return (LK_EXCLUSIVE);
4230 }
4231