]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/vfs_vnops.c
Merge ACPICA 20120620.
[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  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *      @(#)vfs_vnops.c 8.2 (Berkeley) 1/21/94
35  */
36
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/fcntl.h>
43 #include <sys/file.h>
44 #include <sys/kdb.h>
45 #include <sys/stat.h>
46 #include <sys/priv.h>
47 #include <sys/proc.h>
48 #include <sys/limits.h>
49 #include <sys/lock.h>
50 #include <sys/mount.h>
51 #include <sys/mutex.h>
52 #include <sys/namei.h>
53 #include <sys/vnode.h>
54 #include <sys/bio.h>
55 #include <sys/buf.h>
56 #include <sys/filio.h>
57 #include <sys/resourcevar.h>
58 #include <sys/sx.h>
59 #include <sys/sysctl.h>
60 #include <sys/ttycom.h>
61 #include <sys/conf.h>
62 #include <sys/syslog.h>
63 #include <sys/unistd.h>
64
65 #include <security/audit/audit.h>
66 #include <security/mac/mac_framework.h>
67
68 #include <vm/vm.h>
69 #include <vm/vm_extern.h>
70 #include <vm/pmap.h>
71 #include <vm/vm_map.h>
72 #include <vm/vm_object.h>
73 #include <vm/vm_page.h>
74
75 static fo_rdwr_t        vn_read;
76 static fo_rdwr_t        vn_write;
77 static fo_rdwr_t        vn_io_fault;
78 static fo_truncate_t    vn_truncate;
79 static fo_ioctl_t       vn_ioctl;
80 static fo_poll_t        vn_poll;
81 static fo_kqfilter_t    vn_kqfilter;
82 static fo_stat_t        vn_statfile;
83 static fo_close_t       vn_closefile;
84
85 struct  fileops vnops = {
86         .fo_read = vn_io_fault,
87         .fo_write = vn_io_fault,
88         .fo_truncate = vn_truncate,
89         .fo_ioctl = vn_ioctl,
90         .fo_poll = vn_poll,
91         .fo_kqfilter = vn_kqfilter,
92         .fo_stat = vn_statfile,
93         .fo_close = vn_closefile,
94         .fo_chmod = vn_chmod,
95         .fo_chown = vn_chown,
96         .fo_flags = DFLAG_PASSABLE | DFLAG_SEEKABLE
97 };
98
99 int
100 vn_open(ndp, flagp, cmode, fp)
101         struct nameidata *ndp;
102         int *flagp, cmode;
103         struct file *fp;
104 {
105         struct thread *td = ndp->ni_cnd.cn_thread;
106
107         return (vn_open_cred(ndp, flagp, cmode, 0, td->td_ucred, fp));
108 }
109
110 /*
111  * Common code for vnode open operations via a name lookup.
112  * Lookup the vnode and invoke VOP_CREATE if needed.
113  * Check permissions, and call the VOP_OPEN or VOP_CREATE routine.
114  * 
115  * Note that this does NOT free nameidata for the successful case,
116  * due to the NDINIT being done elsewhere.
117  */
118 int
119 vn_open_cred(struct nameidata *ndp, int *flagp, int cmode, u_int vn_open_flags,
120     struct ucred *cred, struct file *fp)
121 {
122         struct vnode *vp;
123         struct mount *mp;
124         struct thread *td = ndp->ni_cnd.cn_thread;
125         struct vattr vat;
126         struct vattr *vap = &vat;
127         int fmode, error;
128         int vfslocked, mpsafe;
129
130         mpsafe = ndp->ni_cnd.cn_flags & MPSAFE;
131 restart:
132         vfslocked = 0;
133         fmode = *flagp;
134         if (fmode & O_CREAT) {
135                 ndp->ni_cnd.cn_nameiop = CREATE;
136                 ndp->ni_cnd.cn_flags = ISOPEN | LOCKPARENT | LOCKLEAF |
137                     MPSAFE;
138                 if ((fmode & O_EXCL) == 0 && (fmode & O_NOFOLLOW) == 0)
139                         ndp->ni_cnd.cn_flags |= FOLLOW;
140                 if (!(vn_open_flags & VN_OPEN_NOAUDIT))
141                         ndp->ni_cnd.cn_flags |= AUDITVNODE1;
142                 bwillwrite();
143                 if ((error = namei(ndp)) != 0)
144                         return (error);
145                 vfslocked = NDHASGIANT(ndp);
146                 if (!mpsafe)
147                         ndp->ni_cnd.cn_flags &= ~MPSAFE;
148                 if (ndp->ni_vp == NULL) {
149                         VATTR_NULL(vap);
150                         vap->va_type = VREG;
151                         vap->va_mode = cmode;
152                         if (fmode & O_EXCL)
153                                 vap->va_vaflags |= VA_EXCLUSIVE;
154                         if (vn_start_write(ndp->ni_dvp, &mp, V_NOWAIT) != 0) {
155                                 NDFREE(ndp, NDF_ONLY_PNBUF);
156                                 vput(ndp->ni_dvp);
157                                 VFS_UNLOCK_GIANT(vfslocked);
158                                 if ((error = vn_start_write(NULL, &mp,
159                                     V_XSLEEP | PCATCH)) != 0)
160                                         return (error);
161                                 goto restart;
162                         }
163 #ifdef MAC
164                         error = mac_vnode_check_create(cred, ndp->ni_dvp,
165                             &ndp->ni_cnd, vap);
166                         if (error == 0)
167 #endif
168                                 error = VOP_CREATE(ndp->ni_dvp, &ndp->ni_vp,
169                                                    &ndp->ni_cnd, vap);
170                         vput(ndp->ni_dvp);
171                         vn_finished_write(mp);
172                         if (error) {
173                                 VFS_UNLOCK_GIANT(vfslocked);
174                                 NDFREE(ndp, NDF_ONLY_PNBUF);
175                                 return (error);
176                         }
177                         fmode &= ~O_TRUNC;
178                         vp = ndp->ni_vp;
179                 } else {
180                         if (ndp->ni_dvp == ndp->ni_vp)
181                                 vrele(ndp->ni_dvp);
182                         else
183                                 vput(ndp->ni_dvp);
184                         ndp->ni_dvp = NULL;
185                         vp = ndp->ni_vp;
186                         if (fmode & O_EXCL) {
187                                 error = EEXIST;
188                                 goto bad;
189                         }
190                         fmode &= ~O_CREAT;
191                 }
192         } else {
193                 ndp->ni_cnd.cn_nameiop = LOOKUP;
194                 ndp->ni_cnd.cn_flags = ISOPEN |
195                     ((fmode & O_NOFOLLOW) ? NOFOLLOW : FOLLOW) |
196                     LOCKLEAF | MPSAFE;
197                 if (!(fmode & FWRITE))
198                         ndp->ni_cnd.cn_flags |= LOCKSHARED;
199                 if (!(vn_open_flags & VN_OPEN_NOAUDIT))
200                         ndp->ni_cnd.cn_flags |= AUDITVNODE1;
201                 if ((error = namei(ndp)) != 0)
202                         return (error);
203                 if (!mpsafe)
204                         ndp->ni_cnd.cn_flags &= ~MPSAFE;
205                 vfslocked = NDHASGIANT(ndp);
206                 vp = ndp->ni_vp;
207         }
208         error = vn_open_vnode(vp, fmode, cred, td, fp);
209         if (error)
210                 goto bad;
211         *flagp = fmode;
212         if (!mpsafe)
213                 VFS_UNLOCK_GIANT(vfslocked);
214         return (0);
215 bad:
216         NDFREE(ndp, NDF_ONLY_PNBUF);
217         vput(vp);
218         VFS_UNLOCK_GIANT(vfslocked);
219         *flagp = fmode;
220         ndp->ni_vp = NULL;
221         return (error);
222 }
223
224 /*
225  * Common code for vnode open operations once a vnode is located.
226  * Check permissions, and call the VOP_OPEN routine.
227  */
228 int
229 vn_open_vnode(struct vnode *vp, int fmode, struct ucred *cred,
230     struct thread *td, struct file *fp)
231 {
232         accmode_t accmode;
233         int error;
234
235         VFS_ASSERT_GIANT(vp->v_mount);
236         if (vp->v_type == VLNK)
237                 return (EMLINK);
238         if (vp->v_type == VSOCK)
239                 return (EOPNOTSUPP);
240         if (vp->v_type != VDIR && fmode & O_DIRECTORY)
241                 return (ENOTDIR);
242         accmode = 0;
243         if (fmode & (FWRITE | O_TRUNC)) {
244                 if (vp->v_type == VDIR)
245                         return (EISDIR);
246                 accmode |= VWRITE;
247         }
248         if (fmode & FREAD)
249                 accmode |= VREAD;
250         if (fmode & FEXEC)
251                 accmode |= VEXEC;
252         if ((fmode & O_APPEND) && (fmode & FWRITE))
253                 accmode |= VAPPEND;
254 #ifdef MAC
255         error = mac_vnode_check_open(cred, vp, accmode);
256         if (error)
257                 return (error);
258 #endif
259         if ((fmode & O_CREAT) == 0) {
260                 if (accmode & VWRITE) {
261                         error = vn_writechk(vp);
262                         if (error)
263                                 return (error);
264                 }
265                 if (accmode) {
266                         error = VOP_ACCESS(vp, accmode, cred, td);
267                         if (error)
268                                 return (error);
269                 }
270         }
271         if ((error = VOP_OPEN(vp, fmode, cred, td, fp)) != 0)
272                 return (error);
273
274         if (fmode & FWRITE) {
275                 vp->v_writecount++;
276                 CTR3(KTR_VFS, "%s: vp %p v_writecount increased to %d",
277                     __func__, vp, vp->v_writecount);
278         }
279         ASSERT_VOP_LOCKED(vp, "vn_open_vnode");
280         return (0);
281 }
282
283 /*
284  * Check for write permissions on the specified vnode.
285  * Prototype text segments cannot be written.
286  */
287 int
288 vn_writechk(vp)
289         register struct vnode *vp;
290 {
291
292         ASSERT_VOP_LOCKED(vp, "vn_writechk");
293         /*
294          * If there's shared text associated with
295          * the vnode, try to free it up once.  If
296          * we fail, we can't allow writing.
297          */
298         if (vp->v_vflag & VV_TEXT)
299                 return (ETXTBSY);
300
301         return (0);
302 }
303
304 /*
305  * Vnode close call
306  */
307 int
308 vn_close(vp, flags, file_cred, td)
309         register struct vnode *vp;
310         int flags;
311         struct ucred *file_cred;
312         struct thread *td;
313 {
314         struct mount *mp;
315         int error, lock_flags;
316
317         if (!(flags & FWRITE) && vp->v_mount != NULL &&
318             vp->v_mount->mnt_kern_flag & MNTK_EXTENDED_SHARED)
319                 lock_flags = LK_SHARED;
320         else
321                 lock_flags = LK_EXCLUSIVE;
322
323         VFS_ASSERT_GIANT(vp->v_mount);
324
325         vn_start_write(vp, &mp, V_WAIT);
326         vn_lock(vp, lock_flags | LK_RETRY);
327         if (flags & FWRITE) {
328                 VNASSERT(vp->v_writecount > 0, vp, 
329                     ("vn_close: negative writecount"));
330                 vp->v_writecount--;
331                 CTR3(KTR_VFS, "%s: vp %p v_writecount decreased to %d",
332                     __func__, vp, vp->v_writecount);
333         }
334         error = VOP_CLOSE(vp, flags, file_cred, td);
335         vput(vp);
336         vn_finished_write(mp);
337         return (error);
338 }
339
340 /*
341  * Heuristic to detect sequential operation.
342  */
343 static int
344 sequential_heuristic(struct uio *uio, struct file *fp)
345 {
346
347         if (atomic_load_acq_int(&(fp->f_flag)) & FRDAHEAD)
348                 return (fp->f_seqcount << IO_SEQSHIFT);
349
350         /*
351          * Offset 0 is handled specially.  open() sets f_seqcount to 1 so
352          * that the first I/O is normally considered to be slightly
353          * sequential.  Seeking to offset 0 doesn't change sequentiality
354          * unless previous seeks have reduced f_seqcount to 0, in which
355          * case offset 0 is not special.
356          */
357         if ((uio->uio_offset == 0 && fp->f_seqcount > 0) ||
358             uio->uio_offset == fp->f_nextoff) {
359                 /*
360                  * f_seqcount is in units of fixed-size blocks so that it
361                  * depends mainly on the amount of sequential I/O and not
362                  * much on the number of sequential I/O's.  The fixed size
363                  * of 16384 is hard-coded here since it is (not quite) just
364                  * a magic size that works well here.  This size is more
365                  * closely related to the best I/O size for real disks than
366                  * to any block size used by software.
367                  */
368                 fp->f_seqcount += howmany(uio->uio_resid, 16384);
369                 if (fp->f_seqcount > IO_SEQMAX)
370                         fp->f_seqcount = IO_SEQMAX;
371                 return (fp->f_seqcount << IO_SEQSHIFT);
372         }
373
374         /* Not sequential.  Quickly draw-down sequentiality. */
375         if (fp->f_seqcount > 1)
376                 fp->f_seqcount = 1;
377         else
378                 fp->f_seqcount = 0;
379         return (0);
380 }
381
382 /*
383  * Package up an I/O request on a vnode into a uio and do it.
384  */
385 int
386 vn_rdwr(enum uio_rw rw, struct vnode *vp, void *base, int len, off_t offset,
387     enum uio_seg segflg, int ioflg, struct ucred *active_cred,
388     struct ucred *file_cred, ssize_t *aresid, struct thread *td)
389 {
390         struct uio auio;
391         struct iovec aiov;
392         struct mount *mp;
393         struct ucred *cred;
394         void *rl_cookie;
395         int error, lock_flags;
396
397         VFS_ASSERT_GIANT(vp->v_mount);
398
399         auio.uio_iov = &aiov;
400         auio.uio_iovcnt = 1;
401         aiov.iov_base = base;
402         aiov.iov_len = len;
403         auio.uio_resid = len;
404         auio.uio_offset = offset;
405         auio.uio_segflg = segflg;
406         auio.uio_rw = rw;
407         auio.uio_td = td;
408         error = 0;
409
410         if ((ioflg & IO_NODELOCKED) == 0) {
411                 if (rw == UIO_READ) {
412                         rl_cookie = vn_rangelock_rlock(vp, offset,
413                             offset + len);
414                 } else {
415                         rl_cookie = vn_rangelock_wlock(vp, offset,
416                             offset + len);
417                 }
418                 mp = NULL;
419                 if (rw == UIO_WRITE) { 
420                         if (vp->v_type != VCHR &&
421                             (error = vn_start_write(vp, &mp, V_WAIT | PCATCH))
422                             != 0)
423                                 goto out;
424                         if (MNT_SHARED_WRITES(mp) ||
425                             ((mp == NULL) && MNT_SHARED_WRITES(vp->v_mount)))
426                                 lock_flags = LK_SHARED;
427                         else
428                                 lock_flags = LK_EXCLUSIVE;
429                 } else
430                         lock_flags = LK_SHARED;
431                 vn_lock(vp, lock_flags | LK_RETRY);
432         } else
433                 rl_cookie = NULL;
434
435         ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
436 #ifdef MAC
437         if ((ioflg & IO_NOMACCHECK) == 0) {
438                 if (rw == UIO_READ)
439                         error = mac_vnode_check_read(active_cred, file_cred,
440                             vp);
441                 else
442                         error = mac_vnode_check_write(active_cred, file_cred,
443                             vp);
444         }
445 #endif
446         if (error == 0) {
447                 if (file_cred != NULL)
448                         cred = file_cred;
449                 else
450                         cred = active_cred;
451                 if (rw == UIO_READ)
452                         error = VOP_READ(vp, &auio, ioflg, cred);
453                 else
454                         error = VOP_WRITE(vp, &auio, ioflg, cred);
455         }
456         if (aresid)
457                 *aresid = auio.uio_resid;
458         else
459                 if (auio.uio_resid && error == 0)
460                         error = EIO;
461         if ((ioflg & IO_NODELOCKED) == 0) {
462                 VOP_UNLOCK(vp, 0);
463                 if (mp != NULL)
464                         vn_finished_write(mp);
465         }
466  out:
467         if (rl_cookie != NULL)
468                 vn_rangelock_unlock(vp, rl_cookie);
469         return (error);
470 }
471
472 /*
473  * Package up an I/O request on a vnode into a uio and do it.  The I/O
474  * request is split up into smaller chunks and we try to avoid saturating
475  * the buffer cache while potentially holding a vnode locked, so we 
476  * check bwillwrite() before calling vn_rdwr().  We also call kern_yield()
477  * to give other processes a chance to lock the vnode (either other processes
478  * core'ing the same binary, or unrelated processes scanning the directory).
479  */
480 int
481 vn_rdwr_inchunks(rw, vp, base, len, offset, segflg, ioflg, active_cred,
482     file_cred, aresid, td)
483         enum uio_rw rw;
484         struct vnode *vp;
485         void *base;
486         size_t len;
487         off_t offset;
488         enum uio_seg segflg;
489         int ioflg;
490         struct ucred *active_cred;
491         struct ucred *file_cred;
492         size_t *aresid;
493         struct thread *td;
494 {
495         int error = 0;
496         ssize_t iaresid;
497
498         VFS_ASSERT_GIANT(vp->v_mount);
499
500         do {
501                 int chunk;
502
503                 /*
504                  * Force `offset' to a multiple of MAXBSIZE except possibly
505                  * for the first chunk, so that filesystems only need to
506                  * write full blocks except possibly for the first and last
507                  * chunks.
508                  */
509                 chunk = MAXBSIZE - (uoff_t)offset % MAXBSIZE;
510
511                 if (chunk > len)
512                         chunk = len;
513                 if (rw != UIO_READ && vp->v_type == VREG)
514                         bwillwrite();
515                 iaresid = 0;
516                 error = vn_rdwr(rw, vp, base, chunk, offset, segflg,
517                     ioflg, active_cred, file_cred, &iaresid, td);
518                 len -= chunk;   /* aresid calc already includes length */
519                 if (error)
520                         break;
521                 offset += chunk;
522                 base = (char *)base + chunk;
523                 kern_yield(PRI_USER);
524         } while (len);
525         if (aresid)
526                 *aresid = len + iaresid;
527         return (error);
528 }
529
530 static void
531 foffset_lock(struct file *fp, struct uio *uio, int flags)
532 {
533         struct mtx *mtxp;
534
535         if ((flags & FOF_OFFSET) != 0)
536                 return;
537
538         /*
539          * According to McKusick the vn lock was protecting f_offset here.
540          * It is now protected by the FOFFSET_LOCKED flag.
541          */
542         mtxp = mtx_pool_find(mtxpool_sleep, fp);
543         mtx_lock(mtxp);
544         while (fp->f_vnread_flags & FOFFSET_LOCKED) {
545                 fp->f_vnread_flags |= FOFFSET_LOCK_WAITING;
546                 msleep(&fp->f_vnread_flags, mtxp, PUSER -1,
547                     "vnread offlock", 0);
548         }
549         fp->f_vnread_flags |= FOFFSET_LOCKED;
550         uio->uio_offset = fp->f_offset;
551         mtx_unlock(mtxp);
552 }
553
554 static int
555 get_advice(struct file *fp, struct uio *uio)
556 {
557         struct mtx *mtxp;
558         int ret;
559
560         ret = POSIX_FADV_NORMAL;
561         if (fp->f_advice == NULL)
562                 return (ret);
563
564         mtxp = mtx_pool_find(mtxpool_sleep, fp);
565         mtx_lock(mtxp);
566         if (uio->uio_offset >= fp->f_advice->fa_start &&
567             uio->uio_offset + uio->uio_resid <= fp->f_advice->fa_end)
568                 ret = fp->f_advice->fa_advice;
569         mtx_unlock(mtxp);
570         return (ret);
571 }
572
573 static void
574 foffset_unlock(struct file *fp, struct uio *uio, int flags)
575 {
576         struct mtx *mtxp;
577
578         if ((flags & FOF_OFFSET) != 0)
579                 return;
580
581         fp->f_offset = uio->uio_offset;
582         mtxp = mtx_pool_find(mtxpool_sleep, fp);
583         mtx_lock(mtxp);
584         if (fp->f_vnread_flags & FOFFSET_LOCK_WAITING)
585                 wakeup(&fp->f_vnread_flags);
586         fp->f_vnread_flags = 0;
587         mtx_unlock(mtxp);
588 }
589
590 /*
591  * File table vnode read routine.
592  */
593 static int
594 vn_read(fp, uio, active_cred, flags, td)
595         struct file *fp;
596         struct uio *uio;
597         struct ucred *active_cred;
598         int flags;
599         struct thread *td;
600 {
601         struct vnode *vp;
602         struct mtx *mtxp;
603         int error, ioflag;
604         int advice, vfslocked;
605         off_t offset, start, end;
606
607         KASSERT(uio->uio_td == td, ("uio_td %p is not td %p",
608             uio->uio_td, td));
609         KASSERT(flags & FOF_OFFSET, ("No FOF_OFFSET"));
610         vp = fp->f_vnode;
611         ioflag = 0;
612         if (fp->f_flag & FNONBLOCK)
613                 ioflag |= IO_NDELAY;
614         if (fp->f_flag & O_DIRECT)
615                 ioflag |= IO_DIRECT;
616         advice = get_advice(fp, uio);
617         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
618         vn_lock(vp, LK_SHARED | LK_RETRY);
619
620         switch (advice) {
621         case POSIX_FADV_NORMAL:
622         case POSIX_FADV_SEQUENTIAL:
623         case POSIX_FADV_NOREUSE:
624                 ioflag |= sequential_heuristic(uio, fp);
625                 break;
626         case POSIX_FADV_RANDOM:
627                 /* Disable read-ahead for random I/O. */
628                 break;
629         }
630         offset = uio->uio_offset;
631
632 #ifdef MAC
633         error = mac_vnode_check_read(active_cred, fp->f_cred, vp);
634         if (error == 0)
635 #endif
636                 error = VOP_READ(vp, uio, ioflag, fp->f_cred);
637         fp->f_nextoff = uio->uio_offset;
638         VOP_UNLOCK(vp, 0);
639         if (error == 0 && advice == POSIX_FADV_NOREUSE &&
640             offset != uio->uio_offset) {
641                 /*
642                  * Use POSIX_FADV_DONTNEED to flush clean pages and
643                  * buffers for the backing file after a
644                  * POSIX_FADV_NOREUSE read(2).  To optimize the common
645                  * case of using POSIX_FADV_NOREUSE with sequential
646                  * access, track the previous implicit DONTNEED
647                  * request and grow this request to include the
648                  * current read(2) in addition to the previous
649                  * DONTNEED.  With purely sequential access this will
650                  * cause the DONTNEED requests to continously grow to
651                  * cover all of the previously read regions of the
652                  * file.  This allows filesystem blocks that are
653                  * accessed by multiple calls to read(2) to be flushed
654                  * once the last read(2) finishes.
655                  */
656                 start = offset;
657                 end = uio->uio_offset - 1;
658                 mtxp = mtx_pool_find(mtxpool_sleep, fp);
659                 mtx_lock(mtxp);
660                 if (fp->f_advice != NULL &&
661                     fp->f_advice->fa_advice == POSIX_FADV_NOREUSE) {
662                         if (start != 0 && fp->f_advice->fa_prevend + 1 == start)
663                                 start = fp->f_advice->fa_prevstart;
664                         else if (fp->f_advice->fa_prevstart != 0 &&
665                             fp->f_advice->fa_prevstart == end + 1)
666                                 end = fp->f_advice->fa_prevend;
667                         fp->f_advice->fa_prevstart = start;
668                         fp->f_advice->fa_prevend = end;
669                 }
670                 mtx_unlock(mtxp);
671                 error = VOP_ADVISE(vp, start, end, POSIX_FADV_DONTNEED);
672         }
673         VFS_UNLOCK_GIANT(vfslocked);
674         return (error);
675 }
676
677 /*
678  * File table vnode write routine.
679  */
680 static int
681 vn_write(fp, uio, active_cred, flags, td)
682         struct file *fp;
683         struct uio *uio;
684         struct ucred *active_cred;
685         int flags;
686         struct thread *td;
687 {
688         struct vnode *vp;
689         struct mount *mp;
690         struct mtx *mtxp;
691         int error, ioflag, lock_flags;
692         int advice, vfslocked;
693         off_t offset, start, end;
694
695         KASSERT(uio->uio_td == td, ("uio_td %p is not td %p",
696             uio->uio_td, td));
697         KASSERT(flags & FOF_OFFSET, ("No FOF_OFFSET"));
698         vp = fp->f_vnode;
699         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
700         if (vp->v_type == VREG)
701                 bwillwrite();
702         ioflag = IO_UNIT;
703         if (vp->v_type == VREG && (fp->f_flag & O_APPEND))
704                 ioflag |= IO_APPEND;
705         if (fp->f_flag & FNONBLOCK)
706                 ioflag |= IO_NDELAY;
707         if (fp->f_flag & O_DIRECT)
708                 ioflag |= IO_DIRECT;
709         if ((fp->f_flag & O_FSYNC) ||
710             (vp->v_mount && (vp->v_mount->mnt_flag & MNT_SYNCHRONOUS)))
711                 ioflag |= IO_SYNC;
712         mp = NULL;
713         if (vp->v_type != VCHR &&
714             (error = vn_start_write(vp, &mp, V_WAIT | PCATCH)) != 0)
715                 goto unlock;
716
717         advice = get_advice(fp, uio);
718  
719         if ((MNT_SHARED_WRITES(mp) ||
720             ((mp == NULL) && MNT_SHARED_WRITES(vp->v_mount))) &&
721             (flags & FOF_OFFSET) != 0) {
722                 lock_flags = LK_SHARED;
723         } else {
724                 lock_flags = LK_EXCLUSIVE;
725         }
726
727         vn_lock(vp, lock_flags | LK_RETRY);
728         switch (advice) {
729         case POSIX_FADV_NORMAL:
730         case POSIX_FADV_SEQUENTIAL:
731         case POSIX_FADV_NOREUSE:
732                 ioflag |= sequential_heuristic(uio, fp);
733                 break;
734         case POSIX_FADV_RANDOM:
735                 /* XXX: Is this correct? */
736                 break;
737         }
738         offset = uio->uio_offset;
739
740 #ifdef MAC
741         error = mac_vnode_check_write(active_cred, fp->f_cred, vp);
742         if (error == 0)
743 #endif
744                 error = VOP_WRITE(vp, uio, ioflag, fp->f_cred);
745         fp->f_nextoff = uio->uio_offset;
746         VOP_UNLOCK(vp, 0);
747         if (vp->v_type != VCHR)
748                 vn_finished_write(mp);
749         if (error == 0 && advice == POSIX_FADV_NOREUSE &&
750             offset != uio->uio_offset) {
751                 /*
752                  * Use POSIX_FADV_DONTNEED to flush clean pages and
753                  * buffers for the backing file after a
754                  * POSIX_FADV_NOREUSE write(2).  To optimize the
755                  * common case of using POSIX_FADV_NOREUSE with
756                  * sequential access, track the previous implicit
757                  * DONTNEED request and grow this request to include
758                  * the current write(2) in addition to the previous
759                  * DONTNEED.  With purely sequential access this will
760                  * cause the DONTNEED requests to continously grow to
761                  * cover all of the previously written regions of the
762                  * file.
763                  *
764                  * Note that the blocks just written are almost
765                  * certainly still dirty, so this only works when
766                  * VOP_ADVISE() calls from subsequent writes push out
767                  * the data written by this write(2) once the backing
768                  * buffers are clean.  However, as compared to forcing
769                  * IO_DIRECT, this gives much saner behavior.  Write
770                  * clustering is still allowed, and clean pages are
771                  * merely moved to the cache page queue rather than
772                  * outright thrown away.  This means a subsequent
773                  * read(2) can still avoid hitting the disk if the
774                  * pages have not been reclaimed.
775                  *
776                  * This does make POSIX_FADV_NOREUSE largely useless
777                  * with non-sequential access.  However, sequential
778                  * access is the more common use case and the flag is
779                  * merely advisory.
780                  */
781                 start = offset;
782                 end = uio->uio_offset - 1;
783                 mtxp = mtx_pool_find(mtxpool_sleep, fp);
784                 mtx_lock(mtxp);
785                 if (fp->f_advice != NULL &&
786                     fp->f_advice->fa_advice == POSIX_FADV_NOREUSE) {
787                         if (start != 0 && fp->f_advice->fa_prevend + 1 == start)
788                                 start = fp->f_advice->fa_prevstart;
789                         else if (fp->f_advice->fa_prevstart != 0 &&
790                             fp->f_advice->fa_prevstart == end + 1)
791                                 end = fp->f_advice->fa_prevend;
792                         fp->f_advice->fa_prevstart = start;
793                         fp->f_advice->fa_prevend = end;
794                 }
795                 mtx_unlock(mtxp);
796                 error = VOP_ADVISE(vp, start, end, POSIX_FADV_DONTNEED);
797         }
798         
799 unlock:
800         VFS_UNLOCK_GIANT(vfslocked);
801         return (error);
802 }
803
804 static const int io_hold_cnt = 16;
805 static int vn_io_fault_enable = 1;
806 SYSCTL_INT(_debug, OID_AUTO, vn_io_fault_enable, CTLFLAG_RW,
807     &vn_io_fault_enable, 0, "Enable vn_io_fault lock avoidance");
808 static unsigned long vn_io_faults_cnt;
809 SYSCTL_LONG(_debug, OID_AUTO, vn_io_faults, CTLFLAG_RD,
810     &vn_io_faults_cnt, 0, "Count of vn_io_fault lock avoidance triggers");
811
812 /*
813  * The vn_io_fault() is a wrapper around vn_read() and vn_write() to
814  * prevent the following deadlock:
815  *
816  * Assume that the thread A reads from the vnode vp1 into userspace
817  * buffer buf1 backed by the pages of vnode vp2.  If a page in buf1 is
818  * currently not resident, then system ends up with the call chain
819  *   vn_read() -> VOP_READ(vp1) -> uiomove() -> [Page Fault] ->
820  *     vm_fault(buf1) -> vnode_pager_getpages(vp2) -> VOP_GETPAGES(vp2)
821  * which establishes lock order vp1->vn_lock, then vp2->vn_lock.
822  * If, at the same time, thread B reads from vnode vp2 into buffer buf2
823  * backed by the pages of vnode vp1, and some page in buf2 is not
824  * resident, we get a reversed order vp2->vn_lock, then vp1->vn_lock.
825  *
826  * To prevent the lock order reversal and deadlock, vn_io_fault() does
827  * not allow page faults to happen during VOP_READ() or VOP_WRITE().
828  * Instead, it first tries to do the whole range i/o with pagefaults
829  * disabled. If all pages in the i/o buffer are resident and mapped,
830  * VOP will succeed (ignoring the genuine filesystem errors).
831  * Otherwise, we get back EFAULT, and vn_io_fault() falls back to do
832  * i/o in chunks, with all pages in the chunk prefaulted and held
833  * using vm_fault_quick_hold_pages().
834  *
835  * Filesystems using this deadlock avoidance scheme should use the
836  * array of the held pages from uio, saved in the curthread->td_ma,
837  * instead of doing uiomove().  A helper function
838  * vn_io_fault_uiomove() converts uiomove request into
839  * uiomove_fromphys() over td_ma array.
840  *
841  * Since vnode locks do not cover the whole i/o anymore, rangelocks
842  * make the current i/o request atomic with respect to other i/os and
843  * truncations.
844  */
845 static int
846 vn_io_fault(struct file *fp, struct uio *uio, struct ucred *active_cred,
847     int flags, struct thread *td)
848 {
849         vm_page_t ma[io_hold_cnt + 2];
850         struct uio *uio_clone, short_uio;
851         struct iovec short_iovec[1];
852         fo_rdwr_t *doio;
853         struct vnode *vp;
854         void *rl_cookie;
855         struct mount *mp;
856         vm_page_t *prev_td_ma;
857         int cnt, error, save, saveheld, prev_td_ma_cnt;
858         vm_offset_t addr, end;
859         vm_prot_t prot;
860         size_t len, resid;
861         ssize_t adv;
862
863         if (uio->uio_rw == UIO_READ)
864                 doio = vn_read;
865         else
866                 doio = vn_write;
867         vp = fp->f_vnode;
868         foffset_lock(fp, uio, flags);
869
870         if (uio->uio_segflg != UIO_USERSPACE || vp->v_type != VREG ||
871             ((mp = vp->v_mount) != NULL &&
872             (mp->mnt_kern_flag & MNTK_NO_IOPF) == 0) ||
873             !vn_io_fault_enable) {
874                 error = doio(fp, uio, active_cred, flags | FOF_OFFSET, td);
875                 goto out_last;
876         }
877
878         /*
879          * The UFS follows IO_UNIT directive and replays back both
880          * uio_offset and uio_resid if an error is encountered during the
881          * operation.  But, since the iovec may be already advanced,
882          * uio is still in an inconsistent state.
883          *
884          * Cache a copy of the original uio, which is advanced to the redo
885          * point using UIO_NOCOPY below.
886          */
887         uio_clone = cloneuio(uio);
888         resid = uio->uio_resid;
889
890         short_uio.uio_segflg = UIO_USERSPACE;
891         short_uio.uio_rw = uio->uio_rw;
892         short_uio.uio_td = uio->uio_td;
893
894         if (uio->uio_rw == UIO_READ) {
895                 prot = VM_PROT_WRITE;
896                 rl_cookie = vn_rangelock_rlock(vp, uio->uio_offset,
897                     uio->uio_offset + uio->uio_resid);
898         } else {
899                 prot = VM_PROT_READ;
900                 if ((fp->f_flag & O_APPEND) != 0 || (flags & FOF_OFFSET) == 0)
901                         /* For appenders, punt and lock the whole range. */
902                         rl_cookie = vn_rangelock_wlock(vp, 0, OFF_MAX);
903                 else
904                         rl_cookie = vn_rangelock_wlock(vp, uio->uio_offset,
905                             uio->uio_offset + uio->uio_resid);
906         }
907
908         save = vm_fault_disable_pagefaults();
909         error = doio(fp, uio, active_cred, flags | FOF_OFFSET, td);
910         if (error != EFAULT)
911                 goto out;
912
913         atomic_add_long(&vn_io_faults_cnt, 1);
914         uio_clone->uio_segflg = UIO_NOCOPY;
915         uiomove(NULL, resid - uio->uio_resid, uio_clone);
916         uio_clone->uio_segflg = uio->uio_segflg;
917
918         saveheld = curthread_pflags_set(TDP_UIOHELD);
919         prev_td_ma = td->td_ma;
920         prev_td_ma_cnt = td->td_ma_cnt;
921
922         while (uio_clone->uio_resid != 0) {
923                 len = uio_clone->uio_iov->iov_len;
924                 if (len == 0) {
925                         KASSERT(uio_clone->uio_iovcnt >= 1,
926                             ("iovcnt underflow"));
927                         uio_clone->uio_iov++;
928                         uio_clone->uio_iovcnt--;
929                         continue;
930                 }
931
932                 addr = (vm_offset_t)uio_clone->uio_iov->iov_base;
933                 end = round_page(addr + len);
934                 cnt = howmany(end - trunc_page(addr), PAGE_SIZE);
935                 /*
936                  * A perfectly misaligned address and length could cause
937                  * both the start and the end of the chunk to use partial
938                  * page.  +2 accounts for such a situation.
939                  */
940                 if (cnt > io_hold_cnt + 2) {
941                         len = io_hold_cnt * PAGE_SIZE;
942                         KASSERT(howmany(round_page(addr + len) -
943                             trunc_page(addr), PAGE_SIZE) <= io_hold_cnt + 2,
944                             ("cnt overflow"));
945                 }
946                 cnt = vm_fault_quick_hold_pages(&td->td_proc->p_vmspace->vm_map,
947                     addr, len, prot, ma, io_hold_cnt + 2);
948                 if (cnt == -1) {
949                         error = EFAULT;
950                         break;
951                 }
952                 short_uio.uio_iov = &short_iovec[0];
953                 short_iovec[0].iov_base = (void *)addr;
954                 short_uio.uio_iovcnt = 1;
955                 short_uio.uio_resid = short_iovec[0].iov_len = len;
956                 short_uio.uio_offset = uio_clone->uio_offset;
957                 td->td_ma = ma;
958                 td->td_ma_cnt = cnt;
959
960                 error = doio(fp, &short_uio, active_cred, flags | FOF_OFFSET,
961                     td);
962                 vm_page_unhold_pages(ma, cnt);
963                 adv = len - short_uio.uio_resid;
964
965                 uio_clone->uio_iov->iov_base =
966                     (char *)uio_clone->uio_iov->iov_base + adv;
967                 uio_clone->uio_iov->iov_len -= adv;
968                 uio_clone->uio_resid -= adv;
969                 uio_clone->uio_offset += adv;
970
971                 uio->uio_resid -= adv;
972                 uio->uio_offset += adv;
973
974                 if (error != 0 || adv == 0)
975                         break;
976         }
977         td->td_ma = prev_td_ma;
978         td->td_ma_cnt = prev_td_ma_cnt;
979         curthread_pflags_restore(saveheld);
980 out:
981         vm_fault_enable_pagefaults(save);
982         vn_rangelock_unlock(vp, rl_cookie);
983         free(uio_clone, M_IOV);
984 out_last:
985         foffset_unlock(fp, uio, flags);
986         return (error);
987 }
988
989 /*
990  * Helper function to perform the requested uiomove operation using
991  * the held pages for io->uio_iov[0].iov_base buffer instead of
992  * copyin/copyout.  Access to the pages with uiomove_fromphys()
993  * instead of iov_base prevents page faults that could occur due to
994  * pmap_collect() invalidating the mapping created by
995  * vm_fault_quick_hold_pages(), or pageout daemon, page laundry or
996  * object cleanup revoking the write access from page mappings.
997  *
998  * Filesystems specified MNTK_NO_IOPF shall use vn_io_fault_uiomove()
999  * instead of plain uiomove().
1000  */
1001 int
1002 vn_io_fault_uiomove(char *data, int xfersize, struct uio *uio)
1003 {
1004         struct uio transp_uio;
1005         struct iovec transp_iov[1];
1006         struct thread *td;
1007         size_t adv;
1008         int error, pgadv;
1009
1010         td = curthread;
1011         if ((td->td_pflags & TDP_UIOHELD) == 0 ||
1012             uio->uio_segflg != UIO_USERSPACE)
1013                 return (uiomove(data, xfersize, uio));
1014
1015         KASSERT(uio->uio_iovcnt == 1, ("uio_iovcnt %d", uio->uio_iovcnt));
1016         transp_iov[0].iov_base = data;
1017         transp_uio.uio_iov = &transp_iov[0];
1018         transp_uio.uio_iovcnt = 1;
1019         if (xfersize > uio->uio_resid)
1020                 xfersize = uio->uio_resid;
1021         transp_uio.uio_resid = transp_iov[0].iov_len = xfersize;
1022         transp_uio.uio_offset = 0;
1023         transp_uio.uio_segflg = UIO_SYSSPACE;
1024         /*
1025          * Since transp_iov points to data, and td_ma page array
1026          * corresponds to original uio->uio_iov, we need to invert the
1027          * direction of the i/o operation as passed to
1028          * uiomove_fromphys().
1029          */
1030         switch (uio->uio_rw) {
1031         case UIO_WRITE:
1032                 transp_uio.uio_rw = UIO_READ;
1033                 break;
1034         case UIO_READ:
1035                 transp_uio.uio_rw = UIO_WRITE;
1036                 break;
1037         }
1038         transp_uio.uio_td = uio->uio_td;
1039         error = uiomove_fromphys(td->td_ma,
1040             ((vm_offset_t)uio->uio_iov->iov_base) & PAGE_MASK,
1041             xfersize, &transp_uio);
1042         adv = xfersize - transp_uio.uio_resid;
1043         pgadv =
1044             (((vm_offset_t)uio->uio_iov->iov_base + adv) >> PAGE_SHIFT) -
1045             (((vm_offset_t)uio->uio_iov->iov_base) >> PAGE_SHIFT);
1046         td->td_ma += pgadv;
1047         KASSERT(td->td_ma_cnt >= pgadv, ("consumed pages %d %d", td->td_ma_cnt,
1048             pgadv));
1049         td->td_ma_cnt -= pgadv;
1050         uio->uio_iov->iov_base = (char *)uio->uio_iov->iov_base + adv;
1051         uio->uio_iov->iov_len -= adv;
1052         uio->uio_resid -= adv;
1053         uio->uio_offset += adv;
1054         return (error);
1055 }
1056
1057 /*
1058  * File table truncate routine.
1059  */
1060 static int
1061 vn_truncate(struct file *fp, off_t length, struct ucred *active_cred,
1062     struct thread *td)
1063 {
1064         struct vattr vattr;
1065         struct mount *mp;
1066         struct vnode *vp;
1067         void *rl_cookie;
1068         int vfslocked;
1069         int error;
1070
1071         vp = fp->f_vnode;
1072
1073         /*
1074          * Lock the whole range for truncation.  Otherwise split i/o
1075          * might happen partly before and partly after the truncation.
1076          */
1077         rl_cookie = vn_rangelock_wlock(vp, 0, OFF_MAX);
1078         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1079         error = vn_start_write(vp, &mp, V_WAIT | PCATCH);
1080         if (error)
1081                 goto out1;
1082         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1083         if (vp->v_type == VDIR) {
1084                 error = EISDIR;
1085                 goto out;
1086         }
1087 #ifdef MAC
1088         error = mac_vnode_check_write(active_cred, fp->f_cred, vp);
1089         if (error)
1090                 goto out;
1091 #endif
1092         error = vn_writechk(vp);
1093         if (error == 0) {
1094                 VATTR_NULL(&vattr);
1095                 vattr.va_size = length;
1096                 error = VOP_SETATTR(vp, &vattr, fp->f_cred);
1097         }
1098 out:
1099         VOP_UNLOCK(vp, 0);
1100         vn_finished_write(mp);
1101 out1:
1102         VFS_UNLOCK_GIANT(vfslocked);
1103         vn_rangelock_unlock(vp, rl_cookie);
1104         return (error);
1105 }
1106
1107 /*
1108  * File table vnode stat routine.
1109  */
1110 static int
1111 vn_statfile(fp, sb, active_cred, td)
1112         struct file *fp;
1113         struct stat *sb;
1114         struct ucred *active_cred;
1115         struct thread *td;
1116 {
1117         struct vnode *vp = fp->f_vnode;
1118         int vfslocked;
1119         int error;
1120
1121         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1122         vn_lock(vp, LK_SHARED | LK_RETRY);
1123         error = vn_stat(vp, sb, active_cred, fp->f_cred, td);
1124         VOP_UNLOCK(vp, 0);
1125         VFS_UNLOCK_GIANT(vfslocked);
1126
1127         return (error);
1128 }
1129
1130 /*
1131  * Stat a vnode; implementation for the stat syscall
1132  */
1133 int
1134 vn_stat(vp, sb, active_cred, file_cred, td)
1135         struct vnode *vp;
1136         register struct stat *sb;
1137         struct ucred *active_cred;
1138         struct ucred *file_cred;
1139         struct thread *td;
1140 {
1141         struct vattr vattr;
1142         register struct vattr *vap;
1143         int error;
1144         u_short mode;
1145
1146 #ifdef MAC
1147         error = mac_vnode_check_stat(active_cred, file_cred, vp);
1148         if (error)
1149                 return (error);
1150 #endif
1151
1152         vap = &vattr;
1153
1154         /*
1155          * Initialize defaults for new and unusual fields, so that file
1156          * systems which don't support these fields don't need to know
1157          * about them.
1158          */
1159         vap->va_birthtime.tv_sec = -1;
1160         vap->va_birthtime.tv_nsec = 0;
1161         vap->va_fsid = VNOVAL;
1162         vap->va_rdev = NODEV;
1163
1164         error = VOP_GETATTR(vp, vap, active_cred);
1165         if (error)
1166                 return (error);
1167
1168         /*
1169          * Zero the spare stat fields
1170          */
1171         bzero(sb, sizeof *sb);
1172
1173         /*
1174          * Copy from vattr table
1175          */
1176         if (vap->va_fsid != VNOVAL)
1177                 sb->st_dev = vap->va_fsid;
1178         else
1179                 sb->st_dev = vp->v_mount->mnt_stat.f_fsid.val[0];
1180         sb->st_ino = vap->va_fileid;
1181         mode = vap->va_mode;
1182         switch (vap->va_type) {
1183         case VREG:
1184                 mode |= S_IFREG;
1185                 break;
1186         case VDIR:
1187                 mode |= S_IFDIR;
1188                 break;
1189         case VBLK:
1190                 mode |= S_IFBLK;
1191                 break;
1192         case VCHR:
1193                 mode |= S_IFCHR;
1194                 break;
1195         case VLNK:
1196                 mode |= S_IFLNK;
1197                 break;
1198         case VSOCK:
1199                 mode |= S_IFSOCK;
1200                 break;
1201         case VFIFO:
1202                 mode |= S_IFIFO;
1203                 break;
1204         default:
1205                 return (EBADF);
1206         };
1207         sb->st_mode = mode;
1208         sb->st_nlink = vap->va_nlink;
1209         sb->st_uid = vap->va_uid;
1210         sb->st_gid = vap->va_gid;
1211         sb->st_rdev = vap->va_rdev;
1212         if (vap->va_size > OFF_MAX)
1213                 return (EOVERFLOW);
1214         sb->st_size = vap->va_size;
1215         sb->st_atim = vap->va_atime;
1216         sb->st_mtim = vap->va_mtime;
1217         sb->st_ctim = vap->va_ctime;
1218         sb->st_birthtim = vap->va_birthtime;
1219
1220         /*
1221          * According to www.opengroup.org, the meaning of st_blksize is 
1222          *   "a filesystem-specific preferred I/O block size for this 
1223          *    object.  In some filesystem types, this may vary from file
1224          *    to file"
1225          * Use miminum/default of PAGE_SIZE (e.g. for VCHR).
1226          */
1227
1228         sb->st_blksize = max(PAGE_SIZE, vap->va_blocksize);
1229         
1230         sb->st_flags = vap->va_flags;
1231         if (priv_check(td, PRIV_VFS_GENERATION))
1232                 sb->st_gen = 0;
1233         else
1234                 sb->st_gen = vap->va_gen;
1235
1236         sb->st_blocks = vap->va_bytes / S_BLKSIZE;
1237         return (0);
1238 }
1239
1240 /*
1241  * File table vnode ioctl routine.
1242  */
1243 static int
1244 vn_ioctl(fp, com, data, active_cred, td)
1245         struct file *fp;
1246         u_long com;
1247         void *data;
1248         struct ucred *active_cred;
1249         struct thread *td;
1250 {
1251         struct vnode *vp = fp->f_vnode;
1252         struct vattr vattr;
1253         int vfslocked;
1254         int error;
1255
1256         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1257         error = ENOTTY;
1258         switch (vp->v_type) {
1259         case VREG:
1260         case VDIR:
1261                 if (com == FIONREAD) {
1262                         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1263                         error = VOP_GETATTR(vp, &vattr, active_cred);
1264                         VOP_UNLOCK(vp, 0);
1265                         if (!error)
1266                                 *(int *)data = vattr.va_size - fp->f_offset;
1267                 }
1268                 if (com == FIONBIO || com == FIOASYNC)  /* XXX */
1269                         error = 0;
1270                 else
1271                         error = VOP_IOCTL(vp, com, data, fp->f_flag,
1272                             active_cred, td);
1273                 break;
1274
1275         default:
1276                 break;
1277         }
1278         VFS_UNLOCK_GIANT(vfslocked);
1279         return (error);
1280 }
1281
1282 /*
1283  * File table vnode poll routine.
1284  */
1285 static int
1286 vn_poll(fp, events, active_cred, td)
1287         struct file *fp;
1288         int events;
1289         struct ucred *active_cred;
1290         struct thread *td;
1291 {
1292         struct vnode *vp;
1293         int vfslocked;
1294         int error;
1295
1296         vp = fp->f_vnode;
1297         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1298 #ifdef MAC
1299         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1300         error = mac_vnode_check_poll(active_cred, fp->f_cred, vp);
1301         VOP_UNLOCK(vp, 0);
1302         if (!error)
1303 #endif
1304
1305         error = VOP_POLL(vp, events, fp->f_cred, td);
1306         VFS_UNLOCK_GIANT(vfslocked);
1307         return (error);
1308 }
1309
1310 /*
1311  * Acquire the requested lock and then check for validity.  LK_RETRY
1312  * permits vn_lock to return doomed vnodes.
1313  */
1314 int
1315 _vn_lock(struct vnode *vp, int flags, char *file, int line)
1316 {
1317         int error;
1318
1319         VNASSERT((flags & LK_TYPE_MASK) != 0, vp,
1320             ("vn_lock called with no locktype."));
1321         do {
1322 #ifdef DEBUG_VFS_LOCKS
1323                 KASSERT(vp->v_holdcnt != 0,
1324                     ("vn_lock %p: zero hold count", vp));
1325 #endif
1326                 error = VOP_LOCK1(vp, flags, file, line);
1327                 flags &= ~LK_INTERLOCK; /* Interlock is always dropped. */
1328                 KASSERT((flags & LK_RETRY) == 0 || error == 0,
1329                     ("LK_RETRY set with incompatible flags (0x%x) or an error occured (%d)",
1330                     flags, error));
1331                 /*
1332                  * Callers specify LK_RETRY if they wish to get dead vnodes.
1333                  * If RETRY is not set, we return ENOENT instead.
1334                  */
1335                 if (error == 0 && vp->v_iflag & VI_DOOMED &&
1336                     (flags & LK_RETRY) == 0) {
1337                         VOP_UNLOCK(vp, 0);
1338                         error = ENOENT;
1339                         break;
1340                 }
1341         } while (flags & LK_RETRY && error != 0);
1342         return (error);
1343 }
1344
1345 /*
1346  * File table vnode close routine.
1347  */
1348 static int
1349 vn_closefile(fp, td)
1350         struct file *fp;
1351         struct thread *td;
1352 {
1353         struct vnode *vp;
1354         struct flock lf;
1355         int vfslocked;
1356         int error;
1357
1358         vp = fp->f_vnode;
1359
1360         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1361         if (fp->f_type == DTYPE_VNODE && fp->f_flag & FHASLOCK) {
1362                 lf.l_whence = SEEK_SET;
1363                 lf.l_start = 0;
1364                 lf.l_len = 0;
1365                 lf.l_type = F_UNLCK;
1366                 (void) VOP_ADVLOCK(vp, fp, F_UNLCK, &lf, F_FLOCK);
1367         }
1368
1369         fp->f_ops = &badfileops;
1370
1371         error = vn_close(vp, fp->f_flag, fp->f_cred, td);
1372         VFS_UNLOCK_GIANT(vfslocked);
1373         return (error);
1374 }
1375
1376 /*
1377  * Preparing to start a filesystem write operation. If the operation is
1378  * permitted, then we bump the count of operations in progress and
1379  * proceed. If a suspend request is in progress, we wait until the
1380  * suspension is over, and then proceed.
1381  */
1382 int
1383 vn_start_write(vp, mpp, flags)
1384         struct vnode *vp;
1385         struct mount **mpp;
1386         int flags;
1387 {
1388         struct mount *mp;
1389         int error;
1390
1391         error = 0;
1392         /*
1393          * If a vnode is provided, get and return the mount point that
1394          * to which it will write.
1395          */
1396         if (vp != NULL) {
1397                 if ((error = VOP_GETWRITEMOUNT(vp, mpp)) != 0) {
1398                         *mpp = NULL;
1399                         if (error != EOPNOTSUPP)
1400                                 return (error);
1401                         return (0);
1402                 }
1403         }
1404         if ((mp = *mpp) == NULL)
1405                 return (0);
1406
1407         /*
1408          * VOP_GETWRITEMOUNT() returns with the mp refcount held through
1409          * a vfs_ref().
1410          * As long as a vnode is not provided we need to acquire a
1411          * refcount for the provided mountpoint too, in order to
1412          * emulate a vfs_ref().
1413          */
1414         MNT_ILOCK(mp);
1415         if (vp == NULL)
1416                 MNT_REF(mp);
1417
1418         /*
1419          * Check on status of suspension.
1420          */
1421         if ((curthread->td_pflags & TDP_IGNSUSP) == 0 ||
1422             mp->mnt_susp_owner != curthread) {
1423                 while ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0) {
1424                         if (flags & V_NOWAIT) {
1425                                 error = EWOULDBLOCK;
1426                                 goto unlock;
1427                         }
1428                         error = msleep(&mp->mnt_flag, MNT_MTX(mp),
1429                             (PUSER - 1) | (flags & PCATCH), "suspfs", 0);
1430                         if (error)
1431                                 goto unlock;
1432                 }
1433         }
1434         if (flags & V_XSLEEP)
1435                 goto unlock;
1436         mp->mnt_writeopcount++;
1437 unlock:
1438         if (error != 0 || (flags & V_XSLEEP) != 0)
1439                 MNT_REL(mp);
1440         MNT_IUNLOCK(mp);
1441         return (error);
1442 }
1443
1444 /*
1445  * Secondary suspension. Used by operations such as vop_inactive
1446  * routines that are needed by the higher level functions. These
1447  * are allowed to proceed until all the higher level functions have
1448  * completed (indicated by mnt_writeopcount dropping to zero). At that
1449  * time, these operations are halted until the suspension is over.
1450  */
1451 int
1452 vn_start_secondary_write(vp, mpp, flags)
1453         struct vnode *vp;
1454         struct mount **mpp;
1455         int flags;
1456 {
1457         struct mount *mp;
1458         int error;
1459
1460  retry:
1461         if (vp != NULL) {
1462                 if ((error = VOP_GETWRITEMOUNT(vp, mpp)) != 0) {
1463                         *mpp = NULL;
1464                         if (error != EOPNOTSUPP)
1465                                 return (error);
1466                         return (0);
1467                 }
1468         }
1469         /*
1470          * If we are not suspended or have not yet reached suspended
1471          * mode, then let the operation proceed.
1472          */
1473         if ((mp = *mpp) == NULL)
1474                 return (0);
1475
1476         /*
1477          * VOP_GETWRITEMOUNT() returns with the mp refcount held through
1478          * a vfs_ref().
1479          * As long as a vnode is not provided we need to acquire a
1480          * refcount for the provided mountpoint too, in order to
1481          * emulate a vfs_ref().
1482          */
1483         MNT_ILOCK(mp);
1484         if (vp == NULL)
1485                 MNT_REF(mp);
1486         if ((mp->mnt_kern_flag & (MNTK_SUSPENDED | MNTK_SUSPEND2)) == 0) {
1487                 mp->mnt_secondary_writes++;
1488                 mp->mnt_secondary_accwrites++;
1489                 MNT_IUNLOCK(mp);
1490                 return (0);
1491         }
1492         if (flags & V_NOWAIT) {
1493                 MNT_REL(mp);
1494                 MNT_IUNLOCK(mp);
1495                 return (EWOULDBLOCK);
1496         }
1497         /*
1498          * Wait for the suspension to finish.
1499          */
1500         error = msleep(&mp->mnt_flag, MNT_MTX(mp),
1501                        (PUSER - 1) | (flags & PCATCH) | PDROP, "suspfs", 0);
1502         vfs_rel(mp);
1503         if (error == 0)
1504                 goto retry;
1505         return (error);
1506 }
1507
1508 /*
1509  * Filesystem write operation has completed. If we are suspending and this
1510  * operation is the last one, notify the suspender that the suspension is
1511  * now in effect.
1512  */
1513 void
1514 vn_finished_write(mp)
1515         struct mount *mp;
1516 {
1517         if (mp == NULL)
1518                 return;
1519         MNT_ILOCK(mp);
1520         MNT_REL(mp);
1521         mp->mnt_writeopcount--;
1522         if (mp->mnt_writeopcount < 0)
1523                 panic("vn_finished_write: neg cnt");
1524         if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0 &&
1525             mp->mnt_writeopcount <= 0)
1526                 wakeup(&mp->mnt_writeopcount);
1527         MNT_IUNLOCK(mp);
1528 }
1529
1530
1531 /*
1532  * Filesystem secondary write operation has completed. If we are
1533  * suspending and this operation is the last one, notify the suspender
1534  * that the suspension is now in effect.
1535  */
1536 void
1537 vn_finished_secondary_write(mp)
1538         struct mount *mp;
1539 {
1540         if (mp == NULL)
1541                 return;
1542         MNT_ILOCK(mp);
1543         MNT_REL(mp);
1544         mp->mnt_secondary_writes--;
1545         if (mp->mnt_secondary_writes < 0)
1546                 panic("vn_finished_secondary_write: neg cnt");
1547         if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0 &&
1548             mp->mnt_secondary_writes <= 0)
1549                 wakeup(&mp->mnt_secondary_writes);
1550         MNT_IUNLOCK(mp);
1551 }
1552
1553
1554
1555 /*
1556  * Request a filesystem to suspend write operations.
1557  */
1558 int
1559 vfs_write_suspend(mp)
1560         struct mount *mp;
1561 {
1562         int error;
1563
1564         MNT_ILOCK(mp);
1565         if (mp->mnt_susp_owner == curthread) {
1566                 MNT_IUNLOCK(mp);
1567                 return (EALREADY);
1568         }
1569         while (mp->mnt_kern_flag & MNTK_SUSPEND)
1570                 msleep(&mp->mnt_flag, MNT_MTX(mp), PUSER - 1, "wsuspfs", 0);
1571         mp->mnt_kern_flag |= MNTK_SUSPEND;
1572         mp->mnt_susp_owner = curthread;
1573         if (mp->mnt_writeopcount > 0)
1574                 (void) msleep(&mp->mnt_writeopcount, 
1575                     MNT_MTX(mp), (PUSER - 1)|PDROP, "suspwt", 0);
1576         else
1577                 MNT_IUNLOCK(mp);
1578         if ((error = VFS_SYNC(mp, MNT_SUSPEND)) != 0)
1579                 vfs_write_resume(mp);
1580         return (error);
1581 }
1582
1583 /*
1584  * Request a filesystem to resume write operations.
1585  */
1586 void
1587 vfs_write_resume(mp)
1588         struct mount *mp;
1589 {
1590
1591         MNT_ILOCK(mp);
1592         if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0) {
1593                 KASSERT(mp->mnt_susp_owner == curthread, ("mnt_susp_owner"));
1594                 mp->mnt_kern_flag &= ~(MNTK_SUSPEND | MNTK_SUSPEND2 |
1595                                        MNTK_SUSPENDED);
1596                 mp->mnt_susp_owner = NULL;
1597                 wakeup(&mp->mnt_writeopcount);
1598                 wakeup(&mp->mnt_flag);
1599                 curthread->td_pflags &= ~TDP_IGNSUSP;
1600                 MNT_IUNLOCK(mp);
1601                 VFS_SUSP_CLEAN(mp);
1602         } else
1603                 MNT_IUNLOCK(mp);
1604 }
1605
1606 /*
1607  * Implement kqueues for files by translating it to vnode operation.
1608  */
1609 static int
1610 vn_kqfilter(struct file *fp, struct knote *kn)
1611 {
1612         int vfslocked;
1613         int error;
1614
1615         vfslocked = VFS_LOCK_GIANT(fp->f_vnode->v_mount);
1616         error = VOP_KQFILTER(fp->f_vnode, kn);
1617         VFS_UNLOCK_GIANT(vfslocked);
1618
1619         return error;
1620 }
1621
1622 /*
1623  * Simplified in-kernel wrapper calls for extended attribute access.
1624  * Both calls pass in a NULL credential, authorizing as "kernel" access.
1625  * Set IO_NODELOCKED in ioflg if the vnode is already locked.
1626  */
1627 int
1628 vn_extattr_get(struct vnode *vp, int ioflg, int attrnamespace,
1629     const char *attrname, int *buflen, char *buf, struct thread *td)
1630 {
1631         struct uio      auio;
1632         struct iovec    iov;
1633         int     error;
1634
1635         iov.iov_len = *buflen;
1636         iov.iov_base = buf;
1637
1638         auio.uio_iov = &iov;
1639         auio.uio_iovcnt = 1;
1640         auio.uio_rw = UIO_READ;
1641         auio.uio_segflg = UIO_SYSSPACE;
1642         auio.uio_td = td;
1643         auio.uio_offset = 0;
1644         auio.uio_resid = *buflen;
1645
1646         if ((ioflg & IO_NODELOCKED) == 0)
1647                 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1648
1649         ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
1650
1651         /* authorize attribute retrieval as kernel */
1652         error = VOP_GETEXTATTR(vp, attrnamespace, attrname, &auio, NULL, NULL,
1653             td);
1654
1655         if ((ioflg & IO_NODELOCKED) == 0)
1656                 VOP_UNLOCK(vp, 0);
1657
1658         if (error == 0) {
1659                 *buflen = *buflen - auio.uio_resid;
1660         }
1661
1662         return (error);
1663 }
1664
1665 /*
1666  * XXX failure mode if partially written?
1667  */
1668 int
1669 vn_extattr_set(struct vnode *vp, int ioflg, int attrnamespace,
1670     const char *attrname, int buflen, char *buf, struct thread *td)
1671 {
1672         struct uio      auio;
1673         struct iovec    iov;
1674         struct mount    *mp;
1675         int     error;
1676
1677         iov.iov_len = buflen;
1678         iov.iov_base = buf;
1679
1680         auio.uio_iov = &iov;
1681         auio.uio_iovcnt = 1;
1682         auio.uio_rw = UIO_WRITE;
1683         auio.uio_segflg = UIO_SYSSPACE;
1684         auio.uio_td = td;
1685         auio.uio_offset = 0;
1686         auio.uio_resid = buflen;
1687
1688         if ((ioflg & IO_NODELOCKED) == 0) {
1689                 if ((error = vn_start_write(vp, &mp, V_WAIT)) != 0)
1690                         return (error);
1691                 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1692         }
1693
1694         ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
1695
1696         /* authorize attribute setting as kernel */
1697         error = VOP_SETEXTATTR(vp, attrnamespace, attrname, &auio, NULL, td);
1698
1699         if ((ioflg & IO_NODELOCKED) == 0) {
1700                 vn_finished_write(mp);
1701                 VOP_UNLOCK(vp, 0);
1702         }
1703
1704         return (error);
1705 }
1706
1707 int
1708 vn_extattr_rm(struct vnode *vp, int ioflg, int attrnamespace,
1709     const char *attrname, struct thread *td)
1710 {
1711         struct mount    *mp;
1712         int     error;
1713
1714         if ((ioflg & IO_NODELOCKED) == 0) {
1715                 if ((error = vn_start_write(vp, &mp, V_WAIT)) != 0)
1716                         return (error);
1717                 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1718         }
1719
1720         ASSERT_VOP_LOCKED(vp, "IO_NODELOCKED with no vp lock held");
1721
1722         /* authorize attribute removal as kernel */
1723         error = VOP_DELETEEXTATTR(vp, attrnamespace, attrname, NULL, td);
1724         if (error == EOPNOTSUPP)
1725                 error = VOP_SETEXTATTR(vp, attrnamespace, attrname, NULL,
1726                     NULL, td);
1727
1728         if ((ioflg & IO_NODELOCKED) == 0) {
1729                 vn_finished_write(mp);
1730                 VOP_UNLOCK(vp, 0);
1731         }
1732
1733         return (error);
1734 }
1735
1736 int
1737 vn_vget_ino(struct vnode *vp, ino_t ino, int lkflags, struct vnode **rvp)
1738 {
1739         struct mount *mp;
1740         int ltype, error;
1741
1742         mp = vp->v_mount;
1743         ltype = VOP_ISLOCKED(vp);
1744         KASSERT(ltype == LK_EXCLUSIVE || ltype == LK_SHARED,
1745             ("vn_vget_ino: vp not locked"));
1746         error = vfs_busy(mp, MBF_NOWAIT);
1747         if (error != 0) {
1748                 vfs_ref(mp);
1749                 VOP_UNLOCK(vp, 0);
1750                 error = vfs_busy(mp, 0);
1751                 vn_lock(vp, ltype | LK_RETRY);
1752                 vfs_rel(mp);
1753                 if (error != 0)
1754                         return (ENOENT);
1755                 if (vp->v_iflag & VI_DOOMED) {
1756                         vfs_unbusy(mp);
1757                         return (ENOENT);
1758                 }
1759         }
1760         VOP_UNLOCK(vp, 0);
1761         error = VFS_VGET(mp, ino, lkflags, rvp);
1762         vfs_unbusy(mp);
1763         vn_lock(vp, ltype | LK_RETRY);
1764         if (vp->v_iflag & VI_DOOMED) {
1765                 if (error == 0)
1766                         vput(*rvp);
1767                 error = ENOENT;
1768         }
1769         return (error);
1770 }
1771
1772 int
1773 vn_rlimit_fsize(const struct vnode *vp, const struct uio *uio,
1774     const struct thread *td)
1775 {
1776
1777         if (vp->v_type != VREG || td == NULL)
1778                 return (0);
1779         PROC_LOCK(td->td_proc);
1780         if ((uoff_t)uio->uio_offset + uio->uio_resid >
1781             lim_cur(td->td_proc, RLIMIT_FSIZE)) {
1782                 kern_psignal(td->td_proc, SIGXFSZ);
1783                 PROC_UNLOCK(td->td_proc);
1784                 return (EFBIG);
1785         }
1786         PROC_UNLOCK(td->td_proc);
1787         return (0);
1788 }
1789
1790 int
1791 vn_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
1792     struct thread *td)
1793 {
1794         struct vnode *vp;
1795         int error, vfslocked;
1796
1797         vp = fp->f_vnode;
1798         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1799 #ifdef AUDIT
1800         vn_lock(vp, LK_SHARED | LK_RETRY);
1801         AUDIT_ARG_VNODE1(vp);
1802         VOP_UNLOCK(vp, 0);
1803 #endif
1804         error = setfmode(td, active_cred, vp, mode);
1805         VFS_UNLOCK_GIANT(vfslocked);
1806         return (error);
1807 }
1808
1809 int
1810 vn_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
1811     struct thread *td)
1812 {
1813         struct vnode *vp;
1814         int error, vfslocked;
1815
1816         vp = fp->f_vnode;
1817         vfslocked = VFS_LOCK_GIANT(vp->v_mount);
1818 #ifdef AUDIT
1819         vn_lock(vp, LK_SHARED | LK_RETRY);
1820         AUDIT_ARG_VNODE1(vp);
1821         VOP_UNLOCK(vp, 0);
1822 #endif
1823         error = setfown(td, active_cred, vp, uid, gid);
1824         VFS_UNLOCK_GIANT(vfslocked);
1825         return (error);
1826 }
1827
1828 void
1829 vn_pages_remove(struct vnode *vp, vm_pindex_t start, vm_pindex_t end)
1830 {
1831         vm_object_t object;
1832
1833         if ((object = vp->v_object) == NULL)
1834                 return;
1835         VM_OBJECT_LOCK(object);
1836         vm_object_page_remove(object, start, end, 0);
1837         VM_OBJECT_UNLOCK(object);
1838 }
1839
1840 int
1841 vn_bmap_seekhole(struct vnode *vp, u_long cmd, off_t *off, struct ucred *cred)
1842 {
1843         struct vattr va;
1844         daddr_t bn, bnp;
1845         uint64_t bsize;
1846         off_t noff;
1847         int error;
1848
1849         KASSERT(cmd == FIOSEEKHOLE || cmd == FIOSEEKDATA,
1850             ("Wrong command %lu", cmd));
1851
1852         if (vn_lock(vp, LK_SHARED) != 0)
1853                 return (EBADF);
1854         if (vp->v_type != VREG) {
1855                 error = ENOTTY;
1856                 goto unlock;
1857         }
1858         error = VOP_GETATTR(vp, &va, cred);
1859         if (error != 0)
1860                 goto unlock;
1861         noff = *off;
1862         if (noff >= va.va_size) {
1863                 error = ENXIO;
1864                 goto unlock;
1865         }
1866         bsize = vp->v_mount->mnt_stat.f_iosize;
1867         for (bn = noff / bsize; noff < va.va_size; bn++, noff += bsize) {
1868                 error = VOP_BMAP(vp, bn, NULL, &bnp, NULL, NULL);
1869                 if (error == EOPNOTSUPP) {
1870                         error = ENOTTY;
1871                         goto unlock;
1872                 }
1873                 if ((bnp == -1 && cmd == FIOSEEKHOLE) ||
1874                     (bnp != -1 && cmd == FIOSEEKDATA)) {
1875                         noff = bn * bsize;
1876                         if (noff < *off)
1877                                 noff = *off;
1878                         goto unlock;
1879                 }
1880         }
1881         if (noff > va.va_size)
1882                 noff = va.va_size;
1883         /* noff == va.va_size. There is an implicit hole at the end of file. */
1884         if (cmd == FIOSEEKDATA)
1885                 error = ENXIO;
1886 unlock:
1887         VOP_UNLOCK(vp, 0);
1888         if (error == 0)
1889                 *off = noff;
1890         return (error);
1891 }