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