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