]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sys/kern/vfs_subr.c
MFC r211213:
[FreeBSD/stable/8.git] / sys / kern / vfs_subr.c
1 /*-
2  * Copyright (c) 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_subr.c  8.31 (Berkeley) 5/26/95
35  */
36
37 /*
38  * External virtual filesystem routines
39  */
40
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
43
44 #include "opt_ddb.h"
45
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/bio.h>
49 #include <sys/buf.h>
50 #include <sys/condvar.h>
51 #include <sys/conf.h>
52 #include <sys/dirent.h>
53 #include <sys/event.h>
54 #include <sys/eventhandler.h>
55 #include <sys/extattr.h>
56 #include <sys/file.h>
57 #include <sys/fcntl.h>
58 #include <sys/jail.h>
59 #include <sys/kdb.h>
60 #include <sys/kernel.h>
61 #include <sys/kthread.h>
62 #include <sys/lockf.h>
63 #include <sys/malloc.h>
64 #include <sys/mount.h>
65 #include <sys/namei.h>
66 #include <sys/priv.h>
67 #include <sys/reboot.h>
68 #include <sys/sleepqueue.h>
69 #include <sys/stat.h>
70 #include <sys/sysctl.h>
71 #include <sys/syslog.h>
72 #include <sys/vmmeter.h>
73 #include <sys/vnode.h>
74
75 #include <machine/stdarg.h>
76
77 #include <security/mac/mac_framework.h>
78
79 #include <vm/vm.h>
80 #include <vm/vm_object.h>
81 #include <vm/vm_extern.h>
82 #include <vm/pmap.h>
83 #include <vm/vm_map.h>
84 #include <vm/vm_page.h>
85 #include <vm/vm_kern.h>
86 #include <vm/uma.h>
87
88 #ifdef DDB
89 #include <ddb/ddb.h>
90 #endif
91
92 #define WI_MPSAFEQ      0
93 #define WI_GIANTQ       1
94
95 static MALLOC_DEFINE(M_NETADDR, "subr_export_host", "Export host address structure");
96
97 static void     delmntque(struct vnode *vp);
98 static int      flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo,
99                     int slpflag, int slptimeo);
100 static void     syncer_shutdown(void *arg, int howto);
101 static int      vtryrecycle(struct vnode *vp);
102 static void     vbusy(struct vnode *vp);
103 static void     vinactive(struct vnode *, struct thread *);
104 static void     v_incr_usecount(struct vnode *);
105 static void     v_decr_usecount(struct vnode *);
106 static void     v_decr_useonly(struct vnode *);
107 static void     v_upgrade_usecount(struct vnode *);
108 static void     vfree(struct vnode *);
109 static void     vnlru_free(int);
110 static void     vgonel(struct vnode *);
111 static void     vfs_knllock(void *arg);
112 static void     vfs_knlunlock(void *arg);
113 static void     vfs_knl_assert_locked(void *arg);
114 static void     vfs_knl_assert_unlocked(void *arg);
115 static void     destroy_vpollinfo(struct vpollinfo *vi);
116
117 /*
118  * Number of vnodes in existence.  Increased whenever getnewvnode()
119  * allocates a new vnode, decreased on vdestroy() called on VI_DOOMed
120  * vnode.
121  */
122 static unsigned long    numvnodes;
123
124 SYSCTL_LONG(_vfs, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0, "");
125
126 /*
127  * Conversion tables for conversion from vnode types to inode formats
128  * and back.
129  */
130 enum vtype iftovt_tab[16] = {
131         VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
132         VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VBAD,
133 };
134 int vttoif_tab[10] = {
135         0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
136         S_IFSOCK, S_IFIFO, S_IFMT, S_IFMT
137 };
138
139 /*
140  * List of vnodes that are ready for recycling.
141  */
142 static TAILQ_HEAD(freelst, vnode) vnode_free_list;
143
144 /*
145  * Free vnode target.  Free vnodes may simply be files which have been stat'd
146  * but not read.  This is somewhat common, and a small cache of such files
147  * should be kept to avoid recreation costs.
148  */
149 static u_long wantfreevnodes;
150 SYSCTL_LONG(_vfs, OID_AUTO, wantfreevnodes, CTLFLAG_RW, &wantfreevnodes, 0, "");
151 /* Number of vnodes in the free list. */
152 static u_long freevnodes;
153 SYSCTL_LONG(_vfs, OID_AUTO, freevnodes, CTLFLAG_RD, &freevnodes, 0, "");
154
155 static int vlru_allow_cache_src;
156 SYSCTL_INT(_vfs, OID_AUTO, vlru_allow_cache_src, CTLFLAG_RW,
157     &vlru_allow_cache_src, 0, "Allow vlru to reclaim source vnode");
158
159 /*
160  * Various variables used for debugging the new implementation of
161  * reassignbuf().
162  * XXX these are probably of (very) limited utility now.
163  */
164 static int reassignbufcalls;
165 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW, &reassignbufcalls, 0, "");
166
167 /*
168  * Cache for the mount type id assigned to NFS.  This is used for
169  * special checks in nfs/nfs_nqlease.c and vm/vnode_pager.c.
170  */
171 int     nfs_mount_type = -1;
172
173 /* To keep more than one thread at a time from running vfs_getnewfsid */
174 static struct mtx mntid_mtx;
175
176 /*
177  * Lock for any access to the following:
178  *      vnode_free_list
179  *      numvnodes
180  *      freevnodes
181  */
182 static struct mtx vnode_free_list_mtx;
183
184 /* Publicly exported FS */
185 struct nfs_public nfs_pub;
186
187 /* Zone for allocation of new vnodes - used exclusively by getnewvnode() */
188 static uma_zone_t vnode_zone;
189 static uma_zone_t vnodepoll_zone;
190
191 /* Set to 1 to print out reclaim of active vnodes */
192 int     prtactive;
193
194 /*
195  * The workitem queue.
196  *
197  * It is useful to delay writes of file data and filesystem metadata
198  * for tens of seconds so that quickly created and deleted files need
199  * not waste disk bandwidth being created and removed. To realize this,
200  * we append vnodes to a "workitem" queue. When running with a soft
201  * updates implementation, most pending metadata dependencies should
202  * not wait for more than a few seconds. Thus, mounted on block devices
203  * are delayed only about a half the time that file data is delayed.
204  * Similarly, directory updates are more critical, so are only delayed
205  * about a third the time that file data is delayed. Thus, there are
206  * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
207  * one each second (driven off the filesystem syncer process). The
208  * syncer_delayno variable indicates the next queue that is to be processed.
209  * Items that need to be processed soon are placed in this queue:
210  *
211  *      syncer_workitem_pending[syncer_delayno]
212  *
213  * A delay of fifteen seconds is done by placing the request fifteen
214  * entries later in the queue:
215  *
216  *      syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
217  *
218  */
219 static int syncer_delayno;
220 static long syncer_mask;
221 LIST_HEAD(synclist, bufobj);
222 static struct synclist *syncer_workitem_pending[2];
223 /*
224  * The sync_mtx protects:
225  *      bo->bo_synclist
226  *      sync_vnode_count
227  *      syncer_delayno
228  *      syncer_state
229  *      syncer_workitem_pending
230  *      syncer_worklist_len
231  *      rushjob
232  */
233 static struct mtx sync_mtx;
234 static struct cv sync_wakeup;
235
236 #define SYNCER_MAXDELAY         32
237 static int syncer_maxdelay = SYNCER_MAXDELAY;   /* maximum delay time */
238 static int syncdelay = 30;              /* max time to delay syncing data */
239 static int filedelay = 30;              /* time to delay syncing files */
240 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0, "");
241 static int dirdelay = 29;               /* time to delay syncing directories */
242 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0, "");
243 static int metadelay = 28;              /* time to delay syncing metadata */
244 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0, "");
245 static int rushjob;             /* number of slots to run ASAP */
246 static int stat_rush_requests;  /* number of times I/O speeded up */
247 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0, "");
248
249 /*
250  * When shutting down the syncer, run it at four times normal speed.
251  */
252 #define SYNCER_SHUTDOWN_SPEEDUP         4
253 static int sync_vnode_count;
254 static int syncer_worklist_len;
255 static enum { SYNCER_RUNNING, SYNCER_SHUTTING_DOWN, SYNCER_FINAL_DELAY }
256     syncer_state;
257
258 /*
259  * Number of vnodes we want to exist at any one time.  This is mostly used
260  * to size hash tables in vnode-related code.  It is normally not used in
261  * getnewvnode(), as wantfreevnodes is normally nonzero.)
262  *
263  * XXX desiredvnodes is historical cruft and should not exist.
264  */
265 int desiredvnodes;
266 SYSCTL_INT(_kern, KERN_MAXVNODES, maxvnodes, CTLFLAG_RW,
267     &desiredvnodes, 0, "Maximum number of vnodes");
268 SYSCTL_INT(_kern, OID_AUTO, minvnodes, CTLFLAG_RW,
269     &wantfreevnodes, 0, "Minimum number of vnodes (legacy)");
270 static int vnlru_nowhere;
271 SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW,
272     &vnlru_nowhere, 0, "Number of times the vnlru process ran without success");
273
274 /*
275  * Macros to control when a vnode is freed and recycled.  All require
276  * the vnode interlock.
277  */
278 #define VCANRECYCLE(vp) (((vp)->v_iflag & VI_FREE) && !(vp)->v_holdcnt)
279 #define VSHOULDFREE(vp) (!((vp)->v_iflag & VI_FREE) && !(vp)->v_holdcnt)
280 #define VSHOULDBUSY(vp) (((vp)->v_iflag & VI_FREE) && (vp)->v_holdcnt)
281
282
283 /*
284  * Initialize the vnode management data structures.
285  */
286 #ifndef MAXVNODES_MAX
287 #define MAXVNODES_MAX   100000
288 #endif
289 static void
290 vntblinit(void *dummy __unused)
291 {
292
293         /*
294          * Desiredvnodes is a function of the physical memory size and
295          * the kernel's heap size.  Specifically, desiredvnodes scales
296          * in proportion to the physical memory size until two fifths
297          * of the kernel's heap size is consumed by vnodes and vm
298          * objects.
299          */
300         desiredvnodes = min(maxproc + cnt.v_page_count / 4, 2 * vm_kmem_size /
301             (5 * (sizeof(struct vm_object) + sizeof(struct vnode))));
302         if (desiredvnodes > MAXVNODES_MAX) {
303                 if (bootverbose)
304                         printf("Reducing kern.maxvnodes %d -> %d\n",
305                             desiredvnodes, MAXVNODES_MAX);
306                 desiredvnodes = MAXVNODES_MAX;
307         }
308         wantfreevnodes = desiredvnodes / 4;
309         mtx_init(&mntid_mtx, "mntid", NULL, MTX_DEF);
310         TAILQ_INIT(&vnode_free_list);
311         mtx_init(&vnode_free_list_mtx, "vnode_free_list", NULL, MTX_DEF);
312         vnode_zone = uma_zcreate("VNODE", sizeof (struct vnode), NULL, NULL,
313             NULL, NULL, UMA_ALIGN_PTR, 0);
314         vnodepoll_zone = uma_zcreate("VNODEPOLL", sizeof (struct vpollinfo),
315             NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
316         /*
317          * Initialize the filesystem syncer.
318          */
319         syncer_workitem_pending[WI_MPSAFEQ] = hashinit(syncer_maxdelay, M_VNODE,
320             &syncer_mask);
321         syncer_workitem_pending[WI_GIANTQ] = hashinit(syncer_maxdelay, M_VNODE,
322             &syncer_mask);
323         syncer_maxdelay = syncer_mask + 1;
324         mtx_init(&sync_mtx, "Syncer mtx", NULL, MTX_DEF);
325         cv_init(&sync_wakeup, "syncer");
326 }
327 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_FIRST, vntblinit, NULL);
328
329
330 /*
331  * Mark a mount point as busy. Used to synchronize access and to delay
332  * unmounting. Eventually, mountlist_mtx is not released on failure.
333  */
334 int
335 vfs_busy(struct mount *mp, int flags)
336 {
337
338         MPASS((flags & ~MBF_MASK) == 0);
339         CTR3(KTR_VFS, "%s: mp %p with flags %d", __func__, mp, flags);
340
341         MNT_ILOCK(mp);
342         MNT_REF(mp);
343         /*
344          * If mount point is currenly being unmounted, sleep until the
345          * mount point fate is decided.  If thread doing the unmounting fails,
346          * it will clear MNTK_UNMOUNT flag before waking us up, indicating
347          * that this mount point has survived the unmount attempt and vfs_busy
348          * should retry.  Otherwise the unmounter thread will set MNTK_REFEXPIRE
349          * flag in addition to MNTK_UNMOUNT, indicating that mount point is
350          * about to be really destroyed.  vfs_busy needs to release its
351          * reference on the mount point in this case and return with ENOENT,
352          * telling the caller that mount mount it tried to busy is no longer
353          * valid.
354          */
355         while (mp->mnt_kern_flag & MNTK_UNMOUNT) {
356                 if (flags & MBF_NOWAIT || mp->mnt_kern_flag & MNTK_REFEXPIRE) {
357                         MNT_REL(mp);
358                         MNT_IUNLOCK(mp);
359                         CTR1(KTR_VFS, "%s: failed busying before sleeping",
360                             __func__);
361                         return (ENOENT);
362                 }
363                 if (flags & MBF_MNTLSTLOCK)
364                         mtx_unlock(&mountlist_mtx);
365                 mp->mnt_kern_flag |= MNTK_MWAIT;
366                 msleep(mp, MNT_MTX(mp), PVFS, "vfs_busy", 0);
367                 if (flags & MBF_MNTLSTLOCK)
368                         mtx_lock(&mountlist_mtx);
369         }
370         if (flags & MBF_MNTLSTLOCK)
371                 mtx_unlock(&mountlist_mtx);
372         mp->mnt_lockref++;
373         MNT_IUNLOCK(mp);
374         return (0);
375 }
376
377 /*
378  * Free a busy filesystem.
379  */
380 void
381 vfs_unbusy(struct mount *mp)
382 {
383
384         CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
385         MNT_ILOCK(mp);
386         MNT_REL(mp);
387         KASSERT(mp->mnt_lockref > 0, ("negative mnt_lockref"));
388         mp->mnt_lockref--;
389         if (mp->mnt_lockref == 0 && (mp->mnt_kern_flag & MNTK_DRAINING) != 0) {
390                 MPASS(mp->mnt_kern_flag & MNTK_UNMOUNT);
391                 CTR1(KTR_VFS, "%s: waking up waiters", __func__);
392                 mp->mnt_kern_flag &= ~MNTK_DRAINING;
393                 wakeup(&mp->mnt_lockref);
394         }
395         MNT_IUNLOCK(mp);
396 }
397
398 /*
399  * Lookup a mount point by filesystem identifier.
400  */
401 struct mount *
402 vfs_getvfs(fsid_t *fsid)
403 {
404         struct mount *mp;
405
406         CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
407         mtx_lock(&mountlist_mtx);
408         TAILQ_FOREACH(mp, &mountlist, mnt_list) {
409                 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
410                     mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
411                         vfs_ref(mp);
412                         mtx_unlock(&mountlist_mtx);
413                         return (mp);
414                 }
415         }
416         mtx_unlock(&mountlist_mtx);
417         CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
418         return ((struct mount *) 0);
419 }
420
421 /*
422  * Lookup a mount point by filesystem identifier, busying it before
423  * returning.
424  */
425 struct mount *
426 vfs_busyfs(fsid_t *fsid)
427 {
428         struct mount *mp;
429         int error;
430
431         CTR2(KTR_VFS, "%s: fsid %p", __func__, fsid);
432         mtx_lock(&mountlist_mtx);
433         TAILQ_FOREACH(mp, &mountlist, mnt_list) {
434                 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
435                     mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
436                         error = vfs_busy(mp, MBF_MNTLSTLOCK);
437                         if (error) {
438                                 mtx_unlock(&mountlist_mtx);
439                                 return (NULL);
440                         }
441                         return (mp);
442                 }
443         }
444         CTR2(KTR_VFS, "%s: lookup failed for %p id", __func__, fsid);
445         mtx_unlock(&mountlist_mtx);
446         return ((struct mount *) 0);
447 }
448
449 /*
450  * Check if a user can access privileged mount options.
451  */
452 int
453 vfs_suser(struct mount *mp, struct thread *td)
454 {
455         int error;
456
457         /*
458          * If the thread is jailed, but this is not a jail-friendly file
459          * system, deny immediately.
460          */
461         if (!(mp->mnt_vfc->vfc_flags & VFCF_JAIL) && jailed(td->td_ucred))
462                 return (EPERM);
463
464         /*
465          * If the file system was mounted outside the jail of the calling
466          * thread, deny immediately.
467          */
468         if (prison_check(td->td_ucred, mp->mnt_cred) != 0)
469                 return (EPERM);
470
471         /*
472          * If file system supports delegated administration, we don't check
473          * for the PRIV_VFS_MOUNT_OWNER privilege - it will be better verified
474          * by the file system itself.
475          * If this is not the user that did original mount, we check for
476          * the PRIV_VFS_MOUNT_OWNER privilege.
477          */
478         if (!(mp->mnt_vfc->vfc_flags & VFCF_DELEGADMIN) &&
479             mp->mnt_cred->cr_uid != td->td_ucred->cr_uid) {
480                 if ((error = priv_check(td, PRIV_VFS_MOUNT_OWNER)) != 0)
481                         return (error);
482         }
483         return (0);
484 }
485
486 /*
487  * Get a new unique fsid.  Try to make its val[0] unique, since this value
488  * will be used to create fake device numbers for stat().  Also try (but
489  * not so hard) make its val[0] unique mod 2^16, since some emulators only
490  * support 16-bit device numbers.  We end up with unique val[0]'s for the
491  * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
492  *
493  * Keep in mind that several mounts may be running in parallel.  Starting
494  * the search one past where the previous search terminated is both a
495  * micro-optimization and a defense against returning the same fsid to
496  * different mounts.
497  */
498 void
499 vfs_getnewfsid(struct mount *mp)
500 {
501         static u_int16_t mntid_base;
502         struct mount *nmp;
503         fsid_t tfsid;
504         int mtype;
505
506         CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
507         mtx_lock(&mntid_mtx);
508         mtype = mp->mnt_vfc->vfc_typenum;
509         tfsid.val[1] = mtype;
510         mtype = (mtype & 0xFF) << 24;
511         for (;;) {
512                 tfsid.val[0] = makedev(255,
513                     mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
514                 mntid_base++;
515                 if ((nmp = vfs_getvfs(&tfsid)) == NULL)
516                         break;
517                 vfs_rel(nmp);
518         }
519         mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
520         mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
521         mtx_unlock(&mntid_mtx);
522 }
523
524 /*
525  * Knob to control the precision of file timestamps:
526  *
527  *   0 = seconds only; nanoseconds zeroed.
528  *   1 = seconds and nanoseconds, accurate within 1/HZ.
529  *   2 = seconds and nanoseconds, truncated to microseconds.
530  * >=3 = seconds and nanoseconds, maximum precision.
531  */
532 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
533
534 static int timestamp_precision = TSP_SEC;
535 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
536     &timestamp_precision, 0, "");
537
538 /*
539  * Get a current timestamp.
540  */
541 void
542 vfs_timestamp(struct timespec *tsp)
543 {
544         struct timeval tv;
545
546         switch (timestamp_precision) {
547         case TSP_SEC:
548                 tsp->tv_sec = time_second;
549                 tsp->tv_nsec = 0;
550                 break;
551         case TSP_HZ:
552                 getnanotime(tsp);
553                 break;
554         case TSP_USEC:
555                 microtime(&tv);
556                 TIMEVAL_TO_TIMESPEC(&tv, tsp);
557                 break;
558         case TSP_NSEC:
559         default:
560                 nanotime(tsp);
561                 break;
562         }
563 }
564
565 /*
566  * Set vnode attributes to VNOVAL
567  */
568 void
569 vattr_null(struct vattr *vap)
570 {
571
572         vap->va_type = VNON;
573         vap->va_size = VNOVAL;
574         vap->va_bytes = VNOVAL;
575         vap->va_mode = VNOVAL;
576         vap->va_nlink = VNOVAL;
577         vap->va_uid = VNOVAL;
578         vap->va_gid = VNOVAL;
579         vap->va_fsid = VNOVAL;
580         vap->va_fileid = VNOVAL;
581         vap->va_blocksize = VNOVAL;
582         vap->va_rdev = VNOVAL;
583         vap->va_atime.tv_sec = VNOVAL;
584         vap->va_atime.tv_nsec = VNOVAL;
585         vap->va_mtime.tv_sec = VNOVAL;
586         vap->va_mtime.tv_nsec = VNOVAL;
587         vap->va_ctime.tv_sec = VNOVAL;
588         vap->va_ctime.tv_nsec = VNOVAL;
589         vap->va_birthtime.tv_sec = VNOVAL;
590         vap->va_birthtime.tv_nsec = VNOVAL;
591         vap->va_flags = VNOVAL;
592         vap->va_gen = VNOVAL;
593         vap->va_vaflags = 0;
594 }
595
596 /*
597  * This routine is called when we have too many vnodes.  It attempts
598  * to free <count> vnodes and will potentially free vnodes that still
599  * have VM backing store (VM backing store is typically the cause
600  * of a vnode blowout so we want to do this).  Therefore, this operation
601  * is not considered cheap.
602  *
603  * A number of conditions may prevent a vnode from being reclaimed.
604  * the buffer cache may have references on the vnode, a directory
605  * vnode may still have references due to the namei cache representing
606  * underlying files, or the vnode may be in active use.   It is not
607  * desireable to reuse such vnodes.  These conditions may cause the
608  * number of vnodes to reach some minimum value regardless of what
609  * you set kern.maxvnodes to.  Do not set kern.maxvnodes too low.
610  */
611 static int
612 vlrureclaim(struct mount *mp)
613 {
614         struct vnode *vp;
615         int done;
616         int trigger;
617         int usevnodes;
618         int count;
619
620         /*
621          * Calculate the trigger point, don't allow user
622          * screwups to blow us up.   This prevents us from
623          * recycling vnodes with lots of resident pages.  We
624          * aren't trying to free memory, we are trying to
625          * free vnodes.
626          */
627         usevnodes = desiredvnodes;
628         if (usevnodes <= 0)
629                 usevnodes = 1;
630         trigger = cnt.v_page_count * 2 / usevnodes;
631         done = 0;
632         vn_start_write(NULL, &mp, V_WAIT);
633         MNT_ILOCK(mp);
634         count = mp->mnt_nvnodelistsize / 10 + 1;
635         while (count != 0) {
636                 vp = TAILQ_FIRST(&mp->mnt_nvnodelist);
637                 while (vp != NULL && vp->v_type == VMARKER)
638                         vp = TAILQ_NEXT(vp, v_nmntvnodes);
639                 if (vp == NULL)
640                         break;
641                 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
642                 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
643                 --count;
644                 if (!VI_TRYLOCK(vp))
645                         goto next_iter;
646                 /*
647                  * If it's been deconstructed already, it's still
648                  * referenced, or it exceeds the trigger, skip it.
649                  */
650                 if (vp->v_usecount ||
651                     (!vlru_allow_cache_src &&
652                         !LIST_EMPTY(&(vp)->v_cache_src)) ||
653                     (vp->v_iflag & VI_DOOMED) != 0 || (vp->v_object != NULL &&
654                     vp->v_object->resident_page_count > trigger)) {
655                         VI_UNLOCK(vp);
656                         goto next_iter;
657                 }
658                 MNT_IUNLOCK(mp);
659                 vholdl(vp);
660                 if (VOP_LOCK(vp, LK_INTERLOCK|LK_EXCLUSIVE|LK_NOWAIT)) {
661                         vdrop(vp);
662                         goto next_iter_mntunlocked;
663                 }
664                 VI_LOCK(vp);
665                 /*
666                  * v_usecount may have been bumped after VOP_LOCK() dropped
667                  * the vnode interlock and before it was locked again.
668                  *
669                  * It is not necessary to recheck VI_DOOMED because it can
670                  * only be set by another thread that holds both the vnode
671                  * lock and vnode interlock.  If another thread has the
672                  * vnode lock before we get to VOP_LOCK() and obtains the
673                  * vnode interlock after VOP_LOCK() drops the vnode
674                  * interlock, the other thread will be unable to drop the
675                  * vnode lock before our VOP_LOCK() call fails.
676                  */
677                 if (vp->v_usecount ||
678                     (!vlru_allow_cache_src &&
679                         !LIST_EMPTY(&(vp)->v_cache_src)) ||
680                     (vp->v_object != NULL &&
681                     vp->v_object->resident_page_count > trigger)) {
682                         VOP_UNLOCK(vp, LK_INTERLOCK);
683                         goto next_iter_mntunlocked;
684                 }
685                 KASSERT((vp->v_iflag & VI_DOOMED) == 0,
686                     ("VI_DOOMED unexpectedly detected in vlrureclaim()"));
687                 vgonel(vp);
688                 VOP_UNLOCK(vp, 0);
689                 vdropl(vp);
690                 done++;
691 next_iter_mntunlocked:
692                 if ((count % 256) != 0)
693                         goto relock_mnt;
694                 goto yield;
695 next_iter:
696                 if ((count % 256) != 0)
697                         continue;
698                 MNT_IUNLOCK(mp);
699 yield:
700                 uio_yield();
701 relock_mnt:
702                 MNT_ILOCK(mp);
703         }
704         MNT_IUNLOCK(mp);
705         vn_finished_write(mp);
706         return done;
707 }
708
709 /*
710  * Attempt to keep the free list at wantfreevnodes length.
711  */
712 static void
713 vnlru_free(int count)
714 {
715         struct vnode *vp;
716         int vfslocked;
717
718         mtx_assert(&vnode_free_list_mtx, MA_OWNED);
719         for (; count > 0; count--) {
720                 vp = TAILQ_FIRST(&vnode_free_list);
721                 /*
722                  * The list can be modified while the free_list_mtx
723                  * has been dropped and vp could be NULL here.
724                  */
725                 if (!vp)
726                         break;
727                 VNASSERT(vp->v_op != NULL, vp,
728                     ("vnlru_free: vnode already reclaimed."));
729                 TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
730                 /*
731                  * Don't recycle if we can't get the interlock.
732                  */
733                 if (!VI_TRYLOCK(vp)) {
734                         TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
735                         continue;
736                 }
737                 VNASSERT(VCANRECYCLE(vp), vp,
738                     ("vp inconsistent on freelist"));
739                 freevnodes--;
740                 vp->v_iflag &= ~VI_FREE;
741                 vholdl(vp);
742                 mtx_unlock(&vnode_free_list_mtx);
743                 VI_UNLOCK(vp);
744                 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
745                 vtryrecycle(vp);
746                 VFS_UNLOCK_GIANT(vfslocked);
747                 /*
748                  * If the recycled succeeded this vdrop will actually free
749                  * the vnode.  If not it will simply place it back on
750                  * the free list.
751                  */
752                 vdrop(vp);
753                 mtx_lock(&vnode_free_list_mtx);
754         }
755 }
756 /*
757  * Attempt to recycle vnodes in a context that is always safe to block.
758  * Calling vlrurecycle() from the bowels of filesystem code has some
759  * interesting deadlock problems.
760  */
761 static struct proc *vnlruproc;
762 static int vnlruproc_sig;
763
764 static void
765 vnlru_proc(void)
766 {
767         struct mount *mp, *nmp;
768         int done, vfslocked;
769         struct proc *p = vnlruproc;
770
771         EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, p,
772             SHUTDOWN_PRI_FIRST);
773
774         for (;;) {
775                 kproc_suspend_check(p);
776                 mtx_lock(&vnode_free_list_mtx);
777                 if (freevnodes > wantfreevnodes)
778                         vnlru_free(freevnodes - wantfreevnodes);
779                 if (numvnodes <= desiredvnodes * 9 / 10) {
780                         vnlruproc_sig = 0;
781                         wakeup(&vnlruproc_sig);
782                         msleep(vnlruproc, &vnode_free_list_mtx,
783                             PVFS|PDROP, "vlruwt", hz);
784                         continue;
785                 }
786                 mtx_unlock(&vnode_free_list_mtx);
787                 done = 0;
788                 mtx_lock(&mountlist_mtx);
789                 for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
790                         if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK)) {
791                                 nmp = TAILQ_NEXT(mp, mnt_list);
792                                 continue;
793                         }
794                         vfslocked = VFS_LOCK_GIANT(mp);
795                         done += vlrureclaim(mp);
796                         VFS_UNLOCK_GIANT(vfslocked);
797                         mtx_lock(&mountlist_mtx);
798                         nmp = TAILQ_NEXT(mp, mnt_list);
799                         vfs_unbusy(mp);
800                 }
801                 mtx_unlock(&mountlist_mtx);
802                 if (done == 0) {
803 #if 0
804                         /* These messages are temporary debugging aids */
805                         if (vnlru_nowhere < 5)
806                                 printf("vnlru process getting nowhere..\n");
807                         else if (vnlru_nowhere == 5)
808                                 printf("vnlru process messages stopped.\n");
809 #endif
810                         vnlru_nowhere++;
811                         tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
812                 } else
813                         uio_yield();
814         }
815 }
816
817 static struct kproc_desc vnlru_kp = {
818         "vnlru",
819         vnlru_proc,
820         &vnlruproc
821 };
822 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start,
823     &vnlru_kp);
824  
825 /*
826  * Routines having to do with the management of the vnode table.
827  */
828
829 void
830 vdestroy(struct vnode *vp)
831 {
832         struct bufobj *bo;
833
834         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
835         mtx_lock(&vnode_free_list_mtx);
836         numvnodes--;
837         mtx_unlock(&vnode_free_list_mtx);
838         bo = &vp->v_bufobj;
839         VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
840             ("cleaned vnode still on the free list."));
841         VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
842         VNASSERT(vp->v_holdcnt == 0, vp, ("Non-zero hold count"));
843         VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
844         VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
845         VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
846         VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
847         VNASSERT(bo->bo_clean.bv_root == NULL, vp, ("cleanblkroot not NULL"));
848         VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
849         VNASSERT(bo->bo_dirty.bv_root == NULL, vp, ("dirtyblkroot not NULL"));
850         VNASSERT(TAILQ_EMPTY(&vp->v_cache_dst), vp, ("vp has namecache dst"));
851         VNASSERT(LIST_EMPTY(&vp->v_cache_src), vp, ("vp has namecache src"));
852         VNASSERT(vp->v_cache_dd == NULL, vp, ("vp has namecache for .."));
853         VI_UNLOCK(vp);
854 #ifdef MAC
855         mac_vnode_destroy(vp);
856 #endif
857         if (vp->v_pollinfo != NULL)
858                 destroy_vpollinfo(vp->v_pollinfo);
859 #ifdef INVARIANTS
860         /* XXX Elsewhere we can detect an already freed vnode via NULL v_op. */
861         vp->v_op = NULL;
862 #endif
863         lockdestroy(vp->v_vnlock);
864         mtx_destroy(&vp->v_interlock);
865         mtx_destroy(BO_MTX(bo));
866         uma_zfree(vnode_zone, vp);
867 }
868
869 /*
870  * Try to recycle a freed vnode.  We abort if anyone picks up a reference
871  * before we actually vgone().  This function must be called with the vnode
872  * held to prevent the vnode from being returned to the free list midway
873  * through vgone().
874  */
875 static int
876 vtryrecycle(struct vnode *vp)
877 {
878         struct mount *vnmp;
879
880         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
881         VNASSERT(vp->v_holdcnt, vp,
882             ("vtryrecycle: Recycling vp %p without a reference.", vp));
883         /*
884          * This vnode may found and locked via some other list, if so we
885          * can't recycle it yet.
886          */
887         if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
888                 CTR2(KTR_VFS,
889                     "%s: impossible to recycle, vp %p lock is already held",
890                     __func__, vp);
891                 return (EWOULDBLOCK);
892         }
893         /*
894          * Don't recycle if its filesystem is being suspended.
895          */
896         if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
897                 VOP_UNLOCK(vp, 0);
898                 CTR2(KTR_VFS,
899                     "%s: impossible to recycle, cannot start the write for %p",
900                     __func__, vp);
901                 return (EBUSY);
902         }
903         /*
904          * If we got this far, we need to acquire the interlock and see if
905          * anyone picked up this vnode from another list.  If not, we will
906          * mark it with DOOMED via vgonel() so that anyone who does find it
907          * will skip over it.
908          */
909         VI_LOCK(vp);
910         if (vp->v_usecount) {
911                 VOP_UNLOCK(vp, LK_INTERLOCK);
912                 vn_finished_write(vnmp);
913                 CTR2(KTR_VFS,
914                     "%s: impossible to recycle, %p is already referenced",
915                     __func__, vp);
916                 return (EBUSY);
917         }
918         if ((vp->v_iflag & VI_DOOMED) == 0)
919                 vgonel(vp);
920         VOP_UNLOCK(vp, LK_INTERLOCK);
921         vn_finished_write(vnmp);
922         return (0);
923 }
924
925 /*
926  * Return the next vnode from the free list.
927  */
928 int
929 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
930     struct vnode **vpp)
931 {
932         struct vnode *vp = NULL;
933         struct bufobj *bo;
934
935         CTR3(KTR_VFS, "%s: mp %p with tag %s", __func__, mp, tag);
936         mtx_lock(&vnode_free_list_mtx);
937         /*
938          * Lend our context to reclaim vnodes if they've exceeded the max.
939          */
940         if (freevnodes > wantfreevnodes)
941                 vnlru_free(1);
942         /*
943          * Wait for available vnodes.
944          */
945         if (numvnodes > desiredvnodes) {
946                 if (mp != NULL && (mp->mnt_kern_flag & MNTK_SUSPEND)) {
947                         /*
948                          * File system is beeing suspended, we cannot risk a
949                          * deadlock here, so allocate new vnode anyway.
950                          */
951                         if (freevnodes > wantfreevnodes)
952                                 vnlru_free(freevnodes - wantfreevnodes);
953                         goto alloc;
954                 }
955                 if (vnlruproc_sig == 0) {
956                         vnlruproc_sig = 1;      /* avoid unnecessary wakeups */
957                         wakeup(vnlruproc);
958                 }
959                 msleep(&vnlruproc_sig, &vnode_free_list_mtx, PVFS,
960                     "vlruwk", hz);
961 #if 0   /* XXX Not all VFS_VGET/ffs_vget callers check returns. */
962                 if (numvnodes > desiredvnodes) {
963                         mtx_unlock(&vnode_free_list_mtx);
964                         return (ENFILE);
965                 }
966 #endif
967         }
968 alloc:
969         numvnodes++;
970         mtx_unlock(&vnode_free_list_mtx);
971         vp = (struct vnode *) uma_zalloc(vnode_zone, M_WAITOK|M_ZERO);
972         /*
973          * Setup locks.
974          */
975         vp->v_vnlock = &vp->v_lock;
976         mtx_init(&vp->v_interlock, "vnode interlock", NULL, MTX_DEF);
977         /*
978          * By default, don't allow shared locks unless filesystems
979          * opt-in.
980          */
981         lockinit(vp->v_vnlock, PVFS, tag, VLKTIMEOUT, LK_NOSHARE);
982         /*
983          * Initialize bufobj.
984          */
985         bo = &vp->v_bufobj;
986         bo->__bo_vnode = vp;
987         mtx_init(BO_MTX(bo), "bufobj interlock", NULL, MTX_DEF);
988         bo->bo_ops = &buf_ops_bio;
989         bo->bo_private = vp;
990         TAILQ_INIT(&bo->bo_clean.bv_hd);
991         TAILQ_INIT(&bo->bo_dirty.bv_hd);
992         /*
993          * Initialize namecache.
994          */
995         LIST_INIT(&vp->v_cache_src);
996         TAILQ_INIT(&vp->v_cache_dst);
997         /*
998          * Finalize various vnode identity bits.
999          */
1000         vp->v_type = VNON;
1001         vp->v_tag = tag;
1002         vp->v_op = vops;
1003         v_incr_usecount(vp);
1004         vp->v_data = 0;
1005 #ifdef MAC
1006         mac_vnode_init(vp);
1007         if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
1008                 mac_vnode_associate_singlelabel(mp, vp);
1009         else if (mp == NULL && vops != &dead_vnodeops)
1010                 printf("NULL mp in getnewvnode()\n");
1011 #endif
1012         if (mp != NULL) {
1013                 bo->bo_bsize = mp->mnt_stat.f_iosize;
1014                 if ((mp->mnt_kern_flag & MNTK_NOKNOTE) != 0)
1015                         vp->v_vflag |= VV_NOKNOTE;
1016         }
1017
1018         *vpp = vp;
1019         return (0);
1020 }
1021
1022 /*
1023  * Delete from old mount point vnode list, if on one.
1024  */
1025 static void
1026 delmntque(struct vnode *vp)
1027 {
1028         struct mount *mp;
1029
1030         mp = vp->v_mount;
1031         if (mp == NULL)
1032                 return;
1033         MNT_ILOCK(mp);
1034         vp->v_mount = NULL;
1035         VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
1036                 ("bad mount point vnode list size"));
1037         TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1038         mp->mnt_nvnodelistsize--;
1039         MNT_REL(mp);
1040         MNT_IUNLOCK(mp);
1041 }
1042
1043 static void
1044 insmntque_stddtr(struct vnode *vp, void *dtr_arg)
1045 {
1046
1047         vp->v_data = NULL;
1048         vp->v_op = &dead_vnodeops;
1049         /* XXX non mp-safe fs may still call insmntque with vnode
1050            unlocked */
1051         if (!VOP_ISLOCKED(vp))
1052                 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1053         vgone(vp);
1054         vput(vp);
1055 }
1056
1057 /*
1058  * Insert into list of vnodes for the new mount point, if available.
1059  */
1060 int
1061 insmntque1(struct vnode *vp, struct mount *mp,
1062         void (*dtr)(struct vnode *, void *), void *dtr_arg)
1063 {
1064         int locked;
1065
1066         KASSERT(vp->v_mount == NULL,
1067                 ("insmntque: vnode already on per mount vnode list"));
1068         VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
1069 #ifdef DEBUG_VFS_LOCKS
1070         if (!VFS_NEEDSGIANT(mp))
1071                 ASSERT_VOP_ELOCKED(vp,
1072                     "insmntque: mp-safe fs and non-locked vp");
1073 #endif
1074         MNT_ILOCK(mp);
1075         if ((mp->mnt_kern_flag & MNTK_NOINSMNTQ) != 0 &&
1076             ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
1077              mp->mnt_nvnodelistsize == 0)) {
1078                 locked = VOP_ISLOCKED(vp);
1079                 if (!locked || (locked == LK_EXCLUSIVE &&
1080                      (vp->v_vflag & VV_FORCEINSMQ) == 0)) {
1081                         MNT_IUNLOCK(mp);
1082                         if (dtr != NULL)
1083                                 dtr(vp, dtr_arg);
1084                         return (EBUSY);
1085                 }
1086         }
1087         vp->v_mount = mp;
1088         MNT_REF(mp);
1089         TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1090         VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
1091                 ("neg mount point vnode list size"));
1092         mp->mnt_nvnodelistsize++;
1093         MNT_IUNLOCK(mp);
1094         return (0);
1095 }
1096
1097 int
1098 insmntque(struct vnode *vp, struct mount *mp)
1099 {
1100
1101         return (insmntque1(vp, mp, insmntque_stddtr, NULL));
1102 }
1103
1104 /*
1105  * Flush out and invalidate all buffers associated with a bufobj
1106  * Called with the underlying object locked.
1107  */
1108 int
1109 bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo)
1110 {
1111         int error;
1112
1113         BO_LOCK(bo);
1114         if (flags & V_SAVE) {
1115                 error = bufobj_wwait(bo, slpflag, slptimeo);
1116                 if (error) {
1117                         BO_UNLOCK(bo);
1118                         return (error);
1119                 }
1120                 if (bo->bo_dirty.bv_cnt > 0) {
1121                         BO_UNLOCK(bo);
1122                         if ((error = BO_SYNC(bo, MNT_WAIT)) != 0)
1123                                 return (error);
1124                         /*
1125                          * XXX We could save a lock/unlock if this was only
1126                          * enabled under INVARIANTS
1127                          */
1128                         BO_LOCK(bo);
1129                         if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0)
1130                                 panic("vinvalbuf: dirty bufs");
1131                 }
1132         }
1133         /*
1134          * If you alter this loop please notice that interlock is dropped and
1135          * reacquired in flushbuflist.  Special care is needed to ensure that
1136          * no race conditions occur from this.
1137          */
1138         do {
1139                 error = flushbuflist(&bo->bo_clean,
1140                     flags, bo, slpflag, slptimeo);
1141                 if (error == 0)
1142                         error = flushbuflist(&bo->bo_dirty,
1143                             flags, bo, slpflag, slptimeo);
1144                 if (error != 0 && error != EAGAIN) {
1145                         BO_UNLOCK(bo);
1146                         return (error);
1147                 }
1148         } while (error != 0);
1149
1150         /*
1151          * Wait for I/O to complete.  XXX needs cleaning up.  The vnode can
1152          * have write I/O in-progress but if there is a VM object then the
1153          * VM object can also have read-I/O in-progress.
1154          */
1155         do {
1156                 bufobj_wwait(bo, 0, 0);
1157                 BO_UNLOCK(bo);
1158                 if (bo->bo_object != NULL) {
1159                         VM_OBJECT_LOCK(bo->bo_object);
1160                         vm_object_pip_wait(bo->bo_object, "bovlbx");
1161                         VM_OBJECT_UNLOCK(bo->bo_object);
1162                 }
1163                 BO_LOCK(bo);
1164         } while (bo->bo_numoutput > 0);
1165         BO_UNLOCK(bo);
1166
1167         /*
1168          * Destroy the copy in the VM cache, too.
1169          */
1170         if (bo->bo_object != NULL && (flags & (V_ALT | V_NORMAL)) == 0) {
1171                 VM_OBJECT_LOCK(bo->bo_object);
1172                 vm_object_page_remove(bo->bo_object, 0, 0,
1173                         (flags & V_SAVE) ? TRUE : FALSE);
1174                 VM_OBJECT_UNLOCK(bo->bo_object);
1175         }
1176
1177 #ifdef INVARIANTS
1178         BO_LOCK(bo);
1179         if ((flags & (V_ALT | V_NORMAL)) == 0 &&
1180             (bo->bo_dirty.bv_cnt > 0 || bo->bo_clean.bv_cnt > 0))
1181                 panic("vinvalbuf: flush failed");
1182         BO_UNLOCK(bo);
1183 #endif
1184         return (0);
1185 }
1186
1187 /*
1188  * Flush out and invalidate all buffers associated with a vnode.
1189  * Called with the underlying object locked.
1190  */
1191 int
1192 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
1193 {
1194
1195         CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
1196         ASSERT_VOP_LOCKED(vp, "vinvalbuf");
1197         return (bufobj_invalbuf(&vp->v_bufobj, flags, slpflag, slptimeo));
1198 }
1199
1200 /*
1201  * Flush out buffers on the specified list.
1202  *
1203  */
1204 static int
1205 flushbuflist( struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
1206     int slptimeo)
1207 {
1208         struct buf *bp, *nbp;
1209         int retval, error;
1210         daddr_t lblkno;
1211         b_xflags_t xflags;
1212
1213         ASSERT_BO_LOCKED(bo);
1214
1215         retval = 0;
1216         TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
1217                 if (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA)) ||
1218                     ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0)) {
1219                         continue;
1220                 }
1221                 lblkno = 0;
1222                 xflags = 0;
1223                 if (nbp != NULL) {
1224                         lblkno = nbp->b_lblkno;
1225                         xflags = nbp->b_xflags &
1226                                 (BX_BKGRDMARKER | BX_VNDIRTY | BX_VNCLEAN);
1227                 }
1228                 retval = EAGAIN;
1229                 error = BUF_TIMELOCK(bp,
1230                     LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_MTX(bo),
1231                     "flushbuf", slpflag, slptimeo);
1232                 if (error) {
1233                         BO_LOCK(bo);
1234                         return (error != ENOLCK ? error : EAGAIN);
1235                 }
1236                 KASSERT(bp->b_bufobj == bo,
1237                     ("bp %p wrong b_bufobj %p should be %p",
1238                     bp, bp->b_bufobj, bo));
1239                 if (bp->b_bufobj != bo) {       /* XXX: necessary ? */
1240                         BUF_UNLOCK(bp);
1241                         BO_LOCK(bo);
1242                         return (EAGAIN);
1243                 }
1244                 /*
1245                  * XXX Since there are no node locks for NFS, I
1246                  * believe there is a slight chance that a delayed
1247                  * write will occur while sleeping just above, so
1248                  * check for it.
1249                  */
1250                 if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
1251                     (flags & V_SAVE)) {
1252                         BO_LOCK(bo);
1253                         bremfree(bp);
1254                         BO_UNLOCK(bo);
1255                         bp->b_flags |= B_ASYNC;
1256                         bwrite(bp);
1257                         BO_LOCK(bo);
1258                         return (EAGAIN);        /* XXX: why not loop ? */
1259                 }
1260                 BO_LOCK(bo);
1261                 bremfree(bp);
1262                 BO_UNLOCK(bo);
1263                 bp->b_flags |= (B_INVAL | B_RELBUF);
1264                 bp->b_flags &= ~B_ASYNC;
1265                 brelse(bp);
1266                 BO_LOCK(bo);
1267                 if (nbp != NULL &&
1268                     (nbp->b_bufobj != bo ||
1269                      nbp->b_lblkno != lblkno ||
1270                      (nbp->b_xflags &
1271                       (BX_BKGRDMARKER | BX_VNDIRTY | BX_VNCLEAN)) != xflags))
1272                         break;                  /* nbp invalid */
1273         }
1274         return (retval);
1275 }
1276
1277 /*
1278  * Truncate a file's buffer and pages to a specified length.  This
1279  * is in lieu of the old vinvalbuf mechanism, which performed unneeded
1280  * sync activity.
1281  */
1282 int
1283 vtruncbuf(struct vnode *vp, struct ucred *cred, struct thread *td,
1284     off_t length, int blksize)
1285 {
1286         struct buf *bp, *nbp;
1287         int anyfreed;
1288         int trunclbn;
1289         struct bufobj *bo;
1290
1291         CTR5(KTR_VFS, "%s: vp %p with cred %p and block %d:%ju", __func__,
1292             vp, cred, blksize, (uintmax_t)length);
1293
1294         /*
1295          * Round up to the *next* lbn.
1296          */
1297         trunclbn = (length + blksize - 1) / blksize;
1298
1299         ASSERT_VOP_LOCKED(vp, "vtruncbuf");
1300 restart:
1301         bo = &vp->v_bufobj;
1302         BO_LOCK(bo);
1303         anyfreed = 1;
1304         for (;anyfreed;) {
1305                 anyfreed = 0;
1306                 TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
1307                         if (bp->b_lblkno < trunclbn)
1308                                 continue;
1309                         if (BUF_LOCK(bp,
1310                             LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1311                             BO_MTX(bo)) == ENOLCK)
1312                                 goto restart;
1313
1314                         BO_LOCK(bo);
1315                         bremfree(bp);
1316                         BO_UNLOCK(bo);
1317                         bp->b_flags |= (B_INVAL | B_RELBUF);
1318                         bp->b_flags &= ~B_ASYNC;
1319                         brelse(bp);
1320                         anyfreed = 1;
1321
1322                         if (nbp != NULL &&
1323                             (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
1324                             (nbp->b_vp != vp) ||
1325                             (nbp->b_flags & B_DELWRI))) {
1326                                 goto restart;
1327                         }
1328                         BO_LOCK(bo);
1329                 }
1330
1331                 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
1332                         if (bp->b_lblkno < trunclbn)
1333                                 continue;
1334                         if (BUF_LOCK(bp,
1335                             LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1336                             BO_MTX(bo)) == ENOLCK)
1337                                 goto restart;
1338                         BO_LOCK(bo);
1339                         bremfree(bp);
1340                         BO_UNLOCK(bo);
1341                         bp->b_flags |= (B_INVAL | B_RELBUF);
1342                         bp->b_flags &= ~B_ASYNC;
1343                         brelse(bp);
1344                         anyfreed = 1;
1345                         if (nbp != NULL &&
1346                             (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
1347                             (nbp->b_vp != vp) ||
1348                             (nbp->b_flags & B_DELWRI) == 0)) {
1349                                 goto restart;
1350                         }
1351                         BO_LOCK(bo);
1352                 }
1353         }
1354
1355         if (length > 0) {
1356 restartsync:
1357                 TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
1358                         if (bp->b_lblkno > 0)
1359                                 continue;
1360                         /*
1361                          * Since we hold the vnode lock this should only
1362                          * fail if we're racing with the buf daemon.
1363                          */
1364                         if (BUF_LOCK(bp,
1365                             LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1366                             BO_MTX(bo)) == ENOLCK) {
1367                                 goto restart;
1368                         }
1369                         VNASSERT((bp->b_flags & B_DELWRI), vp,
1370                             ("buf(%p) on dirty queue without DELWRI", bp));
1371
1372                         BO_LOCK(bo);
1373                         bremfree(bp);
1374                         BO_UNLOCK(bo);
1375                         bawrite(bp);
1376                         BO_LOCK(bo);
1377                         goto restartsync;
1378                 }
1379         }
1380
1381         bufobj_wwait(bo, 0, 0);
1382         BO_UNLOCK(bo);
1383         vnode_pager_setsize(vp, length);
1384
1385         return (0);
1386 }
1387
1388 /*
1389  * buf_splay() - splay tree core for the clean/dirty list of buffers in
1390  *               a vnode.
1391  *
1392  *      NOTE: We have to deal with the special case of a background bitmap
1393  *      buffer, a situation where two buffers will have the same logical
1394  *      block offset.  We want (1) only the foreground buffer to be accessed
1395  *      in a lookup and (2) must differentiate between the foreground and
1396  *      background buffer in the splay tree algorithm because the splay
1397  *      tree cannot normally handle multiple entities with the same 'index'.
1398  *      We accomplish this by adding differentiating flags to the splay tree's
1399  *      numerical domain.
1400  */
1401 static
1402 struct buf *
1403 buf_splay(daddr_t lblkno, b_xflags_t xflags, struct buf *root)
1404 {
1405         struct buf dummy;
1406         struct buf *lefttreemax, *righttreemin, *y;
1407
1408         if (root == NULL)
1409                 return (NULL);
1410         lefttreemax = righttreemin = &dummy;
1411         for (;;) {
1412                 if (lblkno < root->b_lblkno ||
1413                     (lblkno == root->b_lblkno &&
1414                     (xflags & BX_BKGRDMARKER) < (root->b_xflags & BX_BKGRDMARKER))) {
1415                         if ((y = root->b_left) == NULL)
1416                                 break;
1417                         if (lblkno < y->b_lblkno) {
1418                                 /* Rotate right. */
1419                                 root->b_left = y->b_right;
1420                                 y->b_right = root;
1421                                 root = y;
1422                                 if ((y = root->b_left) == NULL)
1423                                         break;
1424                         }
1425                         /* Link into the new root's right tree. */
1426                         righttreemin->b_left = root;
1427                         righttreemin = root;
1428                 } else if (lblkno > root->b_lblkno ||
1429                     (lblkno == root->b_lblkno &&
1430                     (xflags & BX_BKGRDMARKER) > (root->b_xflags & BX_BKGRDMARKER))) {
1431                         if ((y = root->b_right) == NULL)
1432                                 break;
1433                         if (lblkno > y->b_lblkno) {
1434                                 /* Rotate left. */
1435                                 root->b_right = y->b_left;
1436                                 y->b_left = root;
1437                                 root = y;
1438                                 if ((y = root->b_right) == NULL)
1439                                         break;
1440                         }
1441                         /* Link into the new root's left tree. */
1442                         lefttreemax->b_right = root;
1443                         lefttreemax = root;
1444                 } else {
1445                         break;
1446                 }
1447                 root = y;
1448         }
1449         /* Assemble the new root. */
1450         lefttreemax->b_right = root->b_left;
1451         righttreemin->b_left = root->b_right;
1452         root->b_left = dummy.b_right;
1453         root->b_right = dummy.b_left;
1454         return (root);
1455 }
1456
1457 static void
1458 buf_vlist_remove(struct buf *bp)
1459 {
1460         struct buf *root;
1461         struct bufv *bv;
1462
1463         KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1464         ASSERT_BO_LOCKED(bp->b_bufobj);
1465         KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) !=
1466             (BX_VNDIRTY|BX_VNCLEAN),
1467             ("buf_vlist_remove: Buf %p is on two lists", bp));
1468         if (bp->b_xflags & BX_VNDIRTY)
1469                 bv = &bp->b_bufobj->bo_dirty;
1470         else
1471                 bv = &bp->b_bufobj->bo_clean;
1472         if (bp != bv->bv_root) {
1473                 root = buf_splay(bp->b_lblkno, bp->b_xflags, bv->bv_root);
1474                 KASSERT(root == bp, ("splay lookup failed in remove"));
1475         }
1476         if (bp->b_left == NULL) {
1477                 root = bp->b_right;
1478         } else {
1479                 root = buf_splay(bp->b_lblkno, bp->b_xflags, bp->b_left);
1480                 root->b_right = bp->b_right;
1481         }
1482         bv->bv_root = root;
1483         TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
1484         bv->bv_cnt--;
1485         bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
1486 }
1487
1488 /*
1489  * Add the buffer to the sorted clean or dirty block list using a
1490  * splay tree algorithm.
1491  *
1492  * NOTE: xflags is passed as a constant, optimizing this inline function!
1493  */
1494 static void
1495 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
1496 {
1497         struct buf *root;
1498         struct bufv *bv;
1499
1500         ASSERT_BO_LOCKED(bo);
1501         KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
1502             ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
1503         bp->b_xflags |= xflags;
1504         if (xflags & BX_VNDIRTY)
1505                 bv = &bo->bo_dirty;
1506         else
1507                 bv = &bo->bo_clean;
1508
1509         root = buf_splay(bp->b_lblkno, bp->b_xflags, bv->bv_root);
1510         if (root == NULL) {
1511                 bp->b_left = NULL;
1512                 bp->b_right = NULL;
1513                 TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
1514         } else if (bp->b_lblkno < root->b_lblkno ||
1515             (bp->b_lblkno == root->b_lblkno &&
1516             (bp->b_xflags & BX_BKGRDMARKER) < (root->b_xflags & BX_BKGRDMARKER))) {
1517                 bp->b_left = root->b_left;
1518                 bp->b_right = root;
1519                 root->b_left = NULL;
1520                 TAILQ_INSERT_BEFORE(root, bp, b_bobufs);
1521         } else {
1522                 bp->b_right = root->b_right;
1523                 bp->b_left = root;
1524                 root->b_right = NULL;
1525                 TAILQ_INSERT_AFTER(&bv->bv_hd, root, bp, b_bobufs);
1526         }
1527         bv->bv_cnt++;
1528         bv->bv_root = bp;
1529 }
1530
1531 /*
1532  * Lookup a buffer using the splay tree.  Note that we specifically avoid
1533  * shadow buffers used in background bitmap writes.
1534  *
1535  * This code isn't quite efficient as it could be because we are maintaining
1536  * two sorted lists and do not know which list the block resides in.
1537  *
1538  * During a "make buildworld" the desired buffer is found at one of
1539  * the roots more than 60% of the time.  Thus, checking both roots
1540  * before performing either splay eliminates unnecessary splays on the
1541  * first tree splayed.
1542  */
1543 struct buf *
1544 gbincore(struct bufobj *bo, daddr_t lblkno)
1545 {
1546         struct buf *bp;
1547
1548         ASSERT_BO_LOCKED(bo);
1549         if ((bp = bo->bo_clean.bv_root) != NULL &&
1550             bp->b_lblkno == lblkno && !(bp->b_xflags & BX_BKGRDMARKER))
1551                 return (bp);
1552         if ((bp = bo->bo_dirty.bv_root) != NULL &&
1553             bp->b_lblkno == lblkno && !(bp->b_xflags & BX_BKGRDMARKER))
1554                 return (bp);
1555         if ((bp = bo->bo_clean.bv_root) != NULL) {
1556                 bo->bo_clean.bv_root = bp = buf_splay(lblkno, 0, bp);
1557                 if (bp->b_lblkno == lblkno && !(bp->b_xflags & BX_BKGRDMARKER))
1558                         return (bp);
1559         }
1560         if ((bp = bo->bo_dirty.bv_root) != NULL) {
1561                 bo->bo_dirty.bv_root = bp = buf_splay(lblkno, 0, bp);
1562                 if (bp->b_lblkno == lblkno && !(bp->b_xflags & BX_BKGRDMARKER))
1563                         return (bp);
1564         }
1565         return (NULL);
1566 }
1567
1568 /*
1569  * Associate a buffer with a vnode.
1570  */
1571 void
1572 bgetvp(struct vnode *vp, struct buf *bp)
1573 {
1574         struct bufobj *bo;
1575
1576         bo = &vp->v_bufobj;
1577         ASSERT_BO_LOCKED(bo);
1578         VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
1579
1580         CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
1581         VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
1582             ("bgetvp: bp already attached! %p", bp));
1583
1584         vhold(vp);
1585         if (VFS_NEEDSGIANT(vp->v_mount) || bo->bo_flag & BO_NEEDSGIANT)
1586                 bp->b_flags |= B_NEEDSGIANT;
1587         bp->b_vp = vp;
1588         bp->b_bufobj = bo;
1589         /*
1590          * Insert onto list for new vnode.
1591          */
1592         buf_vlist_add(bp, bo, BX_VNCLEAN);
1593 }
1594
1595 /*
1596  * Disassociate a buffer from a vnode.
1597  */
1598 void
1599 brelvp(struct buf *bp)
1600 {
1601         struct bufobj *bo;
1602         struct vnode *vp;
1603
1604         CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1605         KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
1606
1607         /*
1608          * Delete from old vnode list, if on one.
1609          */
1610         vp = bp->b_vp;          /* XXX */
1611         bo = bp->b_bufobj;
1612         BO_LOCK(bo);
1613         if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
1614                 buf_vlist_remove(bp);
1615         else
1616                 panic("brelvp: Buffer %p not on queue.", bp);
1617         if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
1618                 bo->bo_flag &= ~BO_ONWORKLST;
1619                 mtx_lock(&sync_mtx);
1620                 LIST_REMOVE(bo, bo_synclist);
1621                 syncer_worklist_len--;
1622                 mtx_unlock(&sync_mtx);
1623         }
1624         bp->b_flags &= ~B_NEEDSGIANT;
1625         bp->b_vp = NULL;
1626         bp->b_bufobj = NULL;
1627         BO_UNLOCK(bo);
1628         vdrop(vp);
1629 }
1630
1631 /*
1632  * Add an item to the syncer work queue.
1633  */
1634 static void
1635 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
1636 {
1637         int queue, slot;
1638
1639         ASSERT_BO_LOCKED(bo);
1640
1641         mtx_lock(&sync_mtx);
1642         if (bo->bo_flag & BO_ONWORKLST)
1643                 LIST_REMOVE(bo, bo_synclist);
1644         else {
1645                 bo->bo_flag |= BO_ONWORKLST;
1646                 syncer_worklist_len++;
1647         }
1648
1649         if (delay > syncer_maxdelay - 2)
1650                 delay = syncer_maxdelay - 2;
1651         slot = (syncer_delayno + delay) & syncer_mask;
1652
1653         queue = VFS_NEEDSGIANT(bo->__bo_vnode->v_mount) ? WI_GIANTQ :
1654             WI_MPSAFEQ;
1655         LIST_INSERT_HEAD(&syncer_workitem_pending[queue][slot], bo,
1656             bo_synclist);
1657         mtx_unlock(&sync_mtx);
1658 }
1659
1660 static int
1661 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
1662 {
1663         int error, len;
1664
1665         mtx_lock(&sync_mtx);
1666         len = syncer_worklist_len - sync_vnode_count;
1667         mtx_unlock(&sync_mtx);
1668         error = SYSCTL_OUT(req, &len, sizeof(len));
1669         return (error);
1670 }
1671
1672 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len, CTLTYPE_INT | CTLFLAG_RD, NULL, 0,
1673     sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
1674
1675 static struct proc *updateproc;
1676 static void sched_sync(void);
1677 static struct kproc_desc up_kp = {
1678         "syncer",
1679         sched_sync,
1680         &updateproc
1681 };
1682 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
1683
1684 static int
1685 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
1686 {
1687         struct vnode *vp;
1688         struct mount *mp;
1689
1690         *bo = LIST_FIRST(slp);
1691         if (*bo == NULL)
1692                 return (0);
1693         vp = (*bo)->__bo_vnode; /* XXX */
1694         if (VOP_ISLOCKED(vp) != 0 || VI_TRYLOCK(vp) == 0)
1695                 return (1);
1696         /*
1697          * We use vhold in case the vnode does not
1698          * successfully sync.  vhold prevents the vnode from
1699          * going away when we unlock the sync_mtx so that
1700          * we can acquire the vnode interlock.
1701          */
1702         vholdl(vp);
1703         mtx_unlock(&sync_mtx);
1704         VI_UNLOCK(vp);
1705         if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
1706                 vdrop(vp);
1707                 mtx_lock(&sync_mtx);
1708                 return (*bo == LIST_FIRST(slp));
1709         }
1710         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1711         (void) VOP_FSYNC(vp, MNT_LAZY, td);
1712         VOP_UNLOCK(vp, 0);
1713         vn_finished_write(mp);
1714         BO_LOCK(*bo);
1715         if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
1716                 /*
1717                  * Put us back on the worklist.  The worklist
1718                  * routine will remove us from our current
1719                  * position and then add us back in at a later
1720                  * position.
1721                  */
1722                 vn_syncer_add_to_worklist(*bo, syncdelay);
1723         }
1724         BO_UNLOCK(*bo);
1725         vdrop(vp);
1726         mtx_lock(&sync_mtx);
1727         return (0);
1728 }
1729
1730 /*
1731  * System filesystem synchronizer daemon.
1732  */
1733 static void
1734 sched_sync(void)
1735 {
1736         struct synclist *gnext, *next;
1737         struct synclist *gslp, *slp;
1738         struct bufobj *bo;
1739         long starttime;
1740         struct thread *td = curthread;
1741         int last_work_seen;
1742         int net_worklist_len;
1743         int syncer_final_iter;
1744         int first_printf;
1745         int error;
1746
1747         last_work_seen = 0;
1748         syncer_final_iter = 0;
1749         first_printf = 1;
1750         syncer_state = SYNCER_RUNNING;
1751         starttime = time_uptime;
1752         td->td_pflags |= TDP_NORUNNINGBUF;
1753
1754         EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
1755             SHUTDOWN_PRI_LAST);
1756
1757         mtx_lock(&sync_mtx);
1758         for (;;) {
1759                 if (syncer_state == SYNCER_FINAL_DELAY &&
1760                     syncer_final_iter == 0) {
1761                         mtx_unlock(&sync_mtx);
1762                         kproc_suspend_check(td->td_proc);
1763                         mtx_lock(&sync_mtx);
1764                 }
1765                 net_worklist_len = syncer_worklist_len - sync_vnode_count;
1766                 if (syncer_state != SYNCER_RUNNING &&
1767                     starttime != time_uptime) {
1768                         if (first_printf) {
1769                                 printf("\nSyncing disks, vnodes remaining...");
1770                                 first_printf = 0;
1771                         }
1772                         printf("%d ", net_worklist_len);
1773                 }
1774                 starttime = time_uptime;
1775
1776                 /*
1777                  * Push files whose dirty time has expired.  Be careful
1778                  * of interrupt race on slp queue.
1779                  *
1780                  * Skip over empty worklist slots when shutting down.
1781                  */
1782                 do {
1783                         slp = &syncer_workitem_pending[WI_MPSAFEQ][syncer_delayno];
1784                         gslp = &syncer_workitem_pending[WI_GIANTQ][syncer_delayno];
1785                         syncer_delayno += 1;
1786                         if (syncer_delayno == syncer_maxdelay)
1787                                 syncer_delayno = 0;
1788                         next = &syncer_workitem_pending[WI_MPSAFEQ][syncer_delayno];
1789                         gnext = &syncer_workitem_pending[WI_GIANTQ][syncer_delayno];
1790                         /*
1791                          * If the worklist has wrapped since the
1792                          * it was emptied of all but syncer vnodes,
1793                          * switch to the FINAL_DELAY state and run
1794                          * for one more second.
1795                          */
1796                         if (syncer_state == SYNCER_SHUTTING_DOWN &&
1797                             net_worklist_len == 0 &&
1798                             last_work_seen == syncer_delayno) {
1799                                 syncer_state = SYNCER_FINAL_DELAY;
1800                                 syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
1801                         }
1802                 } while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
1803                     LIST_EMPTY(gslp) && syncer_worklist_len > 0);
1804
1805                 /*
1806                  * Keep track of the last time there was anything
1807                  * on the worklist other than syncer vnodes.
1808                  * Return to the SHUTTING_DOWN state if any
1809                  * new work appears.
1810                  */
1811                 if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
1812                         last_work_seen = syncer_delayno;
1813                 if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
1814                         syncer_state = SYNCER_SHUTTING_DOWN;
1815                 while (!LIST_EMPTY(slp)) {
1816                         error = sync_vnode(slp, &bo, td);
1817                         if (error == 1) {
1818                                 LIST_REMOVE(bo, bo_synclist);
1819                                 LIST_INSERT_HEAD(next, bo, bo_synclist);
1820                                 continue;
1821                         }
1822                 }
1823                 if (!LIST_EMPTY(gslp)) {
1824                         mtx_unlock(&sync_mtx);
1825                         mtx_lock(&Giant);
1826                         mtx_lock(&sync_mtx);
1827                         while (!LIST_EMPTY(gslp)) {
1828                                 error = sync_vnode(gslp, &bo, td);
1829                                 if (error == 1) {
1830                                         LIST_REMOVE(bo, bo_synclist);
1831                                         LIST_INSERT_HEAD(gnext, bo,
1832                                             bo_synclist);
1833                                         continue;
1834                                 }
1835                         }
1836                         mtx_unlock(&Giant);
1837                 }
1838                 if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
1839                         syncer_final_iter--;
1840                 /*
1841                  * The variable rushjob allows the kernel to speed up the
1842                  * processing of the filesystem syncer process. A rushjob
1843                  * value of N tells the filesystem syncer to process the next
1844                  * N seconds worth of work on its queue ASAP. Currently rushjob
1845                  * is used by the soft update code to speed up the filesystem
1846                  * syncer process when the incore state is getting so far
1847                  * ahead of the disk that the kernel memory pool is being
1848                  * threatened with exhaustion.
1849                  */
1850                 if (rushjob > 0) {
1851                         rushjob -= 1;
1852                         continue;
1853                 }
1854                 /*
1855                  * Just sleep for a short period of time between
1856                  * iterations when shutting down to allow some I/O
1857                  * to happen.
1858                  *
1859                  * If it has taken us less than a second to process the
1860                  * current work, then wait. Otherwise start right over
1861                  * again. We can still lose time if any single round
1862                  * takes more than two seconds, but it does not really
1863                  * matter as we are just trying to generally pace the
1864                  * filesystem activity.
1865                  */
1866                 if (syncer_state != SYNCER_RUNNING)
1867                         cv_timedwait(&sync_wakeup, &sync_mtx,
1868                             hz / SYNCER_SHUTDOWN_SPEEDUP);
1869                 else if (time_uptime == starttime)
1870                         cv_timedwait(&sync_wakeup, &sync_mtx, hz);
1871         }
1872 }
1873
1874 /*
1875  * Request the syncer daemon to speed up its work.
1876  * We never push it to speed up more than half of its
1877  * normal turn time, otherwise it could take over the cpu.
1878  */
1879 int
1880 speedup_syncer(void)
1881 {
1882         int ret = 0;
1883
1884         mtx_lock(&sync_mtx);
1885         if (rushjob < syncdelay / 2) {
1886                 rushjob += 1;
1887                 stat_rush_requests += 1;
1888                 ret = 1;
1889         }
1890         mtx_unlock(&sync_mtx);
1891         cv_broadcast(&sync_wakeup);
1892         return (ret);
1893 }
1894
1895 /*
1896  * Tell the syncer to speed up its work and run though its work
1897  * list several times, then tell it to shut down.
1898  */
1899 static void
1900 syncer_shutdown(void *arg, int howto)
1901 {
1902
1903         if (howto & RB_NOSYNC)
1904                 return;
1905         mtx_lock(&sync_mtx);
1906         syncer_state = SYNCER_SHUTTING_DOWN;
1907         rushjob = 0;
1908         mtx_unlock(&sync_mtx);
1909         cv_broadcast(&sync_wakeup);
1910         kproc_shutdown(arg, howto);
1911 }
1912
1913 /*
1914  * Reassign a buffer from one vnode to another.
1915  * Used to assign file specific control information
1916  * (indirect blocks) to the vnode to which they belong.
1917  */
1918 void
1919 reassignbuf(struct buf *bp)
1920 {
1921         struct vnode *vp;
1922         struct bufobj *bo;
1923         int delay;
1924 #ifdef INVARIANTS
1925         struct bufv *bv;
1926 #endif
1927
1928         vp = bp->b_vp;
1929         bo = bp->b_bufobj;
1930         ++reassignbufcalls;
1931
1932         CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
1933             bp, bp->b_vp, bp->b_flags);
1934         /*
1935          * B_PAGING flagged buffers cannot be reassigned because their vp
1936          * is not fully linked in.
1937          */
1938         if (bp->b_flags & B_PAGING)
1939                 panic("cannot reassign paging buffer");
1940
1941         /*
1942          * Delete from old vnode list, if on one.
1943          */
1944         BO_LOCK(bo);
1945         if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
1946                 buf_vlist_remove(bp);
1947         else
1948                 panic("reassignbuf: Buffer %p not on queue.", bp);
1949         /*
1950          * If dirty, put on list of dirty buffers; otherwise insert onto list
1951          * of clean buffers.
1952          */
1953         if (bp->b_flags & B_DELWRI) {
1954                 if ((bo->bo_flag & BO_ONWORKLST) == 0) {
1955                         switch (vp->v_type) {
1956                         case VDIR:
1957                                 delay = dirdelay;
1958                                 break;
1959                         case VCHR:
1960                                 delay = metadelay;
1961                                 break;
1962                         default:
1963                                 delay = filedelay;
1964                         }
1965                         vn_syncer_add_to_worklist(bo, delay);
1966                 }
1967                 buf_vlist_add(bp, bo, BX_VNDIRTY);
1968         } else {
1969                 buf_vlist_add(bp, bo, BX_VNCLEAN);
1970
1971                 if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
1972                         mtx_lock(&sync_mtx);
1973                         LIST_REMOVE(bo, bo_synclist);
1974                         syncer_worklist_len--;
1975                         mtx_unlock(&sync_mtx);
1976                         bo->bo_flag &= ~BO_ONWORKLST;
1977                 }
1978         }
1979 #ifdef INVARIANTS
1980         bv = &bo->bo_clean;
1981         bp = TAILQ_FIRST(&bv->bv_hd);
1982         KASSERT(bp == NULL || bp->b_bufobj == bo,
1983             ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
1984         bp = TAILQ_LAST(&bv->bv_hd, buflists);
1985         KASSERT(bp == NULL || bp->b_bufobj == bo,
1986             ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
1987         bv = &bo->bo_dirty;
1988         bp = TAILQ_FIRST(&bv->bv_hd);
1989         KASSERT(bp == NULL || bp->b_bufobj == bo,
1990             ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
1991         bp = TAILQ_LAST(&bv->bv_hd, buflists);
1992         KASSERT(bp == NULL || bp->b_bufobj == bo,
1993             ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
1994 #endif
1995         BO_UNLOCK(bo);
1996 }
1997
1998 /*
1999  * Increment the use and hold counts on the vnode, taking care to reference
2000  * the driver's usecount if this is a chardev.  The vholdl() will remove
2001  * the vnode from the free list if it is presently free.  Requires the
2002  * vnode interlock and returns with it held.
2003  */
2004 static void
2005 v_incr_usecount(struct vnode *vp)
2006 {
2007
2008         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2009         vp->v_usecount++;
2010         if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2011                 dev_lock();
2012                 vp->v_rdev->si_usecount++;
2013                 dev_unlock();
2014         }
2015         vholdl(vp);
2016 }
2017
2018 /*
2019  * Turn a holdcnt into a use+holdcnt such that only one call to
2020  * v_decr_usecount is needed.
2021  */
2022 static void
2023 v_upgrade_usecount(struct vnode *vp)
2024 {
2025
2026         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2027         vp->v_usecount++;
2028         if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2029                 dev_lock();
2030                 vp->v_rdev->si_usecount++;
2031                 dev_unlock();
2032         }
2033 }
2034
2035 /*
2036  * Decrement the vnode use and hold count along with the driver's usecount
2037  * if this is a chardev.  The vdropl() below releases the vnode interlock
2038  * as it may free the vnode.
2039  */
2040 static void
2041 v_decr_usecount(struct vnode *vp)
2042 {
2043
2044         ASSERT_VI_LOCKED(vp, __FUNCTION__);
2045         VNASSERT(vp->v_usecount > 0, vp,
2046             ("v_decr_usecount: negative usecount"));
2047         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2048         vp->v_usecount--;
2049         if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2050                 dev_lock();
2051                 vp->v_rdev->si_usecount--;
2052                 dev_unlock();
2053         }
2054         vdropl(vp);
2055 }
2056
2057 /*
2058  * Decrement only the use count and driver use count.  This is intended to
2059  * be paired with a follow on vdropl() to release the remaining hold count.
2060  * In this way we may vgone() a vnode with a 0 usecount without risk of
2061  * having it end up on a free list because the hold count is kept above 0.
2062  */
2063 static void
2064 v_decr_useonly(struct vnode *vp)
2065 {
2066
2067         ASSERT_VI_LOCKED(vp, __FUNCTION__);
2068         VNASSERT(vp->v_usecount > 0, vp,
2069             ("v_decr_useonly: negative usecount"));
2070         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2071         vp->v_usecount--;
2072         if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2073                 dev_lock();
2074                 vp->v_rdev->si_usecount--;
2075                 dev_unlock();
2076         }
2077 }
2078
2079 /*
2080  * Grab a particular vnode from the free list, increment its
2081  * reference count and lock it.  VI_DOOMED is set if the vnode
2082  * is being destroyed.  Only callers who specify LK_RETRY will
2083  * see doomed vnodes.  If inactive processing was delayed in
2084  * vput try to do it here.
2085  */
2086 int
2087 vget(struct vnode *vp, int flags, struct thread *td)
2088 {
2089         int error;
2090
2091         error = 0;
2092         VFS_ASSERT_GIANT(vp->v_mount);
2093         VNASSERT((flags & LK_TYPE_MASK) != 0, vp,
2094             ("vget: invalid lock operation"));
2095         CTR3(KTR_VFS, "%s: vp %p with flags %d", __func__, vp, flags);
2096
2097         if ((flags & LK_INTERLOCK) == 0)
2098                 VI_LOCK(vp);
2099         vholdl(vp);
2100         if ((error = vn_lock(vp, flags | LK_INTERLOCK)) != 0) {
2101                 vdrop(vp);
2102                 CTR2(KTR_VFS, "%s: impossible to lock vnode %p", __func__,
2103                     vp);
2104                 return (error);
2105         }
2106         if (vp->v_iflag & VI_DOOMED && (flags & LK_RETRY) == 0)
2107                 panic("vget: vn_lock failed to return ENOENT\n");
2108         VI_LOCK(vp);
2109         /* Upgrade our holdcnt to a usecount. */
2110         v_upgrade_usecount(vp);
2111         /*
2112          * We don't guarantee that any particular close will
2113          * trigger inactive processing so just make a best effort
2114          * here at preventing a reference to a removed file.  If
2115          * we don't succeed no harm is done.
2116          */
2117         if (vp->v_iflag & VI_OWEINACT) {
2118                 if (VOP_ISLOCKED(vp) == LK_EXCLUSIVE && 
2119                     (flags & LK_NOWAIT) == 0)
2120                         vinactive(vp, td);
2121                 vp->v_iflag &= ~VI_OWEINACT;
2122         }
2123         VI_UNLOCK(vp);
2124         return (0);
2125 }
2126
2127 /*
2128  * Increase the reference count of a vnode.
2129  */
2130 void
2131 vref(struct vnode *vp)
2132 {
2133
2134         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2135         VI_LOCK(vp);
2136         v_incr_usecount(vp);
2137         VI_UNLOCK(vp);
2138 }
2139
2140 /*
2141  * Return reference count of a vnode.
2142  *
2143  * The results of this call are only guaranteed when some mechanism other
2144  * than the VI lock is used to stop other processes from gaining references
2145  * to the vnode.  This may be the case if the caller holds the only reference.
2146  * This is also useful when stale data is acceptable as race conditions may
2147  * be accounted for by some other means.
2148  */
2149 int
2150 vrefcnt(struct vnode *vp)
2151 {
2152         int usecnt;
2153
2154         VI_LOCK(vp);
2155         usecnt = vp->v_usecount;
2156         VI_UNLOCK(vp);
2157
2158         return (usecnt);
2159 }
2160
2161 #define VPUTX_VRELE     1
2162 #define VPUTX_VPUT      2
2163 #define VPUTX_VUNREF    3
2164
2165 static void
2166 vputx(struct vnode *vp, int func)
2167 {
2168         int error;
2169
2170         KASSERT(vp != NULL, ("vputx: null vp"));
2171         if (func == VPUTX_VUNREF)
2172                 ASSERT_VOP_ELOCKED(vp, "vunref");
2173         else if (func == VPUTX_VPUT)
2174                 ASSERT_VOP_LOCKED(vp, "vput");
2175         else
2176                 KASSERT(func == VPUTX_VRELE, ("vputx: wrong func"));
2177         VFS_ASSERT_GIANT(vp->v_mount);
2178         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2179         VI_LOCK(vp);
2180
2181         /* Skip this v_writecount check if we're going to panic below. */
2182         VNASSERT(vp->v_writecount < vp->v_usecount || vp->v_usecount < 1, vp,
2183             ("vputx: missed vn_close"));
2184         error = 0;
2185
2186         if (vp->v_usecount > 1 || ((vp->v_iflag & VI_DOINGINACT) &&
2187             vp->v_usecount == 1)) {
2188                 if (func == VPUTX_VPUT)
2189                         VOP_UNLOCK(vp, 0);
2190                 v_decr_usecount(vp);
2191                 return;
2192         }
2193
2194         if (vp->v_usecount != 1) {
2195 #ifdef DIAGNOSTIC
2196                 vprint("vputx: negative ref count", vp);
2197 #endif
2198                 panic("vputx: negative ref cnt");
2199         }
2200         CTR2(KTR_VFS, "%s: return vnode %p to the freelist", __func__, vp);
2201         /*
2202          * We want to hold the vnode until the inactive finishes to
2203          * prevent vgone() races.  We drop the use count here and the
2204          * hold count below when we're done.
2205          */
2206         v_decr_useonly(vp);
2207         /*
2208          * We must call VOP_INACTIVE with the node locked. Mark
2209          * as VI_DOINGINACT to avoid recursion.
2210          */
2211         vp->v_iflag |= VI_OWEINACT;
2212         if (func == VPUTX_VRELE) {
2213                 error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
2214                 VI_LOCK(vp);
2215         } else if (func == VPUTX_VPUT && VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
2216                 error = VOP_LOCK(vp, LK_UPGRADE | LK_INTERLOCK | LK_NOWAIT);
2217                 VI_LOCK(vp);
2218         }
2219         if (vp->v_usecount > 0)
2220                 vp->v_iflag &= ~VI_OWEINACT;
2221         if (error == 0) {
2222                 if (vp->v_iflag & VI_OWEINACT)
2223                         vinactive(vp, curthread);
2224                 if (func != VPUTX_VUNREF)
2225                         VOP_UNLOCK(vp, 0);
2226         }
2227         vdropl(vp);
2228 }
2229
2230 /*
2231  * Vnode put/release.
2232  * If count drops to zero, call inactive routine and return to freelist.
2233  */
2234 void
2235 vrele(struct vnode *vp)
2236 {
2237
2238         vputx(vp, VPUTX_VRELE);
2239 }
2240
2241 /*
2242  * Release an already locked vnode.  This give the same effects as
2243  * unlock+vrele(), but takes less time and avoids releasing and
2244  * re-aquiring the lock (as vrele() acquires the lock internally.)
2245  */
2246 void
2247 vput(struct vnode *vp)
2248 {
2249
2250         vputx(vp, VPUTX_VPUT);
2251 }
2252
2253 /*
2254  * Release an exclusively locked vnode. Do not unlock the vnode lock.
2255  */
2256 void
2257 vunref(struct vnode *vp)
2258 {
2259
2260         vputx(vp, VPUTX_VUNREF);
2261 }
2262
2263 /*
2264  * Somebody doesn't want the vnode recycled.
2265  */
2266 void
2267 vhold(struct vnode *vp)
2268 {
2269
2270         VI_LOCK(vp);
2271         vholdl(vp);
2272         VI_UNLOCK(vp);
2273 }
2274
2275 void
2276 vholdl(struct vnode *vp)
2277 {
2278
2279         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2280         vp->v_holdcnt++;
2281         if (VSHOULDBUSY(vp))
2282                 vbusy(vp);
2283 }
2284
2285 /*
2286  * Note that there is one less who cares about this vnode.  vdrop() is the
2287  * opposite of vhold().
2288  */
2289 void
2290 vdrop(struct vnode *vp)
2291 {
2292
2293         VI_LOCK(vp);
2294         vdropl(vp);
2295 }
2296
2297 /*
2298  * Drop the hold count of the vnode.  If this is the last reference to
2299  * the vnode we will free it if it has been vgone'd otherwise it is
2300  * placed on the free list.
2301  */
2302 void
2303 vdropl(struct vnode *vp)
2304 {
2305
2306         ASSERT_VI_LOCKED(vp, "vdropl");
2307         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2308         if (vp->v_holdcnt <= 0)
2309                 panic("vdrop: holdcnt %d", vp->v_holdcnt);
2310         vp->v_holdcnt--;
2311         if (vp->v_holdcnt == 0) {
2312                 if (vp->v_iflag & VI_DOOMED) {
2313                         CTR2(KTR_VFS, "%s: destroying the vnode %p", __func__,
2314                             vp);
2315                         vdestroy(vp);
2316                         return;
2317                 } else
2318                         vfree(vp);
2319         }
2320         VI_UNLOCK(vp);
2321 }
2322
2323 /*
2324  * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
2325  * flags.  DOINGINACT prevents us from recursing in calls to vinactive.
2326  * OWEINACT tracks whether a vnode missed a call to inactive due to a
2327  * failed lock upgrade.
2328  */
2329 static void
2330 vinactive(struct vnode *vp, struct thread *td)
2331 {
2332
2333         ASSERT_VOP_ELOCKED(vp, "vinactive");
2334         ASSERT_VI_LOCKED(vp, "vinactive");
2335         VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
2336             ("vinactive: recursed on VI_DOINGINACT"));
2337         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2338         vp->v_iflag |= VI_DOINGINACT;
2339         vp->v_iflag &= ~VI_OWEINACT;
2340         VI_UNLOCK(vp);
2341         VOP_INACTIVE(vp, td);
2342         VI_LOCK(vp);
2343         VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
2344             ("vinactive: lost VI_DOINGINACT"));
2345         vp->v_iflag &= ~VI_DOINGINACT;
2346 }
2347
2348 /*
2349  * Remove any vnodes in the vnode table belonging to mount point mp.
2350  *
2351  * If FORCECLOSE is not specified, there should not be any active ones,
2352  * return error if any are found (nb: this is a user error, not a
2353  * system error). If FORCECLOSE is specified, detach any active vnodes
2354  * that are found.
2355  *
2356  * If WRITECLOSE is set, only flush out regular file vnodes open for
2357  * writing.
2358  *
2359  * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
2360  *
2361  * `rootrefs' specifies the base reference count for the root vnode
2362  * of this filesystem. The root vnode is considered busy if its
2363  * v_usecount exceeds this value. On a successful return, vflush(, td)
2364  * will call vrele() on the root vnode exactly rootrefs times.
2365  * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
2366  * be zero.
2367  */
2368 #ifdef DIAGNOSTIC
2369 static int busyprt = 0;         /* print out busy vnodes */
2370 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "");
2371 #endif
2372
2373 int
2374 vflush( struct mount *mp, int rootrefs, int flags, struct thread *td)
2375 {
2376         struct vnode *vp, *mvp, *rootvp = NULL;
2377         struct vattr vattr;
2378         int busy = 0, error;
2379
2380         CTR4(KTR_VFS, "%s: mp %p with rootrefs %d and flags %d", __func__, mp,
2381             rootrefs, flags);
2382         if (rootrefs > 0) {
2383                 KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
2384                     ("vflush: bad args"));
2385                 /*
2386                  * Get the filesystem root vnode. We can vput() it
2387                  * immediately, since with rootrefs > 0, it won't go away.
2388                  */
2389                 if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp)) != 0) {
2390                         CTR2(KTR_VFS, "%s: vfs_root lookup failed with %d",
2391                             __func__, error);
2392                         return (error);
2393                 }
2394                 vput(rootvp);
2395
2396         }
2397         MNT_ILOCK(mp);
2398 loop:
2399         MNT_VNODE_FOREACH(vp, mp, mvp) {
2400
2401                 VI_LOCK(vp);
2402                 vholdl(vp);
2403                 MNT_IUNLOCK(mp);
2404                 error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
2405                 if (error) {
2406                         vdrop(vp);
2407                         MNT_ILOCK(mp);
2408                         MNT_VNODE_FOREACH_ABORT_ILOCKED(mp, mvp);
2409                         goto loop;
2410                 }
2411                 /*
2412                  * Skip over a vnodes marked VV_SYSTEM.
2413                  */
2414                 if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
2415                         VOP_UNLOCK(vp, 0);
2416                         vdrop(vp);
2417                         MNT_ILOCK(mp);
2418                         continue;
2419                 }
2420                 /*
2421                  * If WRITECLOSE is set, flush out unlinked but still open
2422                  * files (even if open only for reading) and regular file
2423                  * vnodes open for writing.
2424                  */
2425                 if (flags & WRITECLOSE) {
2426                         error = VOP_GETATTR(vp, &vattr, td->td_ucred);
2427                         VI_LOCK(vp);
2428
2429                         if ((vp->v_type == VNON ||
2430                             (error == 0 && vattr.va_nlink > 0)) &&
2431                             (vp->v_writecount == 0 || vp->v_type != VREG)) {
2432                                 VOP_UNLOCK(vp, 0);
2433                                 vdropl(vp);
2434                                 MNT_ILOCK(mp);
2435                                 continue;
2436                         }
2437                 } else
2438                         VI_LOCK(vp);
2439                 /*
2440                  * With v_usecount == 0, all we need to do is clear out the
2441                  * vnode data structures and we are done.
2442                  *
2443                  * If FORCECLOSE is set, forcibly close the vnode.
2444                  */
2445                 if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
2446                         VNASSERT(vp->v_usecount == 0 ||
2447                             (vp->v_type != VCHR && vp->v_type != VBLK), vp,
2448                             ("device VNODE %p is FORCECLOSED", vp));
2449                         vgonel(vp);
2450                 } else {
2451                         busy++;
2452 #ifdef DIAGNOSTIC
2453                         if (busyprt)
2454                                 vprint("vflush: busy vnode", vp);
2455 #endif
2456                 }
2457                 VOP_UNLOCK(vp, 0);
2458                 vdropl(vp);
2459                 MNT_ILOCK(mp);
2460         }
2461         MNT_IUNLOCK(mp);
2462         if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
2463                 /*
2464                  * If just the root vnode is busy, and if its refcount
2465                  * is equal to `rootrefs', then go ahead and kill it.
2466                  */
2467                 VI_LOCK(rootvp);
2468                 KASSERT(busy > 0, ("vflush: not busy"));
2469                 VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
2470                     ("vflush: usecount %d < rootrefs %d",
2471                      rootvp->v_usecount, rootrefs));
2472                 if (busy == 1 && rootvp->v_usecount == rootrefs) {
2473                         VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
2474                         vgone(rootvp);
2475                         VOP_UNLOCK(rootvp, 0);
2476                         busy = 0;
2477                 } else
2478                         VI_UNLOCK(rootvp);
2479         }
2480         if (busy) {
2481                 CTR2(KTR_VFS, "%s: failing as %d vnodes are busy", __func__,
2482                     busy);
2483                 return (EBUSY);
2484         }
2485         for (; rootrefs > 0; rootrefs--)
2486                 vrele(rootvp);
2487         return (0);
2488 }
2489
2490 /*
2491  * Recycle an unused vnode to the front of the free list.
2492  */
2493 int
2494 vrecycle(struct vnode *vp, struct thread *td)
2495 {
2496         int recycled;
2497
2498         ASSERT_VOP_ELOCKED(vp, "vrecycle");
2499         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2500         recycled = 0;
2501         VI_LOCK(vp);
2502         if (vp->v_usecount == 0) {
2503                 recycled = 1;
2504                 vgonel(vp);
2505         }
2506         VI_UNLOCK(vp);
2507         return (recycled);
2508 }
2509
2510 /*
2511  * Eliminate all activity associated with a vnode
2512  * in preparation for reuse.
2513  */
2514 void
2515 vgone(struct vnode *vp)
2516 {
2517         VI_LOCK(vp);
2518         vgonel(vp);
2519         VI_UNLOCK(vp);
2520 }
2521
2522 /*
2523  * vgone, with the vp interlock held.
2524  */
2525 void
2526 vgonel(struct vnode *vp)
2527 {
2528         struct thread *td;
2529         int oweinact;
2530         int active;
2531         struct mount *mp;
2532
2533         ASSERT_VOP_ELOCKED(vp, "vgonel");
2534         ASSERT_VI_LOCKED(vp, "vgonel");
2535         VNASSERT(vp->v_holdcnt, vp,
2536             ("vgonel: vp %p has no reference.", vp));
2537         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
2538         td = curthread;
2539
2540         /*
2541          * Don't vgonel if we're already doomed.
2542          */
2543         if (vp->v_iflag & VI_DOOMED)
2544                 return;
2545         vp->v_iflag |= VI_DOOMED;
2546         /*
2547          * Check to see if the vnode is in use.  If so, we have to call
2548          * VOP_CLOSE() and VOP_INACTIVE().
2549          */
2550         active = vp->v_usecount;
2551         oweinact = (vp->v_iflag & VI_OWEINACT);
2552         VI_UNLOCK(vp);
2553         /*
2554          * Clean out any buffers associated with the vnode.
2555          * If the flush fails, just toss the buffers.
2556          */
2557         mp = NULL;
2558         if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
2559                 (void) vn_start_secondary_write(vp, &mp, V_WAIT);
2560         if (vinvalbuf(vp, V_SAVE, 0, 0) != 0)
2561                 vinvalbuf(vp, 0, 0, 0);
2562
2563         /*
2564          * If purging an active vnode, it must be closed and
2565          * deactivated before being reclaimed.
2566          */
2567         if (active)
2568                 VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
2569         if (oweinact || active) {
2570                 VI_LOCK(vp);
2571                 if ((vp->v_iflag & VI_DOINGINACT) == 0)
2572                         vinactive(vp, td);
2573                 VI_UNLOCK(vp);
2574         }
2575         /*
2576          * Reclaim the vnode.
2577          */
2578         if (VOP_RECLAIM(vp, td))
2579                 panic("vgone: cannot reclaim");
2580         if (mp != NULL)
2581                 vn_finished_secondary_write(mp);
2582         VNASSERT(vp->v_object == NULL, vp,
2583             ("vop_reclaim left v_object vp=%p, tag=%s", vp, vp->v_tag));
2584         /*
2585          * Clear the advisory locks and wake up waiting threads.
2586          */
2587         lf_purgelocks(vp, &(vp->v_lockf));
2588         /*
2589          * Delete from old mount point vnode list.
2590          */
2591         delmntque(vp);
2592         cache_purge(vp);
2593         /*
2594          * Done with purge, reset to the standard lock and invalidate
2595          * the vnode.
2596          */
2597         VI_LOCK(vp);
2598         vp->v_vnlock = &vp->v_lock;
2599         vp->v_op = &dead_vnodeops;
2600         vp->v_tag = "none";
2601         vp->v_type = VBAD;
2602 }
2603
2604 /*
2605  * Calculate the total number of references to a special device.
2606  */
2607 int
2608 vcount(struct vnode *vp)
2609 {
2610         int count;
2611
2612         dev_lock();
2613         count = vp->v_rdev->si_usecount;
2614         dev_unlock();
2615         return (count);
2616 }
2617
2618 /*
2619  * Same as above, but using the struct cdev *as argument
2620  */
2621 int
2622 count_dev(struct cdev *dev)
2623 {
2624         int count;
2625
2626         dev_lock();
2627         count = dev->si_usecount;
2628         dev_unlock();
2629         return(count);
2630 }
2631
2632 /*
2633  * Print out a description of a vnode.
2634  */
2635 static char *typename[] =
2636 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
2637  "VMARKER"};
2638
2639 void
2640 vn_printf(struct vnode *vp, const char *fmt, ...)
2641 {
2642         va_list ap;
2643         char buf[256], buf2[16];
2644         u_long flags;
2645
2646         va_start(ap, fmt);
2647         vprintf(fmt, ap);
2648         va_end(ap);
2649         printf("%p: ", (void *)vp);
2650         printf("tag %s, type %s\n", vp->v_tag, typename[vp->v_type]);
2651         printf("    usecount %d, writecount %d, refcount %d mountedhere %p\n",
2652             vp->v_usecount, vp->v_writecount, vp->v_holdcnt, vp->v_mountedhere);
2653         buf[0] = '\0';
2654         buf[1] = '\0';
2655         if (vp->v_vflag & VV_ROOT)
2656                 strlcat(buf, "|VV_ROOT", sizeof(buf));
2657         if (vp->v_vflag & VV_ISTTY)
2658                 strlcat(buf, "|VV_ISTTY", sizeof(buf));
2659         if (vp->v_vflag & VV_NOSYNC)
2660                 strlcat(buf, "|VV_NOSYNC", sizeof(buf));
2661         if (vp->v_vflag & VV_CACHEDLABEL)
2662                 strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
2663         if (vp->v_vflag & VV_TEXT)
2664                 strlcat(buf, "|VV_TEXT", sizeof(buf));
2665         if (vp->v_vflag & VV_COPYONWRITE)
2666                 strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
2667         if (vp->v_vflag & VV_SYSTEM)
2668                 strlcat(buf, "|VV_SYSTEM", sizeof(buf));
2669         if (vp->v_vflag & VV_PROCDEP)
2670                 strlcat(buf, "|VV_PROCDEP", sizeof(buf));
2671         if (vp->v_vflag & VV_NOKNOTE)
2672                 strlcat(buf, "|VV_NOKNOTE", sizeof(buf));
2673         if (vp->v_vflag & VV_DELETED)
2674                 strlcat(buf, "|VV_DELETED", sizeof(buf));
2675         if (vp->v_vflag & VV_MD)
2676                 strlcat(buf, "|VV_MD", sizeof(buf));
2677         flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC |
2678             VV_CACHEDLABEL | VV_TEXT | VV_COPYONWRITE | VV_SYSTEM | VV_PROCDEP |
2679             VV_NOKNOTE | VV_DELETED | VV_MD);
2680         if (flags != 0) {
2681                 snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
2682                 strlcat(buf, buf2, sizeof(buf));
2683         }
2684         if (vp->v_iflag & VI_MOUNT)
2685                 strlcat(buf, "|VI_MOUNT", sizeof(buf));
2686         if (vp->v_iflag & VI_AGE)
2687                 strlcat(buf, "|VI_AGE", sizeof(buf));
2688         if (vp->v_iflag & VI_DOOMED)
2689                 strlcat(buf, "|VI_DOOMED", sizeof(buf));
2690         if (vp->v_iflag & VI_FREE)
2691                 strlcat(buf, "|VI_FREE", sizeof(buf));
2692         if (vp->v_iflag & VI_DOINGINACT)
2693                 strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
2694         if (vp->v_iflag & VI_OWEINACT)
2695                 strlcat(buf, "|VI_OWEINACT", sizeof(buf));
2696         flags = vp->v_iflag & ~(VI_MOUNT | VI_AGE | VI_DOOMED | VI_FREE |
2697             VI_DOINGINACT | VI_OWEINACT);
2698         if (flags != 0) {
2699                 snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
2700                 strlcat(buf, buf2, sizeof(buf));
2701         }
2702         printf("    flags (%s)\n", buf + 1);
2703         if (mtx_owned(VI_MTX(vp)))
2704                 printf(" VI_LOCKed");
2705         if (vp->v_object != NULL)
2706                 printf("    v_object %p ref %d pages %d\n",
2707                     vp->v_object, vp->v_object->ref_count,
2708                     vp->v_object->resident_page_count);
2709         printf("    ");
2710         lockmgr_printinfo(vp->v_vnlock);
2711         if (vp->v_data != NULL)
2712                 VOP_PRINT(vp);
2713 }
2714
2715 #ifdef DDB
2716 /*
2717  * List all of the locked vnodes in the system.
2718  * Called when debugging the kernel.
2719  */
2720 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
2721 {
2722         struct mount *mp, *nmp;
2723         struct vnode *vp;
2724
2725         /*
2726          * Note: because this is DDB, we can't obey the locking semantics
2727          * for these structures, which means we could catch an inconsistent
2728          * state and dereference a nasty pointer.  Not much to be done
2729          * about that.
2730          */
2731         db_printf("Locked vnodes\n");
2732         for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
2733                 nmp = TAILQ_NEXT(mp, mnt_list);
2734                 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
2735                         if (vp->v_type != VMARKER &&
2736                             VOP_ISLOCKED(vp))
2737                                 vprint("", vp);
2738                 }
2739                 nmp = TAILQ_NEXT(mp, mnt_list);
2740         }
2741 }
2742
2743 /*
2744  * Show details about the given vnode.
2745  */
2746 DB_SHOW_COMMAND(vnode, db_show_vnode)
2747 {
2748         struct vnode *vp;
2749
2750         if (!have_addr)
2751                 return;
2752         vp = (struct vnode *)addr;
2753         vn_printf(vp, "vnode ");
2754 }
2755
2756 /*
2757  * Show details about the given mount point.
2758  */
2759 DB_SHOW_COMMAND(mount, db_show_mount)
2760 {
2761         struct mount *mp;
2762         struct vfsopt *opt;
2763         struct statfs *sp;
2764         struct vnode *vp;
2765         char buf[512];
2766         u_int flags;
2767
2768         if (!have_addr) {
2769                 /* No address given, print short info about all mount points. */
2770                 TAILQ_FOREACH(mp, &mountlist, mnt_list) {
2771                         db_printf("%p %s on %s (%s)\n", mp,
2772                             mp->mnt_stat.f_mntfromname,
2773                             mp->mnt_stat.f_mntonname,
2774                             mp->mnt_stat.f_fstypename);
2775                         if (db_pager_quit)
2776                                 break;
2777                 }
2778                 db_printf("\nMore info: show mount <addr>\n");
2779                 return;
2780         }
2781
2782         mp = (struct mount *)addr;
2783         db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
2784             mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
2785
2786         buf[0] = '\0';
2787         flags = mp->mnt_flag;
2788 #define MNT_FLAG(flag)  do {                                            \
2789         if (flags & (flag)) {                                           \
2790                 if (buf[0] != '\0')                                     \
2791                         strlcat(buf, ", ", sizeof(buf));                \
2792                 strlcat(buf, (#flag) + 4, sizeof(buf));                 \
2793                 flags &= ~(flag);                                       \
2794         }                                                               \
2795 } while (0)
2796         MNT_FLAG(MNT_RDONLY);
2797         MNT_FLAG(MNT_SYNCHRONOUS);
2798         MNT_FLAG(MNT_NOEXEC);
2799         MNT_FLAG(MNT_NOSUID);
2800         MNT_FLAG(MNT_UNION);
2801         MNT_FLAG(MNT_ASYNC);
2802         MNT_FLAG(MNT_SUIDDIR);
2803         MNT_FLAG(MNT_SOFTDEP);
2804         MNT_FLAG(MNT_NOSYMFOLLOW);
2805         MNT_FLAG(MNT_GJOURNAL);
2806         MNT_FLAG(MNT_MULTILABEL);
2807         MNT_FLAG(MNT_ACLS);
2808         MNT_FLAG(MNT_NOATIME);
2809         MNT_FLAG(MNT_NOCLUSTERR);
2810         MNT_FLAG(MNT_NOCLUSTERW);
2811         MNT_FLAG(MNT_NFS4ACLS);
2812         MNT_FLAG(MNT_EXRDONLY);
2813         MNT_FLAG(MNT_EXPORTED);
2814         MNT_FLAG(MNT_DEFEXPORTED);
2815         MNT_FLAG(MNT_EXPORTANON);
2816         MNT_FLAG(MNT_EXKERB);
2817         MNT_FLAG(MNT_EXPUBLIC);
2818         MNT_FLAG(MNT_LOCAL);
2819         MNT_FLAG(MNT_QUOTA);
2820         MNT_FLAG(MNT_ROOTFS);
2821         MNT_FLAG(MNT_USER);
2822         MNT_FLAG(MNT_IGNORE);
2823         MNT_FLAG(MNT_UPDATE);
2824         MNT_FLAG(MNT_DELEXPORT);
2825         MNT_FLAG(MNT_RELOAD);
2826         MNT_FLAG(MNT_FORCE);
2827         MNT_FLAG(MNT_SNAPSHOT);
2828         MNT_FLAG(MNT_BYFSID);
2829 #undef MNT_FLAG
2830         if (flags != 0) {
2831                 if (buf[0] != '\0')
2832                         strlcat(buf, ", ", sizeof(buf));
2833                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2834                     "0x%08x", flags);
2835         }
2836         db_printf("    mnt_flag = %s\n", buf);
2837
2838         buf[0] = '\0';
2839         flags = mp->mnt_kern_flag;
2840 #define MNT_KERN_FLAG(flag)     do {                                    \
2841         if (flags & (flag)) {                                           \
2842                 if (buf[0] != '\0')                                     \
2843                         strlcat(buf, ", ", sizeof(buf));                \
2844                 strlcat(buf, (#flag) + 5, sizeof(buf));                 \
2845                 flags &= ~(flag);                                       \
2846         }                                                               \
2847 } while (0)
2848         MNT_KERN_FLAG(MNTK_UNMOUNTF);
2849         MNT_KERN_FLAG(MNTK_ASYNC);
2850         MNT_KERN_FLAG(MNTK_SOFTDEP);
2851         MNT_KERN_FLAG(MNTK_NOINSMNTQ);
2852         MNT_KERN_FLAG(MNTK_UNMOUNT);
2853         MNT_KERN_FLAG(MNTK_MWAIT);
2854         MNT_KERN_FLAG(MNTK_SUSPEND);
2855         MNT_KERN_FLAG(MNTK_SUSPEND2);
2856         MNT_KERN_FLAG(MNTK_SUSPENDED);
2857         MNT_KERN_FLAG(MNTK_MPSAFE);
2858         MNT_KERN_FLAG(MNTK_NOKNOTE);
2859         MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
2860 #undef MNT_KERN_FLAG
2861         if (flags != 0) {
2862                 if (buf[0] != '\0')
2863                         strlcat(buf, ", ", sizeof(buf));
2864                 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2865                     "0x%08x", flags);
2866         }
2867         db_printf("    mnt_kern_flag = %s\n", buf);
2868
2869         db_printf("    mnt_opt = ");
2870         opt = TAILQ_FIRST(mp->mnt_opt);
2871         if (opt != NULL) {
2872                 db_printf("%s", opt->name);
2873                 opt = TAILQ_NEXT(opt, link);
2874                 while (opt != NULL) {
2875                         db_printf(", %s", opt->name);
2876                         opt = TAILQ_NEXT(opt, link);
2877                 }
2878         }
2879         db_printf("\n");
2880
2881         sp = &mp->mnt_stat;
2882         db_printf("    mnt_stat = { version=%u type=%u flags=0x%016jx "
2883             "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
2884             "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
2885             "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
2886             (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
2887             (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
2888             (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
2889             (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
2890             (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
2891             (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
2892             (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
2893             (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
2894
2895         db_printf("    mnt_cred = { uid=%u ruid=%u",
2896             (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
2897         if (jailed(mp->mnt_cred))
2898                 db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
2899         db_printf(" }\n");
2900         db_printf("    mnt_ref = %d\n", mp->mnt_ref);
2901         db_printf("    mnt_gen = %d\n", mp->mnt_gen);
2902         db_printf("    mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
2903         db_printf("    mnt_writeopcount = %d\n", mp->mnt_writeopcount);
2904         db_printf("    mnt_noasync = %u\n", mp->mnt_noasync);
2905         db_printf("    mnt_maxsymlinklen = %d\n", mp->mnt_maxsymlinklen);
2906         db_printf("    mnt_iosize_max = %d\n", mp->mnt_iosize_max);
2907         db_printf("    mnt_hashseed = %u\n", mp->mnt_hashseed);
2908         db_printf("    mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
2909         db_printf("    mnt_secondary_accwrites = %d\n",
2910             mp->mnt_secondary_accwrites);
2911         db_printf("    mnt_gjprovider = %s\n",
2912             mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
2913         db_printf("\n");
2914
2915         TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
2916                 if (vp->v_type != VMARKER) {
2917                         vn_printf(vp, "vnode ");
2918                         if (db_pager_quit)
2919                                 break;
2920                 }
2921         }
2922 }
2923 #endif  /* DDB */
2924
2925 /*
2926  * Fill in a struct xvfsconf based on a struct vfsconf.
2927  */
2928 static void
2929 vfsconf2x(struct vfsconf *vfsp, struct xvfsconf *xvfsp)
2930 {
2931
2932         strcpy(xvfsp->vfc_name, vfsp->vfc_name);
2933         xvfsp->vfc_typenum = vfsp->vfc_typenum;
2934         xvfsp->vfc_refcount = vfsp->vfc_refcount;
2935         xvfsp->vfc_flags = vfsp->vfc_flags;
2936         /*
2937          * These are unused in userland, we keep them
2938          * to not break binary compatibility.
2939          */
2940         xvfsp->vfc_vfsops = NULL;
2941         xvfsp->vfc_next = NULL;
2942 }
2943
2944 /*
2945  * Top level filesystem related information gathering.
2946  */
2947 static int
2948 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
2949 {
2950         struct vfsconf *vfsp;
2951         struct xvfsconf xvfsp;
2952         int error;
2953
2954         error = 0;
2955         TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
2956                 bzero(&xvfsp, sizeof(xvfsp));
2957                 vfsconf2x(vfsp, &xvfsp);
2958                 error = SYSCTL_OUT(req, &xvfsp, sizeof xvfsp);
2959                 if (error)
2960                         break;
2961         }
2962         return (error);
2963 }
2964
2965 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLFLAG_RD, NULL, 0, sysctl_vfs_conflist,
2966     "S,xvfsconf", "List of all configured filesystems");
2967
2968 #ifndef BURN_BRIDGES
2969 static int      sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
2970
2971 static int
2972 vfs_sysctl(SYSCTL_HANDLER_ARGS)
2973 {
2974         int *name = (int *)arg1 - 1;    /* XXX */
2975         u_int namelen = arg2 + 1;       /* XXX */
2976         struct vfsconf *vfsp;
2977         struct xvfsconf xvfsp;
2978
2979         printf("WARNING: userland calling deprecated sysctl, "
2980             "please rebuild world\n");
2981
2982 #if 1 || defined(COMPAT_PRELITE2)
2983         /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
2984         if (namelen == 1)
2985                 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
2986 #endif
2987
2988         switch (name[1]) {
2989         case VFS_MAXTYPENUM:
2990                 if (namelen != 2)
2991                         return (ENOTDIR);
2992                 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
2993         case VFS_CONF:
2994                 if (namelen != 3)
2995                         return (ENOTDIR);       /* overloaded */
2996                 TAILQ_FOREACH(vfsp, &vfsconf, vfc_list)
2997                         if (vfsp->vfc_typenum == name[2])
2998                                 break;
2999                 if (vfsp == NULL)
3000                         return (EOPNOTSUPP);
3001                 bzero(&xvfsp, sizeof(xvfsp));
3002                 vfsconf2x(vfsp, &xvfsp);
3003                 return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
3004         }
3005         return (EOPNOTSUPP);
3006 }
3007
3008 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP,
3009         vfs_sysctl, "Generic filesystem");
3010
3011 #if 1 || defined(COMPAT_PRELITE2)
3012
3013 static int
3014 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
3015 {
3016         int error;
3017         struct vfsconf *vfsp;
3018         struct ovfsconf ovfs;
3019
3020         TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
3021                 bzero(&ovfs, sizeof(ovfs));
3022                 ovfs.vfc_vfsops = vfsp->vfc_vfsops;     /* XXX used as flag */
3023                 strcpy(ovfs.vfc_name, vfsp->vfc_name);
3024                 ovfs.vfc_index = vfsp->vfc_typenum;
3025                 ovfs.vfc_refcount = vfsp->vfc_refcount;
3026                 ovfs.vfc_flags = vfsp->vfc_flags;
3027                 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
3028                 if (error)
3029                         return error;
3030         }
3031         return 0;
3032 }
3033
3034 #endif /* 1 || COMPAT_PRELITE2 */
3035 #endif /* !BURN_BRIDGES */
3036
3037 #define KINFO_VNODESLOP         10
3038 #ifdef notyet
3039 /*
3040  * Dump vnode list (via sysctl).
3041  */
3042 /* ARGSUSED */
3043 static int
3044 sysctl_vnode(SYSCTL_HANDLER_ARGS)
3045 {
3046         struct xvnode *xvn;
3047         struct mount *mp;
3048         struct vnode *vp;
3049         int error, len, n;
3050
3051         /*
3052          * Stale numvnodes access is not fatal here.
3053          */
3054         req->lock = 0;
3055         len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
3056         if (!req->oldptr)
3057                 /* Make an estimate */
3058                 return (SYSCTL_OUT(req, 0, len));
3059
3060         error = sysctl_wire_old_buffer(req, 0);
3061         if (error != 0)
3062                 return (error);
3063         xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
3064         n = 0;
3065         mtx_lock(&mountlist_mtx);
3066         TAILQ_FOREACH(mp, &mountlist, mnt_list) {
3067                 if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
3068                         continue;
3069                 MNT_ILOCK(mp);
3070                 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
3071                         if (n == len)
3072                                 break;
3073                         vref(vp);
3074                         xvn[n].xv_size = sizeof *xvn;
3075                         xvn[n].xv_vnode = vp;
3076                         xvn[n].xv_id = 0;       /* XXX compat */
3077 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
3078                         XV_COPY(usecount);
3079                         XV_COPY(writecount);
3080                         XV_COPY(holdcnt);
3081                         XV_COPY(mount);
3082                         XV_COPY(numoutput);
3083                         XV_COPY(type);
3084 #undef XV_COPY
3085                         xvn[n].xv_flag = vp->v_vflag;
3086
3087                         switch (vp->v_type) {
3088                         case VREG:
3089                         case VDIR:
3090                         case VLNK:
3091                                 break;
3092                         case VBLK:
3093                         case VCHR:
3094                                 if (vp->v_rdev == NULL) {
3095                                         vrele(vp);
3096                                         continue;
3097                                 }
3098                                 xvn[n].xv_dev = dev2udev(vp->v_rdev);
3099                                 break;
3100                         case VSOCK:
3101                                 xvn[n].xv_socket = vp->v_socket;
3102                                 break;
3103                         case VFIFO:
3104                                 xvn[n].xv_fifo = vp->v_fifoinfo;
3105                                 break;
3106                         case VNON:
3107                         case VBAD:
3108                         default:
3109                                 /* shouldn't happen? */
3110                                 vrele(vp);
3111                                 continue;
3112                         }
3113                         vrele(vp);
3114                         ++n;
3115                 }
3116                 MNT_IUNLOCK(mp);
3117                 mtx_lock(&mountlist_mtx);
3118                 vfs_unbusy(mp);
3119                 if (n == len)
3120                         break;
3121         }
3122         mtx_unlock(&mountlist_mtx);
3123
3124         error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
3125         free(xvn, M_TEMP);
3126         return (error);
3127 }
3128
3129 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE|CTLFLAG_RD,
3130         0, 0, sysctl_vnode, "S,xvnode", "");
3131 #endif
3132
3133 /*
3134  * Unmount all filesystems. The list is traversed in reverse order
3135  * of mounting to avoid dependencies.
3136  */
3137 void
3138 vfs_unmountall(void)
3139 {
3140         struct mount *mp;
3141         struct thread *td;
3142         int error;
3143
3144         KASSERT(curthread != NULL, ("vfs_unmountall: NULL curthread"));
3145         CTR1(KTR_VFS, "%s: unmounting all filesystems", __func__);
3146         td = curthread;
3147
3148         /*
3149          * Since this only runs when rebooting, it is not interlocked.
3150          */
3151         while(!TAILQ_EMPTY(&mountlist)) {
3152                 mp = TAILQ_LAST(&mountlist, mntlist);
3153                 error = dounmount(mp, MNT_FORCE, td);
3154                 if (error) {
3155                         TAILQ_REMOVE(&mountlist, mp, mnt_list);
3156                         /*
3157                          * XXX: Due to the way in which we mount the root
3158                          * file system off of devfs, devfs will generate a
3159                          * "busy" warning when we try to unmount it before
3160                          * the root.  Don't print a warning as a result in
3161                          * order to avoid false positive errors that may
3162                          * cause needless upset.
3163                          */
3164                         if (strcmp(mp->mnt_vfc->vfc_name, "devfs") != 0) {
3165                                 printf("unmount of %s failed (",
3166                                     mp->mnt_stat.f_mntonname);
3167                                 if (error == EBUSY)
3168                                         printf("BUSY)\n");
3169                                 else
3170                                         printf("%d)\n", error);
3171                         }
3172                 } else {
3173                         /* The unmount has removed mp from the mountlist */
3174                 }
3175         }
3176 }
3177
3178 /*
3179  * perform msync on all vnodes under a mount point
3180  * the mount point must be locked.
3181  */
3182 void
3183 vfs_msync(struct mount *mp, int flags)
3184 {
3185         struct vnode *vp, *mvp;
3186         struct vm_object *obj;
3187
3188         CTR2(KTR_VFS, "%s: mp %p", __func__, mp);
3189         MNT_ILOCK(mp);
3190         MNT_VNODE_FOREACH(vp, mp, mvp) {
3191                 VI_LOCK(vp);
3192                 obj = vp->v_object;
3193                 if (obj != NULL && (obj->flags & OBJ_MIGHTBEDIRTY) != 0 &&
3194                     (flags == MNT_WAIT || VOP_ISLOCKED(vp) == 0)) {
3195                         MNT_IUNLOCK(mp);
3196                         if (!vget(vp,
3197                             LK_EXCLUSIVE | LK_RETRY | LK_INTERLOCK,
3198                             curthread)) {
3199                                 if (vp->v_vflag & VV_NOSYNC) {  /* unlinked */
3200                                         vput(vp);
3201                                         MNT_ILOCK(mp);
3202                                         continue;
3203                                 }
3204
3205                                 obj = vp->v_object;
3206                                 if (obj != NULL) {
3207                                         VM_OBJECT_LOCK(obj);
3208                                         vm_object_page_clean(obj, 0, 0,
3209                                             flags == MNT_WAIT ?
3210                                             OBJPC_SYNC : OBJPC_NOSYNC);
3211                                         VM_OBJECT_UNLOCK(obj);
3212                                 }
3213                                 vput(vp);
3214                         }
3215                         MNT_ILOCK(mp);
3216                 } else
3217                         VI_UNLOCK(vp);
3218         }
3219         MNT_IUNLOCK(mp);
3220 }
3221
3222 /*
3223  * Mark a vnode as free, putting it up for recycling.
3224  */
3225 static void
3226 vfree(struct vnode *vp)
3227 {
3228
3229         ASSERT_VI_LOCKED(vp, "vfree");
3230         mtx_lock(&vnode_free_list_mtx);
3231         VNASSERT(vp->v_op != NULL, vp, ("vfree: vnode already reclaimed."));
3232         VNASSERT((vp->v_iflag & VI_FREE) == 0, vp, ("vnode already free"));
3233         VNASSERT(VSHOULDFREE(vp), vp, ("vfree: freeing when we shouldn't"));
3234         VNASSERT((vp->v_iflag & VI_DOOMED) == 0, vp,
3235             ("vfree: Freeing doomed vnode"));
3236         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3237         if (vp->v_iflag & VI_AGE) {
3238                 TAILQ_INSERT_HEAD(&vnode_free_list, vp, v_freelist);
3239         } else {
3240                 TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
3241         }
3242         freevnodes++;
3243         vp->v_iflag &= ~VI_AGE;
3244         vp->v_iflag |= VI_FREE;
3245         mtx_unlock(&vnode_free_list_mtx);
3246 }
3247
3248 /*
3249  * Opposite of vfree() - mark a vnode as in use.
3250  */
3251 static void
3252 vbusy(struct vnode *vp)
3253 {
3254         ASSERT_VI_LOCKED(vp, "vbusy");
3255         VNASSERT((vp->v_iflag & VI_FREE) != 0, vp, ("vnode not free"));
3256         VNASSERT(vp->v_op != NULL, vp, ("vbusy: vnode already reclaimed."));
3257         CTR2(KTR_VFS, "%s: vp %p", __func__, vp);
3258
3259         mtx_lock(&vnode_free_list_mtx);
3260         TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
3261         freevnodes--;
3262         vp->v_iflag &= ~(VI_FREE|VI_AGE);
3263         mtx_unlock(&vnode_free_list_mtx);
3264 }
3265
3266 static void
3267 destroy_vpollinfo(struct vpollinfo *vi)
3268 {
3269         knlist_destroy(&vi->vpi_selinfo.si_note);
3270         mtx_destroy(&vi->vpi_lock);
3271         uma_zfree(vnodepoll_zone, vi);
3272 }
3273
3274 /*
3275  * Initalize per-vnode helper structure to hold poll-related state.
3276  */
3277 void
3278 v_addpollinfo(struct vnode *vp)
3279 {
3280         struct vpollinfo *vi;
3281
3282         if (vp->v_pollinfo != NULL)
3283                 return;
3284         vi = uma_zalloc(vnodepoll_zone, M_WAITOK);
3285         mtx_init(&vi->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
3286         knlist_init(&vi->vpi_selinfo.si_note, vp, vfs_knllock,
3287             vfs_knlunlock, vfs_knl_assert_locked, vfs_knl_assert_unlocked);
3288         VI_LOCK(vp);
3289         if (vp->v_pollinfo != NULL) {
3290                 VI_UNLOCK(vp);
3291                 destroy_vpollinfo(vi);
3292                 return;
3293         }
3294         vp->v_pollinfo = vi;
3295         VI_UNLOCK(vp);
3296 }
3297
3298 /*
3299  * Record a process's interest in events which might happen to
3300  * a vnode.  Because poll uses the historic select-style interface
3301  * internally, this routine serves as both the ``check for any
3302  * pending events'' and the ``record my interest in future events''
3303  * functions.  (These are done together, while the lock is held,
3304  * to avoid race conditions.)
3305  */
3306 int
3307 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
3308 {
3309
3310         v_addpollinfo(vp);
3311         mtx_lock(&vp->v_pollinfo->vpi_lock);
3312         if (vp->v_pollinfo->vpi_revents & events) {
3313                 /*
3314                  * This leaves events we are not interested
3315                  * in available for the other process which
3316                  * which presumably had requested them
3317                  * (otherwise they would never have been
3318                  * recorded).
3319                  */
3320                 events &= vp->v_pollinfo->vpi_revents;
3321                 vp->v_pollinfo->vpi_revents &= ~events;
3322
3323                 mtx_unlock(&vp->v_pollinfo->vpi_lock);
3324                 return (events);
3325         }
3326         vp->v_pollinfo->vpi_events |= events;
3327         selrecord(td, &vp->v_pollinfo->vpi_selinfo);
3328         mtx_unlock(&vp->v_pollinfo->vpi_lock);
3329         return (0);
3330 }
3331
3332 /*
3333  * Routine to create and manage a filesystem syncer vnode.
3334  */
3335 #define sync_close ((int (*)(struct  vop_close_args *))nullop)
3336 static int      sync_fsync(struct  vop_fsync_args *);
3337 static int      sync_inactive(struct  vop_inactive_args *);
3338 static int      sync_reclaim(struct  vop_reclaim_args *);
3339
3340 static struct vop_vector sync_vnodeops = {
3341         .vop_bypass =   VOP_EOPNOTSUPP,
3342         .vop_close =    sync_close,             /* close */
3343         .vop_fsync =    sync_fsync,             /* fsync */
3344         .vop_inactive = sync_inactive,  /* inactive */
3345         .vop_reclaim =  sync_reclaim,   /* reclaim */
3346         .vop_lock1 =    vop_stdlock,    /* lock */
3347         .vop_unlock =   vop_stdunlock,  /* unlock */
3348         .vop_islocked = vop_stdislocked,        /* islocked */
3349 };
3350
3351 /*
3352  * Create a new filesystem syncer vnode for the specified mount point.
3353  */
3354 int
3355 vfs_allocate_syncvnode(struct mount *mp)
3356 {
3357         struct vnode *vp;
3358         struct bufobj *bo;
3359         static long start, incr, next;
3360         int error;
3361
3362         /* Allocate a new vnode */
3363         if ((error = getnewvnode("syncer", mp, &sync_vnodeops, &vp)) != 0) {
3364                 mp->mnt_syncer = NULL;
3365                 return (error);
3366         }
3367         vp->v_type = VNON;
3368         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3369         vp->v_vflag |= VV_FORCEINSMQ;
3370         error = insmntque(vp, mp);
3371         if (error != 0)
3372                 panic("vfs_allocate_syncvnode: insmntque failed");
3373         vp->v_vflag &= ~VV_FORCEINSMQ;
3374         VOP_UNLOCK(vp, 0);
3375         /*
3376          * Place the vnode onto the syncer worklist. We attempt to
3377          * scatter them about on the list so that they will go off
3378          * at evenly distributed times even if all the filesystems
3379          * are mounted at once.
3380          */
3381         next += incr;
3382         if (next == 0 || next > syncer_maxdelay) {
3383                 start /= 2;
3384                 incr /= 2;
3385                 if (start == 0) {
3386                         start = syncer_maxdelay / 2;
3387                         incr = syncer_maxdelay;
3388                 }
3389                 next = start;
3390         }
3391         bo = &vp->v_bufobj;
3392         BO_LOCK(bo);
3393         vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
3394         /* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
3395         mtx_lock(&sync_mtx);
3396         sync_vnode_count++;
3397         mtx_unlock(&sync_mtx);
3398         BO_UNLOCK(bo);
3399         mp->mnt_syncer = vp;
3400         return (0);
3401 }
3402
3403 /*
3404  * Do a lazy sync of the filesystem.
3405  */
3406 static int
3407 sync_fsync(struct vop_fsync_args *ap)
3408 {
3409         struct vnode *syncvp = ap->a_vp;
3410         struct mount *mp = syncvp->v_mount;
3411         int error;
3412         struct bufobj *bo;
3413
3414         /*
3415          * We only need to do something if this is a lazy evaluation.
3416          */
3417         if (ap->a_waitfor != MNT_LAZY)
3418                 return (0);
3419
3420         /*
3421          * Move ourselves to the back of the sync list.
3422          */
3423         bo = &syncvp->v_bufobj;
3424         BO_LOCK(bo);
3425         vn_syncer_add_to_worklist(bo, syncdelay);
3426         BO_UNLOCK(bo);
3427
3428         /*
3429          * Walk the list of vnodes pushing all that are dirty and
3430          * not already on the sync list.
3431          */
3432         mtx_lock(&mountlist_mtx);
3433         if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK) != 0) {
3434                 mtx_unlock(&mountlist_mtx);
3435                 return (0);
3436         }
3437         if (vn_start_write(NULL, &mp, V_NOWAIT) != 0) {
3438                 vfs_unbusy(mp);
3439                 return (0);
3440         }
3441         MNT_ILOCK(mp);
3442         mp->mnt_noasync++;
3443         mp->mnt_kern_flag &= ~MNTK_ASYNC;
3444         MNT_IUNLOCK(mp);
3445         vfs_msync(mp, MNT_NOWAIT);
3446         error = VFS_SYNC(mp, MNT_LAZY);
3447         MNT_ILOCK(mp);
3448         mp->mnt_noasync--;
3449         if ((mp->mnt_flag & MNT_ASYNC) != 0 && mp->mnt_noasync == 0)
3450                 mp->mnt_kern_flag |= MNTK_ASYNC;
3451         MNT_IUNLOCK(mp);
3452         vn_finished_write(mp);
3453         vfs_unbusy(mp);
3454         return (error);
3455 }
3456
3457 /*
3458  * The syncer vnode is no referenced.
3459  */
3460 static int
3461 sync_inactive(struct vop_inactive_args *ap)
3462 {
3463
3464         vgone(ap->a_vp);
3465         return (0);
3466 }
3467
3468 /*
3469  * The syncer vnode is no longer needed and is being decommissioned.
3470  *
3471  * Modifications to the worklist must be protected by sync_mtx.
3472  */
3473 static int
3474 sync_reclaim(struct vop_reclaim_args *ap)
3475 {
3476         struct vnode *vp = ap->a_vp;
3477         struct bufobj *bo;
3478
3479         bo = &vp->v_bufobj;
3480         BO_LOCK(bo);
3481         vp->v_mount->mnt_syncer = NULL;
3482         if (bo->bo_flag & BO_ONWORKLST) {
3483                 mtx_lock(&sync_mtx);
3484                 LIST_REMOVE(bo, bo_synclist);
3485                 syncer_worklist_len--;
3486                 sync_vnode_count--;
3487                 mtx_unlock(&sync_mtx);
3488                 bo->bo_flag &= ~BO_ONWORKLST;
3489         }
3490         BO_UNLOCK(bo);
3491
3492         return (0);
3493 }
3494
3495 /*
3496  * Check if vnode represents a disk device
3497  */
3498 int
3499 vn_isdisk(struct vnode *vp, int *errp)
3500 {
3501         int error;
3502
3503         error = 0;
3504         dev_lock();
3505         if (vp->v_type != VCHR)
3506                 error = ENOTBLK;
3507         else if (vp->v_rdev == NULL)
3508                 error = ENXIO;
3509         else if (vp->v_rdev->si_devsw == NULL)
3510                 error = ENXIO;
3511         else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
3512                 error = ENOTBLK;
3513         dev_unlock();
3514         if (errp != NULL)
3515                 *errp = error;
3516         return (error == 0);
3517 }
3518
3519 /*
3520  * Common filesystem object access control check routine.  Accepts a
3521  * vnode's type, "mode", uid and gid, requested access mode, credentials,
3522  * and optional call-by-reference privused argument allowing vaccess()
3523  * to indicate to the caller whether privilege was used to satisfy the
3524  * request (obsoleted).  Returns 0 on success, or an errno on failure.
3525  *
3526  * The ifdef'd CAPABILITIES version is here for reference, but is not
3527  * actually used.
3528  */
3529 int
3530 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
3531     accmode_t accmode, struct ucred *cred, int *privused)
3532 {
3533         accmode_t dac_granted;
3534         accmode_t priv_granted;
3535
3536         KASSERT((accmode & ~(VEXEC | VWRITE | VREAD | VADMIN | VAPPEND)) == 0,
3537             ("invalid bit in accmode"));
3538
3539         /*
3540          * Look for a normal, non-privileged way to access the file/directory
3541          * as requested.  If it exists, go with that.
3542          */
3543
3544         if (privused != NULL)
3545                 *privused = 0;
3546
3547         dac_granted = 0;
3548
3549         /* Check the owner. */
3550         if (cred->cr_uid == file_uid) {
3551                 dac_granted |= VADMIN;
3552                 if (file_mode & S_IXUSR)
3553                         dac_granted |= VEXEC;
3554                 if (file_mode & S_IRUSR)
3555                         dac_granted |= VREAD;
3556                 if (file_mode & S_IWUSR)
3557                         dac_granted |= (VWRITE | VAPPEND);
3558
3559                 if ((accmode & dac_granted) == accmode)
3560                         return (0);
3561
3562                 goto privcheck;
3563         }
3564
3565         /* Otherwise, check the groups (first match) */
3566         if (groupmember(file_gid, cred)) {
3567                 if (file_mode & S_IXGRP)
3568                         dac_granted |= VEXEC;
3569                 if (file_mode & S_IRGRP)
3570                         dac_granted |= VREAD;
3571                 if (file_mode & S_IWGRP)
3572                         dac_granted |= (VWRITE | VAPPEND);
3573
3574                 if ((accmode & dac_granted) == accmode)
3575                         return (0);
3576
3577                 goto privcheck;
3578         }
3579
3580         /* Otherwise, check everyone else. */
3581         if (file_mode & S_IXOTH)
3582                 dac_granted |= VEXEC;
3583         if (file_mode & S_IROTH)
3584                 dac_granted |= VREAD;
3585         if (file_mode & S_IWOTH)
3586                 dac_granted |= (VWRITE | VAPPEND);
3587         if ((accmode & dac_granted) == accmode)
3588                 return (0);
3589
3590 privcheck:
3591         /*
3592          * Build a privilege mask to determine if the set of privileges
3593          * satisfies the requirements when combined with the granted mask
3594          * from above.  For each privilege, if the privilege is required,
3595          * bitwise or the request type onto the priv_granted mask.
3596          */
3597         priv_granted = 0;
3598
3599         if (type == VDIR) {
3600                 /*
3601                  * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
3602                  * requests, instead of PRIV_VFS_EXEC.
3603                  */
3604                 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
3605                     !priv_check_cred(cred, PRIV_VFS_LOOKUP, 0))
3606                         priv_granted |= VEXEC;
3607         } else {
3608                 if ((accmode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
3609                     !priv_check_cred(cred, PRIV_VFS_EXEC, 0))
3610                         priv_granted |= VEXEC;
3611         }
3612
3613         if ((accmode & VREAD) && ((dac_granted & VREAD) == 0) &&
3614             !priv_check_cred(cred, PRIV_VFS_READ, 0))
3615                 priv_granted |= VREAD;
3616
3617         if ((accmode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
3618             !priv_check_cred(cred, PRIV_VFS_WRITE, 0))
3619                 priv_granted |= (VWRITE | VAPPEND);
3620
3621         if ((accmode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
3622             !priv_check_cred(cred, PRIV_VFS_ADMIN, 0))
3623                 priv_granted |= VADMIN;
3624
3625         if ((accmode & (priv_granted | dac_granted)) == accmode) {
3626                 /* XXX audit: privilege used */
3627                 if (privused != NULL)
3628                         *privused = 1;
3629                 return (0);
3630         }
3631
3632         return ((accmode & VADMIN) ? EPERM : EACCES);
3633 }
3634
3635 /*
3636  * Credential check based on process requesting service, and per-attribute
3637  * permissions.
3638  */
3639 int
3640 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
3641     struct thread *td, accmode_t accmode)
3642 {
3643
3644         /*
3645          * Kernel-invoked always succeeds.
3646          */
3647         if (cred == NOCRED)
3648                 return (0);
3649
3650         /*
3651          * Do not allow privileged processes in jail to directly manipulate
3652          * system attributes.
3653          */
3654         switch (attrnamespace) {
3655         case EXTATTR_NAMESPACE_SYSTEM:
3656                 /* Potentially should be: return (EPERM); */
3657                 return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM, 0));
3658         case EXTATTR_NAMESPACE_USER:
3659                 return (VOP_ACCESS(vp, accmode, cred, td));
3660         default:
3661                 return (EPERM);
3662         }
3663 }
3664
3665 #ifdef DEBUG_VFS_LOCKS
3666 /*
3667  * This only exists to supress warnings from unlocked specfs accesses.  It is
3668  * no longer ok to have an unlocked VFS.
3669  */
3670 #define IGNORE_LOCK(vp) (panicstr != NULL || (vp) == NULL ||            \
3671         (vp)->v_type == VCHR || (vp)->v_type == VBAD)
3672
3673 int vfs_badlock_ddb = 1;        /* Drop into debugger on violation. */
3674 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0, "");
3675
3676 int vfs_badlock_mutex = 1;      /* Check for interlock across VOPs. */
3677 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex, 0, "");
3678
3679 int vfs_badlock_print = 1;      /* Print lock violations. */
3680 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print, 0, "");
3681
3682 #ifdef KDB
3683 int vfs_badlock_backtrace = 1;  /* Print backtrace at lock violations. */
3684 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW, &vfs_badlock_backtrace, 0, "");
3685 #endif
3686
3687 static void
3688 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
3689 {
3690
3691 #ifdef KDB
3692         if (vfs_badlock_backtrace)
3693                 kdb_backtrace();
3694 #endif
3695         if (vfs_badlock_print)
3696                 printf("%s: %p %s\n", str, (void *)vp, msg);
3697         if (vfs_badlock_ddb)
3698                 kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
3699 }
3700
3701 void
3702 assert_vi_locked(struct vnode *vp, const char *str)
3703 {
3704
3705         if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
3706                 vfs_badlock("interlock is not locked but should be", str, vp);
3707 }
3708
3709 void
3710 assert_vi_unlocked(struct vnode *vp, const char *str)
3711 {
3712
3713         if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
3714                 vfs_badlock("interlock is locked but should not be", str, vp);
3715 }
3716
3717 void
3718 assert_vop_locked(struct vnode *vp, const char *str)
3719 {
3720
3721         if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) == 0)
3722                 vfs_badlock("is not locked but should be", str, vp);
3723 }
3724
3725 void
3726 assert_vop_unlocked(struct vnode *vp, const char *str)
3727 {
3728
3729         if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
3730                 vfs_badlock("is locked but should not be", str, vp);
3731 }
3732
3733 void
3734 assert_vop_elocked(struct vnode *vp, const char *str)
3735 {
3736
3737         if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
3738                 vfs_badlock("is not exclusive locked but should be", str, vp);
3739 }
3740
3741 #if 0
3742 void
3743 assert_vop_elocked_other(struct vnode *vp, const char *str)
3744 {
3745
3746         if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLOTHER)
3747                 vfs_badlock("is not exclusive locked by another thread",
3748                     str, vp);
3749 }
3750
3751 void
3752 assert_vop_slocked(struct vnode *vp, const char *str)
3753 {
3754
3755         if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_SHARED)
3756                 vfs_badlock("is not locked shared but should be", str, vp);
3757 }
3758 #endif /* 0 */
3759 #endif /* DEBUG_VFS_LOCKS */
3760
3761 void
3762 vop_rename_fail(struct vop_rename_args *ap)
3763 {
3764
3765         if (ap->a_tvp != NULL)
3766                 vput(ap->a_tvp);
3767         if (ap->a_tdvp == ap->a_tvp)
3768                 vrele(ap->a_tdvp);
3769         else
3770                 vput(ap->a_tdvp);
3771         vrele(ap->a_fdvp);
3772         vrele(ap->a_fvp);
3773 }
3774
3775 void
3776 vop_rename_pre(void *ap)
3777 {
3778         struct vop_rename_args *a = ap;
3779
3780 #ifdef DEBUG_VFS_LOCKS
3781         if (a->a_tvp)
3782                 ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
3783         ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
3784         ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
3785         ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
3786
3787         /* Check the source (from). */
3788         if (a->a_tdvp->v_vnlock != a->a_fdvp->v_vnlock &&
3789             (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fdvp->v_vnlock))
3790                 ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
3791         if (a->a_tvp == NULL || a->a_tvp->v_vnlock != a->a_fvp->v_vnlock)
3792                 ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
3793
3794         /* Check the target. */
3795         if (a->a_tvp)
3796                 ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
3797         ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
3798 #endif
3799         if (a->a_tdvp != a->a_fdvp)
3800                 vhold(a->a_fdvp);
3801         if (a->a_tvp != a->a_fvp)
3802                 vhold(a->a_fvp);
3803         vhold(a->a_tdvp);
3804         if (a->a_tvp)
3805                 vhold(a->a_tvp);
3806 }
3807
3808 void
3809 vop_strategy_pre(void *ap)
3810 {
3811 #ifdef DEBUG_VFS_LOCKS
3812         struct vop_strategy_args *a;
3813         struct buf *bp;
3814
3815         a = ap;
3816         bp = a->a_bp;
3817
3818         /*
3819          * Cluster ops lock their component buffers but not the IO container.
3820          */
3821         if ((bp->b_flags & B_CLUSTER) != 0)
3822                 return;
3823
3824         if (!BUF_ISLOCKED(bp)) {
3825                 if (vfs_badlock_print)
3826                         printf(
3827                             "VOP_STRATEGY: bp is not locked but should be\n");
3828                 if (vfs_badlock_ddb)
3829                         kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
3830         }
3831 #endif
3832 }
3833
3834 void
3835 vop_lookup_pre(void *ap)
3836 {
3837 #ifdef DEBUG_VFS_LOCKS
3838         struct vop_lookup_args *a;
3839         struct vnode *dvp;
3840
3841         a = ap;
3842         dvp = a->a_dvp;
3843         ASSERT_VI_UNLOCKED(dvp, "VOP_LOOKUP");
3844         ASSERT_VOP_LOCKED(dvp, "VOP_LOOKUP");
3845 #endif
3846 }
3847
3848 void
3849 vop_lookup_post(void *ap, int rc)
3850 {
3851 #ifdef DEBUG_VFS_LOCKS
3852         struct vop_lookup_args *a;
3853         struct vnode *dvp;
3854         struct vnode *vp;
3855
3856         a = ap;
3857         dvp = a->a_dvp;
3858         vp = *(a->a_vpp);
3859
3860         ASSERT_VI_UNLOCKED(dvp, "VOP_LOOKUP");
3861         ASSERT_VOP_LOCKED(dvp, "VOP_LOOKUP");
3862
3863         if (!rc)
3864                 ASSERT_VOP_LOCKED(vp, "VOP_LOOKUP (child)");
3865 #endif
3866 }
3867
3868 void
3869 vop_lock_pre(void *ap)
3870 {
3871 #ifdef DEBUG_VFS_LOCKS
3872         struct vop_lock1_args *a = ap;
3873
3874         if ((a->a_flags & LK_INTERLOCK) == 0)
3875                 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
3876         else
3877                 ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
3878 #endif
3879 }
3880
3881 void
3882 vop_lock_post(void *ap, int rc)
3883 {
3884 #ifdef DEBUG_VFS_LOCKS
3885         struct vop_lock1_args *a = ap;
3886
3887         ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
3888         if (rc == 0)
3889                 ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
3890 #endif
3891 }
3892
3893 void
3894 vop_unlock_pre(void *ap)
3895 {
3896 #ifdef DEBUG_VFS_LOCKS
3897         struct vop_unlock_args *a = ap;
3898
3899         if (a->a_flags & LK_INTERLOCK)
3900                 ASSERT_VI_LOCKED(a->a_vp, "VOP_UNLOCK");
3901         ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
3902 #endif
3903 }
3904
3905 void
3906 vop_unlock_post(void *ap, int rc)
3907 {
3908 #ifdef DEBUG_VFS_LOCKS
3909         struct vop_unlock_args *a = ap;
3910
3911         if (a->a_flags & LK_INTERLOCK)
3912                 ASSERT_VI_UNLOCKED(a->a_vp, "VOP_UNLOCK");
3913 #endif
3914 }
3915
3916 void
3917 vop_create_post(void *ap, int rc)
3918 {
3919         struct vop_create_args *a = ap;
3920
3921         if (!rc)
3922                 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
3923 }
3924
3925 void
3926 vop_link_post(void *ap, int rc)
3927 {
3928         struct vop_link_args *a = ap;
3929
3930         if (!rc) {
3931                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_LINK);
3932                 VFS_KNOTE_LOCKED(a->a_tdvp, NOTE_WRITE);
3933         }
3934 }
3935
3936 void
3937 vop_mkdir_post(void *ap, int rc)
3938 {
3939         struct vop_mkdir_args *a = ap;
3940
3941         if (!rc)
3942                 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
3943 }
3944
3945 void
3946 vop_mknod_post(void *ap, int rc)
3947 {
3948         struct vop_mknod_args *a = ap;
3949
3950         if (!rc)
3951                 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
3952 }
3953
3954 void
3955 vop_remove_post(void *ap, int rc)
3956 {
3957         struct vop_remove_args *a = ap;
3958
3959         if (!rc) {
3960                 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
3961                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
3962         }
3963 }
3964
3965 void
3966 vop_rename_post(void *ap, int rc)
3967 {
3968         struct vop_rename_args *a = ap;
3969
3970         if (!rc) {
3971                 VFS_KNOTE_UNLOCKED(a->a_fdvp, NOTE_WRITE);
3972                 VFS_KNOTE_UNLOCKED(a->a_tdvp, NOTE_WRITE);
3973                 VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
3974                 if (a->a_tvp)
3975                         VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
3976         }
3977         if (a->a_tdvp != a->a_fdvp)
3978                 vdrop(a->a_fdvp);
3979         if (a->a_tvp != a->a_fvp)
3980                 vdrop(a->a_fvp);
3981         vdrop(a->a_tdvp);
3982         if (a->a_tvp)
3983                 vdrop(a->a_tvp);
3984 }
3985
3986 void
3987 vop_rmdir_post(void *ap, int rc)
3988 {
3989         struct vop_rmdir_args *a = ap;
3990
3991         if (!rc) {
3992                 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
3993                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
3994         }
3995 }
3996
3997 void
3998 vop_setattr_post(void *ap, int rc)
3999 {
4000         struct vop_setattr_args *a = ap;
4001
4002         if (!rc)
4003                 VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
4004 }
4005
4006 void
4007 vop_symlink_post(void *ap, int rc)
4008 {
4009         struct vop_symlink_args *a = ap;
4010
4011         if (!rc)
4012                 VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
4013 }
4014
4015 static struct knlist fs_knlist;
4016
4017 static void
4018 vfs_event_init(void *arg)
4019 {
4020         knlist_init_mtx(&fs_knlist, NULL);
4021 }
4022 /* XXX - correct order? */
4023 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
4024
4025 void
4026 vfs_event_signal(fsid_t *fsid, u_int32_t event, intptr_t data __unused)
4027 {
4028
4029         KNOTE_UNLOCKED(&fs_knlist, event);
4030 }
4031
4032 static int      filt_fsattach(struct knote *kn);
4033 static void     filt_fsdetach(struct knote *kn);
4034 static int      filt_fsevent(struct knote *kn, long hint);
4035
4036 struct filterops fs_filtops =
4037         { 0, filt_fsattach, filt_fsdetach, filt_fsevent };
4038
4039 static int
4040 filt_fsattach(struct knote *kn)
4041 {
4042
4043         kn->kn_flags |= EV_CLEAR;
4044         knlist_add(&fs_knlist, kn, 0);
4045         return (0);
4046 }
4047
4048 static void
4049 filt_fsdetach(struct knote *kn)
4050 {
4051
4052         knlist_remove(&fs_knlist, kn, 0);
4053 }
4054
4055 static int
4056 filt_fsevent(struct knote *kn, long hint)
4057 {
4058
4059         kn->kn_fflags |= hint;
4060         return (kn->kn_fflags != 0);
4061 }
4062
4063 static int
4064 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
4065 {
4066         struct vfsidctl vc;
4067         int error;
4068         struct mount *mp;
4069
4070         error = SYSCTL_IN(req, &vc, sizeof(vc));
4071         if (error)
4072                 return (error);
4073         if (vc.vc_vers != VFS_CTL_VERS1)
4074                 return (EINVAL);
4075         mp = vfs_getvfs(&vc.vc_fsid);
4076         if (mp == NULL)
4077                 return (ENOENT);
4078         /* ensure that a specific sysctl goes to the right filesystem. */
4079         if (strcmp(vc.vc_fstypename, "*") != 0 &&
4080             strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
4081                 vfs_rel(mp);
4082                 return (EINVAL);
4083         }
4084         VCTLTOREQ(&vc, req);
4085         error = VFS_SYSCTL(mp, vc.vc_op, req);
4086         vfs_rel(mp);
4087         return (error);
4088 }
4089
4090 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLFLAG_WR, NULL, 0, sysctl_vfs_ctl, "",
4091     "Sysctl by fsid");
4092
4093 /*
4094  * Function to initialize a va_filerev field sensibly.
4095  * XXX: Wouldn't a random number make a lot more sense ??
4096  */
4097 u_quad_t
4098 init_va_filerev(void)
4099 {
4100         struct bintime bt;
4101
4102         getbinuptime(&bt);
4103         return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
4104 }
4105
4106 static int      filt_vfsread(struct knote *kn, long hint);
4107 static int      filt_vfswrite(struct knote *kn, long hint);
4108 static int      filt_vfsvnode(struct knote *kn, long hint);
4109 static void     filt_vfsdetach(struct knote *kn);
4110 static struct filterops vfsread_filtops =
4111         { 1, NULL, filt_vfsdetach, filt_vfsread };
4112 static struct filterops vfswrite_filtops =
4113         { 1, NULL, filt_vfsdetach, filt_vfswrite };
4114 static struct filterops vfsvnode_filtops =
4115         { 1, NULL, filt_vfsdetach, filt_vfsvnode };
4116
4117 static void
4118 vfs_knllock(void *arg)
4119 {
4120         struct vnode *vp = arg;
4121
4122         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4123 }
4124
4125 static void
4126 vfs_knlunlock(void *arg)
4127 {
4128         struct vnode *vp = arg;
4129
4130         VOP_UNLOCK(vp, 0);
4131 }
4132
4133 static void
4134 vfs_knl_assert_locked(void *arg)
4135 {
4136 #ifdef DEBUG_VFS_LOCKS
4137         struct vnode *vp = arg;
4138
4139         ASSERT_VOP_LOCKED(vp, "vfs_knl_assert_locked");
4140 #endif
4141 }
4142
4143 static void
4144 vfs_knl_assert_unlocked(void *arg)
4145 {
4146 #ifdef DEBUG_VFS_LOCKS
4147         struct vnode *vp = arg;
4148
4149         ASSERT_VOP_UNLOCKED(vp, "vfs_knl_assert_unlocked");
4150 #endif
4151 }
4152
4153 int
4154 vfs_kqfilter(struct vop_kqfilter_args *ap)
4155 {
4156         struct vnode *vp = ap->a_vp;
4157         struct knote *kn = ap->a_kn;
4158         struct knlist *knl;
4159
4160         switch (kn->kn_filter) {
4161         case EVFILT_READ:
4162                 kn->kn_fop = &vfsread_filtops;
4163                 break;
4164         case EVFILT_WRITE:
4165                 kn->kn_fop = &vfswrite_filtops;
4166                 break;
4167         case EVFILT_VNODE:
4168                 kn->kn_fop = &vfsvnode_filtops;
4169                 break;
4170         default:
4171                 return (EINVAL);
4172         }
4173
4174         kn->kn_hook = (caddr_t)vp;
4175
4176         v_addpollinfo(vp);
4177         if (vp->v_pollinfo == NULL)
4178                 return (ENOMEM);
4179         knl = &vp->v_pollinfo->vpi_selinfo.si_note;
4180         knlist_add(knl, kn, 0);
4181
4182         return (0);
4183 }
4184
4185 /*
4186  * Detach knote from vnode
4187  */
4188 static void
4189 filt_vfsdetach(struct knote *kn)
4190 {
4191         struct vnode *vp = (struct vnode *)kn->kn_hook;
4192
4193         KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
4194         knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
4195 }
4196
4197 /*ARGSUSED*/
4198 static int
4199 filt_vfsread(struct knote *kn, long hint)
4200 {
4201         struct vnode *vp = (struct vnode *)kn->kn_hook;
4202         struct vattr va;
4203         int res;
4204
4205         /*
4206          * filesystem is gone, so set the EOF flag and schedule
4207          * the knote for deletion.
4208          */
4209         if (hint == NOTE_REVOKE) {
4210                 VI_LOCK(vp);
4211                 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
4212                 VI_UNLOCK(vp);
4213                 return (1);
4214         }
4215
4216         if (VOP_GETATTR(vp, &va, curthread->td_ucred))
4217                 return (0);
4218
4219         VI_LOCK(vp);
4220         kn->kn_data = va.va_size - kn->kn_fp->f_offset;
4221         res = (kn->kn_data != 0);
4222         VI_UNLOCK(vp);
4223         return (res);
4224 }
4225
4226 /*ARGSUSED*/
4227 static int
4228 filt_vfswrite(struct knote *kn, long hint)
4229 {
4230         struct vnode *vp = (struct vnode *)kn->kn_hook;
4231
4232         VI_LOCK(vp);
4233
4234         /*
4235          * filesystem is gone, so set the EOF flag and schedule
4236          * the knote for deletion.
4237          */
4238         if (hint == NOTE_REVOKE)
4239                 kn->kn_flags |= (EV_EOF | EV_ONESHOT);
4240
4241         kn->kn_data = 0;
4242         VI_UNLOCK(vp);
4243         return (1);
4244 }
4245
4246 static int
4247 filt_vfsvnode(struct knote *kn, long hint)
4248 {
4249         struct vnode *vp = (struct vnode *)kn->kn_hook;
4250         int res;
4251
4252         VI_LOCK(vp);
4253         if (kn->kn_sfflags & hint)
4254                 kn->kn_fflags |= hint;
4255         if (hint == NOTE_REVOKE) {
4256                 kn->kn_flags |= EV_EOF;
4257                 VI_UNLOCK(vp);
4258                 return (1);
4259         }
4260         res = (kn->kn_fflags != 0);
4261         VI_UNLOCK(vp);
4262         return (res);
4263 }
4264
4265 int
4266 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
4267 {
4268         int error;
4269
4270         if (dp->d_reclen > ap->a_uio->uio_resid)
4271                 return (ENAMETOOLONG);
4272         error = uiomove(dp, dp->d_reclen, ap->a_uio);
4273         if (error) {
4274                 if (ap->a_ncookies != NULL) {
4275                         if (ap->a_cookies != NULL)
4276                                 free(ap->a_cookies, M_TEMP);
4277                         ap->a_cookies = NULL;
4278                         *ap->a_ncookies = 0;
4279                 }
4280                 return (error);
4281         }
4282         if (ap->a_ncookies == NULL)
4283                 return (0);
4284
4285         KASSERT(ap->a_cookies,
4286             ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
4287
4288         *ap->a_cookies = realloc(*ap->a_cookies,
4289             (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
4290         (*ap->a_cookies)[*ap->a_ncookies] = off;
4291         return (0);
4292 }
4293
4294 /*
4295  * Mark for update the access time of the file if the filesystem
4296  * supports VOP_MARKATIME.  This functionality is used by execve and
4297  * mmap, so we want to avoid the I/O implied by directly setting
4298  * va_atime for the sake of efficiency.
4299  */
4300 void
4301 vfs_mark_atime(struct vnode *vp, struct ucred *cred)
4302 {
4303         struct mount *mp;
4304
4305         mp = vp->v_mount;
4306         VFS_ASSERT_GIANT(mp);
4307         ASSERT_VOP_LOCKED(vp, "vfs_mark_atime");
4308         if (mp != NULL && (mp->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0)
4309                 (void)VOP_MARKATIME(vp);
4310 }
4311
4312 /*
4313  * The purpose of this routine is to remove granularity from accmode_t,
4314  * reducing it into standard unix access bits - VEXEC, VREAD, VWRITE,
4315  * VADMIN and VAPPEND.
4316  *
4317  * If it returns 0, the caller is supposed to continue with the usual
4318  * access checks using 'accmode' as modified by this routine.  If it
4319  * returns nonzero value, the caller is supposed to return that value
4320  * as errno.
4321  *
4322  * Note that after this routine runs, accmode may be zero.
4323  */
4324 int
4325 vfs_unixify_accmode(accmode_t *accmode)
4326 {
4327         /*
4328          * There is no way to specify explicit "deny" rule using
4329          * file mode or POSIX.1e ACLs.
4330          */
4331         if (*accmode & VEXPLICIT_DENY) {
4332                 *accmode = 0;
4333                 return (0);
4334         }
4335
4336         /*
4337          * None of these can be translated into usual access bits.
4338          * Also, the common case for NFSv4 ACLs is to not contain
4339          * either of these bits. Caller should check for VWRITE
4340          * on the containing directory instead.
4341          */
4342         if (*accmode & (VDELETE_CHILD | VDELETE))
4343                 return (EPERM);
4344
4345         if (*accmode & VADMIN_PERMS) {
4346                 *accmode &= ~VADMIN_PERMS;
4347                 *accmode |= VADMIN;
4348         }
4349
4350         /*
4351          * There is no way to deny VREAD_ATTRIBUTES, VREAD_ACL
4352          * or VSYNCHRONIZE using file mode or POSIX.1e ACL.
4353          */
4354         *accmode &= ~(VSTAT_PERMS | VSYNCHRONIZE);
4355
4356         return (0);
4357 }