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