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