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