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