]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/vfs_vnops.c
Import lib9p 9d5aee77bcc1bf0e79b0a3bfefff5fdf2146283c.
[FreeBSD/FreeBSD.git] / sys / kern / vfs_vnops.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1989, 1993
5  *      The Regents of the University of California.  All rights reserved.
6  * (c) UNIX System Laboratories, Inc.
7  * All or some portions of this file are derived from material licensed
8  * to the University of California by American Telephone and Telegraph
9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10  * the permission of UNIX System Laboratories, Inc.
11  *
12  * Copyright (c) 2012 Konstantin Belousov <kib@FreeBSD.org>
13  * Copyright (c) 2013, 2014 The FreeBSD Foundation
14  *
15  * Portions of this software were developed by Konstantin Belousov
16  * under sponsorship from the FreeBSD Foundation.
17  *
18  * Redistribution and use in source and binary forms, with or without
19  * modification, are permitted provided that the following conditions
20  * are met:
21  * 1. Redistributions of source code must retain the above copyright
22  *    notice, this list of conditions and the following disclaimer.
23  * 2. Redistributions in binary form must reproduce the above copyright
24  *    notice, this list of conditions and the following disclaimer in the
25  *    documentation and/or other materials provided with the distribution.
26  * 3. Neither the name of the University nor the names of its contributors
27  *    may be used to endorse or promote products derived from this software
28  *    without specific prior written permission.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
31  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
34  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40  * SUCH DAMAGE.
41  *
42  *      @(#)vfs_vnops.c 8.2 (Berkeley) 1/21/94
43  */
44
45 #include <sys/cdefs.h>
46 __FBSDID("$FreeBSD$");
47
48 #include "opt_hwpmc_hooks.h"
49
50 #include <sys/param.h>
51 #include <sys/systm.h>
52 #include <sys/disk.h>
53 #include <sys/fail.h>
54 #include <sys/fcntl.h>
55 #include <sys/file.h>
56 #include <sys/kdb.h>
57 #include <sys/ktr.h>
58 #include <sys/stat.h>
59 #include <sys/priv.h>
60 #include <sys/proc.h>
61 #include <sys/limits.h>
62 #include <sys/lock.h>
63 #include <sys/mman.h>
64 #include <sys/mount.h>
65 #include <sys/mutex.h>
66 #include <sys/namei.h>
67 #include <sys/vnode.h>
68 #include <sys/bio.h>
69 #include <sys/buf.h>
70 #include <sys/filio.h>
71 #include <sys/resourcevar.h>
72 #include <sys/rwlock.h>
73 #include <sys/sx.h>
74 #include <sys/sleepqueue.h>
75 #include <sys/sysctl.h>
76 #include <sys/ttycom.h>
77 #include <sys/conf.h>
78 #include <sys/syslog.h>
79 #include <sys/unistd.h>
80 #include <sys/user.h>
81
82 #include <security/audit/audit.h>
83 #include <security/mac/mac_framework.h>
84
85 #include <vm/vm.h>
86 #include <vm/vm_extern.h>
87 #include <vm/pmap.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>
92
93 #ifdef HWPMC_HOOKS
94 #include <sys/pmckern.h>
95 #endif
96
97 static fo_rdwr_t        vn_read;
98 static fo_rdwr_t        vn_write;
99 static fo_rdwr_t        vn_io_fault;
100 static fo_truncate_t    vn_truncate;
101 static fo_ioctl_t       vn_ioctl;
102 static fo_poll_t        vn_poll;
103 static fo_kqfilter_t    vn_kqfilter;
104 static fo_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;
108
109 struct  fileops vnops = {
110         .fo_read = vn_io_fault,
111         .fo_write = vn_io_fault,
112         .fo_truncate = vn_truncate,
113         .fo_ioctl = vn_ioctl,
114         .fo_poll = vn_poll,
115         .fo_kqfilter = vn_kqfilter,
116         .fo_stat = vn_statfile,
117         .fo_close = vn_closefile,
118         .fo_chmod = vn_chmod,
119         .fo_chown = vn_chown,
120         .fo_sendfile = vn_sendfile,
121         .fo_seek = vn_seek,
122         .fo_fill_kinfo = vn_fill_kinfo,
123         .fo_mmap = vn_mmap,
124         .fo_fallocate = vn_fallocate,
125         .fo_flags = DFLAG_PASSABLE | DFLAG_SEEKABLE
126 };
127
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");
142
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");
147
148 /*
149  * Returns true if vn_io_fault mode of handling the i/o request should
150  * be used.
151  */
152 static bool
153 do_vn_io_fault(struct vnode *vp, struct uio *uio)
154 {
155         struct mount *mp;
156
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);
160 }
161
162 /*
163  * Structure used to pass arguments to vn_io_fault1(), to do either
164  * file- or vnode-based I/O calls.
165  */
166 struct vn_io_fault_args {
167         enum {
168                 VN_IO_FAULT_FOP,
169                 VN_IO_FAULT_VOP
170         } kind;
171         struct ucred *cred;
172         int flags;
173         union {
174                 struct fop_args_tag {
175                         struct file *fp;
176                         fo_rdwr_t *doio;
177                 } fop_args;
178                 struct vop_args_tag {
179                         struct vnode *vp;
180                 } vop_args;
181         } args;
182 };
183
184 static int vn_io_fault1(struct vnode *vp, struct uio *uio,
185     struct vn_io_fault_args *args, struct thread *td);
186
187 int
188 vn_open(struct nameidata *ndp, int *flagp, int cmode, struct file *fp)
189 {
190         struct thread *td = ndp->ni_cnd.cn_thread;
191
192         return (vn_open_cred(ndp, flagp, cmode, 0, td->td_ucred, fp));
193 }
194
195 static uint64_t
196 open2nameif(int fmode, u_int vn_open_flags)
197 {
198         uint64_t res;
199
200         res = ISOPEN | LOCKLEAF;
201         if ((fmode & O_BENEATH) != 0)
202                 res |= BENEATH;
203         if ((fmode & O_RESOLVE_BENEATH) != 0)
204                 res |= RBENEATH;
205         if ((vn_open_flags & VN_OPEN_NOAUDIT) == 0)
206                 res |= AUDITVNODE1;
207         if ((vn_open_flags & VN_OPEN_NOCAPCHECK) != 0)
208                 res |= NOCAPCHECK;
209         return (res);
210 }
211
212 /*
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.
216  *
217  * Note that this does NOT free nameidata for the successful case,
218  * due to the NDINIT being done elsewhere.
219  */
220 int
221 vn_open_cred(struct nameidata *ndp, int *flagp, int cmode, u_int vn_open_flags,
222     struct ucred *cred, struct file *fp)
223 {
224         struct vnode *vp;
225         struct mount *mp;
226         struct thread *td = ndp->ni_cnd.cn_thread;
227         struct vattr vat;
228         struct vattr *vap = &vat;
229         int fmode, error;
230
231 restart:
232         fmode = *flagp;
233         if ((fmode & (O_CREAT | O_EXCL | O_DIRECTORY)) == (O_CREAT |
234             O_EXCL | O_DIRECTORY))
235                 return (EINVAL);
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);
239                 /*
240                  * Set NOCACHE to avoid flushing the cache when
241                  * rolling in many files at once.
242                 */
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)
247                         bwillwrite();
248                 if ((error = namei(ndp)) != 0)
249                         return (error);
250                 if (ndp->ni_vp == NULL) {
251                         VATTR_NULL(vap);
252                         vap->va_type = VREG;
253                         vap->va_mode = cmode;
254                         if (fmode & O_EXCL)
255                                 vap->va_vaflags |= VA_EXCLUSIVE;
256                         if (vn_start_write(ndp->ni_dvp, &mp, V_NOWAIT) != 0) {
257                                 NDFREE(ndp, NDF_ONLY_PNBUF);
258                                 vput(ndp->ni_dvp);
259                                 if ((error = vn_start_write(NULL, &mp,
260                                     V_XSLEEP | PCATCH)) != 0)
261                                         return (error);
262                                 goto restart;
263                         }
264                         if ((vn_open_flags & VN_OPEN_NAMECACHE) != 0)
265                                 ndp->ni_cnd.cn_flags |= MAKEENTRY;
266 #ifdef MAC
267                         error = mac_vnode_check_create(cred, ndp->ni_dvp,
268                             &ndp->ni_cnd, vap);
269                         if (error == 0)
270 #endif
271                                 error = VOP_CREATE(ndp->ni_dvp, &ndp->ni_vp,
272                                                    &ndp->ni_cnd, vap);
273                         vput(ndp->ni_dvp);
274                         vn_finished_write(mp);
275                         if (error) {
276                                 NDFREE(ndp, NDF_ONLY_PNBUF);
277                                 return (error);
278                         }
279                         fmode &= ~O_TRUNC;
280                         vp = ndp->ni_vp;
281                 } else {
282                         if (ndp->ni_dvp == ndp->ni_vp)
283                                 vrele(ndp->ni_dvp);
284                         else
285                                 vput(ndp->ni_dvp);
286                         ndp->ni_dvp = NULL;
287                         vp = ndp->ni_vp;
288                         if (fmode & O_EXCL) {
289                                 error = EEXIST;
290                                 goto bad;
291                         }
292                         if (vp->v_type == VDIR) {
293                                 error = EISDIR;
294                                 goto bad;
295                         }
296                         fmode &= ~O_CREAT;
297                 }
298         } else {
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 :
302                     FOLLOW;
303                 if ((fmode & FWRITE) == 0)
304                         ndp->ni_cnd.cn_flags |= LOCKSHARED;
305                 if ((error = namei(ndp)) != 0)
306                         return (error);
307                 vp = ndp->ni_vp;
308         }
309         error = vn_open_vnode(vp, fmode, cred, td, fp);
310         if (error)
311                 goto bad;
312         *flagp = fmode;
313         return (0);
314 bad:
315         NDFREE(ndp, NDF_ONLY_PNBUF);
316         vput(vp);
317         *flagp = fmode;
318         ndp->ni_vp = NULL;
319         return (error);
320 }
321
322 static int
323 vn_open_vnode_advlock(struct vnode *vp, int fmode, struct file *fp)
324 {
325         struct flock lf;
326         int error, lock_flags, type;
327
328         ASSERT_VOP_LOCKED(vp, "vn_open_vnode_advlock");
329         if ((fmode & (O_EXLOCK | O_SHLOCK)) == 0)
330                 return (0);
331         KASSERT(fp != NULL, ("open with flock requires fp"));
332         if (fp->f_type != DTYPE_NONE && fp->f_type != DTYPE_VNODE)
333                 return (EOPNOTSUPP);
334
335         lock_flags = VOP_ISLOCKED(vp);
336         VOP_UNLOCK(vp);
337
338         lf.l_whence = SEEK_SET;
339         lf.l_start = 0;
340         lf.l_len = 0;
341         lf.l_type = (fmode & O_EXLOCK) != 0 ? F_WRLCK : F_RDLCK;
342         type = F_FLOCK;
343         if ((fmode & FNONBLOCK) == 0)
344                 type |= F_WAIT;
345         error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, type);
346         if (error == 0)
347                 fp->f_flag |= FHASLOCK;
348
349         vn_lock(vp, lock_flags | LK_RETRY);
350         if (error == 0 && VN_IS_DOOMED(vp))
351                 error = ENOENT;
352         return (error);
353 }
354
355 /*
356  * Common code for vnode open operations once a vnode is located.
357  * Check permissions, and call the VOP_OPEN routine.
358  */
359 int
360 vn_open_vnode(struct vnode *vp, int fmode, struct ucred *cred,
361     struct thread *td, struct file *fp)
362 {
363         accmode_t accmode;
364         int error;
365
366         if (vp->v_type == VLNK)
367                 return (EMLINK);
368         if (vp->v_type == VSOCK)
369                 return (EOPNOTSUPP);
370         if (vp->v_type != VDIR && fmode & O_DIRECTORY)
371                 return (ENOTDIR);
372         accmode = 0;
373         if (fmode & (FWRITE | O_TRUNC)) {
374                 if (vp->v_type == VDIR)
375                         return (EISDIR);
376                 accmode |= VWRITE;
377         }
378         if (fmode & FREAD)
379                 accmode |= VREAD;
380         if (fmode & FEXEC)
381                 accmode |= VEXEC;
382         if ((fmode & O_APPEND) && (fmode & FWRITE))
383                 accmode |= VAPPEND;
384 #ifdef MAC
385         if (fmode & O_CREAT)
386                 accmode |= VCREAT;
387         if (fmode & O_VERIFY)
388                 accmode |= VVERIFY;
389         error = mac_vnode_check_open(cred, vp, accmode);
390         if (error)
391                 return (error);
392
393         accmode &= ~(VCREAT | VVERIFY);
394 #endif
395         if ((fmode & O_CREAT) == 0 && accmode != 0) {
396                 error = VOP_ACCESS(vp, accmode, cred, td);
397                 if (error != 0)
398                         return (error);
399         }
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);
403         if (error != 0)
404                 return (error);
405
406         error = vn_open_vnode_advlock(vp, fmode, fp);
407         if (error == 0 && (fmode & FWRITE) != 0) {
408                 error = VOP_ADD_WRITECOUNT(vp, 1);
409                 if (error == 0) {
410                         CTR3(KTR_VFS, "%s: vp %p v_writecount increased to %d",
411                              __func__, vp, vp->v_writecount);
412                 }
413         }
414
415         /*
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().
419          */
420         if (error != 0) {
421                 fp->f_flag |= FOPENFAILED;
422                 fp->f_vnode = vp;
423                 if (fp->f_ops == &badfileops) {
424                         fp->f_type = DTYPE_VNODE;
425                         fp->f_ops = &vnops;
426                 }
427                 vref(vp);
428         }
429
430         ASSERT_VOP_LOCKED(vp, "vn_open_vnode");
431         return (error);
432
433 }
434
435 /*
436  * Check for write permissions on the specified vnode.
437  * Prototype text segments cannot be written.
438  * It is racy.
439  */
440 int
441 vn_writechk(struct vnode *vp)
442 {
443
444         ASSERT_VOP_LOCKED(vp, "vn_writechk");
445         /*
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.
449          */
450         if (VOP_IS_TEXT(vp))
451                 return (ETXTBSY);
452
453         return (0);
454 }
455
456 /*
457  * Vnode close call
458  */
459 static int
460 vn_close1(struct vnode *vp, int flags, struct ucred *file_cred,
461     struct thread *td, bool keep_ref)
462 {
463         struct mount *mp;
464         int error, lock_flags;
465
466         if (vp->v_type != VFIFO && (flags & FWRITE) == 0 &&
467             MNT_EXTENDED_SHARED(vp->v_mount))
468                 lock_flags = LK_SHARED;
469         else
470                 lock_flags = LK_EXCLUSIVE;
471
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);
479         }
480         error = VOP_CLOSE(vp, flags, file_cred, td);
481         if (keep_ref)
482                 VOP_UNLOCK(vp);
483         else
484                 vput(vp);
485         vn_finished_write(mp);
486         return (error);
487 }
488
489 int
490 vn_close(struct vnode *vp, int flags, struct ucred *file_cred,
491     struct thread *td)
492 {
493
494         return (vn_close1(vp, flags, file_cred, td, false));
495 }
496
497 /*
498  * Heuristic to detect sequential operation.
499  */
500 static int
501 sequential_heuristic(struct uio *uio, struct file *fp)
502 {
503         enum uio_rw rw;
504
505         ASSERT_VOP_LOCKED(fp->f_vnode, __func__);
506
507         rw = uio->uio_rw;
508         if (fp->f_flag & FRDAHEAD)
509                 return (fp->f_seqcount[rw] << IO_SEQSHIFT);
510
511         /*
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.
517          */
518         if ((uio->uio_offset == 0 && fp->f_seqcount[rw] > 0) ||
519             uio->uio_offset == fp->f_nextoff[rw]) {
520                 /*
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.
528                  */
529                 if (uio->uio_resid >= IO_SEQMAX * 16384)
530                         fp->f_seqcount[rw] = IO_SEQMAX;
531                 else {
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;
535                 }
536                 return (fp->f_seqcount[rw] << IO_SEQSHIFT);
537         }
538
539         /* Not sequential.  Quickly draw-down sequentiality. */
540         if (fp->f_seqcount[rw] > 1)
541                 fp->f_seqcount[rw] = 1;
542         else
543                 fp->f_seqcount[rw] = 0;
544         return (0);
545 }
546
547 /*
548  * Package up an I/O request on a vnode into a uio and do it.
549  */
550 int
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)
554 {
555         struct uio auio;
556         struct iovec aiov;
557         struct mount *mp;
558         struct ucred *cred;
559         void *rl_cookie;
560         struct vn_io_fault_args args;
561         int error, lock_flags;
562
563         if (offset < 0 && vp->v_type != VCHR)
564                 return (EINVAL);
565         auio.uio_iov = &aiov;
566         auio.uio_iovcnt = 1;
567         aiov.iov_base = base;
568         aiov.iov_len = len;
569         auio.uio_resid = len;
570         auio.uio_offset = offset;
571         auio.uio_segflg = segflg;
572         auio.uio_rw = rw;
573         auio.uio_td = td;
574         error = 0;
575
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,
580                                     offset + len);
581                         } else {
582                                 rl_cookie = vn_rangelock_wlock(vp, offset,
583                                     offset + len);
584                         }
585                 } else
586                         rl_cookie = NULL;
587                 mp = NULL;
588                 if (rw == UIO_WRITE) { 
589                         if (vp->v_type != VCHR &&
590                             (error = vn_start_write(vp, &mp, V_WAIT | PCATCH))
591                             != 0)
592                                 goto out;
593                         if (MNT_SHARED_WRITES(mp) ||
594                             ((mp == NULL) && MNT_SHARED_WRITES(vp->v_mount)))
595                                 lock_flags = LK_SHARED;
596                         else
597                                 lock_flags = LK_EXCLUSIVE;
598                 } else
599                         lock_flags = LK_SHARED;
600                 vn_lock(vp, lock_flags | LK_RETRY);
601         } else
602                 rl_cookie = NULL;
603
604         ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
605 #ifdef MAC
606         if ((ioflg & IO_NOMACCHECK) == 0) {
607                 if (rw == UIO_READ)
608                         error = mac_vnode_check_read(active_cred, file_cred,
609                             vp);
610                 else
611                         error = mac_vnode_check_write(active_cred, file_cred,
612                             vp);
613         }
614 #endif
615         if (error == 0) {
616                 if (file_cred != NULL)
617                         cred = file_cred;
618                 else
619                         cred = active_cred;
620                 if (do_vn_io_fault(vp, &auio)) {
621                         args.kind = VN_IO_FAULT_VOP;
622                         args.cred = cred;
623                         args.flags = ioflg;
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);
630                 }
631         }
632         if (aresid)
633                 *aresid = auio.uio_resid;
634         else
635                 if (auio.uio_resid && error == 0)
636                         error = EIO;
637         if ((ioflg & IO_NODELOCKED) == 0) {
638                 VOP_UNLOCK(vp);
639                 if (mp != NULL)
640                         vn_finished_write(mp);
641         }
642  out:
643         if (rl_cookie != NULL)
644                 vn_rangelock_unlock(vp, rl_cookie);
645         return (error);
646 }
647
648 /*
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).
655  */
656 int
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)
660 {
661         int error = 0;
662         ssize_t iaresid;
663
664         do {
665                 int chunk;
666
667                 /*
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
671                  * chunks.
672                  */
673                 chunk = MAXBSIZE - (uoff_t)offset % MAXBSIZE;
674
675                 if (chunk > len)
676                         chunk = len;
677                 if (rw != UIO_READ && vp->v_type == VREG)
678                         bwillwrite();
679                 iaresid = 0;
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 */
683                 if (error)
684                         break;
685                 offset += chunk;
686                 base = (char *)base + chunk;
687                 kern_yield(PRI_USER);
688         } while (len);
689         if (aresid)
690                 *aresid = len + iaresid;
691         return (error);
692 }
693
694 #if OFF_MAX <= LONG_MAX
695 off_t
696 foffset_lock(struct file *fp, int flags)
697 {
698         volatile short *flagsp;
699         off_t res;
700         short state;
701
702         KASSERT((flags & FOF_OFFSET) == 0, ("FOF_OFFSET passed"));
703
704         if ((flags & FOF_NOLOCK) != 0)
705                 return (atomic_load_long(&fp->f_offset));
706
707         /*
708          * According to McKusick the vn lock was protecting f_offset here.
709          * It is now protected by the FOFFSET_LOCKED flag.
710          */
711         flagsp = &fp->f_vnread_flags;
712         if (atomic_cmpset_acq_16(flagsp, 0, FOFFSET_LOCKED))
713                 return (atomic_load_long(&fp->f_offset));
714
715         sleepq_lock(&fp->f_vnread_flags);
716         state = atomic_load_16(flagsp);
717         for (;;) {
718                 if ((state & FOFFSET_LOCKED) == 0) {
719                         if (!atomic_fcmpset_acq_16(flagsp, &state,
720                             FOFFSET_LOCKED))
721                                 continue;
722                         break;
723                 }
724                 if ((state & FOFFSET_LOCK_WAITING) == 0) {
725                         if (!atomic_fcmpset_acq_16(flagsp, &state,
726                             state | FOFFSET_LOCK_WAITING))
727                                 continue;
728                 }
729                 DROP_GIANT();
730                 sleepq_add(&fp->f_vnread_flags, NULL, "vofflock", 0, 0);
731                 sleepq_wait(&fp->f_vnread_flags, PUSER -1);
732                 PICKUP_GIANT();
733                 sleepq_lock(&fp->f_vnread_flags);
734                 state = atomic_load_16(flagsp);
735         }
736         res = atomic_load_long(&fp->f_offset);
737         sleepq_release(&fp->f_vnread_flags);
738         return (res);
739 }
740
741 void
742 foffset_unlock(struct file *fp, off_t val, int flags)
743 {
744         volatile short *flagsp;
745         short state;
746
747         KASSERT((flags & FOF_OFFSET) == 0, ("FOF_OFFSET passed"));
748
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;
755
756         if ((flags & FOF_NOLOCK) != 0)
757                 return;
758
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))
763                 return;
764
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);
771 }
772 #else
773 off_t
774 foffset_lock(struct file *fp, int flags)
775 {
776         struct mtx *mtxp;
777         off_t res;
778
779         KASSERT((flags & FOF_OFFSET) == 0, ("FOF_OFFSET passed"));
780
781         mtxp = mtx_pool_find(mtxpool_sleep, fp);
782         mtx_lock(mtxp);
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,
787                             "vofflock", 0);
788                 }
789                 fp->f_vnread_flags |= FOFFSET_LOCKED;
790         }
791         res = fp->f_offset;
792         mtx_unlock(mtxp);
793         return (res);
794 }
795
796 void
797 foffset_unlock(struct file *fp, off_t val, int flags)
798 {
799         struct mtx *mtxp;
800
801         KASSERT((flags & FOF_OFFSET) == 0, ("FOF_OFFSET passed"));
802
803         mtxp = mtx_pool_find(mtxpool_sleep, fp);
804         mtx_lock(mtxp);
805         if ((flags & FOF_NOUPDATE) == 0)
806                 fp->f_offset = val;
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;
817         }
818         mtx_unlock(mtxp);
819 }
820 #endif
821
822 void
823 foffset_lock_uio(struct file *fp, struct uio *uio, int flags)
824 {
825
826         if ((flags & FOF_OFFSET) == 0)
827                 uio->uio_offset = foffset_lock(fp, flags);
828 }
829
830 void
831 foffset_unlock_uio(struct file *fp, struct uio *uio, int flags)
832 {
833
834         if ((flags & FOF_OFFSET) == 0)
835                 foffset_unlock(fp, uio->uio_offset, flags);
836 }
837
838 static int
839 get_advice(struct file *fp, struct uio *uio)
840 {
841         struct mtx *mtxp;
842         int ret;
843
844         ret = POSIX_FADV_NORMAL;
845         if (fp->f_advice == NULL || fp->f_vnode->v_type != VREG)
846                 return (ret);
847
848         mtxp = mtx_pool_find(mtxpool_sleep, fp);
849         mtx_lock(mtxp);
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;
854         mtx_unlock(mtxp);
855         return (ret);
856 }
857
858 int
859 vn_read_from_obj(struct vnode *vp, struct uio *uio)
860 {
861         vm_object_t obj;
862         vm_page_t ma[io_hold_cnt + 2];
863         off_t off, vsz;
864         ssize_t resid;
865         int error, i, j;
866
867         obj = vp->v_object;
868         MPASS(uio->uio_resid <= ptoa(io_hold_cnt + 2));
869         MPASS(obj != NULL);
870         MPASS(obj->type == OBJT_VNODE);
871
872         /*
873          * Depends on type stability of vm_objects.
874          */
875         vm_object_pip_add(obj, 1);
876         if ((obj->flags & OBJ_DEAD) != 0) {
877                 /*
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.
882                  *
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.
886                  */
887                 error = EJUSTRETURN;
888                 goto out_pip;
889         }
890
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 |
897                     VM_ALLOC_NOWAIT);
898                 if (ma[i] == NULL)
899                         break;
900
901                 /*
902                  * Skip invalid pages.  Valid mask can be partial only
903                  * at EOF, and we clip later.
904                  */
905                 if (vm_page_none_valid(ma[i])) {
906                         vm_page_sunbusy(ma[i]);
907                         break;
908                 }
909
910                 resid -= PAGE_SIZE;
911                 off += PAGE_SIZE;
912         }
913         if (i == 0) {
914                 error = EJUSTRETURN;
915                 goto out_pip;
916         }
917
918         /*
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.
922          */
923         if (VN_IS_DOOMED(vp)) {
924                 error = EJUSTRETURN;
925                 goto out;
926         }
927
928         resid = PAGE_SIZE - (uio->uio_offset & PAGE_MASK) + ptoa(i - 1);
929         if (resid > uio->uio_resid)
930                 resid = uio->uio_resid;
931
932         /*
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
936          * break calculation.
937          */
938 #if defined(__powerpc__) && !defined(__powerpc64__)
939         vsz = obj->un_pager.vnp.vnp_size;
940 #else
941         vsz = atomic_load_64(&obj->un_pager.vnp.vnp_size);
942 #endif
943         if (uio->uio_offset + resid > vsz)
944                 resid = vsz - uio->uio_offset;
945
946         error = vn_io_fault_pgmove(ma, uio->uio_offset & PAGE_MASK, resid, uio);
947
948 out:
949         for (j = 0; j < i; j++) {
950                 if (error == 0)
951                         vm_page_reference(ma[j]);
952                 vm_page_sunbusy(ma[j]);
953         }
954 out_pip:
955         vm_object_pip_wakeup(obj);
956         if (error != 0)
957                 return (error);
958         return (uio->uio_resid == 0 ? 0 : EJUSTRETURN);
959 }
960
961 /*
962  * File table vnode read routine.
963  */
964 static int
965 vn_read(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags,
966     struct thread *td)
967 {
968         struct vnode *vp;
969         off_t orig_offset;
970         int error, ioflag;
971         int advice;
972
973         KASSERT(uio->uio_td == td, ("uio_td %p is not td %p",
974             uio->uio_td, td));
975         KASSERT(flags & FOF_OFFSET, ("No FOF_OFFSET"));
976         vp = fp->f_vnode;
977         ioflag = 0;
978         if (fp->f_flag & FNONBLOCK)
979                 ioflag |= IO_NDELAY;
980         if (fp->f_flag & O_DIRECT)
981                 ioflag |= IO_DIRECT;
982
983         /*
984          * Try to read from page cache.  VIRF_DOOMED check is racy but
985          * allows us to avoid unneeded work outright.
986          */
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);
990                 if (error == 0) {
991                         fp->f_nextoff[UIO_READ] = uio->uio_offset;
992                         return (0);
993                 }
994                 if (error != EJUSTRETURN)
995                         return (error);
996         }
997
998         advice = get_advice(fp, uio);
999         vn_lock(vp, LK_SHARED | LK_RETRY);
1000
1001         switch (advice) {
1002         case POSIX_FADV_NORMAL:
1003         case POSIX_FADV_SEQUENTIAL:
1004         case POSIX_FADV_NOREUSE:
1005                 ioflag |= sequential_heuristic(uio, fp);
1006                 break;
1007         case POSIX_FADV_RANDOM:
1008                 /* Disable read-ahead for random I/O. */
1009                 break;
1010         }
1011         orig_offset = uio->uio_offset;
1012
1013 #ifdef MAC
1014         error = mac_vnode_check_read(active_cred, fp->f_cred, vp);
1015         if (error == 0)
1016 #endif
1017                 error = VOP_READ(vp, uio, ioflag, fp->f_cred);
1018         fp->f_nextoff[UIO_READ] = uio->uio_offset;
1019         VOP_UNLOCK(vp);
1020         if (error == 0 && advice == POSIX_FADV_NOREUSE &&
1021             orig_offset != uio->uio_offset)
1022                 /*
1023                  * Use POSIX_FADV_DONTNEED to flush pages and buffers
1024                  * for the backing file after a POSIX_FADV_NOREUSE
1025                  * read(2).
1026                  */
1027                 error = VOP_ADVISE(vp, orig_offset, uio->uio_offset - 1,
1028                     POSIX_FADV_DONTNEED);
1029         return (error);
1030 }
1031
1032 /*
1033  * File table vnode write routine.
1034  */
1035 static int
1036 vn_write(struct file *fp, struct uio *uio, struct ucred *active_cred, int flags,
1037     struct thread *td)
1038 {
1039         struct vnode *vp;
1040         struct mount *mp;
1041         off_t orig_offset;
1042         int error, ioflag, lock_flags;
1043         int advice;
1044
1045         KASSERT(uio->uio_td == td, ("uio_td %p is not td %p",
1046             uio->uio_td, td));
1047         KASSERT(flags & FOF_OFFSET, ("No FOF_OFFSET"));
1048         vp = fp->f_vnode;
1049         if (vp->v_type == VREG)
1050                 bwillwrite();
1051         ioflag = IO_UNIT;
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)))
1060                 ioflag |= IO_SYNC;
1061         mp = NULL;
1062         if (vp->v_type != VCHR &&
1063             (error = vn_start_write(vp, &mp, V_WAIT | PCATCH)) != 0)
1064                 goto unlock;
1065
1066         advice = get_advice(fp, uio);
1067
1068         if (MNT_SHARED_WRITES(mp) ||
1069             (mp == NULL && MNT_SHARED_WRITES(vp->v_mount))) {
1070                 lock_flags = LK_SHARED;
1071         } else {
1072                 lock_flags = LK_EXCLUSIVE;
1073         }
1074
1075         vn_lock(vp, lock_flags | LK_RETRY);
1076         switch (advice) {
1077         case POSIX_FADV_NORMAL:
1078         case POSIX_FADV_SEQUENTIAL:
1079         case POSIX_FADV_NOREUSE:
1080                 ioflag |= sequential_heuristic(uio, fp);
1081                 break;
1082         case POSIX_FADV_RANDOM:
1083                 /* XXX: Is this correct? */
1084                 break;
1085         }
1086         orig_offset = uio->uio_offset;
1087
1088 #ifdef MAC
1089         error = mac_vnode_check_write(active_cred, fp->f_cred, vp);
1090         if (error == 0)
1091 #endif
1092                 error = VOP_WRITE(vp, uio, ioflag, fp->f_cred);
1093         fp->f_nextoff[UIO_WRITE] = uio->uio_offset;
1094         VOP_UNLOCK(vp);
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)
1099                 /*
1100                  * Use POSIX_FADV_DONTNEED to flush pages and buffers
1101                  * for the backing file after a POSIX_FADV_NOREUSE
1102                  * write(2).
1103                  */
1104                 error = VOP_ADVISE(vp, orig_offset, uio->uio_offset - 1,
1105                     POSIX_FADV_DONTNEED);
1106 unlock:
1107         return (error);
1108 }
1109
1110 /*
1111  * The vn_io_fault() is a wrapper around vn_read() and vn_write() to
1112  * prevent the following deadlock:
1113  *
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.
1123  *
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().
1132  *
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.
1138  *
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
1141  * truncations.
1142  */
1143
1144 /*
1145  * Decode vn_io_fault_args and perform the corresponding i/o.
1146  */
1147 static int
1148 vn_io_fault_doio(struct vn_io_fault_args *args, struct uio *uio,
1149     struct thread *td)
1150 {
1151         int error, save;
1152
1153         error = 0;
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);
1159                 break;
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);
1167                 }
1168                 break;
1169         default:
1170                 panic("vn_io_fault_doio: unknown kind of io %d %d",
1171                     args->kind, uio->uio_rw);
1172         }
1173         vm_fault_enable_pagefaults(save);
1174         return (error);
1175 }
1176
1177 static int
1178 vn_io_fault_touch(char *base, const struct uio *uio)
1179 {
1180         int r;
1181
1182         r = fubyte(base);
1183         if (r == -1 || (uio->uio_rw == UIO_READ && subyte(base, r) == -1))
1184                 return (EFAULT);
1185         return (0);
1186 }
1187
1188 static int
1189 vn_io_fault_prefault_user(const struct uio *uio)
1190 {
1191         char *base;
1192         const struct iovec *iov;
1193         size_t len;
1194         ssize_t resid;
1195         int error, i;
1196
1197         KASSERT(uio->uio_segflg == UIO_USERSPACE,
1198             ("vn_io_fault_prefault userspace"));
1199
1200         error = i = 0;
1201         iov = uio->uio_iov;
1202         resid = uio->uio_resid;
1203         base = iov->iov_base;
1204         len = iov->iov_len;
1205         while (resid > 0) {
1206                 error = vn_io_fault_touch(base, uio);
1207                 if (error != 0)
1208                         break;
1209                 if (len < PAGE_SIZE) {
1210                         if (len != 0) {
1211                                 error = vn_io_fault_touch(base + len - 1, uio);
1212                                 if (error != 0)
1213                                         break;
1214                                 resid -= len;
1215                         }
1216                         if (++i >= uio->uio_iovcnt)
1217                                 break;
1218                         iov = uio->uio_iov + i;
1219                         base = iov->iov_base;
1220                         len = iov->iov_len;
1221                 } else {
1222                         len -= PAGE_SIZE;
1223                         base += PAGE_SIZE;
1224                         resid -= PAGE_SIZE;
1225                 }
1226         }
1227         return (error);
1228 }
1229
1230 /*
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.
1236  */
1237 static int
1238 vn_io_fault1(struct vnode *vp, struct uio *uio, struct vn_io_fault_args *args,
1239     struct thread *td)
1240 {
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;
1245         vm_prot_t prot;
1246         vm_offset_t addr, end;
1247         size_t len, resid;
1248         ssize_t adv;
1249         int error, cnt, saveheld, prev_td_ma_cnt;
1250
1251         if (vn_io_fault_prefault) {
1252                 error = vn_io_fault_prefault_user(uio);
1253                 if (error != 0)
1254                         return (error); /* Or ignore ? */
1255         }
1256
1257         prot = uio->uio_rw == UIO_READ ? VM_PROT_WRITE : VM_PROT_READ;
1258
1259         /*
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.
1264          *
1265          * Cache a copy of the original uio, which is advanced to the redo
1266          * point using UIO_NOCOPY below.
1267          */
1268         uio_clone = cloneuio(uio);
1269         resid = uio->uio_resid;
1270
1271         short_uio.uio_segflg = UIO_USERSPACE;
1272         short_uio.uio_rw = uio->uio_rw;
1273         short_uio.uio_td = uio->uio_td;
1274
1275         error = vn_io_fault_doio(args, uio, td);
1276         if (error != EFAULT)
1277                 goto out;
1278
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;
1283
1284         saveheld = curthread_pflags_set(TDP_UIOHELD);
1285         prev_td_ma = td->td_ma;
1286         prev_td_ma_cnt = td->td_ma_cnt;
1287
1288         while (uio_clone->uio_resid != 0) {
1289                 len = uio_clone->uio_iov->iov_len;
1290                 if (len == 0) {
1291                         KASSERT(uio_clone->uio_iovcnt >= 1,
1292                             ("iovcnt underflow"));
1293                         uio_clone->uio_iov++;
1294                         uio_clone->uio_iovcnt--;
1295                         continue;
1296                 }
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);
1301                 if (end < addr) {
1302                         error = EFAULT;
1303                         break;
1304                 }
1305                 cnt = atop(end - trunc_page(addr));
1306                 /*
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.
1310                  */
1311                 cnt = vm_fault_quick_hold_pages(&td->td_proc->p_vmspace->vm_map,
1312                     addr, len, prot, ma, io_hold_cnt + 2);
1313                 if (cnt == -1) {
1314                         error = EFAULT;
1315                         break;
1316                 }
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;
1322                 td->td_ma = ma;
1323                 td->td_ma_cnt = cnt;
1324
1325                 error = vn_io_fault_doio(args, &short_uio, td);
1326                 vm_page_unhold_pages(ma, cnt);
1327                 adv = len - short_uio.uio_resid;
1328
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;
1334
1335                 uio->uio_resid -= adv;
1336                 uio->uio_offset += adv;
1337
1338                 if (error != 0 || adv == 0)
1339                         break;
1340         }
1341         td->td_ma = prev_td_ma;
1342         td->td_ma_cnt = prev_td_ma_cnt;
1343         curthread_pflags_restore(saveheld);
1344 out:
1345         free(uio_clone, M_IOV);
1346         return (error);
1347 }
1348
1349 static int
1350 vn_io_fault(struct file *fp, struct uio *uio, struct ucred *active_cred,
1351     int flags, struct thread *td)
1352 {
1353         fo_rdwr_t *doio;
1354         struct vnode *vp;
1355         void *rl_cookie;
1356         struct vn_io_fault_args args;
1357         int error;
1358
1359         doio = uio->uio_rw == UIO_READ ? vn_read : vn_write;
1360         vp = fp->f_vnode;
1361
1362         /*
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.
1369          */
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)
1374                         return (EISDIR);
1375                 if ((error = priv_check(td, PRIV_VFS_READ_DIR)) != 0)
1376                         return (EISDIR);
1377         }
1378
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);
1393                 } else {
1394                         rl_cookie = vn_rangelock_wlock(vp, uio->uio_offset,
1395                             uio->uio_offset + uio->uio_resid);
1396                 }
1397                 error = vn_io_fault1(vp, uio, &args, td);
1398                 vn_rangelock_unlock(vp, rl_cookie);
1399         } else {
1400                 error = doio(fp, uio, active_cred, flags | FOF_OFFSET, td);
1401         }
1402         foffset_unlock_uio(fp, uio, flags);
1403         return (error);
1404 }
1405
1406 /*
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.
1414  *
1415  * Filesystems specified MNTK_NO_IOPF shall use vn_io_fault_uiomove()
1416  * instead of plain uiomove().
1417  */
1418 int
1419 vn_io_fault_uiomove(char *data, int xfersize, struct uio *uio)
1420 {
1421         struct uio transp_uio;
1422         struct iovec transp_iov[1];
1423         struct thread *td;
1424         size_t adv;
1425         int error, pgadv;
1426
1427         td = curthread;
1428         if ((td->td_pflags & TDP_UIOHELD) == 0 ||
1429             uio->uio_segflg != UIO_USERSPACE)
1430                 return (uiomove(data, xfersize, uio));
1431
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;
1441         /*
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().
1446          */
1447         switch (uio->uio_rw) {
1448         case UIO_WRITE:
1449                 transp_uio.uio_rw = UIO_READ;
1450                 break;
1451         case UIO_READ:
1452                 transp_uio.uio_rw = UIO_WRITE;
1453                 break;
1454         }
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;
1460         pgadv =
1461             (((vm_offset_t)uio->uio_iov->iov_base + adv) >> PAGE_SHIFT) -
1462             (((vm_offset_t)uio->uio_iov->iov_base) >> PAGE_SHIFT);
1463         td->td_ma += pgadv;
1464         KASSERT(td->td_ma_cnt >= pgadv, ("consumed pages %d %d", td->td_ma_cnt,
1465             pgadv));
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;
1471         return (error);
1472 }
1473
1474 int
1475 vn_io_fault_pgmove(vm_page_t ma[], vm_offset_t offset, int xfersize,
1476     struct uio *uio)
1477 {
1478         struct thread *td;
1479         vm_offset_t iov_base;
1480         int cnt, pgadv;
1481
1482         td = curthread;
1483         if ((td->td_pflags & TDP_UIOHELD) == 0 ||
1484             uio->uio_segflg != UIO_USERSPACE)
1485                 return (uiomove_fromphys(ma, offset, xfersize, uio));
1486
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) {
1491         case UIO_WRITE:
1492                 pmap_copy_pages(td->td_ma, iov_base & PAGE_MASK, ma,
1493                     offset, cnt);
1494                 break;
1495         case UIO_READ:
1496                 pmap_copy_pages(ma, offset, td->td_ma, iov_base & PAGE_MASK,
1497                     cnt);
1498                 break;
1499         }
1500         pgadv = ((iov_base + cnt) >> PAGE_SHIFT) - (iov_base >> PAGE_SHIFT);
1501         td->td_ma += pgadv;
1502         KASSERT(td->td_ma_cnt >= pgadv, ("consumed pages %d %d", td->td_ma_cnt,
1503             pgadv));
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;
1509         return (0);
1510 }
1511
1512 /*
1513  * File table truncate routine.
1514  */
1515 static int
1516 vn_truncate(struct file *fp, off_t length, struct ucred *active_cred,
1517     struct thread *td)
1518 {
1519         struct mount *mp;
1520         struct vnode *vp;
1521         void *rl_cookie;
1522         int error;
1523
1524         vp = fp->f_vnode;
1525
1526         /*
1527          * Lock the whole range for truncation.  Otherwise split i/o
1528          * might happen partly before and partly after the truncation.
1529          */
1530         rl_cookie = vn_rangelock_wlock(vp, 0, OFF_MAX);
1531         error = vn_start_write(vp, &mp, V_WAIT | PCATCH);
1532         if (error)
1533                 goto out1;
1534         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1535         AUDIT_ARG_VNODE1(vp);
1536         if (vp->v_type == VDIR) {
1537                 error = EISDIR;
1538                 goto out;
1539         }
1540 #ifdef MAC
1541         error = mac_vnode_check_write(active_cred, fp->f_cred, vp);
1542         if (error)
1543                 goto out;
1544 #endif
1545         error = vn_truncate_locked(vp, length, (fp->f_flag & O_FSYNC) != 0,
1546             fp->f_cred);
1547 out:
1548         VOP_UNLOCK(vp);
1549         vn_finished_write(mp);
1550 out1:
1551         vn_rangelock_unlock(vp, rl_cookie);
1552         return (error);
1553 }
1554
1555 /*
1556  * Truncate a file that is already locked.
1557  */
1558 int
1559 vn_truncate_locked(struct vnode *vp, off_t length, bool sync,
1560     struct ucred *cred)
1561 {
1562         struct vattr vattr;
1563         int error;
1564
1565         error = VOP_ADD_WRITECOUNT(vp, 1);
1566         if (error == 0) {
1567                 VATTR_NULL(&vattr);
1568                 vattr.va_size = length;
1569                 if (sync)
1570                         vattr.va_vaflags |= VA_SYNC;
1571                 error = VOP_SETATTR(vp, &vattr, cred);
1572                 VOP_ADD_WRITECOUNT_CHECKED(vp, -1);
1573         }
1574         return (error);
1575 }
1576
1577 /*
1578  * File table vnode stat routine.
1579  */
1580 static int
1581 vn_statfile(struct file *fp, struct stat *sb, struct ucred *active_cred,
1582     struct thread *td)
1583 {
1584         struct vnode *vp = fp->f_vnode;
1585         int error;
1586
1587         vn_lock(vp, LK_SHARED | LK_RETRY);
1588         error = VOP_STAT(vp, sb, active_cred, fp->f_cred, td);
1589         VOP_UNLOCK(vp);
1590
1591         return (error);
1592 }
1593
1594 /*
1595  * File table vnode ioctl routine.
1596  */
1597 static int
1598 vn_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
1599     struct thread *td)
1600 {
1601         struct vattr vattr;
1602         struct vnode *vp;
1603         struct fiobmap2_arg *bmarg;
1604         int error;
1605
1606         vp = fp->f_vnode;
1607         switch (vp->v_type) {
1608         case VDIR:
1609         case VREG:
1610                 switch (com) {
1611                 case FIONREAD:
1612                         vn_lock(vp, LK_SHARED | LK_RETRY);
1613                         error = VOP_GETATTR(vp, &vattr, active_cred);
1614                         VOP_UNLOCK(vp);
1615                         if (error == 0)
1616                                 *(int *)data = vattr.va_size - fp->f_offset;
1617                         return (error);
1618                 case FIOBMAP2:
1619                         bmarg = (struct fiobmap2_arg *)data;
1620                         vn_lock(vp, LK_SHARED | LK_RETRY);
1621 #ifdef MAC
1622                         error = mac_vnode_check_read(active_cred, fp->f_cred,
1623                             vp);
1624                         if (error == 0)
1625 #endif
1626                                 error = VOP_BMAP(vp, bmarg->bn, NULL,
1627                                     &bmarg->bn, &bmarg->runp, &bmarg->runb);
1628                         VOP_UNLOCK(vp);
1629                         return (error);
1630                 case FIONBIO:
1631                 case FIOASYNC:
1632                         return (0);
1633                 default:
1634                         return (VOP_IOCTL(vp, com, data, fp->f_flag,
1635                             active_cred, td));
1636                 }
1637                 break;
1638         case VCHR:
1639                 return (VOP_IOCTL(vp, com, data, fp->f_flag,
1640                     active_cred, td));
1641         default:
1642                 return (ENOTTY);
1643         }
1644 }
1645
1646 /*
1647  * File table vnode poll routine.
1648  */
1649 static int
1650 vn_poll(struct file *fp, int events, struct ucred *active_cred,
1651     struct thread *td)
1652 {
1653         struct vnode *vp;
1654         int error;
1655
1656         vp = fp->f_vnode;
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);
1662                 VOP_UNLOCK(vp);
1663                 if (error != 0)
1664                         return (error);
1665         }
1666 #endif
1667         error = VOP_POLL(vp, events, fp->f_cred, td);
1668         return (error);
1669 }
1670
1671 /*
1672  * Acquire the requested lock and then check for validity.  LK_RETRY
1673  * permits vn_lock to return doomed vnodes.
1674  */
1675 static int __noinline
1676 _vn_lock_fallback(struct vnode *vp, int flags, const char *file, int line,
1677     int error)
1678 {
1679
1680         KASSERT((flags & LK_RETRY) == 0 || error == 0,
1681             ("vn_lock: error %d incompatible with flags %#x", error, flags));
1682
1683         if (error == 0)
1684                 VNASSERT(VN_IS_DOOMED(vp), vp, ("vnode not doomed"));
1685
1686         if ((flags & LK_RETRY) == 0) {
1687                 if (error == 0) {
1688                         VOP_UNLOCK(vp);
1689                         error = ENOENT;
1690                 }
1691                 return (error);
1692         }
1693
1694         /*
1695          * LK_RETRY case.
1696          *
1697          * Nothing to do if we got the lock.
1698          */
1699         if (error == 0)
1700                 return (0);
1701
1702         /*
1703          * Interlock was dropped by the call in _vn_lock.
1704          */
1705         flags &= ~LK_INTERLOCK;
1706         do {
1707                 error = VOP_LOCK1(vp, flags, file, line);
1708         } while (error != 0);
1709         return (0);
1710 }
1711
1712 int
1713 _vn_lock(struct vnode *vp, int flags, const char *file, int line)
1714 {
1715         int error;
1716
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));
1723         return (0);
1724 }
1725
1726 /*
1727  * File table vnode close routine.
1728  */
1729 static int
1730 vn_closefile(struct file *fp, struct thread *td)
1731 {
1732         struct vnode *vp;
1733         struct flock lf;
1734         int error;
1735         bool ref;
1736
1737         vp = fp->f_vnode;
1738         fp->f_ops = &badfileops;
1739         ref= (fp->f_flag & FHASLOCK) != 0 && fp->f_type == DTYPE_VNODE;
1740
1741         error = vn_close1(vp, fp->f_flag, fp->f_cred, td, ref);
1742
1743         if (__predict_false(ref)) {
1744                 lf.l_whence = SEEK_SET;
1745                 lf.l_start = 0;
1746                 lf.l_len = 0;
1747                 lf.l_type = F_UNLCK;
1748                 (void) VOP_ADVLOCK(vp, fp, F_UNLCK, &lf, F_FLOCK);
1749                 vrele(vp);
1750         }
1751         return (error);
1752 }
1753
1754 /*
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.
1759  */
1760 static int
1761 vn_start_write_refed(struct mount *mp, int flags, bool mplocked)
1762 {
1763         int error, mflags;
1764
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);
1770                 return (0);
1771         }
1772
1773         if (mplocked)
1774                 mtx_assert(MNT_MTX(mp), MA_OWNED);
1775         else
1776                 MNT_ILOCK(mp);
1777
1778         error = 0;
1779
1780         /*
1781          * Check on status of suspension.
1782          */
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;
1790                                 goto unlock;
1791                         }
1792                         error = msleep(&mp->mnt_flag, MNT_MTX(mp), mflags,
1793                             "suspfs", 0);
1794                         if (error)
1795                                 goto unlock;
1796                 }
1797         }
1798         if (flags & V_XSLEEP)
1799                 goto unlock;
1800         mp->mnt_writeopcount++;
1801 unlock:
1802         if (error != 0 || (flags & V_XSLEEP) != 0)
1803                 MNT_REL(mp);
1804         MNT_IUNLOCK(mp);
1805         return (error);
1806 }
1807
1808 int
1809 vn_start_write(struct vnode *vp, struct mount **mpp, int flags)
1810 {
1811         struct mount *mp;
1812         int error;
1813
1814         KASSERT((flags & V_MNTREF) == 0 || (*mpp != NULL && vp == NULL),
1815             ("V_MNTREF requires mp"));
1816
1817         error = 0;
1818         /*
1819          * If a vnode is provided, get and return the mount point that
1820          * to which it will write.
1821          */
1822         if (vp != NULL) {
1823                 if ((error = VOP_GETWRITEMOUNT(vp, mpp)) != 0) {
1824                         *mpp = NULL;
1825                         if (error != EOPNOTSUPP)
1826                                 return (error);
1827                         return (0);
1828                 }
1829         }
1830         if ((mp = *mpp) == NULL)
1831                 return (0);
1832
1833         /*
1834          * VOP_GETWRITEMOUNT() returns with the mp refcount held through
1835          * a vfs_ref().
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().
1839          */
1840         if (vp == NULL && (flags & V_MNTREF) == 0)
1841                 vfs_ref(mp);
1842
1843         return (vn_start_write_refed(mp, flags, false));
1844 }
1845
1846 /*
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.
1852  */
1853 int
1854 vn_start_secondary_write(struct vnode *vp, struct mount **mpp, int flags)
1855 {
1856         struct mount *mp;
1857         int error;
1858
1859         KASSERT((flags & V_MNTREF) == 0 || (*mpp != NULL && vp == NULL),
1860             ("V_MNTREF requires mp"));
1861
1862  retry:
1863         if (vp != NULL) {
1864                 if ((error = VOP_GETWRITEMOUNT(vp, mpp)) != 0) {
1865                         *mpp = NULL;
1866                         if (error != EOPNOTSUPP)
1867                                 return (error);
1868                         return (0);
1869                 }
1870         }
1871         /*
1872          * If we are not suspended or have not yet reached suspended
1873          * mode, then let the operation proceed.
1874          */
1875         if ((mp = *mpp) == NULL)
1876                 return (0);
1877
1878         /*
1879          * VOP_GETWRITEMOUNT() returns with the mp refcount held through
1880          * a vfs_ref().
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().
1884          */
1885         MNT_ILOCK(mp);
1886         if (vp == NULL && (flags & V_MNTREF) == 0)
1887                 MNT_REF(mp);
1888         if ((mp->mnt_kern_flag & (MNTK_SUSPENDED | MNTK_SUSPEND2)) == 0) {
1889                 mp->mnt_secondary_writes++;
1890                 mp->mnt_secondary_accwrites++;
1891                 MNT_IUNLOCK(mp);
1892                 return (0);
1893         }
1894         if (flags & V_NOWAIT) {
1895                 MNT_REL(mp);
1896                 MNT_IUNLOCK(mp);
1897                 return (EWOULDBLOCK);
1898         }
1899         /*
1900          * Wait for the suspension to finish.
1901          */
1902         error = msleep(&mp->mnt_flag, MNT_MTX(mp), (PUSER - 1) | PDROP |
1903             ((mp->mnt_vfc->vfc_flags & VFCF_SBDRY) != 0 ? (flags & PCATCH) : 0),
1904             "suspfs", 0);
1905         vfs_rel(mp);
1906         if (error == 0)
1907                 goto retry;
1908         return (error);
1909 }
1910
1911 /*
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
1914  * now in effect.
1915  */
1916 void
1917 vn_finished_write(struct mount *mp)
1918 {
1919         int c;
1920
1921         if (mp == NULL)
1922                 return;
1923
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);
1928                 return;
1929         }
1930
1931         MNT_ILOCK(mp);
1932         vfs_assert_mount_counters(mp);
1933         MNT_REL(mp);
1934         c = --mp->mnt_writeopcount;
1935         if (mp->mnt_vfs_ops == 0) {
1936                 MPASS((mp->mnt_kern_flag & MNTK_SUSPEND) == 0);
1937                 MNT_IUNLOCK(mp);
1938                 return;
1939         }
1940         if (c < 0)
1941                 vfs_dump_mount_counters(mp);
1942         if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0 && c == 0)
1943                 wakeup(&mp->mnt_writeopcount);
1944         MNT_IUNLOCK(mp);
1945 }
1946
1947 /*
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.
1951  */
1952 void
1953 vn_finished_secondary_write(struct mount *mp)
1954 {
1955         if (mp == NULL)
1956                 return;
1957         MNT_ILOCK(mp);
1958         MNT_REL(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);
1965         MNT_IUNLOCK(mp);
1966 }
1967
1968 /*
1969  * Request a filesystem to suspend write operations.
1970  */
1971 int
1972 vfs_write_suspend(struct mount *mp, int flags)
1973 {
1974         int error;
1975
1976         vfs_op_enter(mp);
1977
1978         MNT_ILOCK(mp);
1979         vfs_assert_mount_counters(mp);
1980         if (mp->mnt_susp_owner == curthread) {
1981                 vfs_op_exit_locked(mp);
1982                 MNT_IUNLOCK(mp);
1983                 return (EALREADY);
1984         }
1985         while (mp->mnt_kern_flag & MNTK_SUSPEND)
1986                 msleep(&mp->mnt_flag, MNT_MTX(mp), PUSER - 1, "wsuspfs", 0);
1987
1988         /*
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
1994          * unmount context.
1995          */
1996         if ((flags & VS_SKIP_UNMOUNT) != 0 &&
1997             (mp->mnt_kern_flag & MNTK_UNMOUNT) != 0) {
1998                 vfs_op_exit_locked(mp);
1999                 MNT_IUNLOCK(mp);
2000                 return (EBUSY);
2001         }
2002
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);
2008         else
2009                 MNT_IUNLOCK(mp);
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 */
2013         }
2014         return (error);
2015 }
2016
2017 /*
2018  * Request a filesystem to resume write operations.
2019  */
2020 void
2021 vfs_write_resume(struct mount *mp, int flags)
2022 {
2023
2024         MNT_ILOCK(mp);
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 |
2028                                        MNTK_SUSPENDED);
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) {
2034                         MNT_REF(mp);
2035                         mp->mnt_writeopcount++;
2036                 }
2037                 MNT_IUNLOCK(mp);
2038                 if ((flags & VR_NO_SUSPCLR) == 0)
2039                         VFS_SUSP_CLEAN(mp);
2040                 vfs_op_exit(mp);
2041         } else if ((flags & VR_START_WRITE) != 0) {
2042                 MNT_REF(mp);
2043                 vn_start_write_refed(mp, 0, true);
2044         } else {
2045                 MNT_IUNLOCK(mp);
2046         }
2047 }
2048
2049 /*
2050  * Helper loop around vfs_write_suspend() for filesystem unmount VFS
2051  * methods.
2052  */
2053 int
2054 vfs_write_suspend_umnt(struct mount *mp)
2055 {
2056         int error;
2057
2058         KASSERT((curthread->td_pflags & TDP_IGNSUSP) == 0,
2059             ("vfs_write_suspend_umnt: recursed"));
2060
2061         /* dounmount() already called vn_start_write(). */
2062         for (;;) {
2063                 vn_finished_write(mp);
2064                 error = vfs_write_suspend(mp, 0);
2065                 if (error != 0) {
2066                         vn_start_write(NULL, &mp, V_WAIT);
2067                         return (error);
2068                 }
2069                 MNT_ILOCK(mp);
2070                 if ((mp->mnt_kern_flag & MNTK_SUSPENDED) != 0)
2071                         break;
2072                 MNT_IUNLOCK(mp);
2073                 vn_start_write(NULL, &mp, V_WAIT);
2074         }
2075         mp->mnt_kern_flag &= ~(MNTK_SUSPENDED | MNTK_SUSPEND2);
2076         wakeup(&mp->mnt_flag);
2077         MNT_IUNLOCK(mp);
2078         curthread->td_pflags |= TDP_IGNSUSP;
2079         return (0);
2080 }
2081
2082 /*
2083  * Implement kqueues for files by translating it to vnode operation.
2084  */
2085 static int
2086 vn_kqfilter(struct file *fp, struct knote *kn)
2087 {
2088
2089         return (VOP_KQFILTER(fp->f_vnode, kn));
2090 }
2091
2092 /*
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.
2096  */
2097 int
2098 vn_extattr_get(struct vnode *vp, int ioflg, int attrnamespace,
2099     const char *attrname, int *buflen, char *buf, struct thread *td)
2100 {
2101         struct uio      auio;
2102         struct iovec    iov;
2103         int     error;
2104
2105         iov.iov_len = *buflen;
2106         iov.iov_base = buf;
2107
2108         auio.uio_iov = &iov;
2109         auio.uio_iovcnt = 1;
2110         auio.uio_rw = UIO_READ;
2111         auio.uio_segflg = UIO_SYSSPACE;
2112         auio.uio_td = td;
2113         auio.uio_offset = 0;
2114         auio.uio_resid = *buflen;
2115
2116         if ((ioflg & IO_NODELOCKED) == 0)
2117                 vn_lock(vp, LK_SHARED | LK_RETRY);
2118
2119         ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
2120
2121         /* authorize attribute retrieval as kernel */
2122         error = VOP_GETEXTATTR(vp, attrnamespace, attrname, &auio, NULL, NULL,
2123             td);
2124
2125         if ((ioflg & IO_NODELOCKED) == 0)
2126                 VOP_UNLOCK(vp);
2127
2128         if (error == 0) {
2129                 *buflen = *buflen - auio.uio_resid;
2130         }
2131
2132         return (error);
2133 }
2134
2135 /*
2136  * XXX failure mode if partially written?
2137  */
2138 int
2139 vn_extattr_set(struct vnode *vp, int ioflg, int attrnamespace,
2140     const char *attrname, int buflen, char *buf, struct thread *td)
2141 {
2142         struct uio      auio;
2143         struct iovec    iov;
2144         struct mount    *mp;
2145         int     error;
2146
2147         iov.iov_len = buflen;
2148         iov.iov_base = buf;
2149
2150         auio.uio_iov = &iov;
2151         auio.uio_iovcnt = 1;
2152         auio.uio_rw = UIO_WRITE;
2153         auio.uio_segflg = UIO_SYSSPACE;
2154         auio.uio_td = td;
2155         auio.uio_offset = 0;
2156         auio.uio_resid = buflen;
2157
2158         if ((ioflg & IO_NODELOCKED) == 0) {
2159                 if ((error = vn_start_write(vp, &mp, V_WAIT)) != 0)
2160                         return (error);
2161                 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2162         }
2163
2164         ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
2165
2166         /* authorize attribute setting as kernel */
2167         error = VOP_SETEXTATTR(vp, attrnamespace, attrname, &auio, NULL, td);
2168
2169         if ((ioflg & IO_NODELOCKED) == 0) {
2170                 vn_finished_write(mp);
2171                 VOP_UNLOCK(vp);
2172         }
2173
2174         return (error);
2175 }
2176
2177 int
2178 vn_extattr_rm(struct vnode *vp, int ioflg, int attrnamespace,
2179     const char *attrname, struct thread *td)
2180 {
2181         struct mount    *mp;
2182         int     error;
2183
2184         if ((ioflg & IO_NODELOCKED) == 0) {
2185                 if ((error = vn_start_write(vp, &mp, V_WAIT)) != 0)
2186                         return (error);
2187                 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2188         }
2189
2190         ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
2191
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,
2196                     NULL, td);
2197
2198         if ((ioflg & IO_NODELOCKED) == 0) {
2199                 vn_finished_write(mp);
2200                 VOP_UNLOCK(vp);
2201         }
2202
2203         return (error);
2204 }
2205
2206 static int
2207 vn_get_ino_alloc_vget(struct mount *mp, void *arg, int lkflags,
2208     struct vnode **rvp)
2209 {
2210
2211         return (VFS_VGET(mp, *(ino_t *)arg, lkflags, rvp));
2212 }
2213
2214 int
2215 vn_vget_ino(struct vnode *vp, ino_t ino, int lkflags, struct vnode **rvp)
2216 {
2217
2218         return (vn_vget_ino_gen(vp, vn_get_ino_alloc_vget, &ino,
2219             lkflags, rvp));
2220 }
2221
2222 int
2223 vn_vget_ino_gen(struct vnode *vp, vn_get_ino_t alloc, void *alloc_arg,
2224     int lkflags, struct vnode **rvp)
2225 {
2226         struct mount *mp;
2227         int ltype, error;
2228
2229         ASSERT_VOP_LOCKED(vp, "vn_vget_ino_get");
2230         mp = vp->v_mount;
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);
2235         if (error != 0) {
2236                 vfs_ref(mp);
2237                 VOP_UNLOCK(vp);
2238                 error = vfs_busy(mp, 0);
2239                 vn_lock(vp, ltype | LK_RETRY);
2240                 vfs_rel(mp);
2241                 if (error != 0)
2242                         return (ENOENT);
2243                 if (VN_IS_DOOMED(vp)) {
2244                         vfs_unbusy(mp);
2245                         return (ENOENT);
2246                 }
2247         }
2248         VOP_UNLOCK(vp);
2249         error = alloc(mp, alloc_arg, lkflags, rvp);
2250         vfs_unbusy(mp);
2251         if (error != 0 || *rvp != vp)
2252                 vn_lock(vp, ltype | LK_RETRY);
2253         if (VN_IS_DOOMED(vp)) {
2254                 if (error == 0) {
2255                         if (*rvp == vp)
2256                                 vunref(vp);
2257                         else
2258                                 vput(*rvp);
2259                 }
2260                 error = ENOENT;
2261         }
2262         return (error);
2263 }
2264
2265 int
2266 vn_rlimit_fsize(const struct vnode *vp, const struct uio *uio,
2267     struct thread *td)
2268 {
2269
2270         if (vp->v_type != VREG || td == NULL)
2271                 return (0);
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);
2277                 return (EFBIG);
2278         }
2279         return (0);
2280 }
2281
2282 int
2283 vn_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
2284     struct thread *td)
2285 {
2286         struct vnode *vp;
2287
2288         vp = fp->f_vnode;
2289 #ifdef AUDIT
2290         vn_lock(vp, LK_SHARED | LK_RETRY);
2291         AUDIT_ARG_VNODE1(vp);
2292         VOP_UNLOCK(vp);
2293 #endif
2294         return (setfmode(td, active_cred, vp, mode));
2295 }
2296
2297 int
2298 vn_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
2299     struct thread *td)
2300 {
2301         struct vnode *vp;
2302
2303         vp = fp->f_vnode;
2304 #ifdef AUDIT
2305         vn_lock(vp, LK_SHARED | LK_RETRY);
2306         AUDIT_ARG_VNODE1(vp);
2307         VOP_UNLOCK(vp);
2308 #endif
2309         return (setfown(td, active_cred, vp, uid, gid));
2310 }
2311
2312 void
2313 vn_pages_remove(struct vnode *vp, vm_pindex_t start, vm_pindex_t end)
2314 {
2315         vm_object_t object;
2316
2317         if ((object = vp->v_object) == NULL)
2318                 return;
2319         VM_OBJECT_WLOCK(object);
2320         vm_object_page_remove(object, start, end, 0);
2321         VM_OBJECT_WUNLOCK(object);
2322 }
2323
2324 int
2325 vn_bmap_seekhole(struct vnode *vp, u_long cmd, off_t *off, struct ucred *cred)
2326 {
2327         struct vattr va;
2328         daddr_t bn, bnp;
2329         uint64_t bsize;
2330         off_t noff;
2331         int error;
2332
2333         KASSERT(cmd == FIOSEEKHOLE || cmd == FIOSEEKDATA,
2334             ("Wrong command %lu", cmd));
2335
2336         if (vn_lock(vp, LK_SHARED) != 0)
2337                 return (EBADF);
2338         if (vp->v_type != VREG) {
2339                 error = ENOTTY;
2340                 goto unlock;
2341         }
2342         error = VOP_GETATTR(vp, &va, cred);
2343         if (error != 0)
2344                 goto unlock;
2345         noff = *off;
2346         if (noff >= va.va_size) {
2347                 error = ENXIO;
2348                 goto unlock;
2349         }
2350         bsize = vp->v_mount->mnt_stat.f_iosize;
2351         for (bn = noff / bsize; noff < va.va_size; bn++, noff += bsize -
2352             noff % bsize) {
2353                 error = VOP_BMAP(vp, bn, NULL, &bnp, NULL, NULL);
2354                 if (error == EOPNOTSUPP) {
2355                         error = ENOTTY;
2356                         goto unlock;
2357                 }
2358                 if ((bnp == -1 && cmd == FIOSEEKHOLE) ||
2359                     (bnp != -1 && cmd == FIOSEEKDATA)) {
2360                         noff = bn * bsize;
2361                         if (noff < *off)
2362                                 noff = *off;
2363                         goto unlock;
2364                 }
2365         }
2366         if (noff > va.va_size)
2367                 noff = va.va_size;
2368         /* noff == va.va_size. There is an implicit hole at the end of file. */
2369         if (cmd == FIOSEEKDATA)
2370                 error = ENXIO;
2371 unlock:
2372         VOP_UNLOCK(vp);
2373         if (error == 0)
2374                 *off = noff;
2375         return (error);
2376 }
2377
2378 int
2379 vn_seek(struct file *fp, off_t offset, int whence, struct thread *td)
2380 {
2381         struct ucred *cred;
2382         struct vnode *vp;
2383         struct vattr vattr;
2384         off_t foffset, size;
2385         int error, noneg;
2386
2387         cred = td->td_ucred;
2388         vp = fp->f_vnode;
2389         foffset = foffset_lock(fp, 0);
2390         noneg = (vp->v_type != VCHR);
2391         error = 0;
2392         switch (whence) {
2393         case L_INCR:
2394                 if (noneg &&
2395                     (foffset < 0 ||
2396                     (offset > 0 && foffset > OFF_MAX - offset))) {
2397                         error = EOVERFLOW;
2398                         break;
2399                 }
2400                 offset += foffset;
2401                 break;
2402         case L_XTND:
2403                 vn_lock(vp, LK_SHARED | LK_RETRY);
2404                 error = VOP_GETATTR(vp, &vattr, cred);
2405                 VOP_UNLOCK(vp);
2406                 if (error)
2407                         break;
2408
2409                 /*
2410                  * If the file references a disk device, then fetch
2411                  * the media size and use that to determine the ending
2412                  * offset.
2413                  */
2414                 if (vattr.va_size == 0 && vp->v_type == VCHR &&
2415                     fo_ioctl(fp, DIOCGMEDIASIZE, &size, cred, td) == 0)
2416                         vattr.va_size = size;
2417                 if (noneg &&
2418                     (vattr.va_size > OFF_MAX ||
2419                     (offset > 0 && vattr.va_size > OFF_MAX - offset))) {
2420                         error = EOVERFLOW;
2421                         break;
2422                 }
2423                 offset += vattr.va_size;
2424                 break;
2425         case L_SET:
2426                 break;
2427         case SEEK_DATA:
2428                 error = fo_ioctl(fp, FIOSEEKDATA, &offset, cred, td);
2429                 if (error == ENOTTY)
2430                         error = EINVAL;
2431                 break;
2432         case SEEK_HOLE:
2433                 error = fo_ioctl(fp, FIOSEEKHOLE, &offset, cred, td);
2434                 if (error == ENOTTY)
2435                         error = EINVAL;
2436                 break;
2437         default:
2438                 error = EINVAL;
2439         }
2440         if (error == 0 && noneg && offset < 0)
2441                 error = EINVAL;
2442         if (error != 0)
2443                 goto drop;
2444         VFS_KNOTE_UNLOCKED(vp, 0);
2445         td->td_uretoff.tdu_off = offset;
2446 drop:
2447         foffset_unlock(fp, offset, error != 0 ? FOF_NOUPDATE : 0);
2448         return (error);
2449 }
2450
2451 int
2452 vn_utimes_perm(struct vnode *vp, struct vattr *vap, struct ucred *cred,
2453     struct thread *td)
2454 {
2455         int error;
2456
2457         /*
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.
2462          *
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
2466          * server time.
2467          */
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);
2471         return (error);
2472 }
2473
2474 int
2475 vn_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
2476 {
2477         struct vnode *vp;
2478         int error;
2479
2480         if (fp->f_type == DTYPE_FIFO)
2481                 kif->kf_type = KF_TYPE_FIFO;
2482         else
2483                 kif->kf_type = KF_TYPE_VNODE;
2484         vp = fp->f_vnode;
2485         vref(vp);
2486         FILEDESC_SUNLOCK(fdp);
2487         error = vn_fill_kinfo_vnode(vp, kif);
2488         vrele(vp);
2489         FILEDESC_SLOCK(fdp);
2490         return (error);
2491 }
2492
2493 static inline void
2494 vn_fill_junk(struct kinfo_file *kif)
2495 {
2496         size_t len, olen;
2497
2498         /*
2499          * Simulate vn_fullpath returning changing values for a given
2500          * vp during e.g. coredump.
2501          */
2502         len = (arc4random() % (sizeof(kif->kf_path) - 2)) + 1;
2503         olen = strlen(kif->kf_path);
2504         if (len < olen)
2505                 strcpy(&kif->kf_path[len - 1], "$");
2506         else
2507                 for (; olen < len; olen++)
2508                         strcpy(&kif->kf_path[olen], "A");
2509 }
2510
2511 int
2512 vn_fill_kinfo_vnode(struct vnode *vp, struct kinfo_file *kif)
2513 {
2514         struct vattr va;
2515         char *fullpath, *freepath;
2516         int error;
2517
2518         kif->kf_un.kf_file.kf_file_type = vntype_to_kinfo(vp->v_type);
2519         freepath = NULL;
2520         fullpath = "-";
2521         error = vn_fullpath(vp, &fullpath, &freepath);
2522         if (error == 0) {
2523                 strlcpy(kif->kf_path, fullpath, sizeof(kif->kf_path));
2524         }
2525         if (freepath != NULL)
2526                 free(freepath, M_TEMP);
2527
2528         KFAIL_POINT_CODE(DEBUG_FP, fill_kinfo_vnode__random_path,
2529                 vn_fill_junk(kif);
2530         );
2531
2532         /*
2533          * Retrieve vnode attributes.
2534          */
2535         va.va_fsid = VNOVAL;
2536         va.va_rdev = NODEV;
2537         vn_lock(vp, LK_SHARED | LK_RETRY);
2538         error = VOP_GETATTR(vp, &va, curthread->td_ucred);
2539         VOP_UNLOCK(vp);
2540         if (error != 0)
2541                 return (error);
2542         if (va.va_fsid != VNOVAL)
2543                 kif->kf_un.kf_file.kf_file_fsid = va.va_fsid;
2544         else
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 */
2555         return (0);
2556 }
2557
2558 int
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,
2561     struct thread *td)
2562 {
2563 #ifdef HWPMC_HOOKS
2564         struct pmckern_map_in pkm;
2565 #endif
2566         struct mount *mp;
2567         struct vnode *vp;
2568         vm_object_t object;
2569         vm_prot_t maxprot;
2570         boolean_t writecounted;
2571         int error;
2572
2573 #if defined(COMPAT_FREEBSD7) || defined(COMPAT_FREEBSD6) || \
2574     defined(COMPAT_FREEBSD5) || defined(COMPAT_FREEBSD4)
2575         /*
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.
2582          */
2583         if ((fp->f_flag & FPOSIXSHM) != 0)
2584                 flags |= MAP_NOSYNC;
2585 #endif
2586         vp = fp->f_vnode;
2587
2588         /*
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?
2596          */
2597         mp = vp->v_mount;
2598         if (mp != NULL && (mp->mnt_flag & MNT_NOEXEC) != 0) {
2599                 maxprot = VM_PROT_NONE;
2600                 if ((prot & VM_PROT_EXECUTE) != 0)
2601                         return (EACCES);
2602         } else
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)
2607                 return (EACCES);
2608
2609         /*
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.
2613          */
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)
2618                         return (EACCES);
2619         } else {
2620                 maxprot |= VM_PROT_WRITE;
2621                 cap_maxprot |= VM_PROT_WRITE;
2622         }
2623         maxprot &= cap_maxprot;
2624
2625         /*
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
2634          * on.
2635          */
2636         if (
2637 #ifdef _LP64
2638             size > OFF_MAX ||
2639 #endif
2640             foff > OFF_MAX - size)
2641                 return (EINVAL);
2642
2643         writecounted = FALSE;
2644         error = vm_mmap_vnode(td, size, prot, &maxprot, &flags, vp,
2645             &foff, &object, &writecounted);
2646         if (error != 0)
2647                 return (error);
2648         error = vm_mmap_object(map, addr, size, prot, maxprot, flags, object,
2649             foff, writecounted, td);
2650         if (error != 0) {
2651                 /*
2652                  * If this mapping was accounted for in the vnode's
2653                  * writecount, then undo that now.
2654                  */
2655                 if (writecounted)
2656                         vm_pager_release_writecount(object, 0, size);
2657                 vm_object_deallocate(object);
2658         }
2659 #ifdef HWPMC_HOOKS
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) {
2663                         pkm.pm_file = vp;
2664                         pkm.pm_address = (uintptr_t) *addr;
2665                         PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_MMAP, (void *) &pkm);
2666                 }
2667         }
2668 #endif
2669         return (error);
2670 }
2671
2672 void
2673 vn_fsid(struct vnode *vp, struct vattr *va)
2674 {
2675         fsid_t *f;
2676
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];
2681 }
2682
2683 int
2684 vn_fsync_buf(struct vnode *vp, int waitfor)
2685 {
2686         struct buf *bp, *nbp;
2687         struct bufobj *bo;
2688         struct mount *mp;
2689         int error, maxretry;
2690
2691         error = 0;
2692         maxretry = 10000;     /* large, arbitrarily chosen */
2693         mp = NULL;
2694         if (vp->v_type == VCHR) {
2695                 VI_LOCK(vp);
2696                 mp = vp->v_rdev->si_mountpt;
2697                 VI_UNLOCK(vp);
2698         }
2699         bo = &vp->v_bufobj;
2700         BO_LOCK(bo);
2701 loop1:
2702         /*
2703          * MARK/SCAN initialization to avoid infinite loops.
2704          */
2705         TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
2706                 bp->b_vflags &= ~BV_SCANNED;
2707                 bp->b_error = 0;
2708         }
2709
2710         /*
2711          * Flush all dirty buffers associated with a vnode.
2712          */
2713 loop2:
2714         TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
2715                 if ((bp->b_vflags & BV_SCANNED) != 0)
2716                         continue;
2717                 bp->b_vflags |= BV_SCANNED;
2718                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL)) {
2719                         if (waitfor != MNT_WAIT)
2720                                 continue;
2721                         if (BUF_LOCK(bp,
2722                             LK_EXCLUSIVE | LK_INTERLOCK | LK_SLEEPFAIL,
2723                             BO_LOCKPTR(bo)) != 0) {
2724                                 BO_LOCK(bo);
2725                                 goto loop1;
2726                         }
2727                         BO_LOCK(bo);
2728                 }
2729                 BO_UNLOCK(bo);
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)) {
2736                         vfs_bio_awrite(bp);
2737                 } else {
2738                         bremfree(bp);
2739                         bawrite(bp);
2740                 }
2741                 if (maxretry < 1000)
2742                         pause("dirty", hz < 1000 ? 1 : hz / 1000);
2743                 BO_LOCK(bo);
2744                 goto loop2;
2745         }
2746
2747         /*
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.
2752          */
2753         if (waitfor == MNT_WAIT) {
2754                 bufobj_wwait(bo, 0, 0);
2755                 if (bo->bo_dirty.bv_cnt > 0) {
2756                         /*
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.
2760                          */
2761                         TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
2762                                 if ((error = bp->b_error) != 0)
2763                                         break;
2764                         if ((mp != NULL && mp->mnt_secondary_writes > 0) ||
2765                             (error == 0 && --maxretry >= 0))
2766                                 goto loop1;
2767                         if (error == 0)
2768                                 error = EAGAIN;
2769                 }
2770         }
2771         BO_UNLOCK(bo);
2772         if (error != 0)
2773                 vn_printf(vp, "fsync: giving up on dirty (error = %d) ", error);
2774
2775         return (error);
2776 }
2777
2778 /*
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.
2785  */
2786 int
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)
2790 {
2791         int error;
2792         size_t len;
2793         uint64_t uval;
2794
2795         len = *lenp;
2796         *lenp = 0;              /* For error returns. */
2797         error = 0;
2798
2799         /* Do some sanity checks on the arguments. */
2800         if (invp->v_type == VDIR || outvp->v_type == VDIR)
2801                 error = EISDIR;
2802         else if (*inoffp < 0 || *outoffp < 0 ||
2803             invp->v_type != VREG || outvp->v_type != VREG)
2804                 error = EINVAL;
2805         if (error != 0)
2806                 goto out;
2807
2808         /* Ensure offset + len does not wrap around. */
2809         uval = *inoffp;
2810         uval += len;
2811         if (uval > INT64_MAX)
2812                 len = INT64_MAX - *inoffp;
2813         uval = *outoffp;
2814         uval += len;
2815         if (uval > INT64_MAX)
2816                 len = INT64_MAX - *outoffp;
2817         if (len == 0)
2818                 goto out;
2819
2820         /*
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.
2824          */
2825         *lenp = len;
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);
2829         else
2830                 error = vn_generic_copy_file_range(invp, inoffp, outvp,
2831                     outoffp, lenp, flags, incred, outcred, fsize_td);
2832 out:
2833         return (error);
2834 }
2835
2836 /*
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.
2840  */
2841 static bool
2842 mem_iszero(void *dat, int len)
2843 {
2844         int i;
2845         const u_int *p;
2846         const char *cp;
2847
2848         for (p = dat; len > 0; len -= sizeof(*p), p++) {
2849                 if (len >= sizeof(*p)) {
2850                         if (*p != 0)
2851                                 return (false);
2852                 } else {
2853                         cp = (const char *)p;
2854                         for (i = 0; i < len; i++, cp++)
2855                                 if (*cp != '\0')
2856                                         return (false);
2857                 }
2858         }
2859         return (true);
2860 }
2861
2862 /*
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.
2867  */
2868 static off_t
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)
2871 {
2872         int error;
2873         off_t delta;
2874
2875         if (*holeoffp == 0 || *holeoffp <= *outoffp) {
2876                 *dataoffp = *outoffp;
2877                 error = VOP_IOCTL(outvp, FIOSEEKDATA, dataoffp, 0, cred,
2878                     curthread);
2879                 if (error == 0) {
2880                         *holeoffp = *dataoffp;
2881                         error = VOP_IOCTL(outvp, FIOSEEKHOLE, holeoffp, 0, cred,
2882                             curthread);
2883                 }
2884                 if (error != 0 || *holeoffp == *dataoffp) {
2885                         /*
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
2890                          * rangelocking.
2891                          * If that happens, *holeoffp == *dataoffp and finding
2892                          * the hole has failed, so disable vn_skip_hole().
2893                          */
2894                         *holeoffp = -1; /* Disable use of vn_skip_hole(). */
2895                         return (xfer2);
2896                 }
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));
2903         }
2904
2905         /*
2906          * If there is a hole before the data starts, advance *outoffp and
2907          * *xferp past the hole.
2908          */
2909         if (*dataoffp > *outoffp) {
2910                 delta = *dataoffp - *outoffp;
2911                 if (delta >= *xferp) {
2912                         /* Entire *xferp is a hole. */
2913                         *outoffp += *xferp;
2914                         *xferp = 0;
2915                         return (0);
2916                 }
2917                 *xferp -= delta;
2918                 *outoffp += delta;
2919                 xfer2 = MIN(xfer2, *xferp);
2920         }
2921
2922         /*
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
2927          * value.
2928          */
2929         if (*holeoffp > *outoffp && *holeoffp < *outoffp + xfer2)
2930                 xfer2 = *holeoffp - *outoffp;
2931         return (xfer2);
2932 }
2933
2934 /*
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
2937  * the chunk.
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.
2942  */
2943 static int
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)
2946 {
2947         struct mount *mp;
2948         off_t dataoff, holeoff, xfer2;
2949         int error, lckf;
2950
2951         /*
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.
2956          */
2957         error = 0;
2958         holeoff = 0;
2959         do {
2960                 xfer2 = MIN(xfer, blksize);
2961                 if (checkhole) {
2962                         /*
2963                          * Punching a hole.  Skip writing if there is
2964                          * already a hole in the output file.
2965                          */
2966                         xfer2 = vn_skip_hole(outvp, xfer2, &outoff, &xfer,
2967                             &dataoff, &holeoff, cred);
2968                         if (xfer == 0)
2969                                 break;
2970                         if (holeoff < 0)
2971                                 checkhole = false;
2972                         KASSERT(xfer2 > 0, ("vn_write_outvp: xfer2=%jd",
2973                             (intmax_t)xfer2));
2974                 }
2975                 bwillwrite();
2976                 mp = NULL;
2977                 error = vn_start_write(outvp, &mp, V_WAIT);
2978                 if (error == 0) {
2979                         if (MNT_SHARED_WRITES(mp))
2980                                 lckf = LK_SHARED;
2981                         else
2982                                 lckf = LK_EXCLUSIVE;
2983                         error = vn_lock(outvp, lckf);
2984                 }
2985                 if (error == 0) {
2986                         if (growfile)
2987                                 error = vn_truncate_locked(outvp, outoff + xfer,
2988                                     false, cred);
2989                         else {
2990                                 error = vn_rdwr(UIO_WRITE, outvp, dat, xfer2,
2991                                     outoff, UIO_SYSSPACE, IO_NODELOCKED,
2992                                     curthread->td_ucred, cred, NULL, curthread);
2993                                 outoff += xfer2;
2994                                 xfer -= xfer2;
2995                         }
2996                         VOP_UNLOCK(outvp);
2997                 }
2998                 if (mp != NULL)
2999                         vn_finished_write(mp);
3000         } while (!growfile && xfer > 0 && error == 0);
3001         return (error);
3002 }
3003
3004 /*
3005  * Copy a byte range of one file to another.  This function can handle the
3006  * case where invp and outvp are on different file systems.
3007  * It can also be called by a VOP_COPY_FILE_RANGE() to do the work, if there
3008  * is no better file system specific way to do it.
3009  */
3010 int
3011 vn_generic_copy_file_range(struct vnode *invp, off_t *inoffp,
3012     struct vnode *outvp, off_t *outoffp, size_t *lenp, unsigned int flags,
3013     struct ucred *incred, struct ucred *outcred, struct thread *fsize_td)
3014 {
3015         struct vattr va;
3016         struct mount *mp;
3017         struct uio io;
3018         off_t startoff, endoff, xfer, xfer2;
3019         u_long blksize;
3020         int error;
3021         bool cantseek, readzeros, eof, lastblock;
3022         ssize_t aresid;
3023         size_t copylen, len, rem, savlen;
3024         char *dat;
3025         long holein, holeout;
3026
3027         holein = holeout = 0;
3028         savlen = len = *lenp;
3029         error = 0;
3030         dat = NULL;
3031
3032         error = vn_lock(invp, LK_SHARED);
3033         if (error != 0)
3034                 goto out;
3035         if (VOP_PATHCONF(invp, _PC_MIN_HOLE_SIZE, &holein) != 0)
3036                 holein = 0;
3037         VOP_UNLOCK(invp);
3038
3039         mp = NULL;
3040         error = vn_start_write(outvp, &mp, V_WAIT);
3041         if (error == 0)
3042                 error = vn_lock(outvp, LK_EXCLUSIVE);
3043         if (error == 0) {
3044                 /*
3045                  * If fsize_td != NULL, do a vn_rlimit_fsize() call,
3046                  * now that outvp is locked.
3047                  */
3048                 if (fsize_td != NULL) {
3049                         io.uio_offset = *outoffp;
3050                         io.uio_resid = len;
3051                         error = vn_rlimit_fsize(outvp, &io, fsize_td);
3052                         if (error != 0)
3053                                 error = EFBIG;
3054                 }
3055                 if (VOP_PATHCONF(outvp, _PC_MIN_HOLE_SIZE, &holeout) != 0)
3056                         holeout = 0;
3057                 /*
3058                  * Holes that are past EOF do not need to be written as a block
3059                  * of zero bytes.  So, truncate the output file as far as
3060                  * possible and then use va.va_size to decide if writing 0
3061                  * bytes is necessary in the loop below.
3062                  */
3063                 if (error == 0)
3064                         error = VOP_GETATTR(outvp, &va, outcred);
3065                 if (error == 0 && va.va_size > *outoffp && va.va_size <=
3066                     *outoffp + len) {
3067 #ifdef MAC
3068                         error = mac_vnode_check_write(curthread->td_ucred,
3069                             outcred, outvp);
3070                         if (error == 0)
3071 #endif
3072                                 error = vn_truncate_locked(outvp, *outoffp,
3073                                     false, outcred);
3074                         if (error == 0)
3075                                 va.va_size = *outoffp;
3076                 }
3077                 VOP_UNLOCK(outvp);
3078         }
3079         if (mp != NULL)
3080                 vn_finished_write(mp);
3081         if (error != 0)
3082                 goto out;
3083
3084         /*
3085          * Set the blksize to the larger of the hole sizes for invp and outvp.
3086          * If hole sizes aren't available, set the blksize to the larger 
3087          * f_iosize of invp and outvp.
3088          * This code expects the hole sizes and f_iosizes to be powers of 2.
3089          * This value is clipped at 4Kbytes and 1Mbyte.
3090          */
3091         blksize = MAX(holein, holeout);
3092
3093         /* Clip len to end at an exact multiple of hole size. */
3094         if (blksize > 1) {
3095                 rem = *inoffp % blksize;
3096                 if (rem > 0)
3097                         rem = blksize - rem;
3098                 if (len - rem > blksize)
3099                         len = savlen = rounddown(len - rem, blksize) + rem;
3100         }
3101
3102         if (blksize <= 1)
3103                 blksize = MAX(invp->v_mount->mnt_stat.f_iosize,
3104                     outvp->v_mount->mnt_stat.f_iosize);
3105         if (blksize < 4096)
3106                 blksize = 4096;
3107         else if (blksize > 1024 * 1024)
3108                 blksize = 1024 * 1024;
3109         dat = malloc(blksize, M_TEMP, M_WAITOK);
3110
3111         /*
3112          * If VOP_IOCTL(FIOSEEKHOLE) works for invp, use it and FIOSEEKDATA
3113          * to find holes.  Otherwise, just scan the read block for all 0s
3114          * in the inner loop where the data copying is done.
3115          * Note that some file systems such as NFSv3, NFSv4.0 and NFSv4.1 may
3116          * support holes on the server, but do not support FIOSEEKHOLE.
3117          */
3118         eof = false;
3119         while (len > 0 && error == 0 && !eof) {
3120                 endoff = 0;                     /* To shut up compilers. */
3121                 cantseek = true;
3122                 startoff = *inoffp;
3123                 copylen = len;
3124
3125                 /*
3126                  * Find the next data area.  If there is just a hole to EOF,
3127                  * FIOSEEKDATA should fail and then we drop down into the
3128                  * inner loop and create the hole on the outvp file.
3129                  * (I do not know if any file system will report a hole to
3130                  *  EOF via FIOSEEKHOLE, but I am pretty sure FIOSEEKDATA
3131                  *  will fail for those file systems.)
3132                  *
3133                  * For input files that don't support FIOSEEKDATA/FIOSEEKHOLE,
3134                  * the code just falls through to the inner copy loop.
3135                  */
3136                 error = EINVAL;
3137                 if (holein > 0)
3138                         error = VOP_IOCTL(invp, FIOSEEKDATA, &startoff, 0,
3139                             incred, curthread);
3140                 if (error == 0) {
3141                         endoff = startoff;
3142                         error = VOP_IOCTL(invp, FIOSEEKHOLE, &endoff, 0,
3143                             incred, curthread);
3144                         /*
3145                          * Since invp is unlocked, it may be possible for
3146                          * another thread to do a truncate(), lseek(), write()
3147                          * creating a hole at startoff between the above
3148                          * VOP_IOCTL() calls, if the other thread does not do
3149                          * rangelocking.
3150                          * If that happens, startoff == endoff and finding
3151                          * the hole has failed, so set an error.
3152                          */
3153                         if (error == 0 && startoff == endoff)
3154                                 error = EINVAL; /* Any error. Reset to 0. */
3155                 }
3156                 if (error == 0) {
3157                         if (startoff > *inoffp) {
3158                                 /* Found hole before data block. */
3159                                 xfer = MIN(startoff - *inoffp, len);
3160                                 if (*outoffp < va.va_size) {
3161                                         /* Must write 0s to punch hole. */
3162                                         xfer2 = MIN(va.va_size - *outoffp,
3163                                             xfer);
3164                                         memset(dat, 0, MIN(xfer2, blksize));
3165                                         error = vn_write_outvp(outvp, dat,
3166                                             *outoffp, xfer2, blksize, false,
3167                                             holeout > 0, outcred);
3168                                 }
3169
3170                                 if (error == 0 && *outoffp + xfer >
3171                                     va.va_size && xfer == len)
3172                                         /* Grow last block. */
3173                                         error = vn_write_outvp(outvp, dat,
3174                                             *outoffp, xfer, blksize, true,
3175                                             false, outcred);
3176                                 if (error == 0) {
3177                                         *inoffp += xfer;
3178                                         *outoffp += xfer;
3179                                         len -= xfer;
3180                                 }
3181                         }
3182                         copylen = MIN(len, endoff - startoff);
3183                         cantseek = false;
3184                 } else {
3185                         cantseek = true;
3186                         startoff = *inoffp;
3187                         copylen = len;
3188                         error = 0;
3189                 }
3190
3191                 xfer = blksize;
3192                 if (cantseek) {
3193                         /*
3194                          * Set first xfer to end at a block boundary, so that
3195                          * holes are more likely detected in the loop below via
3196                          * the for all bytes 0 method.
3197                          */
3198                         xfer -= (*inoffp % blksize);
3199                 }
3200                 /* Loop copying the data block. */
3201                 while (copylen > 0 && error == 0 && !eof) {
3202                         if (copylen < xfer)
3203                                 xfer = copylen;
3204                         error = vn_lock(invp, LK_SHARED);
3205                         if (error != 0)
3206                                 goto out;
3207                         error = vn_rdwr(UIO_READ, invp, dat, xfer,
3208                             startoff, UIO_SYSSPACE, IO_NODELOCKED,
3209                             curthread->td_ucred, incred, &aresid,
3210                             curthread);
3211                         VOP_UNLOCK(invp);
3212                         lastblock = false;
3213                         if (error == 0 && aresid > 0) {
3214                                 /* Stop the copy at EOF on the input file. */
3215                                 xfer -= aresid;
3216                                 eof = true;
3217                                 lastblock = true;
3218                         }
3219                         if (error == 0) {
3220                                 /*
3221                                  * Skip the write for holes past the initial EOF
3222                                  * of the output file, unless this is the last
3223                                  * write of the output file at EOF.
3224                                  */
3225                                 readzeros = cantseek ? mem_iszero(dat, xfer) :
3226                                     false;
3227                                 if (xfer == len)
3228                                         lastblock = true;
3229                                 if (!cantseek || *outoffp < va.va_size ||
3230                                     lastblock || !readzeros)
3231                                         error = vn_write_outvp(outvp, dat,
3232                                             *outoffp, xfer, blksize,
3233                                             readzeros && lastblock &&
3234                                             *outoffp >= va.va_size, false,
3235                                             outcred);
3236                                 if (error == 0) {
3237                                         *inoffp += xfer;
3238                                         startoff += xfer;
3239                                         *outoffp += xfer;
3240                                         copylen -= xfer;
3241                                         len -= xfer;
3242                                 }
3243                         }
3244                         xfer = blksize;
3245                 }
3246         }
3247 out:
3248         *lenp = savlen - len;
3249         free(dat, M_TEMP);
3250         return (error);
3251 }
3252
3253 static int
3254 vn_fallocate(struct file *fp, off_t offset, off_t len, struct thread *td)
3255 {
3256         struct mount *mp;
3257         struct vnode *vp;
3258         off_t olen, ooffset;
3259         int error;
3260 #ifdef AUDIT
3261         int audited_vnode1 = 0;
3262 #endif
3263
3264         vp = fp->f_vnode;
3265         if (vp->v_type != VREG)
3266                 return (ENODEV);
3267
3268         /* Allocating blocks may take a long time, so iterate. */
3269         for (;;) {
3270                 olen = len;
3271                 ooffset = offset;
3272
3273                 bwillwrite();
3274                 mp = NULL;
3275                 error = vn_start_write(vp, &mp, V_WAIT | PCATCH);
3276                 if (error != 0)
3277                         break;
3278                 error = vn_lock(vp, LK_EXCLUSIVE);
3279                 if (error != 0) {
3280                         vn_finished_write(mp);
3281                         break;
3282                 }
3283 #ifdef AUDIT
3284                 if (!audited_vnode1) {
3285                         AUDIT_ARG_VNODE1(vp);
3286                         audited_vnode1 = 1;
3287                 }
3288 #endif
3289 #ifdef MAC
3290                 error = mac_vnode_check_write(td->td_ucred, fp->f_cred, vp);
3291                 if (error == 0)
3292 #endif
3293                         error = VOP_ALLOCATE(vp, &offset, &len);
3294                 VOP_UNLOCK(vp);
3295                 vn_finished_write(mp);
3296
3297                 if (olen + ooffset != offset + len) {
3298                         panic("offset + len changed from %jx/%jx to %jx/%jx",
3299                             ooffset, olen, offset, len);
3300                 }
3301                 if (error != 0 || len == 0)
3302                         break;
3303                 KASSERT(olen > len, ("Iteration did not make progress?"));
3304                 maybe_yield();
3305         }
3306
3307         return (error);
3308 }