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