2 * SPDX-License-Identifier: BSD-3-Clause
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.
12 * Copyright (c) 2012 Konstantin Belousov <kib@FreeBSD.org>
13 * Copyright (c) 2013, 2014 The FreeBSD Foundation
15 * Portions of this software were developed by Konstantin Belousov
16 * under sponsorship from the FreeBSD Foundation.
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions
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.
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
42 * @(#)vfs_vnops.c 8.2 (Berkeley) 1/21/94
45 #include <sys/cdefs.h>
46 __FBSDID("$FreeBSD$");
48 #include "opt_hwpmc_hooks.h"
50 #include <sys/param.h>
51 #include <sys/systm.h>
54 #include <sys/fcntl.h>
61 #include <sys/limits.h>
64 #include <sys/mount.h>
65 #include <sys/mutex.h>
66 #include <sys/namei.h>
67 #include <sys/vnode.h>
70 #include <sys/filio.h>
71 #include <sys/resourcevar.h>
72 #include <sys/rwlock.h>
74 #include <sys/sleepqueue.h>
75 #include <sys/sysctl.h>
76 #include <sys/ttycom.h>
78 #include <sys/syslog.h>
79 #include <sys/unistd.h>
82 #include <security/audit/audit.h>
83 #include <security/mac/mac_framework.h>
86 #include <vm/vm_extern.h>
88 #include <vm/vm_map.h>
89 #include <vm/vm_object.h>
90 #include <vm/vm_page.h>
91 #include <vm/vm_pager.h>
94 #include <sys/pmckern.h>
97 static fo_rdwr_t vn_read;
98 static fo_rdwr_t vn_write;
99 static fo_rdwr_t vn_io_fault;
100 static fo_truncate_t vn_truncate;
101 static fo_ioctl_t vn_ioctl;
102 static fo_poll_t vn_poll;
103 static fo_kqfilter_t vn_kqfilter;
104 static fo_stat_t vn_statfile;
105 static fo_close_t vn_closefile;
106 static fo_mmap_t vn_mmap;
107 static fo_fallocate_t vn_fallocate;
109 struct fileops vnops = {
110 .fo_read = vn_io_fault,
111 .fo_write = vn_io_fault,
112 .fo_truncate = vn_truncate,
113 .fo_ioctl = vn_ioctl,
115 .fo_kqfilter = vn_kqfilter,
116 .fo_stat = vn_statfile,
117 .fo_close = vn_closefile,
118 .fo_chmod = vn_chmod,
119 .fo_chown = vn_chown,
120 .fo_sendfile = vn_sendfile,
122 .fo_fill_kinfo = vn_fill_kinfo,
124 .fo_fallocate = vn_fallocate,
125 .fo_flags = DFLAG_PASSABLE | DFLAG_SEEKABLE
128 const u_int io_hold_cnt = 16;
129 static int vn_io_fault_enable = 1;
130 SYSCTL_INT(_debug, OID_AUTO, vn_io_fault_enable, CTLFLAG_RWTUN,
131 &vn_io_fault_enable, 0, "Enable vn_io_fault lock avoidance");
132 static int vn_io_fault_prefault = 0;
133 SYSCTL_INT(_debug, OID_AUTO, vn_io_fault_prefault, CTLFLAG_RWTUN,
134 &vn_io_fault_prefault, 0, "Enable vn_io_fault prefaulting");
135 static int vn_io_pgcache_read_enable = 1;
136 SYSCTL_INT(_debug, OID_AUTO, vn_io_pgcache_read_enable, CTLFLAG_RWTUN,
137 &vn_io_pgcache_read_enable, 0,
138 "Enable copying from page cache for reads, avoiding fs");
139 static u_long vn_io_faults_cnt;
140 SYSCTL_ULONG(_debug, OID_AUTO, vn_io_faults, CTLFLAG_RD,
141 &vn_io_faults_cnt, 0, "Count of vn_io_fault lock avoidance triggers");
143 static int vfs_allow_read_dir = 0;
144 SYSCTL_INT(_security_bsd, OID_AUTO, allow_read_dir, CTLFLAG_RW,
145 &vfs_allow_read_dir, 0,
146 "Enable read(2) of directory by root for filesystems that support it");
149 * Returns true if vn_io_fault mode of handling the i/o request should
153 do_vn_io_fault(struct vnode *vp, struct uio *uio)
157 return (uio->uio_segflg == UIO_USERSPACE && vp->v_type == VREG &&
158 (mp = vp->v_mount) != NULL &&
159 (mp->mnt_kern_flag & MNTK_NO_IOPF) != 0 && vn_io_fault_enable);
163 * Structure used to pass arguments to vn_io_fault1(), to do either
164 * file- or vnode-based I/O calls.
166 struct vn_io_fault_args {
174 struct fop_args_tag {
178 struct vop_args_tag {
184 static int vn_io_fault1(struct vnode *vp, struct uio *uio,
185 struct vn_io_fault_args *args, struct thread *td);
188 vn_open(struct nameidata *ndp, int *flagp, int cmode, struct file *fp)
190 struct thread *td = ndp->ni_cnd.cn_thread;
192 return (vn_open_cred(ndp, flagp, cmode, 0, td->td_ucred, fp));
196 open2nameif(int fmode, u_int vn_open_flags)
200 res = ISOPEN | LOCKLEAF;
201 if ((fmode & O_BENEATH) != 0)
203 if ((fmode & O_RESOLVE_BENEATH) != 0)
205 if ((vn_open_flags & VN_OPEN_NOAUDIT) == 0)
207 if ((vn_open_flags & VN_OPEN_NOCAPCHECK) != 0)
213 * Common code for vnode open operations via a name lookup.
214 * Lookup the vnode and invoke VOP_CREATE if needed.
215 * Check permissions, and call the VOP_OPEN or VOP_CREATE routine.
217 * Note that this does NOT free nameidata for the successful case,
218 * due to the NDINIT being done elsewhere.
221 vn_open_cred(struct nameidata *ndp, int *flagp, int cmode, u_int vn_open_flags,
222 struct ucred *cred, struct file *fp)
226 struct thread *td = ndp->ni_cnd.cn_thread;
228 struct vattr *vap = &vat;
233 if ((fmode & (O_CREAT | O_EXCL | O_DIRECTORY)) == (O_CREAT |
234 O_EXCL | O_DIRECTORY))
236 else if ((fmode & (O_CREAT | O_DIRECTORY)) == O_CREAT) {
237 ndp->ni_cnd.cn_nameiop = CREATE;
238 ndp->ni_cnd.cn_flags = open2nameif(fmode, vn_open_flags);
240 * Set NOCACHE to avoid flushing the cache when
241 * rolling in many files at once.
243 ndp->ni_cnd.cn_flags |= LOCKPARENT | NOCACHE;
244 if ((fmode & O_EXCL) == 0 && (fmode & O_NOFOLLOW) == 0)
245 ndp->ni_cnd.cn_flags |= FOLLOW;
246 if ((vn_open_flags & VN_OPEN_INVFS) == 0)
248 if ((error = namei(ndp)) != 0)
250 if (ndp->ni_vp == NULL) {
253 vap->va_mode = cmode;
255 vap->va_vaflags |= VA_EXCLUSIVE;
256 if (vn_start_write(ndp->ni_dvp, &mp, V_NOWAIT) != 0) {
257 NDFREE(ndp, NDF_ONLY_PNBUF);
259 if ((error = vn_start_write(NULL, &mp,
260 V_XSLEEP | PCATCH)) != 0)
264 if ((vn_open_flags & VN_OPEN_NAMECACHE) != 0)
265 ndp->ni_cnd.cn_flags |= MAKEENTRY;
267 error = mac_vnode_check_create(cred, ndp->ni_dvp,
271 error = VOP_CREATE(ndp->ni_dvp, &ndp->ni_vp,
274 vn_finished_write(mp);
276 NDFREE(ndp, NDF_ONLY_PNBUF);
282 if (ndp->ni_dvp == ndp->ni_vp)
288 if (fmode & O_EXCL) {
292 if (vp->v_type == VDIR) {
299 ndp->ni_cnd.cn_nameiop = LOOKUP;
300 ndp->ni_cnd.cn_flags = open2nameif(fmode, vn_open_flags);
301 ndp->ni_cnd.cn_flags |= (fmode & O_NOFOLLOW) != 0 ? NOFOLLOW :
303 if ((fmode & FWRITE) == 0)
304 ndp->ni_cnd.cn_flags |= LOCKSHARED;
305 if ((error = namei(ndp)) != 0)
309 error = vn_open_vnode(vp, fmode, cred, td, fp);
315 NDFREE(ndp, NDF_ONLY_PNBUF);
323 vn_open_vnode_advlock(struct vnode *vp, int fmode, struct file *fp)
326 int error, lock_flags, type;
328 ASSERT_VOP_LOCKED(vp, "vn_open_vnode_advlock");
329 if ((fmode & (O_EXLOCK | O_SHLOCK)) == 0)
331 KASSERT(fp != NULL, ("open with flock requires fp"));
332 if (fp->f_type != DTYPE_NONE && fp->f_type != DTYPE_VNODE)
335 lock_flags = VOP_ISLOCKED(vp);
338 lf.l_whence = SEEK_SET;
341 lf.l_type = (fmode & O_EXLOCK) != 0 ? F_WRLCK : F_RDLCK;
343 if ((fmode & FNONBLOCK) == 0)
345 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, type);
347 fp->f_flag |= FHASLOCK;
349 vn_lock(vp, lock_flags | LK_RETRY);
350 if (error == 0 && VN_IS_DOOMED(vp))
356 * Common code for vnode open operations once a vnode is located.
357 * Check permissions, and call the VOP_OPEN routine.
360 vn_open_vnode(struct vnode *vp, int fmode, struct ucred *cred,
361 struct thread *td, struct file *fp)
366 if (vp->v_type == VLNK)
368 if (vp->v_type == VSOCK)
370 if (vp->v_type != VDIR && fmode & O_DIRECTORY)
373 if (fmode & (FWRITE | O_TRUNC)) {
374 if (vp->v_type == VDIR)
382 if ((fmode & O_APPEND) && (fmode & FWRITE))
387 if (fmode & O_VERIFY)
389 error = mac_vnode_check_open(cred, vp, accmode);
393 accmode &= ~(VCREAT | VVERIFY);
395 if ((fmode & O_CREAT) == 0 && accmode != 0) {
396 error = VOP_ACCESS(vp, accmode, cred, td);
400 if (vp->v_type == VFIFO && VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
401 vn_lock(vp, LK_UPGRADE | LK_RETRY);
402 error = VOP_OPEN(vp, fmode, cred, td, fp);
406 error = vn_open_vnode_advlock(vp, fmode, fp);
407 if (error == 0 && (fmode & FWRITE) != 0) {
408 error = VOP_ADD_WRITECOUNT(vp, 1);
410 CTR3(KTR_VFS, "%s: vp %p v_writecount increased to %d",
411 __func__, vp, vp->v_writecount);
416 * Error from advlock or VOP_ADD_WRITECOUNT() still requires
417 * calling VOP_CLOSE() to pair with earlier VOP_OPEN().
418 * Arrange for that by having fdrop() to use vn_closefile().
421 fp->f_flag |= FOPENFAILED;
423 if (fp->f_ops == &badfileops) {
424 fp->f_type = DTYPE_VNODE;
430 ASSERT_VOP_LOCKED(vp, "vn_open_vnode");
436 * Check for write permissions on the specified vnode.
437 * Prototype text segments cannot be written.
441 vn_writechk(struct vnode *vp)
444 ASSERT_VOP_LOCKED(vp, "vn_writechk");
446 * If there's shared text associated with
447 * the vnode, try to free it up once. If
448 * we fail, we can't allow writing.
460 vn_close1(struct vnode *vp, int flags, struct ucred *file_cred,
461 struct thread *td, bool keep_ref)
464 int error, lock_flags;
466 if (vp->v_type != VFIFO && (flags & FWRITE) == 0 &&
467 MNT_EXTENDED_SHARED(vp->v_mount))
468 lock_flags = LK_SHARED;
470 lock_flags = LK_EXCLUSIVE;
472 vn_start_write(vp, &mp, V_WAIT);
473 vn_lock(vp, lock_flags | LK_RETRY);
474 AUDIT_ARG_VNODE1(vp);
475 if ((flags & (FWRITE | FOPENFAILED)) == FWRITE) {
476 VOP_ADD_WRITECOUNT_CHECKED(vp, -1);
477 CTR3(KTR_VFS, "%s: vp %p v_writecount decreased to %d",
478 __func__, vp, vp->v_writecount);
480 error = VOP_CLOSE(vp, flags, file_cred, td);
485 vn_finished_write(mp);
490 vn_close(struct vnode *vp, int flags, struct ucred *file_cred,
494 return (vn_close1(vp, flags, file_cred, td, false));
498 * Heuristic to detect sequential operation.
501 sequential_heuristic(struct uio *uio, struct file *fp)
505 ASSERT_VOP_LOCKED(fp->f_vnode, __func__);
508 if (fp->f_flag & FRDAHEAD)
509 return (fp->f_seqcount[rw] << IO_SEQSHIFT);
512 * Offset 0 is handled specially. open() sets f_seqcount to 1 so
513 * that the first I/O is normally considered to be slightly
514 * sequential. Seeking to offset 0 doesn't change sequentiality
515 * unless previous seeks have reduced f_seqcount to 0, in which
516 * case offset 0 is not special.
518 if ((uio->uio_offset == 0 && fp->f_seqcount[rw] > 0) ||
519 uio->uio_offset == fp->f_nextoff[rw]) {
521 * f_seqcount is in units of fixed-size blocks so that it
522 * depends mainly on the amount of sequential I/O and not
523 * much on the number of sequential I/O's. The fixed size
524 * of 16384 is hard-coded here since it is (not quite) just
525 * a magic size that works well here. This size is more
526 * closely related to the best I/O size for real disks than
527 * to any block size used by software.
529 if (uio->uio_resid >= IO_SEQMAX * 16384)
530 fp->f_seqcount[rw] = IO_SEQMAX;
532 fp->f_seqcount[rw] += howmany(uio->uio_resid, 16384);
533 if (fp->f_seqcount[rw] > IO_SEQMAX)
534 fp->f_seqcount[rw] = IO_SEQMAX;
536 return (fp->f_seqcount[rw] << IO_SEQSHIFT);
539 /* Not sequential. Quickly draw-down sequentiality. */
540 if (fp->f_seqcount[rw] > 1)
541 fp->f_seqcount[rw] = 1;
543 fp->f_seqcount[rw] = 0;
548 * Package up an I/O request on a vnode into a uio and do it.
551 vn_rdwr(enum uio_rw rw, struct vnode *vp, void *base, int len, off_t offset,
552 enum uio_seg segflg, int ioflg, struct ucred *active_cred,
553 struct ucred *file_cred, ssize_t *aresid, struct thread *td)
560 struct vn_io_fault_args args;
561 int error, lock_flags;
563 if (offset < 0 && vp->v_type != VCHR)
565 auio.uio_iov = &aiov;
567 aiov.iov_base = base;
569 auio.uio_resid = len;
570 auio.uio_offset = offset;
571 auio.uio_segflg = segflg;
576 if ((ioflg & IO_NODELOCKED) == 0) {
577 if ((ioflg & IO_RANGELOCKED) == 0) {
578 if (rw == UIO_READ) {
579 rl_cookie = vn_rangelock_rlock(vp, offset,
582 rl_cookie = vn_rangelock_wlock(vp, offset,
588 if (rw == UIO_WRITE) {
589 if (vp->v_type != VCHR &&
590 (error = vn_start_write(vp, &mp, V_WAIT | PCATCH))
593 if (MNT_SHARED_WRITES(mp) ||
594 ((mp == NULL) && MNT_SHARED_WRITES(vp->v_mount)))
595 lock_flags = LK_SHARED;
597 lock_flags = LK_EXCLUSIVE;
599 lock_flags = LK_SHARED;
600 vn_lock(vp, lock_flags | LK_RETRY);
604 ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
606 if ((ioflg & IO_NOMACCHECK) == 0) {
608 error = mac_vnode_check_read(active_cred, file_cred,
611 error = mac_vnode_check_write(active_cred, file_cred,
616 if (file_cred != NULL)
620 if (do_vn_io_fault(vp, &auio)) {
621 args.kind = VN_IO_FAULT_VOP;
624 args.args.vop_args.vp = vp;
625 error = vn_io_fault1(vp, &auio, &args, td);
626 } else if (rw == UIO_READ) {
627 error = VOP_READ(vp, &auio, ioflg, cred);
628 } else /* if (rw == UIO_WRITE) */ {
629 error = VOP_WRITE(vp, &auio, ioflg, cred);
633 *aresid = auio.uio_resid;
635 if (auio.uio_resid && error == 0)
637 if ((ioflg & IO_NODELOCKED) == 0) {
640 vn_finished_write(mp);
643 if (rl_cookie != NULL)
644 vn_rangelock_unlock(vp, rl_cookie);
649 * Package up an I/O request on a vnode into a uio and do it. The I/O
650 * request is split up into smaller chunks and we try to avoid saturating
651 * the buffer cache while potentially holding a vnode locked, so we
652 * check bwillwrite() before calling vn_rdwr(). We also call kern_yield()
653 * to give other processes a chance to lock the vnode (either other processes
654 * core'ing the same binary, or unrelated processes scanning the directory).
657 vn_rdwr_inchunks(enum uio_rw rw, struct vnode *vp, void *base, size_t len,
658 off_t offset, enum uio_seg segflg, int ioflg, struct ucred *active_cred,
659 struct ucred *file_cred, size_t *aresid, struct thread *td)
668 * Force `offset' to a multiple of MAXBSIZE except possibly
669 * for the first chunk, so that filesystems only need to
670 * write full blocks except possibly for the first and last
673 chunk = MAXBSIZE - (uoff_t)offset % MAXBSIZE;
677 if (rw != UIO_READ && vp->v_type == VREG)
680 error = vn_rdwr(rw, vp, base, chunk, offset, segflg,
681 ioflg, active_cred, file_cred, &iaresid, td);
682 len -= chunk; /* aresid calc already includes length */
686 base = (char *)base + chunk;
687 kern_yield(PRI_USER);
690 *aresid = len + iaresid;
694 #if OFF_MAX <= LONG_MAX
696 foffset_lock(struct file *fp, int flags)
698 volatile short *flagsp;
702 KASSERT((flags & FOF_OFFSET) == 0, ("FOF_OFFSET passed"));
704 if ((flags & FOF_NOLOCK) != 0)
705 return (atomic_load_long(&fp->f_offset));
708 * According to McKusick the vn lock was protecting f_offset here.
709 * It is now protected by the FOFFSET_LOCKED flag.
711 flagsp = &fp->f_vnread_flags;
712 if (atomic_cmpset_acq_16(flagsp, 0, FOFFSET_LOCKED))
713 return (atomic_load_long(&fp->f_offset));
715 sleepq_lock(&fp->f_vnread_flags);
716 state = atomic_load_16(flagsp);
718 if ((state & FOFFSET_LOCKED) == 0) {
719 if (!atomic_fcmpset_acq_16(flagsp, &state,
724 if ((state & FOFFSET_LOCK_WAITING) == 0) {
725 if (!atomic_fcmpset_acq_16(flagsp, &state,
726 state | FOFFSET_LOCK_WAITING))
730 sleepq_add(&fp->f_vnread_flags, NULL, "vofflock", 0, 0);
731 sleepq_wait(&fp->f_vnread_flags, PUSER -1);
733 sleepq_lock(&fp->f_vnread_flags);
734 state = atomic_load_16(flagsp);
736 res = atomic_load_long(&fp->f_offset);
737 sleepq_release(&fp->f_vnread_flags);
742 foffset_unlock(struct file *fp, off_t val, int flags)
744 volatile short *flagsp;
747 KASSERT((flags & FOF_OFFSET) == 0, ("FOF_OFFSET passed"));
749 if ((flags & FOF_NOUPDATE) == 0)
750 atomic_store_long(&fp->f_offset, val);
751 if ((flags & FOF_NEXTOFF_R) != 0)
752 fp->f_nextoff[UIO_READ] = val;
753 if ((flags & FOF_NEXTOFF_W) != 0)
754 fp->f_nextoff[UIO_WRITE] = val;
756 if ((flags & FOF_NOLOCK) != 0)
759 flagsp = &fp->f_vnread_flags;
760 state = atomic_load_16(flagsp);
761 if ((state & FOFFSET_LOCK_WAITING) == 0 &&
762 atomic_cmpset_rel_16(flagsp, state, 0))
765 sleepq_lock(&fp->f_vnread_flags);
766 MPASS((fp->f_vnread_flags & FOFFSET_LOCKED) != 0);
767 MPASS((fp->f_vnread_flags & FOFFSET_LOCK_WAITING) != 0);
768 fp->f_vnread_flags = 0;
769 sleepq_broadcast(&fp->f_vnread_flags, SLEEPQ_SLEEP, 0, 0);
770 sleepq_release(&fp->f_vnread_flags);
774 foffset_lock(struct file *fp, int flags)
779 KASSERT((flags & FOF_OFFSET) == 0, ("FOF_OFFSET passed"));
781 mtxp = mtx_pool_find(mtxpool_sleep, fp);
783 if ((flags & FOF_NOLOCK) == 0) {
784 while (fp->f_vnread_flags & FOFFSET_LOCKED) {
785 fp->f_vnread_flags |= FOFFSET_LOCK_WAITING;
786 msleep(&fp->f_vnread_flags, mtxp, PUSER -1,
789 fp->f_vnread_flags |= FOFFSET_LOCKED;
797 foffset_unlock(struct file *fp, off_t val, int flags)
801 KASSERT((flags & FOF_OFFSET) == 0, ("FOF_OFFSET passed"));
803 mtxp = mtx_pool_find(mtxpool_sleep, fp);
805 if ((flags & FOF_NOUPDATE) == 0)
807 if ((flags & FOF_NEXTOFF_R) != 0)
808 fp->f_nextoff[UIO_READ] = val;
809 if ((flags & FOF_NEXTOFF_W) != 0)
810 fp->f_nextoff[UIO_WRITE] = val;
811 if ((flags & FOF_NOLOCK) == 0) {
812 KASSERT((fp->f_vnread_flags & FOFFSET_LOCKED) != 0,
813 ("Lost FOFFSET_LOCKED"));
814 if (fp->f_vnread_flags & FOFFSET_LOCK_WAITING)
815 wakeup(&fp->f_vnread_flags);
816 fp->f_vnread_flags = 0;
823 foffset_lock_uio(struct file *fp, struct uio *uio, int flags)
826 if ((flags & FOF_OFFSET) == 0)
827 uio->uio_offset = foffset_lock(fp, flags);
831 foffset_unlock_uio(struct file *fp, struct uio *uio, int flags)
834 if ((flags & FOF_OFFSET) == 0)
835 foffset_unlock(fp, uio->uio_offset, flags);
839 get_advice(struct file *fp, struct uio *uio)
844 ret = POSIX_FADV_NORMAL;
845 if (fp->f_advice == NULL || fp->f_vnode->v_type != VREG)
848 mtxp = mtx_pool_find(mtxpool_sleep, fp);
850 if (fp->f_advice != NULL &&
851 uio->uio_offset >= fp->f_advice->fa_start &&
852 uio->uio_offset + uio->uio_resid <= fp->f_advice->fa_end)
853 ret = fp->f_advice->fa_advice;
859 vn_read_from_obj(struct vnode *vp, struct uio *uio)
862 vm_page_t ma[io_hold_cnt + 2];
868 MPASS(uio->uio_resid <= ptoa(io_hold_cnt + 2));
870 MPASS(obj->type == OBJT_VNODE);
873 * Depends on type stability of vm_objects.
875 vm_object_pip_add(obj, 1);
876 if ((obj->flags & OBJ_DEAD) != 0) {
878 * Note that object might be already reused from the
879 * vnode, and the OBJ_DEAD flag cleared. This is fine,
880 * we recheck for DOOMED vnode state after all pages
881 * are busied, and retract then.
883 * But we check for OBJ_DEAD to ensure that we do not
884 * busy pages while vm_object_terminate_pages()
885 * processes the queue.
891 resid = uio->uio_resid;
892 off = uio->uio_offset;
893 for (i = 0; resid > 0; i++) {
894 MPASS(i < io_hold_cnt + 2);
895 ma[i] = vm_page_grab_unlocked(obj, atop(off),
896 VM_ALLOC_NOCREAT | VM_ALLOC_SBUSY | VM_ALLOC_IGN_SBUSY |
902 * Skip invalid pages. Valid mask can be partial only
903 * at EOF, and we clip later.
905 if (vm_page_none_valid(ma[i])) {
906 vm_page_sunbusy(ma[i]);
919 * Check VIRF_DOOMED after we busied our pages. Since
920 * vgonel() terminates the vnode' vm_object, it cannot
921 * process past pages busied by us.
923 if (VN_IS_DOOMED(vp)) {
928 resid = PAGE_SIZE - (uio->uio_offset & PAGE_MASK) + ptoa(i - 1);
929 if (resid > uio->uio_resid)
930 resid = uio->uio_resid;
933 * Unlocked read of vnp_size is safe because truncation cannot
934 * pass busied page. But we load vnp_size into a local
935 * variable so that possible concurrent extension does not
938 #if defined(__powerpc__) && !defined(__powerpc64__)
939 vsz = obj->un_pager.vnp.vnp_size;
941 vsz = atomic_load_64(&obj->un_pager.vnp.vnp_size);
943 if (uio->uio_offset + resid > vsz)
944 resid = vsz - uio->uio_offset;
946 error = vn_io_fault_pgmove(ma, uio->uio_offset & PAGE_MASK, resid, uio);
949 for (j = 0; j < i; j++) {
951 vm_page_reference(ma[j]);
952 vm_page_sunbusy(ma[j]);
955 vm_object_pip_wakeup(obj);
958 return (uio->uio_resid == 0 ? 0 : EJUSTRETURN);
962 * File table vnode read routine.
965 vn_read(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags,
973 KASSERT(uio->uio_td == td, ("uio_td %p is not td %p",
975 KASSERT(flags & FOF_OFFSET, ("No FOF_OFFSET"));
978 if (fp->f_flag & FNONBLOCK)
980 if (fp->f_flag & O_DIRECT)
984 * Try to read from page cache. VIRF_DOOMED check is racy but
985 * allows us to avoid unneeded work outright.
987 if (vn_io_pgcache_read_enable && !mac_vnode_check_read_enabled() &&
988 (vp->v_irflag & (VIRF_DOOMED | VIRF_PGREAD)) == VIRF_PGREAD) {
989 error = VOP_READ_PGCACHE(vp, uio, ioflag, fp->f_cred);
991 fp->f_nextoff[UIO_READ] = uio->uio_offset;
994 if (error != EJUSTRETURN)
998 advice = get_advice(fp, uio);
999 vn_lock(vp, LK_SHARED | LK_RETRY);
1002 case POSIX_FADV_NORMAL:
1003 case POSIX_FADV_SEQUENTIAL:
1004 case POSIX_FADV_NOREUSE:
1005 ioflag |= sequential_heuristic(uio, fp);
1007 case POSIX_FADV_RANDOM:
1008 /* Disable read-ahead for random I/O. */
1011 orig_offset = uio->uio_offset;
1014 error = mac_vnode_check_read(active_cred, fp->f_cred, vp);
1017 error = VOP_READ(vp, uio, ioflag, fp->f_cred);
1018 fp->f_nextoff[UIO_READ] = uio->uio_offset;
1020 if (error == 0 && advice == POSIX_FADV_NOREUSE &&
1021 orig_offset != uio->uio_offset)
1023 * Use POSIX_FADV_DONTNEED to flush pages and buffers
1024 * for the backing file after a POSIX_FADV_NOREUSE
1027 error = VOP_ADVISE(vp, orig_offset, uio->uio_offset - 1,
1028 POSIX_FADV_DONTNEED);
1033 * File table vnode write routine.
1036 vn_write(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags,
1042 int error, ioflag, lock_flags;
1045 KASSERT(uio->uio_td == td, ("uio_td %p is not td %p",
1047 KASSERT(flags & FOF_OFFSET, ("No FOF_OFFSET"));
1049 if (vp->v_type == VREG)
1052 if (vp->v_type == VREG && (fp->f_flag & O_APPEND))
1053 ioflag |= IO_APPEND;
1054 if (fp->f_flag & FNONBLOCK)
1055 ioflag |= IO_NDELAY;
1056 if (fp->f_flag & O_DIRECT)
1057 ioflag |= IO_DIRECT;
1058 if ((fp->f_flag & O_FSYNC) ||
1059 (vp->v_mount && (vp->v_mount->mnt_flag & MNT_SYNCHRONOUS)))
1062 if (vp->v_type != VCHR &&
1063 (error = vn_start_write(vp, &mp, V_WAIT | PCATCH)) != 0)
1066 advice = get_advice(fp, uio);
1068 if (MNT_SHARED_WRITES(mp) ||
1069 (mp == NULL && MNT_SHARED_WRITES(vp->v_mount))) {
1070 lock_flags = LK_SHARED;
1072 lock_flags = LK_EXCLUSIVE;
1075 vn_lock(vp, lock_flags | LK_RETRY);
1077 case POSIX_FADV_NORMAL:
1078 case POSIX_FADV_SEQUENTIAL:
1079 case POSIX_FADV_NOREUSE:
1080 ioflag |= sequential_heuristic(uio, fp);
1082 case POSIX_FADV_RANDOM:
1083 /* XXX: Is this correct? */
1086 orig_offset = uio->uio_offset;
1089 error = mac_vnode_check_write(active_cred, fp->f_cred, vp);
1092 error = VOP_WRITE(vp, uio, ioflag, fp->f_cred);
1093 fp->f_nextoff[UIO_WRITE] = uio->uio_offset;
1095 if (vp->v_type != VCHR)
1096 vn_finished_write(mp);
1097 if (error == 0 && advice == POSIX_FADV_NOREUSE &&
1098 orig_offset != uio->uio_offset)
1100 * Use POSIX_FADV_DONTNEED to flush pages and buffers
1101 * for the backing file after a POSIX_FADV_NOREUSE
1104 error = VOP_ADVISE(vp, orig_offset, uio->uio_offset - 1,
1105 POSIX_FADV_DONTNEED);
1111 * The vn_io_fault() is a wrapper around vn_read() and vn_write() to
1112 * prevent the following deadlock:
1114 * Assume that the thread A reads from the vnode vp1 into userspace
1115 * buffer buf1 backed by the pages of vnode vp2. If a page in buf1 is
1116 * currently not resident, then system ends up with the call chain
1117 * vn_read() -> VOP_READ(vp1) -> uiomove() -> [Page Fault] ->
1118 * vm_fault(buf1) -> vnode_pager_getpages(vp2) -> VOP_GETPAGES(vp2)
1119 * which establishes lock order vp1->vn_lock, then vp2->vn_lock.
1120 * If, at the same time, thread B reads from vnode vp2 into buffer buf2
1121 * backed by the pages of vnode vp1, and some page in buf2 is not
1122 * resident, we get a reversed order vp2->vn_lock, then vp1->vn_lock.
1124 * To prevent the lock order reversal and deadlock, vn_io_fault() does
1125 * not allow page faults to happen during VOP_READ() or VOP_WRITE().
1126 * Instead, it first tries to do the whole range i/o with pagefaults
1127 * disabled. If all pages in the i/o buffer are resident and mapped,
1128 * VOP will succeed (ignoring the genuine filesystem errors).
1129 * Otherwise, we get back EFAULT, and vn_io_fault() falls back to do
1130 * i/o in chunks, with all pages in the chunk prefaulted and held
1131 * using vm_fault_quick_hold_pages().
1133 * Filesystems using this deadlock avoidance scheme should use the
1134 * array of the held pages from uio, saved in the curthread->td_ma,
1135 * instead of doing uiomove(). A helper function
1136 * vn_io_fault_uiomove() converts uiomove request into
1137 * uiomove_fromphys() over td_ma array.
1139 * Since vnode locks do not cover the whole i/o anymore, rangelocks
1140 * make the current i/o request atomic with respect to other i/os and
1145 * Decode vn_io_fault_args and perform the corresponding i/o.
1148 vn_io_fault_doio(struct vn_io_fault_args *args, struct uio *uio,
1154 save = vm_fault_disable_pagefaults();
1155 switch (args->kind) {
1156 case VN_IO_FAULT_FOP:
1157 error = (args->args.fop_args.doio)(args->args.fop_args.fp,
1158 uio, args->cred, args->flags, td);
1160 case VN_IO_FAULT_VOP:
1161 if (uio->uio_rw == UIO_READ) {
1162 error = VOP_READ(args->args.vop_args.vp, uio,
1163 args->flags, args->cred);
1164 } else if (uio->uio_rw == UIO_WRITE) {
1165 error = VOP_WRITE(args->args.vop_args.vp, uio,
1166 args->flags, args->cred);
1170 panic("vn_io_fault_doio: unknown kind of io %d %d",
1171 args->kind, uio->uio_rw);
1173 vm_fault_enable_pagefaults(save);
1178 vn_io_fault_touch(char *base, const struct uio *uio)
1183 if (r == -1 || (uio->uio_rw == UIO_READ && subyte(base, r) == -1))
1189 vn_io_fault_prefault_user(const struct uio *uio)
1192 const struct iovec *iov;
1197 KASSERT(uio->uio_segflg == UIO_USERSPACE,
1198 ("vn_io_fault_prefault userspace"));
1202 resid = uio->uio_resid;
1203 base = iov->iov_base;
1206 error = vn_io_fault_touch(base, uio);
1209 if (len < PAGE_SIZE) {
1211 error = vn_io_fault_touch(base + len - 1, uio);
1216 if (++i >= uio->uio_iovcnt)
1218 iov = uio->uio_iov + i;
1219 base = iov->iov_base;
1231 * Common code for vn_io_fault(), agnostic to the kind of i/o request.
1232 * Uses vn_io_fault_doio() to make the call to an actual i/o function.
1233 * Used from vn_rdwr() and vn_io_fault(), which encode the i/o request
1234 * into args and call vn_io_fault1() to handle faults during the user
1235 * mode buffer accesses.
1238 vn_io_fault1(struct vnode *vp, struct uio *uio, struct vn_io_fault_args *args,
1241 vm_page_t ma[io_hold_cnt + 2];
1242 struct uio *uio_clone, short_uio;
1243 struct iovec short_iovec[1];
1244 vm_page_t *prev_td_ma;
1246 vm_offset_t addr, end;
1249 int error, cnt, saveheld, prev_td_ma_cnt;
1251 if (vn_io_fault_prefault) {
1252 error = vn_io_fault_prefault_user(uio);
1254 return (error); /* Or ignore ? */
1257 prot = uio->uio_rw == UIO_READ ? VM_PROT_WRITE : VM_PROT_READ;
1260 * The UFS follows IO_UNIT directive and replays back both
1261 * uio_offset and uio_resid if an error is encountered during the
1262 * operation. But, since the iovec may be already advanced,
1263 * uio is still in an inconsistent state.
1265 * Cache a copy of the original uio, which is advanced to the redo
1266 * point using UIO_NOCOPY below.
1268 uio_clone = cloneuio(uio);
1269 resid = uio->uio_resid;
1271 short_uio.uio_segflg = UIO_USERSPACE;
1272 short_uio.uio_rw = uio->uio_rw;
1273 short_uio.uio_td = uio->uio_td;
1275 error = vn_io_fault_doio(args, uio, td);
1276 if (error != EFAULT)
1279 atomic_add_long(&vn_io_faults_cnt, 1);
1280 uio_clone->uio_segflg = UIO_NOCOPY;
1281 uiomove(NULL, resid - uio->uio_resid, uio_clone);
1282 uio_clone->uio_segflg = uio->uio_segflg;
1284 saveheld = curthread_pflags_set(TDP_UIOHELD);
1285 prev_td_ma = td->td_ma;
1286 prev_td_ma_cnt = td->td_ma_cnt;
1288 while (uio_clone->uio_resid != 0) {
1289 len = uio_clone->uio_iov->iov_len;
1291 KASSERT(uio_clone->uio_iovcnt >= 1,
1292 ("iovcnt underflow"));
1293 uio_clone->uio_iov++;
1294 uio_clone->uio_iovcnt--;
1297 if (len > ptoa(io_hold_cnt))
1298 len = ptoa(io_hold_cnt);
1299 addr = (uintptr_t)uio_clone->uio_iov->iov_base;
1300 end = round_page(addr + len);
1305 cnt = atop(end - trunc_page(addr));
1307 * A perfectly misaligned address and length could cause
1308 * both the start and the end of the chunk to use partial
1309 * page. +2 accounts for such a situation.
1311 cnt = vm_fault_quick_hold_pages(&td->td_proc->p_vmspace->vm_map,
1312 addr, len, prot, ma, io_hold_cnt + 2);
1317 short_uio.uio_iov = &short_iovec[0];
1318 short_iovec[0].iov_base = (void *)addr;
1319 short_uio.uio_iovcnt = 1;
1320 short_uio.uio_resid = short_iovec[0].iov_len = len;
1321 short_uio.uio_offset = uio_clone->uio_offset;
1323 td->td_ma_cnt = cnt;
1325 error = vn_io_fault_doio(args, &short_uio, td);
1326 vm_page_unhold_pages(ma, cnt);
1327 adv = len - short_uio.uio_resid;
1329 uio_clone->uio_iov->iov_base =
1330 (char *)uio_clone->uio_iov->iov_base + adv;
1331 uio_clone->uio_iov->iov_len -= adv;
1332 uio_clone->uio_resid -= adv;
1333 uio_clone->uio_offset += adv;
1335 uio->uio_resid -= adv;
1336 uio->uio_offset += adv;
1338 if (error != 0 || adv == 0)
1341 td->td_ma = prev_td_ma;
1342 td->td_ma_cnt = prev_td_ma_cnt;
1343 curthread_pflags_restore(saveheld);
1345 free(uio_clone, M_IOV);
1350 vn_io_fault(struct file *fp, struct uio *uio, struct ucred *active_cred,
1351 int flags, struct thread *td)
1356 struct vn_io_fault_args args;
1359 doio = uio->uio_rw == UIO_READ ? vn_read : vn_write;
1363 * The ability to read(2) on a directory has historically been
1364 * allowed for all users, but this can and has been the source of
1365 * at least one security issue in the past. As such, it is now hidden
1366 * away behind a sysctl for those that actually need it to use it, and
1367 * restricted to root when it's turned on to make it relatively safe to
1368 * leave on for longer sessions of need.
1370 if (vp->v_type == VDIR) {
1371 KASSERT(uio->uio_rw == UIO_READ,
1372 ("illegal write attempted on a directory"));
1373 if (!vfs_allow_read_dir)
1375 if ((error = priv_check(td, PRIV_VFS_READ_DIR)) != 0)
1379 foffset_lock_uio(fp, uio, flags);
1380 if (do_vn_io_fault(vp, uio)) {
1381 args.kind = VN_IO_FAULT_FOP;
1382 args.args.fop_args.fp = fp;
1383 args.args.fop_args.doio = doio;
1384 args.cred = active_cred;
1385 args.flags = flags | FOF_OFFSET;
1386 if (uio->uio_rw == UIO_READ) {
1387 rl_cookie = vn_rangelock_rlock(vp, uio->uio_offset,
1388 uio->uio_offset + uio->uio_resid);
1389 } else if ((fp->f_flag & O_APPEND) != 0 ||
1390 (flags & FOF_OFFSET) == 0) {
1391 /* For appenders, punt and lock the whole range. */
1392 rl_cookie = vn_rangelock_wlock(vp, 0, OFF_MAX);
1394 rl_cookie = vn_rangelock_wlock(vp, uio->uio_offset,
1395 uio->uio_offset + uio->uio_resid);
1397 error = vn_io_fault1(vp, uio, &args, td);
1398 vn_rangelock_unlock(vp, rl_cookie);
1400 error = doio(fp, uio, active_cred, flags | FOF_OFFSET, td);
1402 foffset_unlock_uio(fp, uio, flags);
1407 * Helper function to perform the requested uiomove operation using
1408 * the held pages for io->uio_iov[0].iov_base buffer instead of
1409 * copyin/copyout. Access to the pages with uiomove_fromphys()
1410 * instead of iov_base prevents page faults that could occur due to
1411 * pmap_collect() invalidating the mapping created by
1412 * vm_fault_quick_hold_pages(), or pageout daemon, page laundry or
1413 * object cleanup revoking the write access from page mappings.
1415 * Filesystems specified MNTK_NO_IOPF shall use vn_io_fault_uiomove()
1416 * instead of plain uiomove().
1419 vn_io_fault_uiomove(char *data, int xfersize, struct uio *uio)
1421 struct uio transp_uio;
1422 struct iovec transp_iov[1];
1428 if ((td->td_pflags & TDP_UIOHELD) == 0 ||
1429 uio->uio_segflg != UIO_USERSPACE)
1430 return (uiomove(data, xfersize, uio));
1432 KASSERT(uio->uio_iovcnt == 1, ("uio_iovcnt %d", uio->uio_iovcnt));
1433 transp_iov[0].iov_base = data;
1434 transp_uio.uio_iov = &transp_iov[0];
1435 transp_uio.uio_iovcnt = 1;
1436 if (xfersize > uio->uio_resid)
1437 xfersize = uio->uio_resid;
1438 transp_uio.uio_resid = transp_iov[0].iov_len = xfersize;
1439 transp_uio.uio_offset = 0;
1440 transp_uio.uio_segflg = UIO_SYSSPACE;
1442 * Since transp_iov points to data, and td_ma page array
1443 * corresponds to original uio->uio_iov, we need to invert the
1444 * direction of the i/o operation as passed to
1445 * uiomove_fromphys().
1447 switch (uio->uio_rw) {
1449 transp_uio.uio_rw = UIO_READ;
1452 transp_uio.uio_rw = UIO_WRITE;
1455 transp_uio.uio_td = uio->uio_td;
1456 error = uiomove_fromphys(td->td_ma,
1457 ((vm_offset_t)uio->uio_iov->iov_base) & PAGE_MASK,
1458 xfersize, &transp_uio);
1459 adv = xfersize - transp_uio.uio_resid;
1461 (((vm_offset_t)uio->uio_iov->iov_base + adv) >> PAGE_SHIFT) -
1462 (((vm_offset_t)uio->uio_iov->iov_base) >> PAGE_SHIFT);
1464 KASSERT(td->td_ma_cnt >= pgadv, ("consumed pages %d %d", td->td_ma_cnt,
1466 td->td_ma_cnt -= pgadv;
1467 uio->uio_iov->iov_base = (char *)uio->uio_iov->iov_base + adv;
1468 uio->uio_iov->iov_len -= adv;
1469 uio->uio_resid -= adv;
1470 uio->uio_offset += adv;
1475 vn_io_fault_pgmove(vm_page_t ma[], vm_offset_t offset, int xfersize,
1479 vm_offset_t iov_base;
1483 if ((td->td_pflags & TDP_UIOHELD) == 0 ||
1484 uio->uio_segflg != UIO_USERSPACE)
1485 return (uiomove_fromphys(ma, offset, xfersize, uio));
1487 KASSERT(uio->uio_iovcnt == 1, ("uio_iovcnt %d", uio->uio_iovcnt));
1488 cnt = xfersize > uio->uio_resid ? uio->uio_resid : xfersize;
1489 iov_base = (vm_offset_t)uio->uio_iov->iov_base;
1490 switch (uio->uio_rw) {
1492 pmap_copy_pages(td->td_ma, iov_base & PAGE_MASK, ma,
1496 pmap_copy_pages(ma, offset, td->td_ma, iov_base & PAGE_MASK,
1500 pgadv = ((iov_base + cnt) >> PAGE_SHIFT) - (iov_base >> PAGE_SHIFT);
1502 KASSERT(td->td_ma_cnt >= pgadv, ("consumed pages %d %d", td->td_ma_cnt,
1504 td->td_ma_cnt -= pgadv;
1505 uio->uio_iov->iov_base = (char *)(iov_base + cnt);
1506 uio->uio_iov->iov_len -= cnt;
1507 uio->uio_resid -= cnt;
1508 uio->uio_offset += cnt;
1513 * File table truncate routine.
1516 vn_truncate(struct file *fp, off_t length, struct ucred *active_cred,
1527 * Lock the whole range for truncation. Otherwise split i/o
1528 * might happen partly before and partly after the truncation.
1530 rl_cookie = vn_rangelock_wlock(vp, 0, OFF_MAX);
1531 error = vn_start_write(vp, &mp, V_WAIT | PCATCH);
1534 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1535 AUDIT_ARG_VNODE1(vp);
1536 if (vp->v_type == VDIR) {
1541 error = mac_vnode_check_write(active_cred, fp->f_cred, vp);
1545 error = vn_truncate_locked(vp, length, (fp->f_flag & O_FSYNC) != 0,
1549 vn_finished_write(mp);
1551 vn_rangelock_unlock(vp, rl_cookie);
1556 * Truncate a file that is already locked.
1559 vn_truncate_locked(struct vnode *vp, off_t length, bool sync,
1565 error = VOP_ADD_WRITECOUNT(vp, 1);
1568 vattr.va_size = length;
1570 vattr.va_vaflags |= VA_SYNC;
1571 error = VOP_SETATTR(vp, &vattr, cred);
1572 VOP_ADD_WRITECOUNT_CHECKED(vp, -1);
1578 * File table vnode stat routine.
1581 vn_statfile(struct file *fp, struct stat *sb, struct ucred *active_cred,
1584 struct vnode *vp = fp->f_vnode;
1587 vn_lock(vp, LK_SHARED | LK_RETRY);
1588 error = VOP_STAT(vp, sb, active_cred, fp->f_cred, td);
1595 * File table vnode ioctl routine.
1598 vn_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
1603 struct fiobmap2_arg *bmarg;
1607 switch (vp->v_type) {
1612 vn_lock(vp, LK_SHARED | LK_RETRY);
1613 error = VOP_GETATTR(vp, &vattr, active_cred);
1616 *(int *)data = vattr.va_size - fp->f_offset;
1619 bmarg = (struct fiobmap2_arg *)data;
1620 vn_lock(vp, LK_SHARED | LK_RETRY);
1622 error = mac_vnode_check_read(active_cred, fp->f_cred,
1626 error = VOP_BMAP(vp, bmarg->bn, NULL,
1627 &bmarg->bn, &bmarg->runp, &bmarg->runb);
1634 return (VOP_IOCTL(vp, com, data, fp->f_flag,
1639 return (VOP_IOCTL(vp, com, data, fp->f_flag,
1647 * File table vnode poll routine.
1650 vn_poll(struct file *fp, int events, struct ucred *active_cred,
1657 #if defined(MAC) || defined(AUDIT)
1658 if (AUDITING_TD(td) || mac_vnode_check_poll_enabled()) {
1659 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1660 AUDIT_ARG_VNODE1(vp);
1661 error = mac_vnode_check_poll(active_cred, fp->f_cred, vp);
1667 error = VOP_POLL(vp, events, fp->f_cred, td);
1672 * Acquire the requested lock and then check for validity. LK_RETRY
1673 * permits vn_lock to return doomed vnodes.
1675 static int __noinline
1676 _vn_lock_fallback(struct vnode *vp, int flags, const char *file, int line,
1680 KASSERT((flags & LK_RETRY) == 0 || error == 0,
1681 ("vn_lock: error %d incompatible with flags %#x", error, flags));
1684 VNASSERT(VN_IS_DOOMED(vp), vp, ("vnode not doomed"));
1686 if ((flags & LK_RETRY) == 0) {
1697 * Nothing to do if we got the lock.
1703 * Interlock was dropped by the call in _vn_lock.
1705 flags &= ~LK_INTERLOCK;
1707 error = VOP_LOCK1(vp, flags, file, line);
1708 } while (error != 0);
1713 _vn_lock(struct vnode *vp, int flags, const char *file, int line)
1717 VNASSERT((flags & LK_TYPE_MASK) != 0, vp,
1718 ("vn_lock: no locktype (%d passed)", flags));
1719 VNPASS(vp->v_holdcnt > 0, vp);
1720 error = VOP_LOCK1(vp, flags, file, line);
1721 if (__predict_false(error != 0 || VN_IS_DOOMED(vp)))
1722 return (_vn_lock_fallback(vp, flags, file, line, error));
1727 * File table vnode close routine.
1730 vn_closefile(struct file *fp, struct thread *td)
1738 fp->f_ops = &badfileops;
1739 ref= (fp->f_flag & FHASLOCK) != 0 && fp->f_type == DTYPE_VNODE;
1741 error = vn_close1(vp, fp->f_flag, fp->f_cred, td, ref);
1743 if (__predict_false(ref)) {
1744 lf.l_whence = SEEK_SET;
1747 lf.l_type = F_UNLCK;
1748 (void) VOP_ADVLOCK(vp, fp, F_UNLCK, &lf, F_FLOCK);
1755 * Preparing to start a filesystem write operation. If the operation is
1756 * permitted, then we bump the count of operations in progress and
1757 * proceed. If a suspend request is in progress, we wait until the
1758 * suspension is over, and then proceed.
1761 vn_start_write_refed(struct mount *mp, int flags, bool mplocked)
1765 if (__predict_true(!mplocked) && (flags & V_XSLEEP) == 0 &&
1766 vfs_op_thread_enter(mp)) {
1767 MPASS((mp->mnt_kern_flag & MNTK_SUSPEND) == 0);
1768 vfs_mp_count_add_pcpu(mp, writeopcount, 1);
1769 vfs_op_thread_exit(mp);
1774 mtx_assert(MNT_MTX(mp), MA_OWNED);
1781 * Check on status of suspension.
1783 if ((curthread->td_pflags & TDP_IGNSUSP) == 0 ||
1784 mp->mnt_susp_owner != curthread) {
1785 mflags = ((mp->mnt_vfc->vfc_flags & VFCF_SBDRY) != 0 ?
1786 (flags & PCATCH) : 0) | (PUSER - 1);
1787 while ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0) {
1788 if (flags & V_NOWAIT) {
1789 error = EWOULDBLOCK;
1792 error = msleep(&mp->mnt_flag, MNT_MTX(mp), mflags,
1798 if (flags & V_XSLEEP)
1800 mp->mnt_writeopcount++;
1802 if (error != 0 || (flags & V_XSLEEP) != 0)
1809 vn_start_write(struct vnode *vp, struct mount **mpp, int flags)
1814 KASSERT((flags & V_MNTREF) == 0 || (*mpp != NULL && vp == NULL),
1815 ("V_MNTREF requires mp"));
1819 * If a vnode is provided, get and return the mount point that
1820 * to which it will write.
1823 if ((error = VOP_GETWRITEMOUNT(vp, mpp)) != 0) {
1825 if (error != EOPNOTSUPP)
1830 if ((mp = *mpp) == NULL)
1834 * VOP_GETWRITEMOUNT() returns with the mp refcount held through
1836 * As long as a vnode is not provided we need to acquire a
1837 * refcount for the provided mountpoint too, in order to
1838 * emulate a vfs_ref().
1840 if (vp == NULL && (flags & V_MNTREF) == 0)
1843 return (vn_start_write_refed(mp, flags, false));
1847 * Secondary suspension. Used by operations such as vop_inactive
1848 * routines that are needed by the higher level functions. These
1849 * are allowed to proceed until all the higher level functions have
1850 * completed (indicated by mnt_writeopcount dropping to zero). At that
1851 * time, these operations are halted until the suspension is over.
1854 vn_start_secondary_write(struct vnode *vp, struct mount **mpp, int flags)
1859 KASSERT((flags & V_MNTREF) == 0 || (*mpp != NULL && vp == NULL),
1860 ("V_MNTREF requires mp"));
1864 if ((error = VOP_GETWRITEMOUNT(vp, mpp)) != 0) {
1866 if (error != EOPNOTSUPP)
1872 * If we are not suspended or have not yet reached suspended
1873 * mode, then let the operation proceed.
1875 if ((mp = *mpp) == NULL)
1879 * VOP_GETWRITEMOUNT() returns with the mp refcount held through
1881 * As long as a vnode is not provided we need to acquire a
1882 * refcount for the provided mountpoint too, in order to
1883 * emulate a vfs_ref().
1886 if (vp == NULL && (flags & V_MNTREF) == 0)
1888 if ((mp->mnt_kern_flag & (MNTK_SUSPENDED | MNTK_SUSPEND2)) == 0) {
1889 mp->mnt_secondary_writes++;
1890 mp->mnt_secondary_accwrites++;
1894 if (flags & V_NOWAIT) {
1897 return (EWOULDBLOCK);
1900 * Wait for the suspension to finish.
1902 error = msleep(&mp->mnt_flag, MNT_MTX(mp), (PUSER - 1) | PDROP |
1903 ((mp->mnt_vfc->vfc_flags & VFCF_SBDRY) != 0 ? (flags & PCATCH) : 0),
1912 * Filesystem write operation has completed. If we are suspending and this
1913 * operation is the last one, notify the suspender that the suspension is
1917 vn_finished_write(struct mount *mp)
1924 if (vfs_op_thread_enter(mp)) {
1925 vfs_mp_count_sub_pcpu(mp, writeopcount, 1);
1926 vfs_mp_count_sub_pcpu(mp, ref, 1);
1927 vfs_op_thread_exit(mp);
1932 vfs_assert_mount_counters(mp);
1934 c = --mp->mnt_writeopcount;
1935 if (mp->mnt_vfs_ops == 0) {
1936 MPASS((mp->mnt_kern_flag & MNTK_SUSPEND) == 0);
1941 vfs_dump_mount_counters(mp);
1942 if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0 && c == 0)
1943 wakeup(&mp->mnt_writeopcount);
1948 * Filesystem secondary write operation has completed. If we are
1949 * suspending and this operation is the last one, notify the suspender
1950 * that the suspension is now in effect.
1953 vn_finished_secondary_write(struct mount *mp)
1959 mp->mnt_secondary_writes--;
1960 if (mp->mnt_secondary_writes < 0)
1961 panic("vn_finished_secondary_write: neg cnt");
1962 if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0 &&
1963 mp->mnt_secondary_writes <= 0)
1964 wakeup(&mp->mnt_secondary_writes);
1969 * Request a filesystem to suspend write operations.
1972 vfs_write_suspend(struct mount *mp, int flags)
1979 vfs_assert_mount_counters(mp);
1980 if (mp->mnt_susp_owner == curthread) {
1981 vfs_op_exit_locked(mp);
1985 while (mp->mnt_kern_flag & MNTK_SUSPEND)
1986 msleep(&mp->mnt_flag, MNT_MTX(mp), PUSER - 1, "wsuspfs", 0);
1989 * Unmount holds a write reference on the mount point. If we
1990 * own busy reference and drain for writers, we deadlock with
1991 * the reference draining in the unmount path. Callers of
1992 * vfs_write_suspend() must specify VS_SKIP_UNMOUNT if
1993 * vfs_busy() reference is owned and caller is not in the
1996 if ((flags & VS_SKIP_UNMOUNT) != 0 &&
1997 (mp->mnt_kern_flag & MNTK_UNMOUNT) != 0) {
1998 vfs_op_exit_locked(mp);
2003 mp->mnt_kern_flag |= MNTK_SUSPEND;
2004 mp->mnt_susp_owner = curthread;
2005 if (mp->mnt_writeopcount > 0)
2006 (void) msleep(&mp->mnt_writeopcount,
2007 MNT_MTX(mp), (PUSER - 1)|PDROP, "suspwt", 0);
2010 if ((error = VFS_SYNC(mp, MNT_SUSPEND)) != 0) {
2011 vfs_write_resume(mp, 0);
2012 /* vfs_write_resume does vfs_op_exit() for us */
2018 * Request a filesystem to resume write operations.
2021 vfs_write_resume(struct mount *mp, int flags)
2025 if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0) {
2026 KASSERT(mp->mnt_susp_owner == curthread, ("mnt_susp_owner"));
2027 mp->mnt_kern_flag &= ~(MNTK_SUSPEND | MNTK_SUSPEND2 |
2029 mp->mnt_susp_owner = NULL;
2030 wakeup(&mp->mnt_writeopcount);
2031 wakeup(&mp->mnt_flag);
2032 curthread->td_pflags &= ~TDP_IGNSUSP;
2033 if ((flags & VR_START_WRITE) != 0) {
2035 mp->mnt_writeopcount++;
2038 if ((flags & VR_NO_SUSPCLR) == 0)
2041 } else if ((flags & VR_START_WRITE) != 0) {
2043 vn_start_write_refed(mp, 0, true);
2050 * Helper loop around vfs_write_suspend() for filesystem unmount VFS
2054 vfs_write_suspend_umnt(struct mount *mp)
2058 KASSERT((curthread->td_pflags & TDP_IGNSUSP) == 0,
2059 ("vfs_write_suspend_umnt: recursed"));
2061 /* dounmount() already called vn_start_write(). */
2063 vn_finished_write(mp);
2064 error = vfs_write_suspend(mp, 0);
2066 vn_start_write(NULL, &mp, V_WAIT);
2070 if ((mp->mnt_kern_flag & MNTK_SUSPENDED) != 0)
2073 vn_start_write(NULL, &mp, V_WAIT);
2075 mp->mnt_kern_flag &= ~(MNTK_SUSPENDED | MNTK_SUSPEND2);
2076 wakeup(&mp->mnt_flag);
2078 curthread->td_pflags |= TDP_IGNSUSP;
2083 * Implement kqueues for files by translating it to vnode operation.
2086 vn_kqfilter(struct file *fp, struct knote *kn)
2089 return (VOP_KQFILTER(fp->f_vnode, kn));
2093 * Simplified in-kernel wrapper calls for extended attribute access.
2094 * Both calls pass in a NULL credential, authorizing as "kernel" access.
2095 * Set IO_NODELOCKED in ioflg if the vnode is already locked.
2098 vn_extattr_get(struct vnode *vp, int ioflg, int attrnamespace,
2099 const char *attrname, int *buflen, char *buf, struct thread *td)
2105 iov.iov_len = *buflen;
2108 auio.uio_iov = &iov;
2109 auio.uio_iovcnt = 1;
2110 auio.uio_rw = UIO_READ;
2111 auio.uio_segflg = UIO_SYSSPACE;
2113 auio.uio_offset = 0;
2114 auio.uio_resid = *buflen;
2116 if ((ioflg & IO_NODELOCKED) == 0)
2117 vn_lock(vp, LK_SHARED | LK_RETRY);
2119 ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
2121 /* authorize attribute retrieval as kernel */
2122 error = VOP_GETEXTATTR(vp, attrnamespace, attrname, &auio, NULL, NULL,
2125 if ((ioflg & IO_NODELOCKED) == 0)
2129 *buflen = *buflen - auio.uio_resid;
2136 * XXX failure mode if partially written?
2139 vn_extattr_set(struct vnode *vp, int ioflg, int attrnamespace,
2140 const char *attrname, int buflen, char *buf, struct thread *td)
2147 iov.iov_len = buflen;
2150 auio.uio_iov = &iov;
2151 auio.uio_iovcnt = 1;
2152 auio.uio_rw = UIO_WRITE;
2153 auio.uio_segflg = UIO_SYSSPACE;
2155 auio.uio_offset = 0;
2156 auio.uio_resid = buflen;
2158 if ((ioflg & IO_NODELOCKED) == 0) {
2159 if ((error = vn_start_write(vp, &mp, V_WAIT)) != 0)
2161 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2164 ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
2166 /* authorize attribute setting as kernel */
2167 error = VOP_SETEXTATTR(vp, attrnamespace, attrname, &auio, NULL, td);
2169 if ((ioflg & IO_NODELOCKED) == 0) {
2170 vn_finished_write(mp);
2178 vn_extattr_rm(struct vnode *vp, int ioflg, int attrnamespace,
2179 const char *attrname, struct thread *td)
2184 if ((ioflg & IO_NODELOCKED) == 0) {
2185 if ((error = vn_start_write(vp, &mp, V_WAIT)) != 0)
2187 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2190 ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
2192 /* authorize attribute removal as kernel */
2193 error = VOP_DELETEEXTATTR(vp, attrnamespace, attrname, NULL, td);
2194 if (error == EOPNOTSUPP)
2195 error = VOP_SETEXTATTR(vp, attrnamespace, attrname, NULL,
2198 if ((ioflg & IO_NODELOCKED) == 0) {
2199 vn_finished_write(mp);
2207 vn_get_ino_alloc_vget(struct mount *mp, void *arg, int lkflags,
2211 return (VFS_VGET(mp, *(ino_t *)arg, lkflags, rvp));
2215 vn_vget_ino(struct vnode *vp, ino_t ino, int lkflags, struct vnode **rvp)
2218 return (vn_vget_ino_gen(vp, vn_get_ino_alloc_vget, &ino,
2223 vn_vget_ino_gen(struct vnode *vp, vn_get_ino_t alloc, void *alloc_arg,
2224 int lkflags, struct vnode **rvp)
2229 ASSERT_VOP_LOCKED(vp, "vn_vget_ino_get");
2231 ltype = VOP_ISLOCKED(vp);
2232 KASSERT(ltype == LK_EXCLUSIVE || ltype == LK_SHARED,
2233 ("vn_vget_ino: vp not locked"));
2234 error = vfs_busy(mp, MBF_NOWAIT);
2238 error = vfs_busy(mp, 0);
2239 vn_lock(vp, ltype | LK_RETRY);
2243 if (VN_IS_DOOMED(vp)) {
2249 error = alloc(mp, alloc_arg, lkflags, rvp);
2251 if (error != 0 || *rvp != vp)
2252 vn_lock(vp, ltype | LK_RETRY);
2253 if (VN_IS_DOOMED(vp)) {
2266 vn_rlimit_fsize(const struct vnode *vp, const struct uio *uio,
2270 if (vp->v_type != VREG || td == NULL)
2272 if ((uoff_t)uio->uio_offset + uio->uio_resid >
2273 lim_cur(td, RLIMIT_FSIZE)) {
2274 PROC_LOCK(td->td_proc);
2275 kern_psignal(td->td_proc, SIGXFSZ);
2276 PROC_UNLOCK(td->td_proc);
2283 vn_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
2290 vn_lock(vp, LK_SHARED | LK_RETRY);
2291 AUDIT_ARG_VNODE1(vp);
2294 return (setfmode(td, active_cred, vp, mode));
2298 vn_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
2305 vn_lock(vp, LK_SHARED | LK_RETRY);
2306 AUDIT_ARG_VNODE1(vp);
2309 return (setfown(td, active_cred, vp, uid, gid));
2313 vn_pages_remove(struct vnode *vp, vm_pindex_t start, vm_pindex_t end)
2317 if ((object = vp->v_object) == NULL)
2319 VM_OBJECT_WLOCK(object);
2320 vm_object_page_remove(object, start, end, 0);
2321 VM_OBJECT_WUNLOCK(object);
2325 vn_bmap_seekhole(struct vnode *vp, u_long cmd, off_t *off, struct ucred *cred)
2333 KASSERT(cmd == FIOSEEKHOLE || cmd == FIOSEEKDATA,
2334 ("Wrong command %lu", cmd));
2336 if (vn_lock(vp, LK_SHARED) != 0)
2338 if (vp->v_type != VREG) {
2342 error = VOP_GETATTR(vp, &va, cred);
2346 if (noff >= va.va_size) {
2350 bsize = vp->v_mount->mnt_stat.f_iosize;
2351 for (bn = noff / bsize; noff < va.va_size; bn++, noff += bsize -
2353 error = VOP_BMAP(vp, bn, NULL, &bnp, NULL, NULL);
2354 if (error == EOPNOTSUPP) {
2358 if ((bnp == -1 && cmd == FIOSEEKHOLE) ||
2359 (bnp != -1 && cmd == FIOSEEKDATA)) {
2366 if (noff > va.va_size)
2368 /* noff == va.va_size. There is an implicit hole at the end of file. */
2369 if (cmd == FIOSEEKDATA)
2379 vn_seek(struct file *fp, off_t offset, int whence, struct thread *td)
2384 off_t foffset, size;
2387 cred = td->td_ucred;
2389 foffset = foffset_lock(fp, 0);
2390 noneg = (vp->v_type != VCHR);
2396 (offset > 0 && foffset > OFF_MAX - offset))) {
2403 vn_lock(vp, LK_SHARED | LK_RETRY);
2404 error = VOP_GETATTR(vp, &vattr, cred);
2410 * If the file references a disk device, then fetch
2411 * the media size and use that to determine the ending
2414 if (vattr.va_size == 0 && vp->v_type == VCHR &&
2415 fo_ioctl(fp, DIOCGMEDIASIZE, &size, cred, td) == 0)
2416 vattr.va_size = size;
2418 (vattr.va_size > OFF_MAX ||
2419 (offset > 0 && vattr.va_size > OFF_MAX - offset))) {
2423 offset += vattr.va_size;
2428 error = fo_ioctl(fp, FIOSEEKDATA, &offset, cred, td);
2429 if (error == ENOTTY)
2433 error = fo_ioctl(fp, FIOSEEKHOLE, &offset, cred, td);
2434 if (error == ENOTTY)
2440 if (error == 0 && noneg && offset < 0)
2444 VFS_KNOTE_UNLOCKED(vp, 0);
2445 td->td_uretoff.tdu_off = offset;
2447 foffset_unlock(fp, offset, error != 0 ? FOF_NOUPDATE : 0);
2452 vn_utimes_perm(struct vnode *vp, struct vattr *vap, struct ucred *cred,
2458 * Grant permission if the caller is the owner of the file, or
2459 * the super-user, or has ACL_WRITE_ATTRIBUTES permission on
2460 * on the file. If the time pointer is null, then write
2461 * permission on the file is also sufficient.
2463 * From NFSv4.1, draft 21, 6.2.1.3.1, Discussion of Mask Attributes:
2464 * A user having ACL_WRITE_DATA or ACL_WRITE_ATTRIBUTES
2465 * will be allowed to set the times [..] to the current
2468 error = VOP_ACCESSX(vp, VWRITE_ATTRIBUTES, cred, td);
2469 if (error != 0 && (vap->va_vaflags & VA_UTIMES_NULL) != 0)
2470 error = VOP_ACCESS(vp, VWRITE, cred, td);
2475 vn_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
2480 if (fp->f_type == DTYPE_FIFO)
2481 kif->kf_type = KF_TYPE_FIFO;
2483 kif->kf_type = KF_TYPE_VNODE;
2486 FILEDESC_SUNLOCK(fdp);
2487 error = vn_fill_kinfo_vnode(vp, kif);
2489 FILEDESC_SLOCK(fdp);
2494 vn_fill_junk(struct kinfo_file *kif)
2499 * Simulate vn_fullpath returning changing values for a given
2500 * vp during e.g. coredump.
2502 len = (arc4random() % (sizeof(kif->kf_path) - 2)) + 1;
2503 olen = strlen(kif->kf_path);
2505 strcpy(&kif->kf_path[len - 1], "$");
2507 for (; olen < len; olen++)
2508 strcpy(&kif->kf_path[olen], "A");
2512 vn_fill_kinfo_vnode(struct vnode *vp, struct kinfo_file *kif)
2515 char *fullpath, *freepath;
2518 kif->kf_un.kf_file.kf_file_type = vntype_to_kinfo(vp->v_type);
2521 error = vn_fullpath(vp, &fullpath, &freepath);
2523 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2525 if (freepath != NULL)
2526 free(freepath, M_TEMP);
2528 KFAIL_POINT_CODE(DEBUG_FP, fill_kinfo_vnode__random_path,
2533 * Retrieve vnode attributes.
2535 va.va_fsid = VNOVAL;
2537 vn_lock(vp, LK_SHARED | LK_RETRY);
2538 error = VOP_GETATTR(vp, &va, curthread->td_ucred);
2542 if (va.va_fsid != VNOVAL)
2543 kif->kf_un.kf_file.kf_file_fsid = va.va_fsid;
2545 kif->kf_un.kf_file.kf_file_fsid =
2546 vp->v_mount->mnt_stat.f_fsid.val[0];
2547 kif->kf_un.kf_file.kf_file_fsid_freebsd11 =
2548 kif->kf_un.kf_file.kf_file_fsid; /* truncate */
2549 kif->kf_un.kf_file.kf_file_fileid = va.va_fileid;
2550 kif->kf_un.kf_file.kf_file_mode = MAKEIMODE(va.va_type, va.va_mode);
2551 kif->kf_un.kf_file.kf_file_size = va.va_size;
2552 kif->kf_un.kf_file.kf_file_rdev = va.va_rdev;
2553 kif->kf_un.kf_file.kf_file_rdev_freebsd11 =
2554 kif->kf_un.kf_file.kf_file_rdev; /* truncate */
2559 vn_mmap(struct file *fp, vm_map_t map, vm_offset_t *addr, vm_size_t size,
2560 vm_prot_t prot, vm_prot_t cap_maxprot, int flags, vm_ooffset_t foff,
2564 struct pmckern_map_in pkm;
2570 boolean_t writecounted;
2573 #if defined(COMPAT_FREEBSD7) || defined(COMPAT_FREEBSD6) || \
2574 defined(COMPAT_FREEBSD5) || defined(COMPAT_FREEBSD4)
2576 * POSIX shared-memory objects are defined to have
2577 * kernel persistence, and are not defined to support
2578 * read(2)/write(2) -- or even open(2). Thus, we can
2579 * use MAP_ASYNC to trade on-disk coherence for speed.
2580 * The shm_open(3) library routine turns on the FPOSIXSHM
2581 * flag to request this behavior.
2583 if ((fp->f_flag & FPOSIXSHM) != 0)
2584 flags |= MAP_NOSYNC;
2589 * Ensure that file and memory protections are
2590 * compatible. Note that we only worry about
2591 * writability if mapping is shared; in this case,
2592 * current and max prot are dictated by the open file.
2593 * XXX use the vnode instead? Problem is: what
2594 * credentials do we use for determination? What if
2595 * proc does a setuid?
2598 if (mp != NULL && (mp->mnt_flag & MNT_NOEXEC) != 0) {
2599 maxprot = VM_PROT_NONE;
2600 if ((prot & VM_PROT_EXECUTE) != 0)
2603 maxprot = VM_PROT_EXECUTE;
2604 if ((fp->f_flag & FREAD) != 0)
2605 maxprot |= VM_PROT_READ;
2606 else if ((prot & VM_PROT_READ) != 0)
2610 * If we are sharing potential changes via MAP_SHARED and we
2611 * are trying to get write permission although we opened it
2612 * without asking for it, bail out.
2614 if ((flags & MAP_SHARED) != 0) {
2615 if ((fp->f_flag & FWRITE) != 0)
2616 maxprot |= VM_PROT_WRITE;
2617 else if ((prot & VM_PROT_WRITE) != 0)
2620 maxprot |= VM_PROT_WRITE;
2621 cap_maxprot |= VM_PROT_WRITE;
2623 maxprot &= cap_maxprot;
2626 * For regular files and shared memory, POSIX requires that
2627 * the value of foff be a legitimate offset within the data
2628 * object. In particular, negative offsets are invalid.
2629 * Blocking negative offsets and overflows here avoids
2630 * possible wraparound or user-level access into reserved
2631 * ranges of the data object later. In contrast, POSIX does
2632 * not dictate how offsets are used by device drivers, so in
2633 * the case of a device mapping a negative offset is passed
2640 foff > OFF_MAX - size)
2643 writecounted = FALSE;
2644 error = vm_mmap_vnode(td, size, prot, &maxprot, &flags, vp,
2645 &foff, &object, &writecounted);
2648 error = vm_mmap_object(map, addr, size, prot, maxprot, flags, object,
2649 foff, writecounted, td);
2652 * If this mapping was accounted for in the vnode's
2653 * writecount, then undo that now.
2656 vm_pager_release_writecount(object, 0, size);
2657 vm_object_deallocate(object);
2660 /* Inform hwpmc(4) if an executable is being mapped. */
2661 if (PMC_HOOK_INSTALLED(PMC_FN_MMAP)) {
2662 if ((prot & VM_PROT_EXECUTE) != 0 && error == 0) {
2664 pkm.pm_address = (uintptr_t) *addr;
2665 PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_MMAP, (void *) &pkm);
2673 vn_fsid(struct vnode *vp, struct vattr *va)
2677 f = &vp->v_mount->mnt_stat.f_fsid;
2678 va->va_fsid = (uint32_t)f->val[1];
2679 va->va_fsid <<= sizeof(f->val[1]) * NBBY;
2680 va->va_fsid += (uint32_t)f->val[0];
2684 vn_fsync_buf(struct vnode *vp, int waitfor)
2686 struct buf *bp, *nbp;
2689 int error, maxretry;
2692 maxretry = 10000; /* large, arbitrarily chosen */
2694 if (vp->v_type == VCHR) {
2696 mp = vp->v_rdev->si_mountpt;
2703 * MARK/SCAN initialization to avoid infinite loops.
2705 TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
2706 bp->b_vflags &= ~BV_SCANNED;
2711 * Flush all dirty buffers associated with a vnode.
2714 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2715 if ((bp->b_vflags & BV_SCANNED) != 0)
2717 bp->b_vflags |= BV_SCANNED;
2718 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL)) {
2719 if (waitfor != MNT_WAIT)
2722 LK_EXCLUSIVE | LK_INTERLOCK | LK_SLEEPFAIL,
2723 BO_LOCKPTR(bo)) != 0) {
2730 KASSERT(bp->b_bufobj == bo,
2731 ("bp %p wrong b_bufobj %p should be %p",
2732 bp, bp->b_bufobj, bo));
2733 if ((bp->b_flags & B_DELWRI) == 0)
2734 panic("fsync: not dirty");
2735 if ((vp->v_object != NULL) && (bp->b_flags & B_CLUSTEROK)) {
2741 if (maxretry < 1000)
2742 pause("dirty", hz < 1000 ? 1 : hz / 1000);
2748 * If synchronous the caller expects us to completely resolve all
2749 * dirty buffers in the system. Wait for in-progress I/O to
2750 * complete (which could include background bitmap writes), then
2751 * retry if dirty blocks still exist.
2753 if (waitfor == MNT_WAIT) {
2754 bufobj_wwait(bo, 0, 0);
2755 if (bo->bo_dirty.bv_cnt > 0) {
2757 * If we are unable to write any of these buffers
2758 * then we fail now rather than trying endlessly
2759 * to write them out.
2761 TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
2762 if ((error = bp->b_error) != 0)
2764 if ((mp != NULL && mp->mnt_secondary_writes > 0) ||
2765 (error == 0 && --maxretry >= 0))
2773 vn_printf(vp, "fsync: giving up on dirty (error = %d) ", error);
2779 * Copies a byte range from invp to outvp. Calls VOP_COPY_FILE_RANGE()
2780 * or vn_generic_copy_file_range() after rangelocking the byte ranges,
2781 * to do the actual copy.
2782 * vn_generic_copy_file_range() is factored out, so it can be called
2783 * from a VOP_COPY_FILE_RANGE() call as well, but handles vnodes from
2784 * different file systems.
2787 vn_copy_file_range(struct vnode *invp, off_t *inoffp, struct vnode *outvp,
2788 off_t *outoffp, size_t *lenp, unsigned int flags, struct ucred *incred,
2789 struct ucred *outcred, struct thread *fsize_td)
2796 *lenp = 0; /* For error returns. */
2799 /* Do some sanity checks on the arguments. */
2800 if (invp->v_type == VDIR || outvp->v_type == VDIR)
2802 else if (*inoffp < 0 || *outoffp < 0 ||
2803 invp->v_type != VREG || outvp->v_type != VREG)
2808 /* Ensure offset + len does not wrap around. */
2811 if (uval > INT64_MAX)
2812 len = INT64_MAX - *inoffp;
2815 if (uval > INT64_MAX)
2816 len = INT64_MAX - *outoffp;
2821 * If the two vnode are for the same file system, call
2822 * VOP_COPY_FILE_RANGE(), otherwise call vn_generic_copy_file_range()
2823 * which can handle copies across multiple file systems.
2826 if (invp->v_mount == outvp->v_mount)
2827 error = VOP_COPY_FILE_RANGE(invp, inoffp, outvp, outoffp,
2828 lenp, flags, incred, outcred, fsize_td);
2830 error = vn_generic_copy_file_range(invp, inoffp, outvp,
2831 outoffp, lenp, flags, incred, outcred, fsize_td);
2837 * Test len bytes of data starting at dat for all bytes == 0.
2838 * Return true if all bytes are zero, false otherwise.
2839 * Expects dat to be well aligned.
2842 mem_iszero(void *dat, int len)
2848 for (p = dat; len > 0; len -= sizeof(*p), p++) {
2849 if (len >= sizeof(*p)) {
2853 cp = (const char *)p;
2854 for (i = 0; i < len; i++, cp++)
2863 * Look for a hole in the output file and, if found, adjust *outoffp
2864 * and *xferp to skip past the hole.
2865 * *xferp is the entire hole length to be written and xfer2 is how many bytes
2866 * to be written as 0's upon return.
2869 vn_skip_hole(struct vnode *outvp, off_t xfer2, off_t *outoffp, off_t *xferp,
2870 off_t *dataoffp, off_t *holeoffp, struct ucred *cred)
2875 if (*holeoffp == 0 || *holeoffp <= *outoffp) {
2876 *dataoffp = *outoffp;
2877 error = VOP_IOCTL(outvp, FIOSEEKDATA, dataoffp, 0, cred,
2880 *holeoffp = *dataoffp;
2881 error = VOP_IOCTL(outvp, FIOSEEKHOLE, holeoffp, 0, cred,
2884 if (error != 0 || *holeoffp == *dataoffp) {
2886 * Since outvp is unlocked, it may be possible for
2887 * another thread to do a truncate(), lseek(), write()
2888 * creating a hole at startoff between the above
2889 * VOP_IOCTL() calls, if the other thread does not do
2891 * If that happens, *holeoffp == *dataoffp and finding
2892 * the hole has failed, so disable vn_skip_hole().
2894 *holeoffp = -1; /* Disable use of vn_skip_hole(). */
2897 KASSERT(*dataoffp >= *outoffp,
2898 ("vn_skip_hole: dataoff=%jd < outoff=%jd",
2899 (intmax_t)*dataoffp, (intmax_t)*outoffp));
2900 KASSERT(*holeoffp > *dataoffp,
2901 ("vn_skip_hole: holeoff=%jd <= dataoff=%jd",
2902 (intmax_t)*holeoffp, (intmax_t)*dataoffp));
2906 * If there is a hole before the data starts, advance *outoffp and
2907 * *xferp past the hole.
2909 if (*dataoffp > *outoffp) {
2910 delta = *dataoffp - *outoffp;
2911 if (delta >= *xferp) {
2912 /* Entire *xferp is a hole. */
2919 xfer2 = MIN(xfer2, *xferp);
2923 * If a hole starts before the end of this xfer2, reduce this xfer2 so
2924 * that the write ends at the start of the hole.
2925 * *holeoffp should always be greater than *outoffp, but for the
2926 * non-INVARIANTS case, check this to make sure xfer2 remains a sane
2929 if (*holeoffp > *outoffp && *holeoffp < *outoffp + xfer2)
2930 xfer2 = *holeoffp - *outoffp;
2935 * Write an xfer sized chunk to outvp in blksize blocks from dat.
2936 * dat is a maximum of blksize in length and can be written repeatedly in
2938 * If growfile == true, just grow the file via vn_truncate_locked() instead
2939 * of doing actual writes.
2940 * If checkhole == true, a hole is being punched, so skip over any hole
2941 * already in the output file.
2944 vn_write_outvp(struct vnode *outvp, char *dat, off_t outoff, off_t xfer,
2945 u_long blksize, bool growfile, bool checkhole, struct ucred *cred)
2948 off_t dataoff, holeoff, xfer2;
2952 * Loop around doing writes of blksize until write has been completed.
2953 * Lock/unlock on each loop iteration so that a bwillwrite() can be
2954 * done for each iteration, since the xfer argument can be very
2955 * large if there is a large hole to punch in the output file.
2960 xfer2 = MIN(xfer, blksize);
2963 * Punching a hole. Skip writing if there is
2964 * already a hole in the output file.
2966 xfer2 = vn_skip_hole(outvp, xfer2, &outoff, &xfer,
2967 &dataoff, &holeoff, cred);
2972 KASSERT(xfer2 > 0, ("vn_write_outvp: xfer2=%jd",
2977 error = vn_start_write(outvp, &mp, V_WAIT);
2981 error = vn_lock(outvp, LK_EXCLUSIVE);
2983 error = vn_truncate_locked(outvp, outoff + xfer,
2988 if (MNT_SHARED_WRITES(mp))
2991 lckf = LK_EXCLUSIVE;
2992 error = vn_lock(outvp, lckf);
2994 error = vn_rdwr(UIO_WRITE, outvp, dat, xfer2,
2995 outoff, UIO_SYSSPACE, IO_NODELOCKED,
2996 curthread->td_ucred, cred, NULL, curthread);
3003 vn_finished_write(mp);
3004 } while (!growfile && xfer > 0 && error == 0);
3009 * Copy a byte range of one file to another. This function can handle the
3010 * case where invp and outvp are on different file systems.
3011 * It can also be called by a VOP_COPY_FILE_RANGE() to do the work, if there
3012 * is no better file system specific way to do it.
3015 vn_generic_copy_file_range(struct vnode *invp, off_t *inoffp,
3016 struct vnode *outvp, off_t *outoffp, size_t *lenp, unsigned int flags,
3017 struct ucred *incred, struct ucred *outcred, struct thread *fsize_td)
3022 off_t startoff, endoff, xfer, xfer2;
3024 int error, interrupted;
3025 bool cantseek, readzeros, eof, lastblock;
3027 size_t copylen, len, rem, savlen;
3029 long holein, holeout;
3031 holein = holeout = 0;
3032 savlen = len = *lenp;
3037 error = vn_lock(invp, LK_SHARED);
3040 if (VOP_PATHCONF(invp, _PC_MIN_HOLE_SIZE, &holein) != 0)
3045 error = vn_start_write(outvp, &mp, V_WAIT);
3047 error = vn_lock(outvp, LK_EXCLUSIVE);
3050 * If fsize_td != NULL, do a vn_rlimit_fsize() call,
3051 * now that outvp is locked.
3053 if (fsize_td != NULL) {
3054 io.uio_offset = *outoffp;
3056 error = vn_rlimit_fsize(outvp, &io, fsize_td);
3060 if (VOP_PATHCONF(outvp, _PC_MIN_HOLE_SIZE, &holeout) != 0)
3063 * Holes that are past EOF do not need to be written as a block
3064 * of zero bytes. So, truncate the output file as far as
3065 * possible and then use va.va_size to decide if writing 0
3066 * bytes is necessary in the loop below.
3069 error = VOP_GETATTR(outvp, &va, outcred);
3070 if (error == 0 && va.va_size > *outoffp && va.va_size <=
3073 error = mac_vnode_check_write(curthread->td_ucred,
3077 error = vn_truncate_locked(outvp, *outoffp,
3080 va.va_size = *outoffp;
3085 vn_finished_write(mp);
3090 * Set the blksize to the larger of the hole sizes for invp and outvp.
3091 * If hole sizes aren't available, set the blksize to the larger
3092 * f_iosize of invp and outvp.
3093 * This code expects the hole sizes and f_iosizes to be powers of 2.
3094 * This value is clipped at 4Kbytes and 1Mbyte.
3096 blksize = MAX(holein, holeout);
3098 /* Clip len to end at an exact multiple of hole size. */
3100 rem = *inoffp % blksize;
3102 rem = blksize - rem;
3103 if (len - rem > blksize)
3104 len = savlen = rounddown(len - rem, blksize) + rem;
3108 blksize = MAX(invp->v_mount->mnt_stat.f_iosize,
3109 outvp->v_mount->mnt_stat.f_iosize);
3112 else if (blksize > 1024 * 1024)
3113 blksize = 1024 * 1024;
3114 dat = malloc(blksize, M_TEMP, M_WAITOK);
3117 * If VOP_IOCTL(FIOSEEKHOLE) works for invp, use it and FIOSEEKDATA
3118 * to find holes. Otherwise, just scan the read block for all 0s
3119 * in the inner loop where the data copying is done.
3120 * Note that some file systems such as NFSv3, NFSv4.0 and NFSv4.1 may
3121 * support holes on the server, but do not support FIOSEEKHOLE.
3124 while (len > 0 && error == 0 && !eof && interrupted == 0) {
3125 endoff = 0; /* To shut up compilers. */
3131 * Find the next data area. If there is just a hole to EOF,
3132 * FIOSEEKDATA should fail and then we drop down into the
3133 * inner loop and create the hole on the outvp file.
3134 * (I do not know if any file system will report a hole to
3135 * EOF via FIOSEEKHOLE, but I am pretty sure FIOSEEKDATA
3136 * will fail for those file systems.)
3138 * For input files that don't support FIOSEEKDATA/FIOSEEKHOLE,
3139 * the code just falls through to the inner copy loop.
3143 error = VOP_IOCTL(invp, FIOSEEKDATA, &startoff, 0,
3147 error = VOP_IOCTL(invp, FIOSEEKHOLE, &endoff, 0,
3150 * Since invp is unlocked, it may be possible for
3151 * another thread to do a truncate(), lseek(), write()
3152 * creating a hole at startoff between the above
3153 * VOP_IOCTL() calls, if the other thread does not do
3155 * If that happens, startoff == endoff and finding
3156 * the hole has failed, so set an error.
3158 if (error == 0 && startoff == endoff)
3159 error = EINVAL; /* Any error. Reset to 0. */
3162 if (startoff > *inoffp) {
3163 /* Found hole before data block. */
3164 xfer = MIN(startoff - *inoffp, len);
3165 if (*outoffp < va.va_size) {
3166 /* Must write 0s to punch hole. */
3167 xfer2 = MIN(va.va_size - *outoffp,
3169 memset(dat, 0, MIN(xfer2, blksize));
3170 error = vn_write_outvp(outvp, dat,
3171 *outoffp, xfer2, blksize, false,
3172 holeout > 0, outcred);
3175 if (error == 0 && *outoffp + xfer >
3176 va.va_size && xfer == len)
3177 /* Grow last block. */
3178 error = vn_write_outvp(outvp, dat,
3179 *outoffp, xfer, blksize, true,
3186 interrupted = sig_intr();
3189 copylen = MIN(len, endoff - startoff);
3201 * Set first xfer to end at a block boundary, so that
3202 * holes are more likely detected in the loop below via
3203 * the for all bytes 0 method.
3205 xfer -= (*inoffp % blksize);
3207 /* Loop copying the data block. */
3208 while (copylen > 0 && error == 0 && !eof && interrupted == 0) {
3211 error = vn_lock(invp, LK_SHARED);
3214 error = vn_rdwr(UIO_READ, invp, dat, xfer,
3215 startoff, UIO_SYSSPACE, IO_NODELOCKED,
3216 curthread->td_ucred, incred, &aresid,
3220 if (error == 0 && aresid > 0) {
3221 /* Stop the copy at EOF on the input file. */
3228 * Skip the write for holes past the initial EOF
3229 * of the output file, unless this is the last
3230 * write of the output file at EOF.
3232 readzeros = cantseek ? mem_iszero(dat, xfer) :
3236 if (!cantseek || *outoffp < va.va_size ||
3237 lastblock || !readzeros)
3238 error = vn_write_outvp(outvp, dat,
3239 *outoffp, xfer, blksize,
3240 readzeros && lastblock &&
3241 *outoffp >= va.va_size, false,
3250 interrupted = sig_intr();
3257 *lenp = savlen - len;
3263 vn_fallocate(struct file *fp, off_t offset, off_t len, struct thread *td)
3267 off_t olen, ooffset;
3270 int audited_vnode1 = 0;
3274 if (vp->v_type != VREG)
3277 /* Allocating blocks may take a long time, so iterate. */
3284 error = vn_start_write(vp, &mp, V_WAIT | PCATCH);
3287 error = vn_lock(vp, LK_EXCLUSIVE);
3289 vn_finished_write(mp);
3293 if (!audited_vnode1) {
3294 AUDIT_ARG_VNODE1(vp);
3299 error = mac_vnode_check_write(td->td_ucred, fp->f_cred, vp);
3302 error = VOP_ALLOCATE(vp, &offset, &len);
3304 vn_finished_write(mp);
3306 if (olen + ooffset != offset + len) {
3307 panic("offset + len changed from %jx/%jx to %jx/%jx",
3308 ooffset, olen, offset, len);
3310 if (error != 0 || len == 0)
3312 KASSERT(olen > len, ("Iteration did not make progress?"));