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