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