xref: /freebsd/sys/kern/vfs_vnops.c (revision cddbc3b40812213ff00041f79174cac0be360a2a)
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/stat.h>
58 #include <sys/priv.h>
59 #include <sys/proc.h>
60 #include <sys/limits.h>
61 #include <sys/lock.h>
62 #include <sys/mman.h>
63 #include <sys/mount.h>
64 #include <sys/mutex.h>
65 #include <sys/namei.h>
66 #include <sys/vnode.h>
67 #include <sys/bio.h>
68 #include <sys/buf.h>
69 #include <sys/filio.h>
70 #include <sys/resourcevar.h>
71 #include <sys/rwlock.h>
72 #include <sys/sx.h>
73 #include <sys/sysctl.h>
74 #include <sys/ttycom.h>
75 #include <sys/conf.h>
76 #include <sys/syslog.h>
77 #include <sys/unistd.h>
78 #include <sys/user.h>
79 
80 #include <security/audit/audit.h>
81 #include <security/mac/mac_framework.h>
82 
83 #include <vm/vm.h>
84 #include <vm/vm_extern.h>
85 #include <vm/pmap.h>
86 #include <vm/vm_map.h>
87 #include <vm/vm_object.h>
88 #include <vm/vm_page.h>
89 #include <vm/vnode_pager.h>
90 
91 #ifdef HWPMC_HOOKS
92 #include <sys/pmckern.h>
93 #endif
94 
95 static fo_rdwr_t	vn_read;
96 static fo_rdwr_t	vn_write;
97 static fo_rdwr_t	vn_io_fault;
98 static fo_truncate_t	vn_truncate;
99 static fo_ioctl_t	vn_ioctl;
100 static fo_poll_t	vn_poll;
101 static fo_kqfilter_t	vn_kqfilter;
102 static fo_stat_t	vn_statfile;
103 static fo_close_t	vn_closefile;
104 static fo_mmap_t	vn_mmap;
105 
106 struct 	fileops vnops = {
107 	.fo_read = vn_io_fault,
108 	.fo_write = vn_io_fault,
109 	.fo_truncate = vn_truncate,
110 	.fo_ioctl = vn_ioctl,
111 	.fo_poll = vn_poll,
112 	.fo_kqfilter = vn_kqfilter,
113 	.fo_stat = vn_statfile,
114 	.fo_close = vn_closefile,
115 	.fo_chmod = vn_chmod,
116 	.fo_chown = vn_chown,
117 	.fo_sendfile = vn_sendfile,
118 	.fo_seek = vn_seek,
119 	.fo_fill_kinfo = vn_fill_kinfo,
120 	.fo_mmap = vn_mmap,
121 	.fo_flags = DFLAG_PASSABLE | DFLAG_SEEKABLE
122 };
123 
124 static const int io_hold_cnt = 16;
125 static int vn_io_fault_enable = 1;
126 SYSCTL_INT(_debug, OID_AUTO, vn_io_fault_enable, CTLFLAG_RW,
127     &vn_io_fault_enable, 0, "Enable vn_io_fault lock avoidance");
128 static int vn_io_fault_prefault = 0;
129 SYSCTL_INT(_debug, OID_AUTO, vn_io_fault_prefault, CTLFLAG_RW,
130     &vn_io_fault_prefault, 0, "Enable vn_io_fault prefaulting");
131 static u_long vn_io_faults_cnt;
132 SYSCTL_ULONG(_debug, OID_AUTO, vn_io_faults, CTLFLAG_RD,
133     &vn_io_faults_cnt, 0, "Count of vn_io_fault lock avoidance triggers");
134 
135 /*
136  * Returns true if vn_io_fault mode of handling the i/o request should
137  * be used.
138  */
139 static bool
140 do_vn_io_fault(struct vnode *vp, struct uio *uio)
141 {
142 	struct mount *mp;
143 
144 	return (uio->uio_segflg == UIO_USERSPACE && vp->v_type == VREG &&
145 	    (mp = vp->v_mount) != NULL &&
146 	    (mp->mnt_kern_flag & MNTK_NO_IOPF) != 0 && vn_io_fault_enable);
147 }
148 
149 /*
150  * Structure used to pass arguments to vn_io_fault1(), to do either
151  * file- or vnode-based I/O calls.
152  */
153 struct vn_io_fault_args {
154 	enum {
155 		VN_IO_FAULT_FOP,
156 		VN_IO_FAULT_VOP
157 	} kind;
158 	struct ucred *cred;
159 	int flags;
160 	union {
161 		struct fop_args_tag {
162 			struct file *fp;
163 			fo_rdwr_t *doio;
164 		} fop_args;
165 		struct vop_args_tag {
166 			struct vnode *vp;
167 		} vop_args;
168 	} args;
169 };
170 
171 static int vn_io_fault1(struct vnode *vp, struct uio *uio,
172     struct vn_io_fault_args *args, struct thread *td);
173 
174 int
175 vn_open(struct nameidata *ndp, int *flagp, int cmode, struct file *fp)
176 {
177 	struct thread *td = ndp->ni_cnd.cn_thread;
178 
179 	return (vn_open_cred(ndp, flagp, cmode, 0, td->td_ucred, fp));
180 }
181 
182 /*
183  * Common code for vnode open operations via a name lookup.
184  * Lookup the vnode and invoke VOP_CREATE if needed.
185  * Check permissions, and call the VOP_OPEN or VOP_CREATE routine.
186  *
187  * Note that this does NOT free nameidata for the successful case,
188  * due to the NDINIT being done elsewhere.
189  */
190 int
191 vn_open_cred(struct nameidata *ndp, int *flagp, int cmode, u_int vn_open_flags,
192     struct ucred *cred, struct file *fp)
193 {
194 	struct vnode *vp;
195 	struct mount *mp;
196 	struct thread *td = ndp->ni_cnd.cn_thread;
197 	struct vattr vat;
198 	struct vattr *vap = &vat;
199 	int fmode, error;
200 
201 restart:
202 	fmode = *flagp;
203 	if ((fmode & (O_CREAT | O_EXCL | O_DIRECTORY)) == (O_CREAT |
204 	    O_EXCL | O_DIRECTORY))
205 		return (EINVAL);
206 	else if ((fmode & (O_CREAT | O_DIRECTORY)) == O_CREAT) {
207 		ndp->ni_cnd.cn_nameiop = CREATE;
208 		/*
209 		 * Set NOCACHE to avoid flushing the cache when
210 		 * rolling in many files at once.
211 		*/
212 		ndp->ni_cnd.cn_flags = ISOPEN | LOCKPARENT | LOCKLEAF | NOCACHE;
213 		if ((fmode & O_EXCL) == 0 && (fmode & O_NOFOLLOW) == 0)
214 			ndp->ni_cnd.cn_flags |= FOLLOW;
215 		if ((fmode & O_BENEATH) != 0)
216 			ndp->ni_cnd.cn_flags |= BENEATH;
217 		if (!(vn_open_flags & VN_OPEN_NOAUDIT))
218 			ndp->ni_cnd.cn_flags |= AUDITVNODE1;
219 		if (vn_open_flags & VN_OPEN_NOCAPCHECK)
220 			ndp->ni_cnd.cn_flags |= NOCAPCHECK;
221 		bwillwrite();
222 		if ((error = namei(ndp)) != 0)
223 			return (error);
224 		if (ndp->ni_vp == NULL) {
225 			VATTR_NULL(vap);
226 			vap->va_type = VREG;
227 			vap->va_mode = cmode;
228 			if (fmode & O_EXCL)
229 				vap->va_vaflags |= VA_EXCLUSIVE;
230 			if (vn_start_write(ndp->ni_dvp, &mp, V_NOWAIT) != 0) {
231 				NDFREE(ndp, NDF_ONLY_PNBUF);
232 				vput(ndp->ni_dvp);
233 				if ((error = vn_start_write(NULL, &mp,
234 				    V_XSLEEP | PCATCH)) != 0)
235 					return (error);
236 				goto restart;
237 			}
238 			if ((vn_open_flags & VN_OPEN_NAMECACHE) != 0)
239 				ndp->ni_cnd.cn_flags |= MAKEENTRY;
240 #ifdef MAC
241 			error = mac_vnode_check_create(cred, ndp->ni_dvp,
242 			    &ndp->ni_cnd, vap);
243 			if (error == 0)
244 #endif
245 				error = VOP_CREATE(ndp->ni_dvp, &ndp->ni_vp,
246 						   &ndp->ni_cnd, vap);
247 			vput(ndp->ni_dvp);
248 			vn_finished_write(mp);
249 			if (error) {
250 				NDFREE(ndp, NDF_ONLY_PNBUF);
251 				return (error);
252 			}
253 			fmode &= ~O_TRUNC;
254 			vp = ndp->ni_vp;
255 		} else {
256 			if (ndp->ni_dvp == ndp->ni_vp)
257 				vrele(ndp->ni_dvp);
258 			else
259 				vput(ndp->ni_dvp);
260 			ndp->ni_dvp = NULL;
261 			vp = ndp->ni_vp;
262 			if (fmode & O_EXCL) {
263 				error = EEXIST;
264 				goto bad;
265 			}
266 			fmode &= ~O_CREAT;
267 		}
268 	} else {
269 		ndp->ni_cnd.cn_nameiop = LOOKUP;
270 		ndp->ni_cnd.cn_flags = ISOPEN |
271 		    ((fmode & O_NOFOLLOW) ? NOFOLLOW : FOLLOW) | LOCKLEAF;
272 		if (!(fmode & FWRITE))
273 			ndp->ni_cnd.cn_flags |= LOCKSHARED;
274 		if ((fmode & O_BENEATH) != 0)
275 			ndp->ni_cnd.cn_flags |= BENEATH;
276 		if (!(vn_open_flags & VN_OPEN_NOAUDIT))
277 			ndp->ni_cnd.cn_flags |= AUDITVNODE1;
278 		if (vn_open_flags & VN_OPEN_NOCAPCHECK)
279 			ndp->ni_cnd.cn_flags |= NOCAPCHECK;
280 		if ((error = namei(ndp)) != 0)
281 			return (error);
282 		vp = ndp->ni_vp;
283 	}
284 	error = vn_open_vnode(vp, fmode, cred, td, fp);
285 	if (error)
286 		goto bad;
287 	*flagp = fmode;
288 	return (0);
289 bad:
290 	NDFREE(ndp, NDF_ONLY_PNBUF);
291 	vput(vp);
292 	*flagp = fmode;
293 	ndp->ni_vp = NULL;
294 	return (error);
295 }
296 
297 /*
298  * Common code for vnode open operations once a vnode is located.
299  * Check permissions, and call the VOP_OPEN routine.
300  */
301 int
302 vn_open_vnode(struct vnode *vp, int fmode, struct ucred *cred,
303     struct thread *td, struct file *fp)
304 {
305 	accmode_t accmode;
306 	struct flock lf;
307 	int error, lock_flags, type;
308 
309 	if (vp->v_type == VLNK)
310 		return (EMLINK);
311 	if (vp->v_type == VSOCK)
312 		return (EOPNOTSUPP);
313 	if (vp->v_type != VDIR && fmode & O_DIRECTORY)
314 		return (ENOTDIR);
315 	accmode = 0;
316 	if (fmode & (FWRITE | O_TRUNC)) {
317 		if (vp->v_type == VDIR)
318 			return (EISDIR);
319 		accmode |= VWRITE;
320 	}
321 	if (fmode & FREAD)
322 		accmode |= VREAD;
323 	if (fmode & FEXEC)
324 		accmode |= VEXEC;
325 	if ((fmode & O_APPEND) && (fmode & FWRITE))
326 		accmode |= VAPPEND;
327 #ifdef MAC
328 	if (fmode & O_CREAT)
329 		accmode |= VCREAT;
330 	if (fmode & O_VERIFY)
331 		accmode |= VVERIFY;
332 	error = mac_vnode_check_open(cred, vp, accmode);
333 	if (error)
334 		return (error);
335 
336 	accmode &= ~(VCREAT | VVERIFY);
337 #endif
338 	if ((fmode & O_CREAT) == 0) {
339 		if (accmode & VWRITE) {
340 			error = vn_writechk(vp);
341 			if (error)
342 				return (error);
343 		}
344 		if (accmode) {
345 		        error = VOP_ACCESS(vp, accmode, cred, td);
346 			if (error)
347 				return (error);
348 		}
349 	}
350 	if (vp->v_type == VFIFO && VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
351 		vn_lock(vp, LK_UPGRADE | LK_RETRY);
352 	if ((error = VOP_OPEN(vp, fmode, cred, td, fp)) != 0)
353 		return (error);
354 
355 	while ((fmode & (O_EXLOCK | O_SHLOCK)) != 0) {
356 		KASSERT(fp != NULL, ("open with flock requires fp"));
357 		if (fp->f_type != DTYPE_NONE && fp->f_type != DTYPE_VNODE) {
358 			error = EOPNOTSUPP;
359 			break;
360 		}
361 		lock_flags = VOP_ISLOCKED(vp);
362 		VOP_UNLOCK(vp, 0);
363 		lf.l_whence = SEEK_SET;
364 		lf.l_start = 0;
365 		lf.l_len = 0;
366 		if (fmode & O_EXLOCK)
367 			lf.l_type = F_WRLCK;
368 		else
369 			lf.l_type = F_RDLCK;
370 		type = F_FLOCK;
371 		if ((fmode & FNONBLOCK) == 0)
372 			type |= F_WAIT;
373 		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, type);
374 		if (error == 0)
375 			fp->f_flag |= FHASLOCK;
376 		vn_lock(vp, lock_flags | LK_RETRY);
377 		if (error != 0)
378 			break;
379 		if ((vp->v_iflag & VI_DOOMED) != 0) {
380 			error = ENOENT;
381 			break;
382 		}
383 
384 		/*
385 		 * Another thread might have used this vnode as an
386 		 * executable while the vnode lock was dropped.
387 		 * Ensure the vnode is still able to be opened for
388 		 * writing after the lock has been obtained.
389 		 */
390 		if ((accmode & VWRITE) != 0)
391 			error = vn_writechk(vp);
392 		break;
393 	}
394 
395 	if (error != 0) {
396 		fp->f_flag |= FOPENFAILED;
397 		fp->f_vnode = vp;
398 		if (fp->f_ops == &badfileops) {
399 			fp->f_type = DTYPE_VNODE;
400 			fp->f_ops = &vnops;
401 		}
402 		vref(vp);
403 	} else if  ((fmode & FWRITE) != 0) {
404 		VOP_ADD_WRITECOUNT(vp, 1);
405 		CTR3(KTR_VFS, "%s: vp %p v_writecount increased to %d",
406 		    __func__, vp, vp->v_writecount);
407 	}
408 	ASSERT_VOP_LOCKED(vp, "vn_open_vnode");
409 	return (error);
410 }
411 
412 /*
413  * Check for write permissions on the specified vnode.
414  * Prototype text segments cannot be written.
415  */
416 int
417 vn_writechk(struct vnode *vp)
418 {
419 
420 	ASSERT_VOP_LOCKED(vp, "vn_writechk");
421 	/*
422 	 * If there's shared text associated with
423 	 * the vnode, try to free it up once.  If
424 	 * we fail, we can't allow writing.
425 	 */
426 	if (VOP_IS_TEXT(vp))
427 		return (ETXTBSY);
428 
429 	return (0);
430 }
431 
432 /*
433  * Vnode close call
434  */
435 static int
436 vn_close1(struct vnode *vp, int flags, struct ucred *file_cred,
437     struct thread *td, bool keep_ref)
438 {
439 	struct mount *mp;
440 	int error, lock_flags;
441 
442 	if (vp->v_type != VFIFO && (flags & FWRITE) == 0 &&
443 	    MNT_EXTENDED_SHARED(vp->v_mount))
444 		lock_flags = LK_SHARED;
445 	else
446 		lock_flags = LK_EXCLUSIVE;
447 
448 	vn_start_write(vp, &mp, V_WAIT);
449 	vn_lock(vp, lock_flags | LK_RETRY);
450 	AUDIT_ARG_VNODE1(vp);
451 	if ((flags & (FWRITE | FOPENFAILED)) == FWRITE) {
452 		VNASSERT(vp->v_writecount > 0, vp,
453 		    ("vn_close: negative writecount"));
454 		VOP_ADD_WRITECOUNT(vp, -1);
455 		CTR3(KTR_VFS, "%s: vp %p v_writecount decreased to %d",
456 		    __func__, vp, vp->v_writecount);
457 	}
458 	error = VOP_CLOSE(vp, flags, file_cred, td);
459 	if (keep_ref)
460 		VOP_UNLOCK(vp, 0);
461 	else
462 		vput(vp);
463 	vn_finished_write(mp);
464 	return (error);
465 }
466 
467 int
468 vn_close(struct vnode *vp, int flags, struct ucred *file_cred,
469     struct thread *td)
470 {
471 
472 	return (vn_close1(vp, flags, file_cred, td, false));
473 }
474 
475 /*
476  * Heuristic to detect sequential operation.
477  */
478 static int
479 sequential_heuristic(struct uio *uio, struct file *fp)
480 {
481 
482 	ASSERT_VOP_LOCKED(fp->f_vnode, __func__);
483 	if (fp->f_flag & FRDAHEAD)
484 		return (fp->f_seqcount << IO_SEQSHIFT);
485 
486 	/*
487 	 * Offset 0 is handled specially.  open() sets f_seqcount to 1 so
488 	 * that the first I/O is normally considered to be slightly
489 	 * sequential.  Seeking to offset 0 doesn't change sequentiality
490 	 * unless previous seeks have reduced f_seqcount to 0, in which
491 	 * case offset 0 is not special.
492 	 */
493 	if ((uio->uio_offset == 0 && fp->f_seqcount > 0) ||
494 	    uio->uio_offset == fp->f_nextoff) {
495 		/*
496 		 * f_seqcount is in units of fixed-size blocks so that it
497 		 * depends mainly on the amount of sequential I/O and not
498 		 * much on the number of sequential I/O's.  The fixed size
499 		 * of 16384 is hard-coded here since it is (not quite) just
500 		 * a magic size that works well here.  This size is more
501 		 * closely related to the best I/O size for real disks than
502 		 * to any block size used by software.
503 		 */
504 		fp->f_seqcount += howmany(uio->uio_resid, 16384);
505 		if (fp->f_seqcount > IO_SEQMAX)
506 			fp->f_seqcount = IO_SEQMAX;
507 		return (fp->f_seqcount << IO_SEQSHIFT);
508 	}
509 
510 	/* Not sequential.  Quickly draw-down sequentiality. */
511 	if (fp->f_seqcount > 1)
512 		fp->f_seqcount = 1;
513 	else
514 		fp->f_seqcount = 0;
515 	return (0);
516 }
517 
518 /*
519  * Package up an I/O request on a vnode into a uio and do it.
520  */
521 int
522 vn_rdwr(enum uio_rw rw, struct vnode *vp, void *base, int len, off_t offset,
523     enum uio_seg segflg, int ioflg, struct ucred *active_cred,
524     struct ucred *file_cred, ssize_t *aresid, struct thread *td)
525 {
526 	struct uio auio;
527 	struct iovec aiov;
528 	struct mount *mp;
529 	struct ucred *cred;
530 	void *rl_cookie;
531 	struct vn_io_fault_args args;
532 	int error, lock_flags;
533 
534 	if (offset < 0 && vp->v_type != VCHR)
535 		return (EINVAL);
536 	auio.uio_iov = &aiov;
537 	auio.uio_iovcnt = 1;
538 	aiov.iov_base = base;
539 	aiov.iov_len = len;
540 	auio.uio_resid = len;
541 	auio.uio_offset = offset;
542 	auio.uio_segflg = segflg;
543 	auio.uio_rw = rw;
544 	auio.uio_td = td;
545 	error = 0;
546 
547 	if ((ioflg & IO_NODELOCKED) == 0) {
548 		if ((ioflg & IO_RANGELOCKED) == 0) {
549 			if (rw == UIO_READ) {
550 				rl_cookie = vn_rangelock_rlock(vp, offset,
551 				    offset + len);
552 			} else {
553 				rl_cookie = vn_rangelock_wlock(vp, offset,
554 				    offset + len);
555 			}
556 		} else
557 			rl_cookie = NULL;
558 		mp = NULL;
559 		if (rw == UIO_WRITE) {
560 			if (vp->v_type != VCHR &&
561 			    (error = vn_start_write(vp, &mp, V_WAIT | PCATCH))
562 			    != 0)
563 				goto out;
564 			if (MNT_SHARED_WRITES(mp) ||
565 			    ((mp == NULL) && MNT_SHARED_WRITES(vp->v_mount)))
566 				lock_flags = LK_SHARED;
567 			else
568 				lock_flags = LK_EXCLUSIVE;
569 		} else
570 			lock_flags = LK_SHARED;
571 		vn_lock(vp, lock_flags | LK_RETRY);
572 	} else
573 		rl_cookie = NULL;
574 
575 	ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
576 #ifdef MAC
577 	if ((ioflg & IO_NOMACCHECK) == 0) {
578 		if (rw == UIO_READ)
579 			error = mac_vnode_check_read(active_cred, file_cred,
580 			    vp);
581 		else
582 			error = mac_vnode_check_write(active_cred, file_cred,
583 			    vp);
584 	}
585 #endif
586 	if (error == 0) {
587 		if (file_cred != NULL)
588 			cred = file_cred;
589 		else
590 			cred = active_cred;
591 		if (do_vn_io_fault(vp, &auio)) {
592 			args.kind = VN_IO_FAULT_VOP;
593 			args.cred = cred;
594 			args.flags = ioflg;
595 			args.args.vop_args.vp = vp;
596 			error = vn_io_fault1(vp, &auio, &args, td);
597 		} else if (rw == UIO_READ) {
598 			error = VOP_READ(vp, &auio, ioflg, cred);
599 		} else /* if (rw == UIO_WRITE) */ {
600 			error = VOP_WRITE(vp, &auio, ioflg, cred);
601 		}
602 	}
603 	if (aresid)
604 		*aresid = auio.uio_resid;
605 	else
606 		if (auio.uio_resid && error == 0)
607 			error = EIO;
608 	if ((ioflg & IO_NODELOCKED) == 0) {
609 		VOP_UNLOCK(vp, 0);
610 		if (mp != NULL)
611 			vn_finished_write(mp);
612 	}
613  out:
614 	if (rl_cookie != NULL)
615 		vn_rangelock_unlock(vp, rl_cookie);
616 	return (error);
617 }
618 
619 /*
620  * Package up an I/O request on a vnode into a uio and do it.  The I/O
621  * request is split up into smaller chunks and we try to avoid saturating
622  * the buffer cache while potentially holding a vnode locked, so we
623  * check bwillwrite() before calling vn_rdwr().  We also call kern_yield()
624  * to give other processes a chance to lock the vnode (either other processes
625  * core'ing the same binary, or unrelated processes scanning the directory).
626  */
627 int
628 vn_rdwr_inchunks(enum uio_rw rw, struct vnode *vp, void *base, size_t len,
629     off_t offset, enum uio_seg segflg, int ioflg, struct ucred *active_cred,
630     struct ucred *file_cred, size_t *aresid, struct thread *td)
631 {
632 	int error = 0;
633 	ssize_t iaresid;
634 
635 	do {
636 		int chunk;
637 
638 		/*
639 		 * Force `offset' to a multiple of MAXBSIZE except possibly
640 		 * for the first chunk, so that filesystems only need to
641 		 * write full blocks except possibly for the first and last
642 		 * chunks.
643 		 */
644 		chunk = MAXBSIZE - (uoff_t)offset % MAXBSIZE;
645 
646 		if (chunk > len)
647 			chunk = len;
648 		if (rw != UIO_READ && vp->v_type == VREG)
649 			bwillwrite();
650 		iaresid = 0;
651 		error = vn_rdwr(rw, vp, base, chunk, offset, segflg,
652 		    ioflg, active_cred, file_cred, &iaresid, td);
653 		len -= chunk;	/* aresid calc already includes length */
654 		if (error)
655 			break;
656 		offset += chunk;
657 		base = (char *)base + chunk;
658 		kern_yield(PRI_USER);
659 	} while (len);
660 	if (aresid)
661 		*aresid = len + iaresid;
662 	return (error);
663 }
664 
665 off_t
666 foffset_lock(struct file *fp, int flags)
667 {
668 	struct mtx *mtxp;
669 	off_t res;
670 
671 	KASSERT((flags & FOF_OFFSET) == 0, ("FOF_OFFSET passed"));
672 
673 #if OFF_MAX <= LONG_MAX
674 	/*
675 	 * Caller only wants the current f_offset value.  Assume that
676 	 * the long and shorter integer types reads are atomic.
677 	 */
678 	if ((flags & FOF_NOLOCK) != 0)
679 		return (fp->f_offset);
680 #endif
681 
682 	/*
683 	 * According to McKusick the vn lock was protecting f_offset here.
684 	 * It is now protected by the FOFFSET_LOCKED flag.
685 	 */
686 	mtxp = mtx_pool_find(mtxpool_sleep, fp);
687 	mtx_lock(mtxp);
688 	if ((flags & FOF_NOLOCK) == 0) {
689 		while (fp->f_vnread_flags & FOFFSET_LOCKED) {
690 			fp->f_vnread_flags |= FOFFSET_LOCK_WAITING;
691 			msleep(&fp->f_vnread_flags, mtxp, PUSER -1,
692 			    "vofflock", 0);
693 		}
694 		fp->f_vnread_flags |= FOFFSET_LOCKED;
695 	}
696 	res = fp->f_offset;
697 	mtx_unlock(mtxp);
698 	return (res);
699 }
700 
701 void
702 foffset_unlock(struct file *fp, off_t val, int flags)
703 {
704 	struct mtx *mtxp;
705 
706 	KASSERT((flags & FOF_OFFSET) == 0, ("FOF_OFFSET passed"));
707 
708 #if OFF_MAX <= LONG_MAX
709 	if ((flags & FOF_NOLOCK) != 0) {
710 		if ((flags & FOF_NOUPDATE) == 0)
711 			fp->f_offset = val;
712 		if ((flags & FOF_NEXTOFF) != 0)
713 			fp->f_nextoff = val;
714 		return;
715 	}
716 #endif
717 
718 	mtxp = mtx_pool_find(mtxpool_sleep, fp);
719 	mtx_lock(mtxp);
720 	if ((flags & FOF_NOUPDATE) == 0)
721 		fp->f_offset = val;
722 	if ((flags & FOF_NEXTOFF) != 0)
723 		fp->f_nextoff = val;
724 	if ((flags & FOF_NOLOCK) == 0) {
725 		KASSERT((fp->f_vnread_flags & FOFFSET_LOCKED) != 0,
726 		    ("Lost FOFFSET_LOCKED"));
727 		if (fp->f_vnread_flags & FOFFSET_LOCK_WAITING)
728 			wakeup(&fp->f_vnread_flags);
729 		fp->f_vnread_flags = 0;
730 	}
731 	mtx_unlock(mtxp);
732 }
733 
734 void
735 foffset_lock_uio(struct file *fp, struct uio *uio, int flags)
736 {
737 
738 	if ((flags & FOF_OFFSET) == 0)
739 		uio->uio_offset = foffset_lock(fp, flags);
740 }
741 
742 void
743 foffset_unlock_uio(struct file *fp, struct uio *uio, int flags)
744 {
745 
746 	if ((flags & FOF_OFFSET) == 0)
747 		foffset_unlock(fp, uio->uio_offset, flags);
748 }
749 
750 static int
751 get_advice(struct file *fp, struct uio *uio)
752 {
753 	struct mtx *mtxp;
754 	int ret;
755 
756 	ret = POSIX_FADV_NORMAL;
757 	if (fp->f_advice == NULL || fp->f_vnode->v_type != VREG)
758 		return (ret);
759 
760 	mtxp = mtx_pool_find(mtxpool_sleep, fp);
761 	mtx_lock(mtxp);
762 	if (fp->f_advice != NULL &&
763 	    uio->uio_offset >= fp->f_advice->fa_start &&
764 	    uio->uio_offset + uio->uio_resid <= fp->f_advice->fa_end)
765 		ret = fp->f_advice->fa_advice;
766 	mtx_unlock(mtxp);
767 	return (ret);
768 }
769 
770 /*
771  * File table vnode read routine.
772  */
773 static int
774 vn_read(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags,
775     struct thread *td)
776 {
777 	struct vnode *vp;
778 	off_t orig_offset;
779 	int error, ioflag;
780 	int advice;
781 
782 	KASSERT(uio->uio_td == td, ("uio_td %p is not td %p",
783 	    uio->uio_td, td));
784 	KASSERT(flags & FOF_OFFSET, ("No FOF_OFFSET"));
785 	vp = fp->f_vnode;
786 	ioflag = 0;
787 	if (fp->f_flag & FNONBLOCK)
788 		ioflag |= IO_NDELAY;
789 	if (fp->f_flag & O_DIRECT)
790 		ioflag |= IO_DIRECT;
791 	advice = get_advice(fp, uio);
792 	vn_lock(vp, LK_SHARED | LK_RETRY);
793 
794 	switch (advice) {
795 	case POSIX_FADV_NORMAL:
796 	case POSIX_FADV_SEQUENTIAL:
797 	case POSIX_FADV_NOREUSE:
798 		ioflag |= sequential_heuristic(uio, fp);
799 		break;
800 	case POSIX_FADV_RANDOM:
801 		/* Disable read-ahead for random I/O. */
802 		break;
803 	}
804 	orig_offset = uio->uio_offset;
805 
806 #ifdef MAC
807 	error = mac_vnode_check_read(active_cred, fp->f_cred, vp);
808 	if (error == 0)
809 #endif
810 		error = VOP_READ(vp, uio, ioflag, fp->f_cred);
811 	fp->f_nextoff = uio->uio_offset;
812 	VOP_UNLOCK(vp, 0);
813 	if (error == 0 && advice == POSIX_FADV_NOREUSE &&
814 	    orig_offset != uio->uio_offset)
815 		/*
816 		 * Use POSIX_FADV_DONTNEED to flush pages and buffers
817 		 * for the backing file after a POSIX_FADV_NOREUSE
818 		 * read(2).
819 		 */
820 		error = VOP_ADVISE(vp, orig_offset, uio->uio_offset - 1,
821 		    POSIX_FADV_DONTNEED);
822 	return (error);
823 }
824 
825 /*
826  * File table vnode write routine.
827  */
828 static int
829 vn_write(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags,
830     struct thread *td)
831 {
832 	struct vnode *vp;
833 	struct mount *mp;
834 	off_t orig_offset;
835 	int error, ioflag, lock_flags;
836 	int advice;
837 
838 	KASSERT(uio->uio_td == td, ("uio_td %p is not td %p",
839 	    uio->uio_td, td));
840 	KASSERT(flags & FOF_OFFSET, ("No FOF_OFFSET"));
841 	vp = fp->f_vnode;
842 	if (vp->v_type == VREG)
843 		bwillwrite();
844 	ioflag = IO_UNIT;
845 	if (vp->v_type == VREG && (fp->f_flag & O_APPEND))
846 		ioflag |= IO_APPEND;
847 	if (fp->f_flag & FNONBLOCK)
848 		ioflag |= IO_NDELAY;
849 	if (fp->f_flag & O_DIRECT)
850 		ioflag |= IO_DIRECT;
851 	if ((fp->f_flag & O_FSYNC) ||
852 	    (vp->v_mount && (vp->v_mount->mnt_flag & MNT_SYNCHRONOUS)))
853 		ioflag |= IO_SYNC;
854 	mp = NULL;
855 	if (vp->v_type != VCHR &&
856 	    (error = vn_start_write(vp, &mp, V_WAIT | PCATCH)) != 0)
857 		goto unlock;
858 
859 	advice = get_advice(fp, uio);
860 
861 	if (MNT_SHARED_WRITES(mp) ||
862 	    (mp == NULL && MNT_SHARED_WRITES(vp->v_mount))) {
863 		lock_flags = LK_SHARED;
864 	} else {
865 		lock_flags = LK_EXCLUSIVE;
866 	}
867 
868 	vn_lock(vp, lock_flags | LK_RETRY);
869 	switch (advice) {
870 	case POSIX_FADV_NORMAL:
871 	case POSIX_FADV_SEQUENTIAL:
872 	case POSIX_FADV_NOREUSE:
873 		ioflag |= sequential_heuristic(uio, fp);
874 		break;
875 	case POSIX_FADV_RANDOM:
876 		/* XXX: Is this correct? */
877 		break;
878 	}
879 	orig_offset = uio->uio_offset;
880 
881 #ifdef MAC
882 	error = mac_vnode_check_write(active_cred, fp->f_cred, vp);
883 	if (error == 0)
884 #endif
885 		error = VOP_WRITE(vp, uio, ioflag, fp->f_cred);
886 	fp->f_nextoff = uio->uio_offset;
887 	VOP_UNLOCK(vp, 0);
888 	if (vp->v_type != VCHR)
889 		vn_finished_write(mp);
890 	if (error == 0 && advice == POSIX_FADV_NOREUSE &&
891 	    orig_offset != uio->uio_offset)
892 		/*
893 		 * Use POSIX_FADV_DONTNEED to flush pages and buffers
894 		 * for the backing file after a POSIX_FADV_NOREUSE
895 		 * write(2).
896 		 */
897 		error = VOP_ADVISE(vp, orig_offset, uio->uio_offset - 1,
898 		    POSIX_FADV_DONTNEED);
899 unlock:
900 	return (error);
901 }
902 
903 /*
904  * The vn_io_fault() is a wrapper around vn_read() and vn_write() to
905  * prevent the following deadlock:
906  *
907  * Assume that the thread A reads from the vnode vp1 into userspace
908  * buffer buf1 backed by the pages of vnode vp2.  If a page in buf1 is
909  * currently not resident, then system ends up with the call chain
910  *   vn_read() -> VOP_READ(vp1) -> uiomove() -> [Page Fault] ->
911  *     vm_fault(buf1) -> vnode_pager_getpages(vp2) -> VOP_GETPAGES(vp2)
912  * which establishes lock order vp1->vn_lock, then vp2->vn_lock.
913  * If, at the same time, thread B reads from vnode vp2 into buffer buf2
914  * backed by the pages of vnode vp1, and some page in buf2 is not
915  * resident, we get a reversed order vp2->vn_lock, then vp1->vn_lock.
916  *
917  * To prevent the lock order reversal and deadlock, vn_io_fault() does
918  * not allow page faults to happen during VOP_READ() or VOP_WRITE().
919  * Instead, it first tries to do the whole range i/o with pagefaults
920  * disabled. If all pages in the i/o buffer are resident and mapped,
921  * VOP will succeed (ignoring the genuine filesystem errors).
922  * Otherwise, we get back EFAULT, and vn_io_fault() falls back to do
923  * i/o in chunks, with all pages in the chunk prefaulted and held
924  * using vm_fault_quick_hold_pages().
925  *
926  * Filesystems using this deadlock avoidance scheme should use the
927  * array of the held pages from uio, saved in the curthread->td_ma,
928  * instead of doing uiomove().  A helper function
929  * vn_io_fault_uiomove() converts uiomove request into
930  * uiomove_fromphys() over td_ma array.
931  *
932  * Since vnode locks do not cover the whole i/o anymore, rangelocks
933  * make the current i/o request atomic with respect to other i/os and
934  * truncations.
935  */
936 
937 /*
938  * Decode vn_io_fault_args and perform the corresponding i/o.
939  */
940 static int
941 vn_io_fault_doio(struct vn_io_fault_args *args, struct uio *uio,
942     struct thread *td)
943 {
944 	int error, save;
945 
946 	error = 0;
947 	save = vm_fault_disable_pagefaults();
948 	switch (args->kind) {
949 	case VN_IO_FAULT_FOP:
950 		error = (args->args.fop_args.doio)(args->args.fop_args.fp,
951 		    uio, args->cred, args->flags, td);
952 		break;
953 	case VN_IO_FAULT_VOP:
954 		if (uio->uio_rw == UIO_READ) {
955 			error = VOP_READ(args->args.vop_args.vp, uio,
956 			    args->flags, args->cred);
957 		} else if (uio->uio_rw == UIO_WRITE) {
958 			error = VOP_WRITE(args->args.vop_args.vp, uio,
959 			    args->flags, args->cred);
960 		}
961 		break;
962 	default:
963 		panic("vn_io_fault_doio: unknown kind of io %d %d",
964 		    args->kind, uio->uio_rw);
965 	}
966 	vm_fault_enable_pagefaults(save);
967 	return (error);
968 }
969 
970 static int
971 vn_io_fault_touch(char *base, const struct uio *uio)
972 {
973 	int r;
974 
975 	r = fubyte(base);
976 	if (r == -1 || (uio->uio_rw == UIO_READ && subyte(base, r) == -1))
977 		return (EFAULT);
978 	return (0);
979 }
980 
981 static int
982 vn_io_fault_prefault_user(const struct uio *uio)
983 {
984 	char *base;
985 	const struct iovec *iov;
986 	size_t len;
987 	ssize_t resid;
988 	int error, i;
989 
990 	KASSERT(uio->uio_segflg == UIO_USERSPACE,
991 	    ("vn_io_fault_prefault userspace"));
992 
993 	error = i = 0;
994 	iov = uio->uio_iov;
995 	resid = uio->uio_resid;
996 	base = iov->iov_base;
997 	len = iov->iov_len;
998 	while (resid > 0) {
999 		error = vn_io_fault_touch(base, uio);
1000 		if (error != 0)
1001 			break;
1002 		if (len < PAGE_SIZE) {
1003 			if (len != 0) {
1004 				error = vn_io_fault_touch(base + len - 1, uio);
1005 				if (error != 0)
1006 					break;
1007 				resid -= len;
1008 			}
1009 			if (++i >= uio->uio_iovcnt)
1010 				break;
1011 			iov = uio->uio_iov + i;
1012 			base = iov->iov_base;
1013 			len = iov->iov_len;
1014 		} else {
1015 			len -= PAGE_SIZE;
1016 			base += PAGE_SIZE;
1017 			resid -= PAGE_SIZE;
1018 		}
1019 	}
1020 	return (error);
1021 }
1022 
1023 /*
1024  * Common code for vn_io_fault(), agnostic to the kind of i/o request.
1025  * Uses vn_io_fault_doio() to make the call to an actual i/o function.
1026  * Used from vn_rdwr() and vn_io_fault(), which encode the i/o request
1027  * into args and call vn_io_fault1() to handle faults during the user
1028  * mode buffer accesses.
1029  */
1030 static int
1031 vn_io_fault1(struct vnode *vp, struct uio *uio, struct vn_io_fault_args *args,
1032     struct thread *td)
1033 {
1034 	vm_page_t ma[io_hold_cnt + 2];
1035 	struct uio *uio_clone, short_uio;
1036 	struct iovec short_iovec[1];
1037 	vm_page_t *prev_td_ma;
1038 	vm_prot_t prot;
1039 	vm_offset_t addr, end;
1040 	size_t len, resid;
1041 	ssize_t adv;
1042 	int error, cnt, saveheld, prev_td_ma_cnt;
1043 
1044 	if (vn_io_fault_prefault) {
1045 		error = vn_io_fault_prefault_user(uio);
1046 		if (error != 0)
1047 			return (error); /* Or ignore ? */
1048 	}
1049 
1050 	prot = uio->uio_rw == UIO_READ ? VM_PROT_WRITE : VM_PROT_READ;
1051 
1052 	/*
1053 	 * The UFS follows IO_UNIT directive and replays back both
1054 	 * uio_offset and uio_resid if an error is encountered during the
1055 	 * operation.  But, since the iovec may be already advanced,
1056 	 * uio is still in an inconsistent state.
1057 	 *
1058 	 * Cache a copy of the original uio, which is advanced to the redo
1059 	 * point using UIO_NOCOPY below.
1060 	 */
1061 	uio_clone = cloneuio(uio);
1062 	resid = uio->uio_resid;
1063 
1064 	short_uio.uio_segflg = UIO_USERSPACE;
1065 	short_uio.uio_rw = uio->uio_rw;
1066 	short_uio.uio_td = uio->uio_td;
1067 
1068 	error = vn_io_fault_doio(args, uio, td);
1069 	if (error != EFAULT)
1070 		goto out;
1071 
1072 	atomic_add_long(&vn_io_faults_cnt, 1);
1073 	uio_clone->uio_segflg = UIO_NOCOPY;
1074 	uiomove(NULL, resid - uio->uio_resid, uio_clone);
1075 	uio_clone->uio_segflg = uio->uio_segflg;
1076 
1077 	saveheld = curthread_pflags_set(TDP_UIOHELD);
1078 	prev_td_ma = td->td_ma;
1079 	prev_td_ma_cnt = td->td_ma_cnt;
1080 
1081 	while (uio_clone->uio_resid != 0) {
1082 		len = uio_clone->uio_iov->iov_len;
1083 		if (len == 0) {
1084 			KASSERT(uio_clone->uio_iovcnt >= 1,
1085 			    ("iovcnt underflow"));
1086 			uio_clone->uio_iov++;
1087 			uio_clone->uio_iovcnt--;
1088 			continue;
1089 		}
1090 		if (len > io_hold_cnt * PAGE_SIZE)
1091 			len = io_hold_cnt * PAGE_SIZE;
1092 		addr = (uintptr_t)uio_clone->uio_iov->iov_base;
1093 		end = round_page(addr + len);
1094 		if (end < addr) {
1095 			error = EFAULT;
1096 			break;
1097 		}
1098 		cnt = atop(end - trunc_page(addr));
1099 		/*
1100 		 * A perfectly misaligned address and length could cause
1101 		 * both the start and the end of the chunk to use partial
1102 		 * page.  +2 accounts for such a situation.
1103 		 */
1104 		cnt = vm_fault_quick_hold_pages(&td->td_proc->p_vmspace->vm_map,
1105 		    addr, len, prot, ma, io_hold_cnt + 2);
1106 		if (cnt == -1) {
1107 			error = EFAULT;
1108 			break;
1109 		}
1110 		short_uio.uio_iov = &short_iovec[0];
1111 		short_iovec[0].iov_base = (void *)addr;
1112 		short_uio.uio_iovcnt = 1;
1113 		short_uio.uio_resid = short_iovec[0].iov_len = len;
1114 		short_uio.uio_offset = uio_clone->uio_offset;
1115 		td->td_ma = ma;
1116 		td->td_ma_cnt = cnt;
1117 
1118 		error = vn_io_fault_doio(args, &short_uio, td);
1119 		vm_page_unhold_pages(ma, cnt);
1120 		adv = len - short_uio.uio_resid;
1121 
1122 		uio_clone->uio_iov->iov_base =
1123 		    (char *)uio_clone->uio_iov->iov_base + adv;
1124 		uio_clone->uio_iov->iov_len -= adv;
1125 		uio_clone->uio_resid -= adv;
1126 		uio_clone->uio_offset += adv;
1127 
1128 		uio->uio_resid -= adv;
1129 		uio->uio_offset += adv;
1130 
1131 		if (error != 0 || adv == 0)
1132 			break;
1133 	}
1134 	td->td_ma = prev_td_ma;
1135 	td->td_ma_cnt = prev_td_ma_cnt;
1136 	curthread_pflags_restore(saveheld);
1137 out:
1138 	free(uio_clone, M_IOV);
1139 	return (error);
1140 }
1141 
1142 static int
1143 vn_io_fault(struct file *fp, struct uio *uio, struct ucred *active_cred,
1144     int flags, struct thread *td)
1145 {
1146 	fo_rdwr_t *doio;
1147 	struct vnode *vp;
1148 	void *rl_cookie;
1149 	struct vn_io_fault_args args;
1150 	int error;
1151 
1152 	doio = uio->uio_rw == UIO_READ ? vn_read : vn_write;
1153 	vp = fp->f_vnode;
1154 	foffset_lock_uio(fp, uio, flags);
1155 	if (do_vn_io_fault(vp, uio)) {
1156 		args.kind = VN_IO_FAULT_FOP;
1157 		args.args.fop_args.fp = fp;
1158 		args.args.fop_args.doio = doio;
1159 		args.cred = active_cred;
1160 		args.flags = flags | FOF_OFFSET;
1161 		if (uio->uio_rw == UIO_READ) {
1162 			rl_cookie = vn_rangelock_rlock(vp, uio->uio_offset,
1163 			    uio->uio_offset + uio->uio_resid);
1164 		} else if ((fp->f_flag & O_APPEND) != 0 ||
1165 		    (flags & FOF_OFFSET) == 0) {
1166 			/* For appenders, punt and lock the whole range. */
1167 			rl_cookie = vn_rangelock_wlock(vp, 0, OFF_MAX);
1168 		} else {
1169 			rl_cookie = vn_rangelock_wlock(vp, uio->uio_offset,
1170 			    uio->uio_offset + uio->uio_resid);
1171 		}
1172 		error = vn_io_fault1(vp, uio, &args, td);
1173 		vn_rangelock_unlock(vp, rl_cookie);
1174 	} else {
1175 		error = doio(fp, uio, active_cred, flags | FOF_OFFSET, td);
1176 	}
1177 	foffset_unlock_uio(fp, uio, flags);
1178 	return (error);
1179 }
1180 
1181 /*
1182  * Helper function to perform the requested uiomove operation using
1183  * the held pages for io->uio_iov[0].iov_base buffer instead of
1184  * copyin/copyout.  Access to the pages with uiomove_fromphys()
1185  * instead of iov_base prevents page faults that could occur due to
1186  * pmap_collect() invalidating the mapping created by
1187  * vm_fault_quick_hold_pages(), or pageout daemon, page laundry or
1188  * object cleanup revoking the write access from page mappings.
1189  *
1190  * Filesystems specified MNTK_NO_IOPF shall use vn_io_fault_uiomove()
1191  * instead of plain uiomove().
1192  */
1193 int
1194 vn_io_fault_uiomove(char *data, int xfersize, struct uio *uio)
1195 {
1196 	struct uio transp_uio;
1197 	struct iovec transp_iov[1];
1198 	struct thread *td;
1199 	size_t adv;
1200 	int error, pgadv;
1201 
1202 	td = curthread;
1203 	if ((td->td_pflags & TDP_UIOHELD) == 0 ||
1204 	    uio->uio_segflg != UIO_USERSPACE)
1205 		return (uiomove(data, xfersize, uio));
1206 
1207 	KASSERT(uio->uio_iovcnt == 1, ("uio_iovcnt %d", uio->uio_iovcnt));
1208 	transp_iov[0].iov_base = data;
1209 	transp_uio.uio_iov = &transp_iov[0];
1210 	transp_uio.uio_iovcnt = 1;
1211 	if (xfersize > uio->uio_resid)
1212 		xfersize = uio->uio_resid;
1213 	transp_uio.uio_resid = transp_iov[0].iov_len = xfersize;
1214 	transp_uio.uio_offset = 0;
1215 	transp_uio.uio_segflg = UIO_SYSSPACE;
1216 	/*
1217 	 * Since transp_iov points to data, and td_ma page array
1218 	 * corresponds to original uio->uio_iov, we need to invert the
1219 	 * direction of the i/o operation as passed to
1220 	 * uiomove_fromphys().
1221 	 */
1222 	switch (uio->uio_rw) {
1223 	case UIO_WRITE:
1224 		transp_uio.uio_rw = UIO_READ;
1225 		break;
1226 	case UIO_READ:
1227 		transp_uio.uio_rw = UIO_WRITE;
1228 		break;
1229 	}
1230 	transp_uio.uio_td = uio->uio_td;
1231 	error = uiomove_fromphys(td->td_ma,
1232 	    ((vm_offset_t)uio->uio_iov->iov_base) & PAGE_MASK,
1233 	    xfersize, &transp_uio);
1234 	adv = xfersize - transp_uio.uio_resid;
1235 	pgadv =
1236 	    (((vm_offset_t)uio->uio_iov->iov_base + adv) >> PAGE_SHIFT) -
1237 	    (((vm_offset_t)uio->uio_iov->iov_base) >> PAGE_SHIFT);
1238 	td->td_ma += pgadv;
1239 	KASSERT(td->td_ma_cnt >= pgadv, ("consumed pages %d %d", td->td_ma_cnt,
1240 	    pgadv));
1241 	td->td_ma_cnt -= pgadv;
1242 	uio->uio_iov->iov_base = (char *)uio->uio_iov->iov_base + adv;
1243 	uio->uio_iov->iov_len -= adv;
1244 	uio->uio_resid -= adv;
1245 	uio->uio_offset += adv;
1246 	return (error);
1247 }
1248 
1249 int
1250 vn_io_fault_pgmove(vm_page_t ma[], vm_offset_t offset, int xfersize,
1251     struct uio *uio)
1252 {
1253 	struct thread *td;
1254 	vm_offset_t iov_base;
1255 	int cnt, pgadv;
1256 
1257 	td = curthread;
1258 	if ((td->td_pflags & TDP_UIOHELD) == 0 ||
1259 	    uio->uio_segflg != UIO_USERSPACE)
1260 		return (uiomove_fromphys(ma, offset, xfersize, uio));
1261 
1262 	KASSERT(uio->uio_iovcnt == 1, ("uio_iovcnt %d", uio->uio_iovcnt));
1263 	cnt = xfersize > uio->uio_resid ? uio->uio_resid : xfersize;
1264 	iov_base = (vm_offset_t)uio->uio_iov->iov_base;
1265 	switch (uio->uio_rw) {
1266 	case UIO_WRITE:
1267 		pmap_copy_pages(td->td_ma, iov_base & PAGE_MASK, ma,
1268 		    offset, cnt);
1269 		break;
1270 	case UIO_READ:
1271 		pmap_copy_pages(ma, offset, td->td_ma, iov_base & PAGE_MASK,
1272 		    cnt);
1273 		break;
1274 	}
1275 	pgadv = ((iov_base + cnt) >> PAGE_SHIFT) - (iov_base >> PAGE_SHIFT);
1276 	td->td_ma += pgadv;
1277 	KASSERT(td->td_ma_cnt >= pgadv, ("consumed pages %d %d", td->td_ma_cnt,
1278 	    pgadv));
1279 	td->td_ma_cnt -= pgadv;
1280 	uio->uio_iov->iov_base = (char *)(iov_base + cnt);
1281 	uio->uio_iov->iov_len -= cnt;
1282 	uio->uio_resid -= cnt;
1283 	uio->uio_offset += cnt;
1284 	return (0);
1285 }
1286 
1287 
1288 /*
1289  * File table truncate routine.
1290  */
1291 static int
1292 vn_truncate(struct file *fp, off_t length, struct ucred *active_cred,
1293     struct thread *td)
1294 {
1295 	struct vattr vattr;
1296 	struct mount *mp;
1297 	struct vnode *vp;
1298 	void *rl_cookie;
1299 	int error;
1300 
1301 	vp = fp->f_vnode;
1302 
1303 	/*
1304 	 * Lock the whole range for truncation.  Otherwise split i/o
1305 	 * might happen partly before and partly after the truncation.
1306 	 */
1307 	rl_cookie = vn_rangelock_wlock(vp, 0, OFF_MAX);
1308 	error = vn_start_write(vp, &mp, V_WAIT | PCATCH);
1309 	if (error)
1310 		goto out1;
1311 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1312 	AUDIT_ARG_VNODE1(vp);
1313 	if (vp->v_type == VDIR) {
1314 		error = EISDIR;
1315 		goto out;
1316 	}
1317 #ifdef MAC
1318 	error = mac_vnode_check_write(active_cred, fp->f_cred, vp);
1319 	if (error)
1320 		goto out;
1321 #endif
1322 	error = vn_writechk(vp);
1323 	if (error == 0) {
1324 		VATTR_NULL(&vattr);
1325 		vattr.va_size = length;
1326 		if ((fp->f_flag & O_FSYNC) != 0)
1327 			vattr.va_vaflags |= VA_SYNC;
1328 		error = VOP_SETATTR(vp, &vattr, fp->f_cred);
1329 	}
1330 out:
1331 	VOP_UNLOCK(vp, 0);
1332 	vn_finished_write(mp);
1333 out1:
1334 	vn_rangelock_unlock(vp, rl_cookie);
1335 	return (error);
1336 }
1337 
1338 /*
1339  * File table vnode stat routine.
1340  */
1341 static int
1342 vn_statfile(struct file *fp, struct stat *sb, struct ucred *active_cred,
1343     struct thread *td)
1344 {
1345 	struct vnode *vp = fp->f_vnode;
1346 	int error;
1347 
1348 	vn_lock(vp, LK_SHARED | LK_RETRY);
1349 	error = vn_stat(vp, sb, active_cred, fp->f_cred, td);
1350 	VOP_UNLOCK(vp, 0);
1351 
1352 	return (error);
1353 }
1354 
1355 /*
1356  * Stat a vnode; implementation for the stat syscall
1357  */
1358 int
1359 vn_stat(struct vnode *vp, struct stat *sb, struct ucred *active_cred,
1360     struct ucred *file_cred, struct thread *td)
1361 {
1362 	struct vattr vattr;
1363 	struct vattr *vap;
1364 	int error;
1365 	u_short mode;
1366 
1367 	AUDIT_ARG_VNODE1(vp);
1368 #ifdef MAC
1369 	error = mac_vnode_check_stat(active_cred, file_cred, vp);
1370 	if (error)
1371 		return (error);
1372 #endif
1373 
1374 	vap = &vattr;
1375 
1376 	/*
1377 	 * Initialize defaults for new and unusual fields, so that file
1378 	 * systems which don't support these fields don't need to know
1379 	 * about them.
1380 	 */
1381 	vap->va_birthtime.tv_sec = -1;
1382 	vap->va_birthtime.tv_nsec = 0;
1383 	vap->va_fsid = VNOVAL;
1384 	vap->va_rdev = NODEV;
1385 
1386 	error = VOP_GETATTR(vp, vap, active_cred);
1387 	if (error)
1388 		return (error);
1389 
1390 	/*
1391 	 * Zero the spare stat fields
1392 	 */
1393 	bzero(sb, sizeof *sb);
1394 
1395 	/*
1396 	 * Copy from vattr table
1397 	 */
1398 	if (vap->va_fsid != VNOVAL)
1399 		sb->st_dev = vap->va_fsid;
1400 	else
1401 		sb->st_dev = vp->v_mount->mnt_stat.f_fsid.val[0];
1402 	sb->st_ino = vap->va_fileid;
1403 	mode = vap->va_mode;
1404 	switch (vap->va_type) {
1405 	case VREG:
1406 		mode |= S_IFREG;
1407 		break;
1408 	case VDIR:
1409 		mode |= S_IFDIR;
1410 		break;
1411 	case VBLK:
1412 		mode |= S_IFBLK;
1413 		break;
1414 	case VCHR:
1415 		mode |= S_IFCHR;
1416 		break;
1417 	case VLNK:
1418 		mode |= S_IFLNK;
1419 		break;
1420 	case VSOCK:
1421 		mode |= S_IFSOCK;
1422 		break;
1423 	case VFIFO:
1424 		mode |= S_IFIFO;
1425 		break;
1426 	default:
1427 		return (EBADF);
1428 	}
1429 	sb->st_mode = mode;
1430 	sb->st_nlink = vap->va_nlink;
1431 	sb->st_uid = vap->va_uid;
1432 	sb->st_gid = vap->va_gid;
1433 	sb->st_rdev = vap->va_rdev;
1434 	if (vap->va_size > OFF_MAX)
1435 		return (EOVERFLOW);
1436 	sb->st_size = vap->va_size;
1437 	sb->st_atim = vap->va_atime;
1438 	sb->st_mtim = vap->va_mtime;
1439 	sb->st_ctim = vap->va_ctime;
1440 	sb->st_birthtim = vap->va_birthtime;
1441 
1442         /*
1443 	 * According to www.opengroup.org, the meaning of st_blksize is
1444 	 *   "a filesystem-specific preferred I/O block size for this
1445 	 *    object.  In some filesystem types, this may vary from file
1446 	 *    to file"
1447 	 * Use miminum/default of PAGE_SIZE (e.g. for VCHR).
1448 	 */
1449 
1450 	sb->st_blksize = max(PAGE_SIZE, vap->va_blocksize);
1451 
1452 	sb->st_flags = vap->va_flags;
1453 	if (priv_check(td, PRIV_VFS_GENERATION))
1454 		sb->st_gen = 0;
1455 	else
1456 		sb->st_gen = vap->va_gen;
1457 
1458 	sb->st_blocks = vap->va_bytes / S_BLKSIZE;
1459 	return (0);
1460 }
1461 
1462 /*
1463  * File table vnode ioctl routine.
1464  */
1465 static int
1466 vn_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
1467     struct thread *td)
1468 {
1469 	struct vattr vattr;
1470 	struct vnode *vp;
1471 	int error;
1472 
1473 	vp = fp->f_vnode;
1474 	switch (vp->v_type) {
1475 	case VDIR:
1476 	case VREG:
1477 		switch (com) {
1478 		case FIONREAD:
1479 			vn_lock(vp, LK_SHARED | LK_RETRY);
1480 			error = VOP_GETATTR(vp, &vattr, active_cred);
1481 			VOP_UNLOCK(vp, 0);
1482 			if (error == 0)
1483 				*(int *)data = vattr.va_size - fp->f_offset;
1484 			return (error);
1485 		case FIONBIO:
1486 		case FIOASYNC:
1487 			return (0);
1488 		default:
1489 			return (VOP_IOCTL(vp, com, data, fp->f_flag,
1490 			    active_cred, td));
1491 		}
1492 		break;
1493 	case VCHR:
1494 		return (VOP_IOCTL(vp, com, data, fp->f_flag,
1495 		    active_cred, td));
1496 	default:
1497 		return (ENOTTY);
1498 	}
1499 }
1500 
1501 /*
1502  * File table vnode poll routine.
1503  */
1504 static int
1505 vn_poll(struct file *fp, int events, struct ucred *active_cred,
1506     struct thread *td)
1507 {
1508 	struct vnode *vp;
1509 	int error;
1510 
1511 	vp = fp->f_vnode;
1512 #ifdef MAC
1513 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1514 	AUDIT_ARG_VNODE1(vp);
1515 	error = mac_vnode_check_poll(active_cred, fp->f_cred, vp);
1516 	VOP_UNLOCK(vp, 0);
1517 	if (!error)
1518 #endif
1519 
1520 	error = VOP_POLL(vp, events, fp->f_cred, td);
1521 	return (error);
1522 }
1523 
1524 /*
1525  * Acquire the requested lock and then check for validity.  LK_RETRY
1526  * permits vn_lock to return doomed vnodes.
1527  */
1528 int
1529 _vn_lock(struct vnode *vp, int flags, char *file, int line)
1530 {
1531 	int error;
1532 
1533 	VNASSERT((flags & LK_TYPE_MASK) != 0, vp,
1534 	    ("vn_lock: no locktype"));
1535 	VNASSERT(vp->v_holdcnt != 0, vp, ("vn_lock: zero hold count"));
1536 retry:
1537 	error = VOP_LOCK1(vp, flags, file, line);
1538 	flags &= ~LK_INTERLOCK;	/* Interlock is always dropped. */
1539 	KASSERT((flags & LK_RETRY) == 0 || error == 0,
1540 	    ("vn_lock: error %d incompatible with flags %#x", error, flags));
1541 
1542 	if ((flags & LK_RETRY) == 0) {
1543 		if (error == 0 && (vp->v_iflag & VI_DOOMED) != 0) {
1544 			VOP_UNLOCK(vp, 0);
1545 			error = ENOENT;
1546 		}
1547 	} else if (error != 0)
1548 		goto retry;
1549 	return (error);
1550 }
1551 
1552 /*
1553  * File table vnode close routine.
1554  */
1555 static int
1556 vn_closefile(struct file *fp, struct thread *td)
1557 {
1558 	struct vnode *vp;
1559 	struct flock lf;
1560 	int error;
1561 	bool ref;
1562 
1563 	vp = fp->f_vnode;
1564 	fp->f_ops = &badfileops;
1565 	ref= (fp->f_flag & FHASLOCK) != 0 && fp->f_type == DTYPE_VNODE;
1566 
1567 	error = vn_close1(vp, fp->f_flag, fp->f_cred, td, ref);
1568 
1569 	if (__predict_false(ref)) {
1570 		lf.l_whence = SEEK_SET;
1571 		lf.l_start = 0;
1572 		lf.l_len = 0;
1573 		lf.l_type = F_UNLCK;
1574 		(void) VOP_ADVLOCK(vp, fp, F_UNLCK, &lf, F_FLOCK);
1575 		vrele(vp);
1576 	}
1577 	return (error);
1578 }
1579 
1580 static bool
1581 vn_suspendable(struct mount *mp)
1582 {
1583 
1584 	return (mp->mnt_op->vfs_susp_clean != NULL);
1585 }
1586 
1587 /*
1588  * Preparing to start a filesystem write operation. If the operation is
1589  * permitted, then we bump the count of operations in progress and
1590  * proceed. If a suspend request is in progress, we wait until the
1591  * suspension is over, and then proceed.
1592  */
1593 static int
1594 vn_start_write_locked(struct mount *mp, int flags)
1595 {
1596 	int error, mflags;
1597 
1598 	mtx_assert(MNT_MTX(mp), MA_OWNED);
1599 	error = 0;
1600 
1601 	/*
1602 	 * Check on status of suspension.
1603 	 */
1604 	if ((curthread->td_pflags & TDP_IGNSUSP) == 0 ||
1605 	    mp->mnt_susp_owner != curthread) {
1606 		mflags = ((mp->mnt_vfc->vfc_flags & VFCF_SBDRY) != 0 ?
1607 		    (flags & PCATCH) : 0) | (PUSER - 1);
1608 		while ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0) {
1609 			if (flags & V_NOWAIT) {
1610 				error = EWOULDBLOCK;
1611 				goto unlock;
1612 			}
1613 			error = msleep(&mp->mnt_flag, MNT_MTX(mp), mflags,
1614 			    "suspfs", 0);
1615 			if (error)
1616 				goto unlock;
1617 		}
1618 	}
1619 	if (flags & V_XSLEEP)
1620 		goto unlock;
1621 	mp->mnt_writeopcount++;
1622 unlock:
1623 	if (error != 0 || (flags & V_XSLEEP) != 0)
1624 		MNT_REL(mp);
1625 	MNT_IUNLOCK(mp);
1626 	return (error);
1627 }
1628 
1629 int
1630 vn_start_write(struct vnode *vp, struct mount **mpp, int flags)
1631 {
1632 	struct mount *mp;
1633 	int error;
1634 
1635 	KASSERT((flags & V_MNTREF) == 0 || (*mpp != NULL && vp == NULL),
1636 	    ("V_MNTREF requires mp"));
1637 
1638 	error = 0;
1639 	/*
1640 	 * If a vnode is provided, get and return the mount point that
1641 	 * to which it will write.
1642 	 */
1643 	if (vp != NULL) {
1644 		if ((error = VOP_GETWRITEMOUNT(vp, mpp)) != 0) {
1645 			*mpp = NULL;
1646 			if (error != EOPNOTSUPP)
1647 				return (error);
1648 			return (0);
1649 		}
1650 	}
1651 	if ((mp = *mpp) == NULL)
1652 		return (0);
1653 
1654 	if (!vn_suspendable(mp)) {
1655 		if (vp != NULL || (flags & V_MNTREF) != 0)
1656 			vfs_rel(mp);
1657 		return (0);
1658 	}
1659 
1660 	/*
1661 	 * VOP_GETWRITEMOUNT() returns with the mp refcount held through
1662 	 * a vfs_ref().
1663 	 * As long as a vnode is not provided we need to acquire a
1664 	 * refcount for the provided mountpoint too, in order to
1665 	 * emulate a vfs_ref().
1666 	 */
1667 	MNT_ILOCK(mp);
1668 	if (vp == NULL && (flags & V_MNTREF) == 0)
1669 		MNT_REF(mp);
1670 
1671 	return (vn_start_write_locked(mp, flags));
1672 }
1673 
1674 /*
1675  * Secondary suspension. Used by operations such as vop_inactive
1676  * routines that are needed by the higher level functions. These
1677  * are allowed to proceed until all the higher level functions have
1678  * completed (indicated by mnt_writeopcount dropping to zero). At that
1679  * time, these operations are halted until the suspension is over.
1680  */
1681 int
1682 vn_start_secondary_write(struct vnode *vp, struct mount **mpp, int flags)
1683 {
1684 	struct mount *mp;
1685 	int error;
1686 
1687 	KASSERT((flags & V_MNTREF) == 0 || (*mpp != NULL && vp == NULL),
1688 	    ("V_MNTREF requires mp"));
1689 
1690  retry:
1691 	if (vp != NULL) {
1692 		if ((error = VOP_GETWRITEMOUNT(vp, mpp)) != 0) {
1693 			*mpp = NULL;
1694 			if (error != EOPNOTSUPP)
1695 				return (error);
1696 			return (0);
1697 		}
1698 	}
1699 	/*
1700 	 * If we are not suspended or have not yet reached suspended
1701 	 * mode, then let the operation proceed.
1702 	 */
1703 	if ((mp = *mpp) == NULL)
1704 		return (0);
1705 
1706 	if (!vn_suspendable(mp)) {
1707 		if (vp != NULL || (flags & V_MNTREF) != 0)
1708 			vfs_rel(mp);
1709 		return (0);
1710 	}
1711 
1712 	/*
1713 	 * VOP_GETWRITEMOUNT() returns with the mp refcount held through
1714 	 * a vfs_ref().
1715 	 * As long as a vnode is not provided we need to acquire a
1716 	 * refcount for the provided mountpoint too, in order to
1717 	 * emulate a vfs_ref().
1718 	 */
1719 	MNT_ILOCK(mp);
1720 	if (vp == NULL && (flags & V_MNTREF) == 0)
1721 		MNT_REF(mp);
1722 	if ((mp->mnt_kern_flag & (MNTK_SUSPENDED | MNTK_SUSPEND2)) == 0) {
1723 		mp->mnt_secondary_writes++;
1724 		mp->mnt_secondary_accwrites++;
1725 		MNT_IUNLOCK(mp);
1726 		return (0);
1727 	}
1728 	if (flags & V_NOWAIT) {
1729 		MNT_REL(mp);
1730 		MNT_IUNLOCK(mp);
1731 		return (EWOULDBLOCK);
1732 	}
1733 	/*
1734 	 * Wait for the suspension to finish.
1735 	 */
1736 	error = msleep(&mp->mnt_flag, MNT_MTX(mp), (PUSER - 1) | PDROP |
1737 	    ((mp->mnt_vfc->vfc_flags & VFCF_SBDRY) != 0 ? (flags & PCATCH) : 0),
1738 	    "suspfs", 0);
1739 	vfs_rel(mp);
1740 	if (error == 0)
1741 		goto retry;
1742 	return (error);
1743 }
1744 
1745 /*
1746  * Filesystem write operation has completed. If we are suspending and this
1747  * operation is the last one, notify the suspender that the suspension is
1748  * now in effect.
1749  */
1750 void
1751 vn_finished_write(struct mount *mp)
1752 {
1753 	if (mp == NULL || !vn_suspendable(mp))
1754 		return;
1755 	MNT_ILOCK(mp);
1756 	MNT_REL(mp);
1757 	mp->mnt_writeopcount--;
1758 	if (mp->mnt_writeopcount < 0)
1759 		panic("vn_finished_write: neg cnt");
1760 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0 &&
1761 	    mp->mnt_writeopcount <= 0)
1762 		wakeup(&mp->mnt_writeopcount);
1763 	MNT_IUNLOCK(mp);
1764 }
1765 
1766 
1767 /*
1768  * Filesystem secondary write operation has completed. If we are
1769  * suspending and this operation is the last one, notify the suspender
1770  * that the suspension is now in effect.
1771  */
1772 void
1773 vn_finished_secondary_write(struct mount *mp)
1774 {
1775 	if (mp == NULL || !vn_suspendable(mp))
1776 		return;
1777 	MNT_ILOCK(mp);
1778 	MNT_REL(mp);
1779 	mp->mnt_secondary_writes--;
1780 	if (mp->mnt_secondary_writes < 0)
1781 		panic("vn_finished_secondary_write: neg cnt");
1782 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0 &&
1783 	    mp->mnt_secondary_writes <= 0)
1784 		wakeup(&mp->mnt_secondary_writes);
1785 	MNT_IUNLOCK(mp);
1786 }
1787 
1788 
1789 
1790 /*
1791  * Request a filesystem to suspend write operations.
1792  */
1793 int
1794 vfs_write_suspend(struct mount *mp, int flags)
1795 {
1796 	int error;
1797 
1798 	MPASS(vn_suspendable(mp));
1799 
1800 	MNT_ILOCK(mp);
1801 	if (mp->mnt_susp_owner == curthread) {
1802 		MNT_IUNLOCK(mp);
1803 		return (EALREADY);
1804 	}
1805 	while (mp->mnt_kern_flag & MNTK_SUSPEND)
1806 		msleep(&mp->mnt_flag, MNT_MTX(mp), PUSER - 1, "wsuspfs", 0);
1807 
1808 	/*
1809 	 * Unmount holds a write reference on the mount point.  If we
1810 	 * own busy reference and drain for writers, we deadlock with
1811 	 * the reference draining in the unmount path.  Callers of
1812 	 * vfs_write_suspend() must specify VS_SKIP_UNMOUNT if
1813 	 * vfs_busy() reference is owned and caller is not in the
1814 	 * unmount context.
1815 	 */
1816 	if ((flags & VS_SKIP_UNMOUNT) != 0 &&
1817 	    (mp->mnt_kern_flag & MNTK_UNMOUNT) != 0) {
1818 		MNT_IUNLOCK(mp);
1819 		return (EBUSY);
1820 	}
1821 
1822 	mp->mnt_kern_flag |= MNTK_SUSPEND;
1823 	mp->mnt_susp_owner = curthread;
1824 	if (mp->mnt_writeopcount > 0)
1825 		(void) msleep(&mp->mnt_writeopcount,
1826 		    MNT_MTX(mp), (PUSER - 1)|PDROP, "suspwt", 0);
1827 	else
1828 		MNT_IUNLOCK(mp);
1829 	if ((error = VFS_SYNC(mp, MNT_SUSPEND)) != 0)
1830 		vfs_write_resume(mp, 0);
1831 	return (error);
1832 }
1833 
1834 /*
1835  * Request a filesystem to resume write operations.
1836  */
1837 void
1838 vfs_write_resume(struct mount *mp, int flags)
1839 {
1840 
1841 	MPASS(vn_suspendable(mp));
1842 
1843 	MNT_ILOCK(mp);
1844 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0) {
1845 		KASSERT(mp->mnt_susp_owner == curthread, ("mnt_susp_owner"));
1846 		mp->mnt_kern_flag &= ~(MNTK_SUSPEND | MNTK_SUSPEND2 |
1847 				       MNTK_SUSPENDED);
1848 		mp->mnt_susp_owner = NULL;
1849 		wakeup(&mp->mnt_writeopcount);
1850 		wakeup(&mp->mnt_flag);
1851 		curthread->td_pflags &= ~TDP_IGNSUSP;
1852 		if ((flags & VR_START_WRITE) != 0) {
1853 			MNT_REF(mp);
1854 			mp->mnt_writeopcount++;
1855 		}
1856 		MNT_IUNLOCK(mp);
1857 		if ((flags & VR_NO_SUSPCLR) == 0)
1858 			VFS_SUSP_CLEAN(mp);
1859 	} else if ((flags & VR_START_WRITE) != 0) {
1860 		MNT_REF(mp);
1861 		vn_start_write_locked(mp, 0);
1862 	} else {
1863 		MNT_IUNLOCK(mp);
1864 	}
1865 }
1866 
1867 /*
1868  * Helper loop around vfs_write_suspend() for filesystem unmount VFS
1869  * methods.
1870  */
1871 int
1872 vfs_write_suspend_umnt(struct mount *mp)
1873 {
1874 	int error;
1875 
1876 	MPASS(vn_suspendable(mp));
1877 	KASSERT((curthread->td_pflags & TDP_IGNSUSP) == 0,
1878 	    ("vfs_write_suspend_umnt: recursed"));
1879 
1880 	/* dounmount() already called vn_start_write(). */
1881 	for (;;) {
1882 		vn_finished_write(mp);
1883 		error = vfs_write_suspend(mp, 0);
1884 		if (error != 0) {
1885 			vn_start_write(NULL, &mp, V_WAIT);
1886 			return (error);
1887 		}
1888 		MNT_ILOCK(mp);
1889 		if ((mp->mnt_kern_flag & MNTK_SUSPENDED) != 0)
1890 			break;
1891 		MNT_IUNLOCK(mp);
1892 		vn_start_write(NULL, &mp, V_WAIT);
1893 	}
1894 	mp->mnt_kern_flag &= ~(MNTK_SUSPENDED | MNTK_SUSPEND2);
1895 	wakeup(&mp->mnt_flag);
1896 	MNT_IUNLOCK(mp);
1897 	curthread->td_pflags |= TDP_IGNSUSP;
1898 	return (0);
1899 }
1900 
1901 /*
1902  * Implement kqueues for files by translating it to vnode operation.
1903  */
1904 static int
1905 vn_kqfilter(struct file *fp, struct knote *kn)
1906 {
1907 
1908 	return (VOP_KQFILTER(fp->f_vnode, kn));
1909 }
1910 
1911 /*
1912  * Simplified in-kernel wrapper calls for extended attribute access.
1913  * Both calls pass in a NULL credential, authorizing as "kernel" access.
1914  * Set IO_NODELOCKED in ioflg if the vnode is already locked.
1915  */
1916 int
1917 vn_extattr_get(struct vnode *vp, int ioflg, int attrnamespace,
1918     const char *attrname, int *buflen, char *buf, struct thread *td)
1919 {
1920 	struct uio	auio;
1921 	struct iovec	iov;
1922 	int	error;
1923 
1924 	iov.iov_len = *buflen;
1925 	iov.iov_base = buf;
1926 
1927 	auio.uio_iov = &iov;
1928 	auio.uio_iovcnt = 1;
1929 	auio.uio_rw = UIO_READ;
1930 	auio.uio_segflg = UIO_SYSSPACE;
1931 	auio.uio_td = td;
1932 	auio.uio_offset = 0;
1933 	auio.uio_resid = *buflen;
1934 
1935 	if ((ioflg & IO_NODELOCKED) == 0)
1936 		vn_lock(vp, LK_SHARED | LK_RETRY);
1937 
1938 	ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
1939 
1940 	/* authorize attribute retrieval as kernel */
1941 	error = VOP_GETEXTATTR(vp, attrnamespace, attrname, &auio, NULL, NULL,
1942 	    td);
1943 
1944 	if ((ioflg & IO_NODELOCKED) == 0)
1945 		VOP_UNLOCK(vp, 0);
1946 
1947 	if (error == 0) {
1948 		*buflen = *buflen - auio.uio_resid;
1949 	}
1950 
1951 	return (error);
1952 }
1953 
1954 /*
1955  * XXX failure mode if partially written?
1956  */
1957 int
1958 vn_extattr_set(struct vnode *vp, int ioflg, int attrnamespace,
1959     const char *attrname, int buflen, char *buf, struct thread *td)
1960 {
1961 	struct uio	auio;
1962 	struct iovec	iov;
1963 	struct mount	*mp;
1964 	int	error;
1965 
1966 	iov.iov_len = buflen;
1967 	iov.iov_base = buf;
1968 
1969 	auio.uio_iov = &iov;
1970 	auio.uio_iovcnt = 1;
1971 	auio.uio_rw = UIO_WRITE;
1972 	auio.uio_segflg = UIO_SYSSPACE;
1973 	auio.uio_td = td;
1974 	auio.uio_offset = 0;
1975 	auio.uio_resid = buflen;
1976 
1977 	if ((ioflg & IO_NODELOCKED) == 0) {
1978 		if ((error = vn_start_write(vp, &mp, V_WAIT)) != 0)
1979 			return (error);
1980 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1981 	}
1982 
1983 	ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
1984 
1985 	/* authorize attribute setting as kernel */
1986 	error = VOP_SETEXTATTR(vp, attrnamespace, attrname, &auio, NULL, td);
1987 
1988 	if ((ioflg & IO_NODELOCKED) == 0) {
1989 		vn_finished_write(mp);
1990 		VOP_UNLOCK(vp, 0);
1991 	}
1992 
1993 	return (error);
1994 }
1995 
1996 int
1997 vn_extattr_rm(struct vnode *vp, int ioflg, int attrnamespace,
1998     const char *attrname, struct thread *td)
1999 {
2000 	struct mount	*mp;
2001 	int	error;
2002 
2003 	if ((ioflg & IO_NODELOCKED) == 0) {
2004 		if ((error = vn_start_write(vp, &mp, V_WAIT)) != 0)
2005 			return (error);
2006 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2007 	}
2008 
2009 	ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
2010 
2011 	/* authorize attribute removal as kernel */
2012 	error = VOP_DELETEEXTATTR(vp, attrnamespace, attrname, NULL, td);
2013 	if (error == EOPNOTSUPP)
2014 		error = VOP_SETEXTATTR(vp, attrnamespace, attrname, NULL,
2015 		    NULL, td);
2016 
2017 	if ((ioflg & IO_NODELOCKED) == 0) {
2018 		vn_finished_write(mp);
2019 		VOP_UNLOCK(vp, 0);
2020 	}
2021 
2022 	return (error);
2023 }
2024 
2025 static int
2026 vn_get_ino_alloc_vget(struct mount *mp, void *arg, int lkflags,
2027     struct vnode **rvp)
2028 {
2029 
2030 	return (VFS_VGET(mp, *(ino_t *)arg, lkflags, rvp));
2031 }
2032 
2033 int
2034 vn_vget_ino(struct vnode *vp, ino_t ino, int lkflags, struct vnode **rvp)
2035 {
2036 
2037 	return (vn_vget_ino_gen(vp, vn_get_ino_alloc_vget, &ino,
2038 	    lkflags, rvp));
2039 }
2040 
2041 int
2042 vn_vget_ino_gen(struct vnode *vp, vn_get_ino_t alloc, void *alloc_arg,
2043     int lkflags, struct vnode **rvp)
2044 {
2045 	struct mount *mp;
2046 	int ltype, error;
2047 
2048 	ASSERT_VOP_LOCKED(vp, "vn_vget_ino_get");
2049 	mp = vp->v_mount;
2050 	ltype = VOP_ISLOCKED(vp);
2051 	KASSERT(ltype == LK_EXCLUSIVE || ltype == LK_SHARED,
2052 	    ("vn_vget_ino: vp not locked"));
2053 	error = vfs_busy(mp, MBF_NOWAIT);
2054 	if (error != 0) {
2055 		vfs_ref(mp);
2056 		VOP_UNLOCK(vp, 0);
2057 		error = vfs_busy(mp, 0);
2058 		vn_lock(vp, ltype | LK_RETRY);
2059 		vfs_rel(mp);
2060 		if (error != 0)
2061 			return (ENOENT);
2062 		if (vp->v_iflag & VI_DOOMED) {
2063 			vfs_unbusy(mp);
2064 			return (ENOENT);
2065 		}
2066 	}
2067 	VOP_UNLOCK(vp, 0);
2068 	error = alloc(mp, alloc_arg, lkflags, rvp);
2069 	vfs_unbusy(mp);
2070 	if (*rvp != vp)
2071 		vn_lock(vp, ltype | LK_RETRY);
2072 	if (vp->v_iflag & VI_DOOMED) {
2073 		if (error == 0) {
2074 			if (*rvp == vp)
2075 				vunref(vp);
2076 			else
2077 				vput(*rvp);
2078 		}
2079 		error = ENOENT;
2080 	}
2081 	return (error);
2082 }
2083 
2084 int
2085 vn_rlimit_fsize(const struct vnode *vp, const struct uio *uio,
2086     struct thread *td)
2087 {
2088 
2089 	if (vp->v_type != VREG || td == NULL)
2090 		return (0);
2091 	if ((uoff_t)uio->uio_offset + uio->uio_resid >
2092 	    lim_cur(td, RLIMIT_FSIZE)) {
2093 		PROC_LOCK(td->td_proc);
2094 		kern_psignal(td->td_proc, SIGXFSZ);
2095 		PROC_UNLOCK(td->td_proc);
2096 		return (EFBIG);
2097 	}
2098 	return (0);
2099 }
2100 
2101 int
2102 vn_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
2103     struct thread *td)
2104 {
2105 	struct vnode *vp;
2106 
2107 	vp = fp->f_vnode;
2108 #ifdef AUDIT
2109 	vn_lock(vp, LK_SHARED | LK_RETRY);
2110 	AUDIT_ARG_VNODE1(vp);
2111 	VOP_UNLOCK(vp, 0);
2112 #endif
2113 	return (setfmode(td, active_cred, vp, mode));
2114 }
2115 
2116 int
2117 vn_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
2118     struct thread *td)
2119 {
2120 	struct vnode *vp;
2121 
2122 	vp = fp->f_vnode;
2123 #ifdef AUDIT
2124 	vn_lock(vp, LK_SHARED | LK_RETRY);
2125 	AUDIT_ARG_VNODE1(vp);
2126 	VOP_UNLOCK(vp, 0);
2127 #endif
2128 	return (setfown(td, active_cred, vp, uid, gid));
2129 }
2130 
2131 void
2132 vn_pages_remove(struct vnode *vp, vm_pindex_t start, vm_pindex_t end)
2133 {
2134 	vm_object_t object;
2135 
2136 	if ((object = vp->v_object) == NULL)
2137 		return;
2138 	VM_OBJECT_WLOCK(object);
2139 	vm_object_page_remove(object, start, end, 0);
2140 	VM_OBJECT_WUNLOCK(object);
2141 }
2142 
2143 int
2144 vn_bmap_seekhole(struct vnode *vp, u_long cmd, off_t *off, struct ucred *cred)
2145 {
2146 	struct vattr va;
2147 	daddr_t bn, bnp;
2148 	uint64_t bsize;
2149 	off_t noff;
2150 	int error;
2151 
2152 	KASSERT(cmd == FIOSEEKHOLE || cmd == FIOSEEKDATA,
2153 	    ("Wrong command %lu", cmd));
2154 
2155 	if (vn_lock(vp, LK_SHARED) != 0)
2156 		return (EBADF);
2157 	if (vp->v_type != VREG) {
2158 		error = ENOTTY;
2159 		goto unlock;
2160 	}
2161 	error = VOP_GETATTR(vp, &va, cred);
2162 	if (error != 0)
2163 		goto unlock;
2164 	noff = *off;
2165 	if (noff >= va.va_size) {
2166 		error = ENXIO;
2167 		goto unlock;
2168 	}
2169 	bsize = vp->v_mount->mnt_stat.f_iosize;
2170 	for (bn = noff / bsize; noff < va.va_size; bn++, noff += bsize -
2171 	    noff % bsize) {
2172 		error = VOP_BMAP(vp, bn, NULL, &bnp, NULL, NULL);
2173 		if (error == EOPNOTSUPP) {
2174 			error = ENOTTY;
2175 			goto unlock;
2176 		}
2177 		if ((bnp == -1 && cmd == FIOSEEKHOLE) ||
2178 		    (bnp != -1 && cmd == FIOSEEKDATA)) {
2179 			noff = bn * bsize;
2180 			if (noff < *off)
2181 				noff = *off;
2182 			goto unlock;
2183 		}
2184 	}
2185 	if (noff > va.va_size)
2186 		noff = va.va_size;
2187 	/* noff == va.va_size. There is an implicit hole at the end of file. */
2188 	if (cmd == FIOSEEKDATA)
2189 		error = ENXIO;
2190 unlock:
2191 	VOP_UNLOCK(vp, 0);
2192 	if (error == 0)
2193 		*off = noff;
2194 	return (error);
2195 }
2196 
2197 int
2198 vn_seek(struct file *fp, off_t offset, int whence, struct thread *td)
2199 {
2200 	struct ucred *cred;
2201 	struct vnode *vp;
2202 	struct vattr vattr;
2203 	off_t foffset, size;
2204 	int error, noneg;
2205 
2206 	cred = td->td_ucred;
2207 	vp = fp->f_vnode;
2208 	foffset = foffset_lock(fp, 0);
2209 	noneg = (vp->v_type != VCHR);
2210 	error = 0;
2211 	switch (whence) {
2212 	case L_INCR:
2213 		if (noneg &&
2214 		    (foffset < 0 ||
2215 		    (offset > 0 && foffset > OFF_MAX - offset))) {
2216 			error = EOVERFLOW;
2217 			break;
2218 		}
2219 		offset += foffset;
2220 		break;
2221 	case L_XTND:
2222 		vn_lock(vp, LK_SHARED | LK_RETRY);
2223 		error = VOP_GETATTR(vp, &vattr, cred);
2224 		VOP_UNLOCK(vp, 0);
2225 		if (error)
2226 			break;
2227 
2228 		/*
2229 		 * If the file references a disk device, then fetch
2230 		 * the media size and use that to determine the ending
2231 		 * offset.
2232 		 */
2233 		if (vattr.va_size == 0 && vp->v_type == VCHR &&
2234 		    fo_ioctl(fp, DIOCGMEDIASIZE, &size, cred, td) == 0)
2235 			vattr.va_size = size;
2236 		if (noneg &&
2237 		    (vattr.va_size > OFF_MAX ||
2238 		    (offset > 0 && vattr.va_size > OFF_MAX - offset))) {
2239 			error = EOVERFLOW;
2240 			break;
2241 		}
2242 		offset += vattr.va_size;
2243 		break;
2244 	case L_SET:
2245 		break;
2246 	case SEEK_DATA:
2247 		error = fo_ioctl(fp, FIOSEEKDATA, &offset, cred, td);
2248 		break;
2249 	case SEEK_HOLE:
2250 		error = fo_ioctl(fp, FIOSEEKHOLE, &offset, cred, td);
2251 		break;
2252 	default:
2253 		error = EINVAL;
2254 	}
2255 	if (error == 0 && noneg && offset < 0)
2256 		error = EINVAL;
2257 	if (error != 0)
2258 		goto drop;
2259 	VFS_KNOTE_UNLOCKED(vp, 0);
2260 	td->td_uretoff.tdu_off = offset;
2261 drop:
2262 	foffset_unlock(fp, offset, error != 0 ? FOF_NOUPDATE : 0);
2263 	return (error);
2264 }
2265 
2266 int
2267 vn_utimes_perm(struct vnode *vp, struct vattr *vap, struct ucred *cred,
2268     struct thread *td)
2269 {
2270 	int error;
2271 
2272 	/*
2273 	 * Grant permission if the caller is the owner of the file, or
2274 	 * the super-user, or has ACL_WRITE_ATTRIBUTES permission on
2275 	 * on the file.  If the time pointer is null, then write
2276 	 * permission on the file is also sufficient.
2277 	 *
2278 	 * From NFSv4.1, draft 21, 6.2.1.3.1, Discussion of Mask Attributes:
2279 	 * A user having ACL_WRITE_DATA or ACL_WRITE_ATTRIBUTES
2280 	 * will be allowed to set the times [..] to the current
2281 	 * server time.
2282 	 */
2283 	error = VOP_ACCESSX(vp, VWRITE_ATTRIBUTES, cred, td);
2284 	if (error != 0 && (vap->va_vaflags & VA_UTIMES_NULL) != 0)
2285 		error = VOP_ACCESS(vp, VWRITE, cred, td);
2286 	return (error);
2287 }
2288 
2289 int
2290 vn_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
2291 {
2292 	struct vnode *vp;
2293 	int error;
2294 
2295 	if (fp->f_type == DTYPE_FIFO)
2296 		kif->kf_type = KF_TYPE_FIFO;
2297 	else
2298 		kif->kf_type = KF_TYPE_VNODE;
2299 	vp = fp->f_vnode;
2300 	vref(vp);
2301 	FILEDESC_SUNLOCK(fdp);
2302 	error = vn_fill_kinfo_vnode(vp, kif);
2303 	vrele(vp);
2304 	FILEDESC_SLOCK(fdp);
2305 	return (error);
2306 }
2307 
2308 static inline void
2309 vn_fill_junk(struct kinfo_file *kif)
2310 {
2311 	size_t len, olen;
2312 
2313 	/*
2314 	 * Simulate vn_fullpath returning changing values for a given
2315 	 * vp during e.g. coredump.
2316 	 */
2317 	len = (arc4random() % (sizeof(kif->kf_path) - 2)) + 1;
2318 	olen = strlen(kif->kf_path);
2319 	if (len < olen)
2320 		strcpy(&kif->kf_path[len - 1], "$");
2321 	else
2322 		for (; olen < len; olen++)
2323 			strcpy(&kif->kf_path[olen], "A");
2324 }
2325 
2326 int
2327 vn_fill_kinfo_vnode(struct vnode *vp, struct kinfo_file *kif)
2328 {
2329 	struct vattr va;
2330 	char *fullpath, *freepath;
2331 	int error;
2332 
2333 	kif->kf_un.kf_file.kf_file_type = vntype_to_kinfo(vp->v_type);
2334 	freepath = NULL;
2335 	fullpath = "-";
2336 	error = vn_fullpath(curthread, vp, &fullpath, &freepath);
2337 	if (error == 0) {
2338 		strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2339 	}
2340 	if (freepath != NULL)
2341 		free(freepath, M_TEMP);
2342 
2343 	KFAIL_POINT_CODE(DEBUG_FP, fill_kinfo_vnode__random_path,
2344 		vn_fill_junk(kif);
2345 	);
2346 
2347 	/*
2348 	 * Retrieve vnode attributes.
2349 	 */
2350 	va.va_fsid = VNOVAL;
2351 	va.va_rdev = NODEV;
2352 	vn_lock(vp, LK_SHARED | LK_RETRY);
2353 	error = VOP_GETATTR(vp, &va, curthread->td_ucred);
2354 	VOP_UNLOCK(vp, 0);
2355 	if (error != 0)
2356 		return (error);
2357 	if (va.va_fsid != VNOVAL)
2358 		kif->kf_un.kf_file.kf_file_fsid = va.va_fsid;
2359 	else
2360 		kif->kf_un.kf_file.kf_file_fsid =
2361 		    vp->v_mount->mnt_stat.f_fsid.val[0];
2362 	kif->kf_un.kf_file.kf_file_fsid_freebsd11 =
2363 	    kif->kf_un.kf_file.kf_file_fsid; /* truncate */
2364 	kif->kf_un.kf_file.kf_file_fileid = va.va_fileid;
2365 	kif->kf_un.kf_file.kf_file_mode = MAKEIMODE(va.va_type, va.va_mode);
2366 	kif->kf_un.kf_file.kf_file_size = va.va_size;
2367 	kif->kf_un.kf_file.kf_file_rdev = va.va_rdev;
2368 	kif->kf_un.kf_file.kf_file_rdev_freebsd11 =
2369 	    kif->kf_un.kf_file.kf_file_rdev; /* truncate */
2370 	return (0);
2371 }
2372 
2373 int
2374 vn_mmap(struct file *fp, vm_map_t map, vm_offset_t *addr, vm_size_t size,
2375     vm_prot_t prot, vm_prot_t cap_maxprot, int flags, vm_ooffset_t foff,
2376     struct thread *td)
2377 {
2378 #ifdef HWPMC_HOOKS
2379 	struct pmckern_map_in pkm;
2380 #endif
2381 	struct mount *mp;
2382 	struct vnode *vp;
2383 	vm_object_t object;
2384 	vm_prot_t maxprot;
2385 	boolean_t writecounted;
2386 	int error;
2387 
2388 #if defined(COMPAT_FREEBSD7) || defined(COMPAT_FREEBSD6) || \
2389     defined(COMPAT_FREEBSD5) || defined(COMPAT_FREEBSD4)
2390 	/*
2391 	 * POSIX shared-memory objects are defined to have
2392 	 * kernel persistence, and are not defined to support
2393 	 * read(2)/write(2) -- or even open(2).  Thus, we can
2394 	 * use MAP_ASYNC to trade on-disk coherence for speed.
2395 	 * The shm_open(3) library routine turns on the FPOSIXSHM
2396 	 * flag to request this behavior.
2397 	 */
2398 	if ((fp->f_flag & FPOSIXSHM) != 0)
2399 		flags |= MAP_NOSYNC;
2400 #endif
2401 	vp = fp->f_vnode;
2402 
2403 	/*
2404 	 * Ensure that file and memory protections are
2405 	 * compatible.  Note that we only worry about
2406 	 * writability if mapping is shared; in this case,
2407 	 * current and max prot are dictated by the open file.
2408 	 * XXX use the vnode instead?  Problem is: what
2409 	 * credentials do we use for determination? What if
2410 	 * proc does a setuid?
2411 	 */
2412 	mp = vp->v_mount;
2413 	if (mp != NULL && (mp->mnt_flag & MNT_NOEXEC) != 0) {
2414 		maxprot = VM_PROT_NONE;
2415 		if ((prot & VM_PROT_EXECUTE) != 0)
2416 			return (EACCES);
2417 	} else
2418 		maxprot = VM_PROT_EXECUTE;
2419 	if ((fp->f_flag & FREAD) != 0)
2420 		maxprot |= VM_PROT_READ;
2421 	else if ((prot & VM_PROT_READ) != 0)
2422 		return (EACCES);
2423 
2424 	/*
2425 	 * If we are sharing potential changes via MAP_SHARED and we
2426 	 * are trying to get write permission although we opened it
2427 	 * without asking for it, bail out.
2428 	 */
2429 	if ((flags & MAP_SHARED) != 0) {
2430 		if ((fp->f_flag & FWRITE) != 0)
2431 			maxprot |= VM_PROT_WRITE;
2432 		else if ((prot & VM_PROT_WRITE) != 0)
2433 			return (EACCES);
2434 	} else {
2435 		maxprot |= VM_PROT_WRITE;
2436 		cap_maxprot |= VM_PROT_WRITE;
2437 	}
2438 	maxprot &= cap_maxprot;
2439 
2440 	/*
2441 	 * For regular files and shared memory, POSIX requires that
2442 	 * the value of foff be a legitimate offset within the data
2443 	 * object.  In particular, negative offsets are invalid.
2444 	 * Blocking negative offsets and overflows here avoids
2445 	 * possible wraparound or user-level access into reserved
2446 	 * ranges of the data object later.  In contrast, POSIX does
2447 	 * not dictate how offsets are used by device drivers, so in
2448 	 * the case of a device mapping a negative offset is passed
2449 	 * on.
2450 	 */
2451 	if (
2452 #ifdef _LP64
2453 	    size > OFF_MAX ||
2454 #endif
2455 	    foff < 0 || foff > OFF_MAX - size)
2456 		return (EINVAL);
2457 
2458 	writecounted = FALSE;
2459 	error = vm_mmap_vnode(td, size, prot, &maxprot, &flags, vp,
2460 	    &foff, &object, &writecounted);
2461 	if (error != 0)
2462 		return (error);
2463 	error = vm_mmap_object(map, addr, size, prot, maxprot, flags, object,
2464 	    foff, writecounted, td);
2465 	if (error != 0) {
2466 		/*
2467 		 * If this mapping was accounted for in the vnode's
2468 		 * writecount, then undo that now.
2469 		 */
2470 		if (writecounted)
2471 			vnode_pager_release_writecount(object, 0, size);
2472 		vm_object_deallocate(object);
2473 	}
2474 #ifdef HWPMC_HOOKS
2475 	/* Inform hwpmc(4) if an executable is being mapped. */
2476 	if (PMC_HOOK_INSTALLED(PMC_FN_MMAP)) {
2477 		if ((prot & VM_PROT_EXECUTE) != 0 && error == 0) {
2478 			pkm.pm_file = vp;
2479 			pkm.pm_address = (uintptr_t) *addr;
2480 			PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_MMAP, (void *) &pkm);
2481 		}
2482 	}
2483 #endif
2484 	return (error);
2485 }
2486 
2487 void
2488 vn_fsid(struct vnode *vp, struct vattr *va)
2489 {
2490 	fsid_t *f;
2491 
2492 	f = &vp->v_mount->mnt_stat.f_fsid;
2493 	va->va_fsid = (uint32_t)f->val[1];
2494 	va->va_fsid <<= sizeof(f->val[1]) * NBBY;
2495 	va->va_fsid += (uint32_t)f->val[0];
2496 }
2497 
2498 int
2499 vn_fsync_buf(struct vnode *vp, int waitfor)
2500 {
2501 	struct buf *bp, *nbp;
2502 	struct bufobj *bo;
2503 	struct mount *mp;
2504 	int error, maxretry;
2505 
2506 	error = 0;
2507 	maxretry = 10000;     /* large, arbitrarily chosen */
2508 	mp = NULL;
2509 	if (vp->v_type == VCHR) {
2510 		VI_LOCK(vp);
2511 		mp = vp->v_rdev->si_mountpt;
2512 		VI_UNLOCK(vp);
2513 	}
2514 	bo = &vp->v_bufobj;
2515 	BO_LOCK(bo);
2516 loop1:
2517 	/*
2518 	 * MARK/SCAN initialization to avoid infinite loops.
2519 	 */
2520         TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
2521 		bp->b_vflags &= ~BV_SCANNED;
2522 		bp->b_error = 0;
2523 	}
2524 
2525 	/*
2526 	 * Flush all dirty buffers associated with a vnode.
2527 	 */
2528 loop2:
2529 	TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2530 		if ((bp->b_vflags & BV_SCANNED) != 0)
2531 			continue;
2532 		bp->b_vflags |= BV_SCANNED;
2533 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL)) {
2534 			if (waitfor != MNT_WAIT)
2535 				continue;
2536 			if (BUF_LOCK(bp,
2537 			    LK_EXCLUSIVE | LK_INTERLOCK | LK_SLEEPFAIL,
2538 			    BO_LOCKPTR(bo)) != 0) {
2539 				BO_LOCK(bo);
2540 				goto loop1;
2541 			}
2542 			BO_LOCK(bo);
2543 		}
2544 		BO_UNLOCK(bo);
2545 		KASSERT(bp->b_bufobj == bo,
2546 		    ("bp %p wrong b_bufobj %p should be %p",
2547 		    bp, bp->b_bufobj, bo));
2548 		if ((bp->b_flags & B_DELWRI) == 0)
2549 			panic("fsync: not dirty");
2550 		if ((vp->v_object != NULL) && (bp->b_flags & B_CLUSTEROK)) {
2551 			vfs_bio_awrite(bp);
2552 		} else {
2553 			bremfree(bp);
2554 			bawrite(bp);
2555 		}
2556 		if (maxretry < 1000)
2557 			pause("dirty", hz < 1000 ? 1 : hz / 1000);
2558 		BO_LOCK(bo);
2559 		goto loop2;
2560 	}
2561 
2562 	/*
2563 	 * If synchronous the caller expects us to completely resolve all
2564 	 * dirty buffers in the system.  Wait for in-progress I/O to
2565 	 * complete (which could include background bitmap writes), then
2566 	 * retry if dirty blocks still exist.
2567 	 */
2568 	if (waitfor == MNT_WAIT) {
2569 		bufobj_wwait(bo, 0, 0);
2570 		if (bo->bo_dirty.bv_cnt > 0) {
2571 			/*
2572 			 * If we are unable to write any of these buffers
2573 			 * then we fail now rather than trying endlessly
2574 			 * to write them out.
2575 			 */
2576 			TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
2577 				if ((error = bp->b_error) != 0)
2578 					break;
2579 			if ((mp != NULL && mp->mnt_secondary_writes > 0) ||
2580 			    (error == 0 && --maxretry >= 0))
2581 				goto loop1;
2582 			if (error == 0)
2583 				error = EAGAIN;
2584 		}
2585 	}
2586 	BO_UNLOCK(bo);
2587 	if (error != 0)
2588 		vn_printf(vp, "fsync: giving up on dirty (error = %d) ", error);
2589 
2590 	return (error);
2591 }
2592