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