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