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