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