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