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