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