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