namecache work stage 3a: Adjust the VFS APIs to include a namecache pointer
[dragonfly.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  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *      @(#)vfs_subr.c  8.31 (Berkeley) 5/26/95
39  * $FreeBSD: src/sys/kern/vfs_subr.c,v 1.249.2.30 2003/04/04 20:35:57 tegge Exp $
40  * $DragonFly: src/sys/kern/vfs_subr.c,v 1.22 2003/10/09 22:27:19 dillon Exp $
41  */
42
43 /*
44  * External virtual filesystem routines
45  */
46 #include "opt_ddb.h"
47
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/buf.h>
51 #include <sys/conf.h>
52 #include <sys/dirent.h>
53 #include <sys/domain.h>
54 #include <sys/eventhandler.h>
55 #include <sys/fcntl.h>
56 #include <sys/kernel.h>
57 #include <sys/kthread.h>
58 #include <sys/malloc.h>
59 #include <sys/mbuf.h>
60 #include <sys/mount.h>
61 #include <sys/proc.h>
62 #include <sys/namei.h>
63 #include <sys/reboot.h>
64 #include <sys/socket.h>
65 #include <sys/stat.h>
66 #include <sys/sysctl.h>
67 #include <sys/syslog.h>
68 #include <sys/vmmeter.h>
69 #include <sys/vnode.h>
70
71 #include <machine/limits.h>
72
73 #include <vm/vm.h>
74 #include <vm/vm_object.h>
75 #include <vm/vm_extern.h>
76 #include <vm/pmap.h>
77 #include <vm/vm_map.h>
78 #include <vm/vm_page.h>
79 #include <vm/vm_pager.h>
80 #include <vm/vnode_pager.h>
81 #include <vm/vm_zone.h>
82
83 #include <sys/buf2.h>
84 #include <sys/thread2.h>
85
86 static MALLOC_DEFINE(M_NETADDR, "Export Host", "Export host address structure");
87
88 static void     insmntque (struct vnode *vp, struct mount *mp);
89 static void     vclean (struct vnode *vp, int flags, struct thread *td);
90 static unsigned long    numvnodes;
91 static void     vlruvp(struct vnode *vp);
92 SYSCTL_INT(_debug, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0, "");
93
94 enum vtype iftovt_tab[16] = {
95         VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
96         VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VBAD,
97 };
98 int vttoif_tab[9] = {
99         0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
100         S_IFSOCK, S_IFIFO, S_IFMT,
101 };
102
103 static TAILQ_HEAD(freelst, vnode) vnode_free_list;      /* vnode free list */
104
105 static u_long wantfreevnodes = 25;
106 SYSCTL_INT(_debug, OID_AUTO, wantfreevnodes, CTLFLAG_RW, &wantfreevnodes, 0, "");
107 static u_long freevnodes = 0;
108 SYSCTL_INT(_debug, OID_AUTO, freevnodes, CTLFLAG_RD, &freevnodes, 0, "");
109
110 static int reassignbufcalls;
111 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW, &reassignbufcalls, 0, "");
112 static int reassignbufloops;
113 SYSCTL_INT(_vfs, OID_AUTO, reassignbufloops, CTLFLAG_RW, &reassignbufloops, 0, "");
114 static int reassignbufsortgood;
115 SYSCTL_INT(_vfs, OID_AUTO, reassignbufsortgood, CTLFLAG_RW, &reassignbufsortgood, 0, "");
116 static int reassignbufsortbad;
117 SYSCTL_INT(_vfs, OID_AUTO, reassignbufsortbad, CTLFLAG_RW, &reassignbufsortbad, 0, "");
118 static int reassignbufmethod = 1;
119 SYSCTL_INT(_vfs, OID_AUTO, reassignbufmethod, CTLFLAG_RW, &reassignbufmethod, 0, "");
120
121 #ifdef ENABLE_VFS_IOOPT
122 int vfs_ioopt = 0;
123 SYSCTL_INT(_vfs, OID_AUTO, ioopt, CTLFLAG_RW, &vfs_ioopt, 0, "");
124 #endif
125
126 struct mntlist mountlist = TAILQ_HEAD_INITIALIZER(mountlist); /* mounted fs */
127 struct lwkt_token mountlist_token;
128 struct lwkt_token mntvnode_token;
129 int     nfs_mount_type = -1;
130 static struct lwkt_token mntid_token;
131 static struct lwkt_token vnode_free_list_token;
132 static struct lwkt_token spechash_token;
133 struct nfs_public nfs_pub;      /* publicly exported FS */
134 static vm_zone_t vnode_zone;
135
136 /*
137  * The workitem queue.
138  */
139 #define SYNCER_MAXDELAY         32
140 static int syncer_maxdelay = SYNCER_MAXDELAY;   /* maximum delay time */
141 time_t syncdelay = 30;          /* max time to delay syncing data */
142 SYSCTL_INT(_kern, OID_AUTO, syncdelay, CTLFLAG_RW, &syncdelay, 0,
143         "VFS data synchronization delay");
144 time_t filedelay = 30;          /* time to delay syncing files */
145 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0,
146         "File synchronization delay");
147 time_t dirdelay = 29;           /* time to delay syncing directories */
148 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0,
149         "Directory synchronization delay");
150 time_t metadelay = 28;          /* time to delay syncing metadata */
151 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0,
152         "VFS metadata synchronization delay");
153 static int rushjob;                     /* number of slots to run ASAP */
154 static int stat_rush_requests;  /* number of times I/O speeded up */
155 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0, "");
156
157 static int syncer_delayno = 0;
158 static long syncer_mask; 
159 LIST_HEAD(synclist, vnode);
160 static struct synclist *syncer_workitem_pending;
161
162 int desiredvnodes;
163 SYSCTL_INT(_kern, KERN_MAXVNODES, maxvnodes, CTLFLAG_RW, 
164     &desiredvnodes, 0, "Maximum number of vnodes");
165 static int minvnodes;
166 SYSCTL_INT(_kern, OID_AUTO, minvnodes, CTLFLAG_RW, 
167     &minvnodes, 0, "Minimum number of vnodes");
168 static int vnlru_nowhere = 0;
169 SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW, &vnlru_nowhere, 0,
170     "Number of times the vnlru process ran without success");
171
172 static void     vfs_free_addrlist (struct netexport *nep);
173 static int      vfs_free_netcred (struct radix_node *rn, void *w);
174 static int      vfs_hang_addrlist (struct mount *mp, struct netexport *nep,
175                                        struct export_args *argp);
176
177 /*
178  * Initialize the vnode management data structures.
179  */
180 void
181 vntblinit()
182 {
183
184         desiredvnodes = maxproc + vmstats.v_page_count / 4;
185         minvnodes = desiredvnodes / 4;
186         lwkt_inittoken(&mntvnode_token);
187         lwkt_inittoken(&mntid_token);
188         lwkt_inittoken(&spechash_token);
189         TAILQ_INIT(&vnode_free_list);
190         lwkt_inittoken(&vnode_free_list_token);
191         vnode_zone = zinit("VNODE", sizeof (struct vnode), 0, 0, 5);
192         /*
193          * Initialize the filesystem syncer.
194          */     
195         syncer_workitem_pending = hashinit(syncer_maxdelay, M_VNODE, 
196                 &syncer_mask);
197         syncer_maxdelay = syncer_mask + 1;
198 }
199
200 /*
201  * Mark a mount point as busy. Used to synchronize access and to delay
202  * unmounting. Interlock is not released on failure.
203  */
204 int
205 vfs_busy(struct mount *mp, int flags, struct lwkt_token *interlkp,
206         struct thread *td)
207 {
208         int lkflags;
209
210         if (mp->mnt_kern_flag & MNTK_UNMOUNT) {
211                 if (flags & LK_NOWAIT)
212                         return (ENOENT);
213                 mp->mnt_kern_flag |= MNTK_MWAIT;
214                 if (interlkp) {
215                         lwkt_reltoken(interlkp);
216                 }
217                 /*
218                  * Since all busy locks are shared except the exclusive
219                  * lock granted when unmounting, the only place that a
220                  * wakeup needs to be done is at the release of the
221                  * exclusive lock at the end of dounmount.
222                  */
223                 tsleep((caddr_t)mp, 0, "vfs_busy", 0);
224                 if (interlkp) {
225                         lwkt_gettoken(interlkp);
226                 }
227                 return (ENOENT);
228         }
229         lkflags = LK_SHARED | LK_NOPAUSE;
230         if (interlkp)
231                 lkflags |= LK_INTERLOCK;
232         if (lockmgr(&mp->mnt_lock, lkflags, interlkp, td))
233                 panic("vfs_busy: unexpected lock failure");
234         return (0);
235 }
236
237 /*
238  * Free a busy filesystem.
239  */
240 void
241 vfs_unbusy(struct mount *mp, struct thread *td)
242 {
243         lockmgr(&mp->mnt_lock, LK_RELEASE, NULL, td);
244 }
245
246 /*
247  * Lookup a filesystem type, and if found allocate and initialize
248  * a mount structure for it.
249  *
250  * Devname is usually updated by mount(8) after booting.
251  */
252 int
253 vfs_rootmountalloc(char *fstypename, char *devname, struct mount **mpp)
254 {
255         struct thread *td = curthread;  /* XXX */
256         struct vfsconf *vfsp;
257         struct mount *mp;
258
259         if (fstypename == NULL)
260                 return (ENODEV);
261         for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next)
262                 if (!strcmp(vfsp->vfc_name, fstypename))
263                         break;
264         if (vfsp == NULL)
265                 return (ENODEV);
266         mp = malloc((u_long)sizeof(struct mount), M_MOUNT, M_WAITOK);
267         bzero((char *)mp, (u_long)sizeof(struct mount));
268         lockinit(&mp->mnt_lock, 0, "vfslock", VLKTIMEOUT, LK_NOPAUSE);
269         (void)vfs_busy(mp, LK_NOWAIT, 0, td);
270         TAILQ_INIT(&mp->mnt_nvnodelist);
271         TAILQ_INIT(&mp->mnt_reservedvnlist);
272         mp->mnt_nvnodelistsize = 0;
273         mp->mnt_vfc = vfsp;
274         mp->mnt_op = vfsp->vfc_vfsops;
275         mp->mnt_flag = MNT_RDONLY;
276         mp->mnt_vnodecovered = NULLVP;
277         vfsp->vfc_refcount++;
278         mp->mnt_iosize_max = DFLTPHYS;
279         mp->mnt_stat.f_type = vfsp->vfc_typenum;
280         mp->mnt_flag |= vfsp->vfc_flags & MNT_VISFLAGMASK;
281         strncpy(mp->mnt_stat.f_fstypename, vfsp->vfc_name, MFSNAMELEN);
282         mp->mnt_stat.f_mntonname[0] = '/';
283         mp->mnt_stat.f_mntonname[1] = 0;
284         (void) copystr(devname, mp->mnt_stat.f_mntfromname, MNAMELEN - 1, 0);
285         *mpp = mp;
286         return (0);
287 }
288
289 /*
290  * Find an appropriate filesystem to use for the root. If a filesystem
291  * has not been preselected, walk through the list of known filesystems
292  * trying those that have mountroot routines, and try them until one
293  * works or we have tried them all.
294  */
295 #ifdef notdef   /* XXX JH */
296 int
297 lite2_vfs_mountroot()
298 {
299         struct vfsconf *vfsp;
300         extern int (*lite2_mountroot) (void);
301         int error;
302
303         if (lite2_mountroot != NULL)
304                 return ((*lite2_mountroot)());
305         for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next) {
306                 if (vfsp->vfc_mountroot == NULL)
307                         continue;
308                 if ((error = (*vfsp->vfc_mountroot)()) == 0)
309                         return (0);
310                 printf("%s_mountroot failed: %d\n", vfsp->vfc_name, error);
311         }
312         return (ENODEV);
313 }
314 #endif
315
316 /*
317  * Lookup a mount point by filesystem identifier.
318  */
319 struct mount *
320 vfs_getvfs(fsid)
321         fsid_t *fsid;
322 {
323         struct mount *mp;
324
325         lwkt_gettoken(&mountlist_token);
326         TAILQ_FOREACH(mp, &mountlist, mnt_list) {
327                 if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
328                     mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
329                         lwkt_reltoken(&mountlist_token);
330                         return (mp);
331             }
332         }
333         lwkt_reltoken(&mountlist_token);
334         return ((struct mount *) 0);
335 }
336
337 /*
338  * Get a new unique fsid.  Try to make its val[0] unique, since this value
339  * will be used to create fake device numbers for stat().  Also try (but
340  * not so hard) make its val[0] unique mod 2^16, since some emulators only
341  * support 16-bit device numbers.  We end up with unique val[0]'s for the
342  * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
343  *
344  * Keep in mind that several mounts may be running in parallel.  Starting
345  * the search one past where the previous search terminated is both a
346  * micro-optimization and a defense against returning the same fsid to
347  * different mounts.
348  */
349 void
350 vfs_getnewfsid(mp)
351         struct mount *mp;
352 {
353         static u_int16_t mntid_base;
354         fsid_t tfsid;
355         int mtype;
356
357         lwkt_gettoken(&mntid_token);
358         mtype = mp->mnt_vfc->vfc_typenum;
359         tfsid.val[1] = mtype;
360         mtype = (mtype & 0xFF) << 24;
361         for (;;) {
362                 tfsid.val[0] = makeudev(255,
363                     mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
364                 mntid_base++;
365                 if (vfs_getvfs(&tfsid) == NULL)
366                         break;
367         }
368         mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
369         mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
370         lwkt_reltoken(&mntid_token);
371 }
372
373 /*
374  * Knob to control the precision of file timestamps:
375  *
376  *   0 = seconds only; nanoseconds zeroed.
377  *   1 = seconds and nanoseconds, accurate within 1/HZ.
378  *   2 = seconds and nanoseconds, truncated to microseconds.
379  * >=3 = seconds and nanoseconds, maximum precision.
380  */
381 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
382
383 static int timestamp_precision = TSP_SEC;
384 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
385     &timestamp_precision, 0, "");
386
387 /*
388  * Get a current timestamp.
389  */
390 void
391 vfs_timestamp(tsp)
392         struct timespec *tsp;
393 {
394         struct timeval tv;
395
396         switch (timestamp_precision) {
397         case TSP_SEC:
398                 tsp->tv_sec = time_second;
399                 tsp->tv_nsec = 0;
400                 break;
401         case TSP_HZ:
402                 getnanotime(tsp);
403                 break;
404         case TSP_USEC:
405                 microtime(&tv);
406                 TIMEVAL_TO_TIMESPEC(&tv, tsp);
407                 break;
408         case TSP_NSEC:
409         default:
410                 nanotime(tsp);
411                 break;
412         }
413 }
414
415 /*
416  * Set vnode attributes to VNOVAL
417  */
418 void
419 vattr_null(vap)
420         struct vattr *vap;
421 {
422
423         vap->va_type = VNON;
424         vap->va_size = VNOVAL;
425         vap->va_bytes = VNOVAL;
426         vap->va_mode = VNOVAL;
427         vap->va_nlink = VNOVAL;
428         vap->va_uid = VNOVAL;
429         vap->va_gid = VNOVAL;
430         vap->va_fsid = VNOVAL;
431         vap->va_fileid = VNOVAL;
432         vap->va_blocksize = VNOVAL;
433         vap->va_rdev = VNOVAL;
434         vap->va_atime.tv_sec = VNOVAL;
435         vap->va_atime.tv_nsec = VNOVAL;
436         vap->va_mtime.tv_sec = VNOVAL;
437         vap->va_mtime.tv_nsec = VNOVAL;
438         vap->va_ctime.tv_sec = VNOVAL;
439         vap->va_ctime.tv_nsec = VNOVAL;
440         vap->va_flags = VNOVAL;
441         vap->va_gen = VNOVAL;
442         vap->va_vaflags = 0;
443 }
444
445 /*
446  * This routine is called when we have too many vnodes.  It attempts
447  * to free <count> vnodes and will potentially free vnodes that still
448  * have VM backing store (VM backing store is typically the cause
449  * of a vnode blowout so we want to do this).  Therefore, this operation
450  * is not considered cheap.
451  *
452  * A number of conditions may prevent a vnode from being reclaimed.
453  * the buffer cache may have references on the vnode, a directory
454  * vnode may still have references due to the namei cache representing
455  * underlying files, or the vnode may be in active use.   It is not
456  * desireable to reuse such vnodes.  These conditions may cause the
457  * number of vnodes to reach some minimum value regardless of what
458  * you set kern.maxvnodes to.  Do not set kern.maxvnodes too low.
459  */
460 static int
461 vlrureclaim(struct mount *mp)
462 {
463         struct vnode *vp;
464         int done;
465         int trigger;
466         int usevnodes;
467         int count;
468         int gen;
469
470         /*
471          * Calculate the trigger point, don't allow user
472          * screwups to blow us up.   This prevents us from
473          * recycling vnodes with lots of resident pages.  We
474          * aren't trying to free memory, we are trying to
475          * free vnodes.
476          */
477         usevnodes = desiredvnodes;
478         if (usevnodes <= 0)
479                 usevnodes = 1;
480         trigger = vmstats.v_page_count * 2 / usevnodes;
481
482         done = 0;
483         gen = lwkt_gettoken(&mntvnode_token);
484         count = mp->mnt_nvnodelistsize / 10 + 1;
485         while (count && (vp = TAILQ_FIRST(&mp->mnt_nvnodelist)) != NULL) {
486                 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
487                 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
488
489                 if (vp->v_type != VNON &&
490                     vp->v_type != VBAD &&
491                     VMIGHTFREE(vp) &&           /* critical path opt */
492                     (vp->v_object == NULL || vp->v_object->resident_page_count < trigger)
493                 ) {
494                         lwkt_gettoken(&vp->v_interlock);
495                         if (lwkt_gentoken(&mntvnode_token, &gen) == 0) {
496                                 if (VMIGHTFREE(vp)) {
497                                         vgonel(vp, curthread);
498                                         done++;
499                                 } else {
500                                         lwkt_reltoken(&vp->v_interlock);
501                                 }
502                         } else {
503                                 lwkt_reltoken(&vp->v_interlock);
504                         }
505                 }
506                 --count;
507         }
508         lwkt_reltoken(&mntvnode_token);
509         return done;
510 }
511
512 /*
513  * Attempt to recycle vnodes in a context that is always safe to block.
514  * Calling vlrurecycle() from the bowels of file system code has some
515  * interesting deadlock problems.
516  */
517 static struct thread *vnlruthread;
518 static int vnlruproc_sig;
519
520 static void 
521 vnlru_proc(void)
522 {
523         struct mount *mp, *nmp;
524         int s;
525         int done;
526         struct thread *td = curthread;
527
528         EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc, td,
529             SHUTDOWN_PRI_FIRST);   
530
531         s = splbio();
532         for (;;) {
533                 kproc_suspend_loop();
534                 if (numvnodes - freevnodes <= desiredvnodes * 9 / 10) {
535                         vnlruproc_sig = 0;
536                         wakeup(&vnlruproc_sig);
537                         tsleep(td, 0, "vlruwt", hz);
538                         continue;
539                 }
540                 done = 0;
541                 lwkt_gettoken(&mountlist_token);
542                 for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
543                         if (vfs_busy(mp, LK_NOWAIT, &mountlist_token, td)) {
544                                 nmp = TAILQ_NEXT(mp, mnt_list);
545                                 continue;
546                         }
547                         done += vlrureclaim(mp);
548                         lwkt_gettoken(&mountlist_token);
549                         nmp = TAILQ_NEXT(mp, mnt_list);
550                         vfs_unbusy(mp, td);
551                 }
552                 lwkt_reltoken(&mountlist_token);
553                 if (done == 0) {
554                         vnlru_nowhere++;
555                         tsleep(td, 0, "vlrup", hz * 3);
556                 }
557         }
558         splx(s);
559 }
560
561 static struct kproc_desc vnlru_kp = {
562         "vnlru",
563         vnlru_proc,
564         &vnlruthread
565 };
566 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &vnlru_kp)
567
568 /*
569  * Routines having to do with the management of the vnode table.
570  */
571 extern vop_t **dead_vnodeop_p;
572
573 /*
574  * Return the next vnode from the free list.
575  */
576 int
577 getnewvnode(tag, mp, vops, vpp)
578         enum vtagtype tag;
579         struct mount *mp;
580         vop_t **vops;
581         struct vnode **vpp;
582 {
583         int s;
584         int gen;
585         int vgen;
586         struct thread *td = curthread;  /* XXX */
587         struct vnode *vp = NULL;
588         vm_object_t object;
589
590         s = splbio();
591
592         /*
593          * Try to reuse vnodes if we hit the max.  This situation only
594          * occurs in certain large-memory (2G+) situations.  We cannot
595          * attempt to directly reclaim vnodes due to nasty recursion
596          * problems.
597          */
598         while (numvnodes - freevnodes > desiredvnodes) {
599                 if (vnlruproc_sig == 0) {
600                         vnlruproc_sig = 1;      /* avoid unnecessary wakeups */
601                         wakeup(vnlruthread);
602                 }
603                 tsleep(&vnlruproc_sig, 0, "vlruwk", hz);
604         }
605
606
607         /*
608          * Attempt to reuse a vnode already on the free list, allocating
609          * a new vnode if we can't find one or if we have not reached a
610          * good minimum for good LRU performance.
611          */
612         gen = lwkt_gettoken(&vnode_free_list_token);
613         if (freevnodes >= wantfreevnodes && numvnodes >= minvnodes) {
614                 int count;
615
616                 for (count = 0; count < freevnodes; count++) {
617                         vp = TAILQ_FIRST(&vnode_free_list);
618                         if (vp == NULL || vp->v_usecount)
619                                 panic("getnewvnode: free vnode isn't");
620
621                         /*
622                          * Get the vnode's interlock, then re-obtain 
623                          * vnode_free_list_token in case we lost it.  If we
624                          * did lose it while getting the vnode interlock,
625                          * even if we got it back again, then retry.
626                          */
627                         vgen = lwkt_gettoken(&vp->v_interlock);
628                         if (lwkt_gentoken(&vnode_free_list_token, &gen) != 0) {
629                                 --count;
630                                 lwkt_reltoken(&vp->v_interlock);
631                                 vp = NULL;
632                                 continue;
633                         }
634
635                         /*
636                          * Whew!  We have both tokens.  Since we didn't lose
637                          * the free list VFREE had better still be set.  But
638                          * we aren't out of the woods yet.  We have to get
639                          * the object (may block).  If the vnode is not 
640                          * suitable then move it to the end of the list
641                          * if we can.  If we can't move it to the end of the
642                          * list retry again.
643                          */
644                         if ((VOP_GETVOBJECT(vp, &object) == 0 &&
645                             (object->resident_page_count || object->ref_count))
646                         ) {
647                                 if (lwkt_gentoken(&vp->v_interlock, &vgen) == 0 &&
648                                    lwkt_gentoken(&vnode_free_list_token, &gen) == 0
649                                 ) {
650                                         TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
651                                         TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
652                                 } else {
653                                         --count;
654                                 }
655                                 lwkt_reltoken(&vp->v_interlock);
656                                 vp = NULL;
657                                 continue;
658                         }
659
660                         /*
661                          * Still not out of the woods.  VOBJECT might have
662                          * blocked, if we did not retain our tokens we have
663                          * to retry.
664                          */
665                         if (lwkt_gentoken(&vp->v_interlock, &vgen) != 0 ||
666                             lwkt_gentoken(&vnode_free_list_token, &gen) != 0) {
667                                 --count;
668                                 vp = NULL;
669                                 continue;
670                         }
671                         TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
672                         KKASSERT(vp->v_flag & VFREE);
673
674                         /*
675                          * If we have children in the namecache we cannot
676                          * reuse the vnode yet because it will break the
677                          * namecache chain (YYY use nc_refs for the check?)
678                          */
679                         if (TAILQ_FIRST(&vp->v_namecache)) {
680                                 if (cache_leaf_test(vp) < 0) {
681                                         lwkt_reltoken(&vp->v_interlock);
682                                         TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
683                                         vp = NULL;
684                                         continue;
685                                 }
686                         }
687                         break;
688                 }
689         }
690
691         if (vp) {
692                 vp->v_flag |= VDOOMED;
693                 vp->v_flag &= ~VFREE;
694                 freevnodes--;
695                 lwkt_reltoken(&vnode_free_list_token);
696                 cache_purge(vp);        /* YYY may block */
697                 vp->v_lease = NULL;
698                 if (vp->v_type != VBAD) {
699                         vgonel(vp, td);
700                 } else {
701                         lwkt_reltoken(&vp->v_interlock);
702                 }
703
704 #ifdef INVARIANTS
705                 {
706                         int s;
707
708                         if (vp->v_data)
709                                 panic("cleaned vnode isn't");
710                         s = splbio();
711                         if (vp->v_numoutput)
712                                 panic("Clean vnode has pending I/O's");
713                         splx(s);
714                 }
715 #endif
716                 vp->v_flag = 0;
717                 vp->v_lastw = 0;
718                 vp->v_lasta = 0;
719                 vp->v_cstart = 0;
720                 vp->v_clen = 0;
721                 vp->v_socket = 0;
722                 vp->v_writecount = 0;   /* XXX */
723         } else {
724                 lwkt_reltoken(&vnode_free_list_token);
725                 vp = (struct vnode *) zalloc(vnode_zone);
726                 bzero((char *) vp, sizeof *vp);
727                 lwkt_inittoken(&vp->v_interlock);
728                 vp->v_dd = vp;
729                 cache_purge(vp);
730                 TAILQ_INIT(&vp->v_namecache);
731                 numvnodes++;
732         }
733
734         TAILQ_INIT(&vp->v_cleanblkhd);
735         TAILQ_INIT(&vp->v_dirtyblkhd);
736         vp->v_type = VNON;
737         vp->v_tag = tag;
738         vp->v_op = vops;
739         insmntque(vp, mp);
740         *vpp = vp;
741         vp->v_usecount = 1;
742         vp->v_data = 0;
743         splx(s);
744
745         vfs_object_create(vp, td);
746         return (0);
747 }
748
749 /*
750  * Move a vnode from one mount queue to another.
751  */
752 static void
753 insmntque(vp, mp)
754         struct vnode *vp;
755         struct mount *mp;
756 {
757
758         lwkt_gettoken(&mntvnode_token);
759         /*
760          * Delete from old mount point vnode list, if on one.
761          */
762         if (vp->v_mount != NULL) {
763                 KASSERT(vp->v_mount->mnt_nvnodelistsize > 0,
764                         ("bad mount point vnode list size"));
765                 TAILQ_REMOVE(&vp->v_mount->mnt_nvnodelist, vp, v_nmntvnodes);
766                 vp->v_mount->mnt_nvnodelistsize--;
767         }
768         /*
769          * Insert into list of vnodes for the new mount point, if available.
770          */
771         if ((vp->v_mount = mp) == NULL) {
772                 lwkt_reltoken(&mntvnode_token);
773                 return;
774         }
775         TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
776         mp->mnt_nvnodelistsize++;
777         lwkt_reltoken(&mntvnode_token);
778 }
779
780 /*
781  * Update outstanding I/O count and do wakeup if requested.
782  */
783 void
784 vwakeup(bp)
785         struct buf *bp;
786 {
787         struct vnode *vp;
788
789         bp->b_flags &= ~B_WRITEINPROG;
790         if ((vp = bp->b_vp)) {
791                 vp->v_numoutput--;
792                 if (vp->v_numoutput < 0)
793                         panic("vwakeup: neg numoutput");
794                 if ((vp->v_numoutput == 0) && (vp->v_flag & VBWAIT)) {
795                         vp->v_flag &= ~VBWAIT;
796                         wakeup((caddr_t) &vp->v_numoutput);
797                 }
798         }
799 }
800
801 /*
802  * Flush out and invalidate all buffers associated with a vnode.
803  * Called with the underlying object locked.
804  */
805 int
806 vinvalbuf(struct vnode *vp, int flags, struct thread *td,
807         int slpflag, int slptimeo)
808 {
809         struct buf *bp;
810         struct buf *nbp, *blist;
811         int s, error;
812         vm_object_t object;
813
814         if (flags & V_SAVE) {
815                 s = splbio();
816                 while (vp->v_numoutput) {
817                         vp->v_flag |= VBWAIT;
818                         error = tsleep((caddr_t)&vp->v_numoutput,
819                             slpflag, "vinvlbuf", slptimeo);
820                         if (error) {
821                                 splx(s);
822                                 return (error);
823                         }
824                 }
825                 if (!TAILQ_EMPTY(&vp->v_dirtyblkhd)) {
826                         splx(s);
827                         if ((error = VOP_FSYNC(vp, MNT_WAIT, td)) != 0)
828                                 return (error);
829                         s = splbio();
830                         if (vp->v_numoutput > 0 ||
831                             !TAILQ_EMPTY(&vp->v_dirtyblkhd))
832                                 panic("vinvalbuf: dirty bufs");
833                 }
834                 splx(s);
835         }
836         s = splbio();
837         for (;;) {
838                 blist = TAILQ_FIRST(&vp->v_cleanblkhd);
839                 if (!blist)
840                         blist = TAILQ_FIRST(&vp->v_dirtyblkhd);
841                 if (!blist)
842                         break;
843
844                 for (bp = blist; bp; bp = nbp) {
845                         nbp = TAILQ_NEXT(bp, b_vnbufs);
846                         if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
847                                 error = BUF_TIMELOCK(bp,
848                                     LK_EXCLUSIVE | LK_SLEEPFAIL,
849                                     "vinvalbuf", slpflag, slptimeo);
850                                 if (error == ENOLCK)
851                                         break;
852                                 splx(s);
853                                 return (error);
854                         }
855                         /*
856                          * XXX Since there are no node locks for NFS, I
857                          * believe there is a slight chance that a delayed
858                          * write will occur while sleeping just above, so
859                          * check for it.  Note that vfs_bio_awrite expects
860                          * buffers to reside on a queue, while VOP_BWRITE and
861                          * brelse do not.
862                          */
863                         if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
864                                 (flags & V_SAVE)) {
865
866                                 if (bp->b_vp == vp) {
867                                         if (bp->b_flags & B_CLUSTEROK) {
868                                                 BUF_UNLOCK(bp);
869                                                 vfs_bio_awrite(bp);
870                                         } else {
871                                                 bremfree(bp);
872                                                 bp->b_flags |= B_ASYNC;
873                                                 VOP_BWRITE(bp->b_vp, bp);
874                                         }
875                                 } else {
876                                         bremfree(bp);
877                                         (void) VOP_BWRITE(bp->b_vp, bp);
878                                 }
879                                 break;
880                         }
881                         bremfree(bp);
882                         bp->b_flags |= (B_INVAL | B_NOCACHE | B_RELBUF);
883                         bp->b_flags &= ~B_ASYNC;
884                         brelse(bp);
885                 }
886         }
887
888         /*
889          * Wait for I/O to complete.  XXX needs cleaning up.  The vnode can
890          * have write I/O in-progress but if there is a VM object then the
891          * VM object can also have read-I/O in-progress.
892          */
893         do {
894                 while (vp->v_numoutput > 0) {
895                         vp->v_flag |= VBWAIT;
896                         tsleep(&vp->v_numoutput, 0, "vnvlbv", 0);
897                 }
898                 if (VOP_GETVOBJECT(vp, &object) == 0) {
899                         while (object->paging_in_progress)
900                                 vm_object_pip_sleep(object, "vnvlbx");
901                 }
902         } while (vp->v_numoutput > 0);
903
904         splx(s);
905
906         /*
907          * Destroy the copy in the VM cache, too.
908          */
909         lwkt_gettoken(&vp->v_interlock);
910         if (VOP_GETVOBJECT(vp, &object) == 0) {
911                 vm_object_page_remove(object, 0, 0,
912                         (flags & V_SAVE) ? TRUE : FALSE);
913         }
914         lwkt_reltoken(&vp->v_interlock);
915
916         if (!TAILQ_EMPTY(&vp->v_dirtyblkhd) || !TAILQ_EMPTY(&vp->v_cleanblkhd))
917                 panic("vinvalbuf: flush failed");
918         return (0);
919 }
920
921 /*
922  * Truncate a file's buffer and pages to a specified length.  This
923  * is in lieu of the old vinvalbuf mechanism, which performed unneeded
924  * sync activity.
925  */
926 int
927 vtruncbuf(struct vnode *vp, struct thread *td, off_t length, int blksize)
928 {
929         struct buf *bp;
930         struct buf *nbp;
931         int s, anyfreed;
932         int trunclbn;
933
934         /*
935          * Round up to the *next* lbn.
936          */
937         trunclbn = (length + blksize - 1) / blksize;
938
939         s = splbio();
940 restart:
941         anyfreed = 1;
942         for (;anyfreed;) {
943                 anyfreed = 0;
944                 for (bp = TAILQ_FIRST(&vp->v_cleanblkhd); bp; bp = nbp) {
945                         nbp = TAILQ_NEXT(bp, b_vnbufs);
946                         if (bp->b_lblkno >= trunclbn) {
947                                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
948                                         BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL);
949                                         goto restart;
950                                 } else {
951                                         bremfree(bp);
952                                         bp->b_flags |= (B_INVAL | B_RELBUF);
953                                         bp->b_flags &= ~B_ASYNC;
954                                         brelse(bp);
955                                         anyfreed = 1;
956                                 }
957                                 if (nbp &&
958                                     (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
959                                     (nbp->b_vp != vp) ||
960                                     (nbp->b_flags & B_DELWRI))) {
961                                         goto restart;
962                                 }
963                         }
964                 }
965
966                 for (bp = TAILQ_FIRST(&vp->v_dirtyblkhd); bp; bp = nbp) {
967                         nbp = TAILQ_NEXT(bp, b_vnbufs);
968                         if (bp->b_lblkno >= trunclbn) {
969                                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
970                                         BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL);
971                                         goto restart;
972                                 } else {
973                                         bremfree(bp);
974                                         bp->b_flags |= (B_INVAL | B_RELBUF);
975                                         bp->b_flags &= ~B_ASYNC;
976                                         brelse(bp);
977                                         anyfreed = 1;
978                                 }
979                                 if (nbp &&
980                                     (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
981                                     (nbp->b_vp != vp) ||
982                                     (nbp->b_flags & B_DELWRI) == 0)) {
983                                         goto restart;
984                                 }
985                         }
986                 }
987         }
988
989         if (length > 0) {
990 restartsync:
991                 for (bp = TAILQ_FIRST(&vp->v_dirtyblkhd); bp; bp = nbp) {
992                         nbp = TAILQ_NEXT(bp, b_vnbufs);
993                         if ((bp->b_flags & B_DELWRI) && (bp->b_lblkno < 0)) {
994                                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
995                                         BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL);
996                                         goto restart;
997                                 } else {
998                                         bremfree(bp);
999                                         if (bp->b_vp == vp) {
1000                                                 bp->b_flags |= B_ASYNC;
1001                                         } else {
1002                                                 bp->b_flags &= ~B_ASYNC;
1003                                         }
1004                                         VOP_BWRITE(bp->b_vp, bp);
1005                                 }
1006                                 goto restartsync;
1007                         }
1008
1009                 }
1010         }
1011
1012         while (vp->v_numoutput > 0) {
1013                 vp->v_flag |= VBWAIT;
1014                 tsleep(&vp->v_numoutput, 0, "vbtrunc", 0);
1015         }
1016
1017         splx(s);
1018
1019         vnode_pager_setsize(vp, length);
1020
1021         return (0);
1022 }
1023
1024 /*
1025  * Associate a buffer with a vnode.
1026  */
1027 void
1028 bgetvp(vp, bp)
1029         struct vnode *vp;
1030         struct buf *bp;
1031 {
1032         int s;
1033
1034         KASSERT(bp->b_vp == NULL, ("bgetvp: not free"));
1035
1036         vhold(vp);
1037         bp->b_vp = vp;
1038         bp->b_dev = vn_todev(vp);
1039         /*
1040          * Insert onto list for new vnode.
1041          */
1042         s = splbio();
1043         bp->b_xflags |= BX_VNCLEAN;
1044         bp->b_xflags &= ~BX_VNDIRTY;
1045         TAILQ_INSERT_TAIL(&vp->v_cleanblkhd, bp, b_vnbufs);
1046         splx(s);
1047 }
1048
1049 /*
1050  * Disassociate a buffer from a vnode.
1051  */
1052 void
1053 brelvp(bp)
1054         struct buf *bp;
1055 {
1056         struct vnode *vp;
1057         struct buflists *listheadp;
1058         int s;
1059
1060         KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
1061
1062         /*
1063          * Delete from old vnode list, if on one.
1064          */
1065         vp = bp->b_vp;
1066         s = splbio();
1067         if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN)) {
1068                 if (bp->b_xflags & BX_VNDIRTY)
1069                         listheadp = &vp->v_dirtyblkhd;
1070                 else 
1071                         listheadp = &vp->v_cleanblkhd;
1072                 TAILQ_REMOVE(listheadp, bp, b_vnbufs);
1073                 bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
1074         }
1075         if ((vp->v_flag & VONWORKLST) && TAILQ_EMPTY(&vp->v_dirtyblkhd)) {
1076                 vp->v_flag &= ~VONWORKLST;
1077                 LIST_REMOVE(vp, v_synclist);
1078         }
1079         splx(s);
1080         bp->b_vp = (struct vnode *) 0;
1081         vdrop(vp);
1082 }
1083
1084 /*
1085  * The workitem queue.
1086  * 
1087  * It is useful to delay writes of file data and filesystem metadata
1088  * for tens of seconds so that quickly created and deleted files need
1089  * not waste disk bandwidth being created and removed. To realize this,
1090  * we append vnodes to a "workitem" queue. When running with a soft
1091  * updates implementation, most pending metadata dependencies should
1092  * not wait for more than a few seconds. Thus, mounted on block devices
1093  * are delayed only about a half the time that file data is delayed.
1094  * Similarly, directory updates are more critical, so are only delayed
1095  * about a third the time that file data is delayed. Thus, there are
1096  * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
1097  * one each second (driven off the filesystem syncer process). The
1098  * syncer_delayno variable indicates the next queue that is to be processed.
1099  * Items that need to be processed soon are placed in this queue:
1100  *
1101  *      syncer_workitem_pending[syncer_delayno]
1102  *
1103  * A delay of fifteen seconds is done by placing the request fifteen
1104  * entries later in the queue:
1105  *
1106  *      syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
1107  *
1108  */
1109
1110 /*
1111  * Add an item to the syncer work queue.
1112  */
1113 static void
1114 vn_syncer_add_to_worklist(struct vnode *vp, int delay)
1115 {
1116         int s, slot;
1117
1118         s = splbio();
1119
1120         if (vp->v_flag & VONWORKLST) {
1121                 LIST_REMOVE(vp, v_synclist);
1122         }
1123
1124         if (delay > syncer_maxdelay - 2)
1125                 delay = syncer_maxdelay - 2;
1126         slot = (syncer_delayno + delay) & syncer_mask;
1127
1128         LIST_INSERT_HEAD(&syncer_workitem_pending[slot], vp, v_synclist);
1129         vp->v_flag |= VONWORKLST;
1130         splx(s);
1131 }
1132
1133 struct  thread *updatethread;
1134 static void sched_sync (void);
1135 static struct kproc_desc up_kp = {
1136         "syncer",
1137         sched_sync,
1138         &updatethread
1139 };
1140 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp)
1141
1142 /*
1143  * System filesystem synchronizer daemon.
1144  */
1145 void 
1146 sched_sync(void)
1147 {
1148         struct synclist *slp;
1149         struct vnode *vp;
1150         long starttime;
1151         int s;
1152         struct thread *td = curthread;
1153
1154         EVENTHANDLER_REGISTER(shutdown_pre_sync, shutdown_kproc, td,
1155             SHUTDOWN_PRI_LAST);   
1156
1157         for (;;) {
1158                 kproc_suspend_loop();
1159
1160                 starttime = time_second;
1161
1162                 /*
1163                  * Push files whose dirty time has expired.  Be careful
1164                  * of interrupt race on slp queue.
1165                  */
1166                 s = splbio();
1167                 slp = &syncer_workitem_pending[syncer_delayno];
1168                 syncer_delayno += 1;
1169                 if (syncer_delayno == syncer_maxdelay)
1170                         syncer_delayno = 0;
1171                 splx(s);
1172
1173                 while ((vp = LIST_FIRST(slp)) != NULL) {
1174                         if (VOP_ISLOCKED(vp, NULL) == 0) {
1175                                 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
1176                                 (void) VOP_FSYNC(vp, MNT_LAZY, td);
1177                                 VOP_UNLOCK(vp, 0, td);
1178                         }
1179                         s = splbio();
1180                         if (LIST_FIRST(slp) == vp) {
1181                                 /*
1182                                  * Note: v_tag VT_VFS vps can remain on the
1183                                  * worklist too with no dirty blocks, but 
1184                                  * since sync_fsync() moves it to a different 
1185                                  * slot we are safe.
1186                                  */
1187                                 if (TAILQ_EMPTY(&vp->v_dirtyblkhd) &&
1188                                     !vn_isdisk(vp, NULL))
1189                                         panic("sched_sync: fsync failed vp %p tag %d", vp, vp->v_tag);
1190                                 /*
1191                                  * Put us back on the worklist.  The worklist
1192                                  * routine will remove us from our current
1193                                  * position and then add us back in at a later
1194                                  * position.
1195                                  */
1196                                 vn_syncer_add_to_worklist(vp, syncdelay);
1197                         }
1198                         splx(s);
1199                 }
1200
1201                 /*
1202                  * Do soft update processing.
1203                  */
1204                 if (bioops.io_sync)
1205                         (*bioops.io_sync)(NULL);
1206
1207                 /*
1208                  * The variable rushjob allows the kernel to speed up the
1209                  * processing of the filesystem syncer process. A rushjob
1210                  * value of N tells the filesystem syncer to process the next
1211                  * N seconds worth of work on its queue ASAP. Currently rushjob
1212                  * is used by the soft update code to speed up the filesystem
1213                  * syncer process when the incore state is getting so far
1214                  * ahead of the disk that the kernel memory pool is being
1215                  * threatened with exhaustion.
1216                  */
1217                 if (rushjob > 0) {
1218                         rushjob -= 1;
1219                         continue;
1220                 }
1221                 /*
1222                  * If it has taken us less than a second to process the
1223                  * current work, then wait. Otherwise start right over
1224                  * again. We can still lose time if any single round
1225                  * takes more than two seconds, but it does not really
1226                  * matter as we are just trying to generally pace the
1227                  * filesystem activity.
1228                  */
1229                 if (time_second == starttime)
1230                         tsleep(&lbolt, 0, "syncer", 0);
1231         }
1232 }
1233
1234 /*
1235  * Request the syncer daemon to speed up its work.
1236  * We never push it to speed up more than half of its
1237  * normal turn time, otherwise it could take over the cpu.
1238  *
1239  * YYY wchan field protected by the BGL.
1240  */
1241 int
1242 speedup_syncer()
1243 {
1244         crit_enter();
1245         if (updatethread->td_wchan == &lbolt) { /* YYY */
1246                 unsleep(updatethread);
1247                 lwkt_schedule(updatethread);
1248         }
1249         crit_exit();
1250         if (rushjob < syncdelay / 2) {
1251                 rushjob += 1;
1252                 stat_rush_requests += 1;
1253                 return (1);
1254         }
1255         return(0);
1256 }
1257
1258 /*
1259  * Associate a p-buffer with a vnode.
1260  *
1261  * Also sets B_PAGING flag to indicate that vnode is not fully associated
1262  * with the buffer.  i.e. the bp has not been linked into the vnode or
1263  * ref-counted.
1264  */
1265 void
1266 pbgetvp(vp, bp)
1267         struct vnode *vp;
1268         struct buf *bp;
1269 {
1270
1271         KASSERT(bp->b_vp == NULL, ("pbgetvp: not free"));
1272
1273         bp->b_vp = vp;
1274         bp->b_flags |= B_PAGING;
1275         bp->b_dev = vn_todev(vp);
1276 }
1277
1278 /*
1279  * Disassociate a p-buffer from a vnode.
1280  */
1281 void
1282 pbrelvp(bp)
1283         struct buf *bp;
1284 {
1285
1286         KASSERT(bp->b_vp != NULL, ("pbrelvp: NULL"));
1287
1288         /* XXX REMOVE ME */
1289         if (TAILQ_NEXT(bp, b_vnbufs) != NULL) {
1290                 panic(
1291                     "relpbuf(): b_vp was probably reassignbuf()d %p %x", 
1292                     bp,
1293                     (int)bp->b_flags
1294                 );
1295         }
1296         bp->b_vp = (struct vnode *) 0;
1297         bp->b_flags &= ~B_PAGING;
1298 }
1299
1300 void
1301 pbreassignbuf(bp, newvp)
1302         struct buf *bp;
1303         struct vnode *newvp;
1304 {
1305         if ((bp->b_flags & B_PAGING) == 0) {
1306                 panic(
1307                     "pbreassignbuf() on non phys bp %p", 
1308                     bp
1309                 );
1310         }
1311         bp->b_vp = newvp;
1312 }
1313
1314 /*
1315  * Reassign a buffer from one vnode to another.
1316  * Used to assign file specific control information
1317  * (indirect blocks) to the vnode to which they belong.
1318  */
1319 void
1320 reassignbuf(bp, newvp)
1321         struct buf *bp;
1322         struct vnode *newvp;
1323 {
1324         struct buflists *listheadp;
1325         int delay;
1326         int s;
1327
1328         if (newvp == NULL) {
1329                 printf("reassignbuf: NULL");
1330                 return;
1331         }
1332         ++reassignbufcalls;
1333
1334         /*
1335          * B_PAGING flagged buffers cannot be reassigned because their vp
1336          * is not fully linked in.
1337          */
1338         if (bp->b_flags & B_PAGING)
1339                 panic("cannot reassign paging buffer");
1340
1341         s = splbio();
1342         /*
1343          * Delete from old vnode list, if on one.
1344          */
1345         if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN)) {
1346                 if (bp->b_xflags & BX_VNDIRTY)
1347                         listheadp = &bp->b_vp->v_dirtyblkhd;
1348                 else 
1349                         listheadp = &bp->b_vp->v_cleanblkhd;
1350                 TAILQ_REMOVE(listheadp, bp, b_vnbufs);
1351                 bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
1352                 if (bp->b_vp != newvp) {
1353                         vdrop(bp->b_vp);
1354                         bp->b_vp = NULL;        /* for clarification */
1355                 }
1356         }
1357         /*
1358          * If dirty, put on list of dirty buffers; otherwise insert onto list
1359          * of clean buffers.
1360          */
1361         if (bp->b_flags & B_DELWRI) {
1362                 struct buf *tbp;
1363
1364                 listheadp = &newvp->v_dirtyblkhd;
1365                 if ((newvp->v_flag & VONWORKLST) == 0) {
1366                         switch (newvp->v_type) {
1367                         case VDIR:
1368                                 delay = dirdelay;
1369                                 break;
1370                         case VCHR:
1371                         case VBLK:
1372                                 if (newvp->v_specmountpoint != NULL) {
1373                                         delay = metadelay;
1374                                         break;
1375                                 }
1376                                 /* fall through */
1377                         default:
1378                                 delay = filedelay;
1379                         }
1380                         vn_syncer_add_to_worklist(newvp, delay);
1381                 }
1382                 bp->b_xflags |= BX_VNDIRTY;
1383                 tbp = TAILQ_FIRST(listheadp);
1384                 if (tbp == NULL ||
1385                     bp->b_lblkno == 0 ||
1386                     (bp->b_lblkno > 0 && tbp->b_lblkno < 0) ||
1387                     (bp->b_lblkno > 0 && bp->b_lblkno < tbp->b_lblkno)) {
1388                         TAILQ_INSERT_HEAD(listheadp, bp, b_vnbufs);
1389                         ++reassignbufsortgood;
1390                 } else if (bp->b_lblkno < 0) {
1391                         TAILQ_INSERT_TAIL(listheadp, bp, b_vnbufs);
1392                         ++reassignbufsortgood;
1393                 } else if (reassignbufmethod == 1) {
1394                         /*
1395                          * New sorting algorithm, only handle sequential case,
1396                          * otherwise append to end (but before metadata)
1397                          */
1398                         if ((tbp = gbincore(newvp, bp->b_lblkno - 1)) != NULL &&
1399                             (tbp->b_xflags & BX_VNDIRTY)) {
1400                                 /*
1401                                  * Found the best place to insert the buffer
1402                                  */
1403                                 TAILQ_INSERT_AFTER(listheadp, tbp, bp, b_vnbufs);
1404                                 ++reassignbufsortgood;
1405                         } else {
1406                                 /*
1407                                  * Missed, append to end, but before meta-data.
1408                                  * We know that the head buffer in the list is
1409                                  * not meta-data due to prior conditionals.
1410                                  *
1411                                  * Indirect effects:  NFS second stage write
1412                                  * tends to wind up here, giving maximum 
1413                                  * distance between the unstable write and the
1414                                  * commit rpc.
1415                                  */
1416                                 tbp = TAILQ_LAST(listheadp, buflists);
1417                                 while (tbp && tbp->b_lblkno < 0)
1418                                         tbp = TAILQ_PREV(tbp, buflists, b_vnbufs);
1419                                 TAILQ_INSERT_AFTER(listheadp, tbp, bp, b_vnbufs);
1420                                 ++reassignbufsortbad;
1421                         }
1422                 } else {
1423                         /*
1424                          * Old sorting algorithm, scan queue and insert
1425                          */
1426                         struct buf *ttbp;
1427                         while ((ttbp = TAILQ_NEXT(tbp, b_vnbufs)) &&
1428                             (ttbp->b_lblkno < bp->b_lblkno)) {
1429                                 ++reassignbufloops;
1430                                 tbp = ttbp;
1431                         }
1432                         TAILQ_INSERT_AFTER(listheadp, tbp, bp, b_vnbufs);
1433                 }
1434         } else {
1435                 bp->b_xflags |= BX_VNCLEAN;
1436                 TAILQ_INSERT_TAIL(&newvp->v_cleanblkhd, bp, b_vnbufs);
1437                 if ((newvp->v_flag & VONWORKLST) &&
1438                     TAILQ_EMPTY(&newvp->v_dirtyblkhd)) {
1439                         newvp->v_flag &= ~VONWORKLST;
1440                         LIST_REMOVE(newvp, v_synclist);
1441                 }
1442         }
1443         if (bp->b_vp != newvp) {
1444                 bp->b_vp = newvp;
1445                 vhold(bp->b_vp);
1446         }
1447         splx(s);
1448 }
1449
1450 /*
1451  * Create a vnode for a block device.
1452  * Used for mounting the root file system.
1453  */
1454 int
1455 bdevvp(dev, vpp)
1456         dev_t dev;
1457         struct vnode **vpp;
1458 {
1459         struct vnode *vp;
1460         struct vnode *nvp;
1461         int error;
1462
1463         if (dev == NODEV) {
1464                 *vpp = NULLVP;
1465                 return (ENXIO);
1466         }
1467         error = getnewvnode(VT_NON, (struct mount *)0, spec_vnodeop_p, &nvp);
1468         if (error) {
1469                 *vpp = NULLVP;
1470                 return (error);
1471         }
1472         vp = nvp;
1473         vp->v_type = VBLK;
1474         addalias(vp, dev);
1475         *vpp = vp;
1476         return (0);
1477 }
1478
1479 /*
1480  * Add a vnode to the alias list hung off the dev_t.
1481  *
1482  * The reason for this gunk is that multiple vnodes can reference
1483  * the same physical device, so checking vp->v_usecount to see
1484  * how many users there are is inadequate; the v_usecount for
1485  * the vnodes need to be accumulated.  vcount() does that.
1486  */
1487 void
1488 addaliasu(struct vnode *nvp, udev_t nvp_rdev)
1489 {
1490         dev_t dev;
1491
1492         if (nvp->v_type != VBLK && nvp->v_type != VCHR)
1493                 panic("addaliasu on non-special vnode");
1494         dev = udev2dev(nvp_rdev, nvp->v_type == VBLK ? 1 : 0);
1495         if (dev != NODEV) {
1496                 nvp->v_rdev = dev;
1497                 addalias(nvp, dev);
1498         } else
1499                 nvp->v_rdev = NULL;
1500 }
1501
1502 void
1503 addalias(struct vnode *nvp, dev_t dev)
1504 {
1505
1506         if (nvp->v_type != VBLK && nvp->v_type != VCHR)
1507                 panic("addalias on non-special vnode");
1508
1509         nvp->v_rdev = dev;
1510         lwkt_gettoken(&spechash_token);
1511         SLIST_INSERT_HEAD(&dev->si_hlist, nvp, v_specnext);
1512         lwkt_reltoken(&spechash_token);
1513 }
1514
1515 /*
1516  * Grab a particular vnode from the free list, increment its
1517  * reference count and lock it. The vnode lock bit is set if the
1518  * vnode is being eliminated in vgone. The process is awakened
1519  * when the transition is completed, and an error returned to
1520  * indicate that the vnode is no longer usable (possibly having
1521  * been changed to a new file system type).
1522  */
1523 int
1524 vget(vp, flags, td)
1525         struct vnode *vp;
1526         int flags;
1527         struct thread *td;
1528 {
1529         int error;
1530
1531         /*
1532          * If the vnode is in the process of being cleaned out for
1533          * another use, we wait for the cleaning to finish and then
1534          * return failure. Cleaning is determined by checking that
1535          * the VXLOCK flag is set.
1536          */
1537         if ((flags & LK_INTERLOCK) == 0) {
1538                 lwkt_gettoken(&vp->v_interlock);
1539         }
1540         if (vp->v_flag & VXLOCK) {
1541                 if (vp->v_vxproc == curproc) {
1542 #if 0
1543                         /* this can now occur in normal operation */
1544                         log(LOG_INFO, "VXLOCK interlock avoided\n");
1545 #endif
1546                 } else {
1547                         vp->v_flag |= VXWANT;
1548                         lwkt_reltoken(&vp->v_interlock);
1549                         tsleep((caddr_t)vp, 0, "vget", 0);
1550                         return (ENOENT);
1551                 }
1552         }
1553
1554         vp->v_usecount++;
1555
1556         if (VSHOULDBUSY(vp))
1557                 vbusy(vp);
1558         if (flags & LK_TYPE_MASK) {
1559                 if ((error = vn_lock(vp, flags | LK_INTERLOCK, td)) != 0) {
1560                         /*
1561                          * must expand vrele here because we do not want
1562                          * to call VOP_INACTIVE if the reference count
1563                          * drops back to zero since it was never really
1564                          * active. We must remove it from the free list
1565                          * before sleeping so that multiple processes do
1566                          * not try to recycle it.
1567                          */
1568                         lwkt_gettoken(&vp->v_interlock);
1569                         vp->v_usecount--;
1570                         if (VSHOULDFREE(vp))
1571                                 vfree(vp);
1572                         else
1573                                 vlruvp(vp);
1574                         lwkt_reltoken(&vp->v_interlock);
1575                 }
1576                 return (error);
1577         }
1578         lwkt_reltoken(&vp->v_interlock);
1579         return (0);
1580 }
1581
1582 void
1583 vref(struct vnode *vp)
1584 {
1585         lwkt_gettoken(&vp->v_interlock);
1586         vp->v_usecount++;
1587         lwkt_reltoken(&vp->v_interlock);
1588 }
1589
1590 /*
1591  * Vnode put/release.
1592  * If count drops to zero, call inactive routine and return to freelist.
1593  */
1594 void
1595 vrele(struct vnode *vp)
1596 {
1597         struct thread *td = curthread;  /* XXX */
1598
1599         KASSERT(vp != NULL, ("vrele: null vp"));
1600
1601         lwkt_gettoken(&vp->v_interlock);
1602
1603         if (vp->v_usecount > 1) {
1604
1605                 vp->v_usecount--;
1606                 lwkt_reltoken(&vp->v_interlock);
1607
1608                 return;
1609         }
1610
1611         if (vp->v_usecount == 1) {
1612                 vp->v_usecount--;
1613                 /*
1614                  * We must call VOP_INACTIVE with the node locked.
1615                  * If we are doing a vpu, the node is already locked,
1616                  * but, in the case of vrele, we must explicitly lock
1617                  * the vnode before calling VOP_INACTIVE
1618                  */
1619
1620                 if (vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK, td) == 0)
1621                         VOP_INACTIVE(vp, td);
1622                 if (VSHOULDFREE(vp))
1623                         vfree(vp);
1624                 else
1625                         vlruvp(vp);
1626         } else {
1627 #ifdef DIAGNOSTIC
1628                 vprint("vrele: negative ref count", vp);
1629                 lwkt_reltoken(&vp->v_interlock);
1630 #endif
1631                 panic("vrele: negative ref cnt");
1632         }
1633 }
1634
1635 void
1636 vput(struct vnode *vp)
1637 {
1638         struct thread *td = curthread;  /* XXX */
1639
1640         KASSERT(vp != NULL, ("vput: null vp"));
1641
1642         lwkt_gettoken(&vp->v_interlock);
1643
1644         if (vp->v_usecount > 1) {
1645                 vp->v_usecount--;
1646                 VOP_UNLOCK(vp, LK_INTERLOCK, td);
1647                 return;
1648         }
1649
1650         if (vp->v_usecount == 1) {
1651                 vp->v_usecount--;
1652                 /*
1653                  * We must call VOP_INACTIVE with the node locked.
1654                  * If we are doing a vpu, the node is already locked,
1655                  * so we just need to release the vnode mutex.
1656                  */
1657                 lwkt_reltoken(&vp->v_interlock);
1658                 VOP_INACTIVE(vp, td);
1659                 if (VSHOULDFREE(vp))
1660                         vfree(vp);
1661                 else
1662                         vlruvp(vp);
1663         } else {
1664 #ifdef DIAGNOSTIC
1665                 vprint("vput: negative ref count", vp);
1666 #endif
1667                 panic("vput: negative ref cnt");
1668         }
1669 }
1670
1671 /*
1672  * Somebody doesn't want the vnode recycled.
1673  */
1674 void
1675 vhold(vp)
1676         struct vnode *vp;
1677 {
1678         int s;
1679
1680         s = splbio();
1681         vp->v_holdcnt++;
1682         if (VSHOULDBUSY(vp))
1683                 vbusy(vp);
1684         splx(s);
1685 }
1686
1687 /*
1688  * One less who cares about this vnode.
1689  */
1690 void
1691 vdrop(vp)
1692         struct vnode *vp;
1693 {
1694         int s;
1695
1696         s = splbio();
1697         if (vp->v_holdcnt <= 0)
1698                 panic("vdrop: holdcnt");
1699         vp->v_holdcnt--;
1700         if (VSHOULDFREE(vp))
1701                 vfree(vp);
1702         splx(s);
1703 }
1704
1705 /*
1706  * Remove any vnodes in the vnode table belonging to mount point mp.
1707  *
1708  * If FORCECLOSE is not specified, there should not be any active ones,
1709  * return error if any are found (nb: this is a user error, not a
1710  * system error). If FORCECLOSE is specified, detach any active vnodes
1711  * that are found.
1712  *
1713  * If WRITECLOSE is set, only flush out regular file vnodes open for
1714  * writing.
1715  *
1716  * SKIPSYSTEM causes any vnodes marked VSYSTEM to be skipped.
1717  *
1718  * `rootrefs' specifies the base reference count for the root vnode
1719  * of this filesystem. The root vnode is considered busy if its
1720  * v_usecount exceeds this value. On a successful return, vflush()
1721  * will call vrele() on the root vnode exactly rootrefs times.
1722  * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
1723  * be zero.
1724  */
1725 #ifdef DIAGNOSTIC
1726 static int busyprt = 0;         /* print out busy vnodes */
1727 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "");
1728 #endif
1729
1730 int
1731 vflush(mp, rootrefs, flags)
1732         struct mount *mp;
1733         int rootrefs;
1734         int flags;
1735 {
1736         struct thread *td = curthread;  /* XXX */
1737         struct vnode *vp, *nvp, *rootvp = NULL;
1738         struct vattr vattr;
1739         int busy = 0, error;
1740
1741         if (rootrefs > 0) {
1742                 KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
1743                     ("vflush: bad args"));
1744                 /*
1745                  * Get the filesystem root vnode. We can vput() it
1746                  * immediately, since with rootrefs > 0, it won't go away.
1747                  */
1748                 if ((error = VFS_ROOT(mp, &rootvp)) != 0)
1749                         return (error);
1750                 vput(rootvp);
1751         }
1752         lwkt_gettoken(&mntvnode_token);
1753 loop:
1754         for (vp = TAILQ_FIRST(&mp->mnt_nvnodelist); vp; vp = nvp) {
1755                 /*
1756                  * Make sure this vnode wasn't reclaimed in getnewvnode().
1757                  * Start over if it has (it won't be on the list anymore).
1758                  */
1759                 if (vp->v_mount != mp)
1760                         goto loop;
1761                 nvp = TAILQ_NEXT(vp, v_nmntvnodes);
1762
1763                 lwkt_gettoken(&vp->v_interlock);
1764                 /*
1765                  * Skip over a vnodes marked VSYSTEM.
1766                  */
1767                 if ((flags & SKIPSYSTEM) && (vp->v_flag & VSYSTEM)) {
1768                         lwkt_reltoken(&vp->v_interlock);
1769                         continue;
1770                 }
1771                 /*
1772                  * If WRITECLOSE is set, flush out unlinked but still open
1773                  * files (even if open only for reading) and regular file
1774                  * vnodes open for writing. 
1775                  */
1776                 if ((flags & WRITECLOSE) &&
1777                     (vp->v_type == VNON ||
1778                     (VOP_GETATTR(vp, &vattr, td) == 0 &&
1779                     vattr.va_nlink > 0)) &&
1780                     (vp->v_writecount == 0 || vp->v_type != VREG)) {
1781                         lwkt_reltoken(&vp->v_interlock);
1782                         continue;
1783                 }
1784
1785                 /*
1786                  * With v_usecount == 0, all we need to do is clear out the
1787                  * vnode data structures and we are done.
1788                  */
1789                 if (vp->v_usecount == 0) {
1790                         lwkt_reltoken(&mntvnode_token);
1791                         vgonel(vp, td);
1792                         lwkt_gettoken(&mntvnode_token);
1793                         continue;
1794                 }
1795
1796                 /*
1797                  * If FORCECLOSE is set, forcibly close the vnode. For block
1798                  * or character devices, revert to an anonymous device. For
1799                  * all other files, just kill them.
1800                  */
1801                 if (flags & FORCECLOSE) {
1802                         lwkt_reltoken(&mntvnode_token);
1803                         if (vp->v_type != VBLK && vp->v_type != VCHR) {
1804                                 vgonel(vp, td);
1805                         } else {
1806                                 vclean(vp, 0, td);
1807                                 vp->v_op = spec_vnodeop_p;
1808                                 insmntque(vp, (struct mount *) 0);
1809                         }
1810                         lwkt_gettoken(&mntvnode_token);
1811                         continue;
1812                 }
1813 #ifdef DIAGNOSTIC
1814                 if (busyprt)
1815                         vprint("vflush: busy vnode", vp);
1816 #endif
1817                 lwkt_reltoken(&vp->v_interlock);
1818                 busy++;
1819         }
1820         lwkt_reltoken(&mntvnode_token);
1821         if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
1822                 /*
1823                  * If just the root vnode is busy, and if its refcount
1824                  * is equal to `rootrefs', then go ahead and kill it.
1825                  */
1826                 lwkt_gettoken(&rootvp->v_interlock);
1827                 KASSERT(busy > 0, ("vflush: not busy"));
1828                 KASSERT(rootvp->v_usecount >= rootrefs, ("vflush: rootrefs"));
1829                 if (busy == 1 && rootvp->v_usecount == rootrefs) {
1830                         vgonel(rootvp, td);
1831                         busy = 0;
1832                 } else
1833                         lwkt_reltoken(&rootvp->v_interlock);
1834         }
1835         if (busy)
1836                 return (EBUSY);
1837         for (; rootrefs > 0; rootrefs--)
1838                 vrele(rootvp);
1839         return (0);
1840 }
1841
1842 /*
1843  * We do not want to recycle the vnode too quickly.
1844  *
1845  * XXX we can't move vp's around the nvnodelist without really screwing
1846  * up the efficiency of filesystem SYNC and friends.  This code is 
1847  * disabled until we fix the syncing code's scanning algorithm.
1848  */
1849 static void
1850 vlruvp(struct vnode *vp)
1851 {
1852 #if 0
1853         struct mount *mp;
1854
1855         if ((mp = vp->v_mount) != NULL) {
1856                 lwkt_gettoken(&mntvnode_token);
1857                 TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1858                 TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1859                 lwkt_reltoken(&mntvnode_token);
1860         }
1861 #endif
1862 }
1863
1864 /*
1865  * Disassociate the underlying file system from a vnode.
1866  */
1867 static void
1868 vclean(struct vnode *vp, int flags, struct thread *td)
1869 {
1870         int active;
1871
1872         /*
1873          * Check to see if the vnode is in use. If so we have to reference it
1874          * before we clean it out so that its count cannot fall to zero and
1875          * generate a race against ourselves to recycle it.
1876          */
1877         if ((active = vp->v_usecount))
1878                 vp->v_usecount++;
1879
1880         /*
1881          * Prevent the vnode from being recycled or brought into use while we
1882          * clean it out.
1883          */
1884         if (vp->v_flag & VXLOCK)
1885                 panic("vclean: deadlock");
1886         vp->v_flag |= VXLOCK;
1887         vp->v_vxproc = curproc;
1888         /*
1889          * Even if the count is zero, the VOP_INACTIVE routine may still
1890          * have the object locked while it cleans it out. The VOP_LOCK
1891          * ensures that the VOP_INACTIVE routine is done with its work.
1892          * For active vnodes, it ensures that no other activity can
1893          * occur while the underlying object is being cleaned out.
1894          */
1895         VOP_LOCK(vp, LK_DRAIN | LK_INTERLOCK, td);
1896
1897         /*
1898          * Clean out any buffers associated with the vnode.
1899          */
1900         vinvalbuf(vp, V_SAVE, td, 0, 0);
1901
1902         VOP_DESTROYVOBJECT(vp);
1903
1904         /*
1905          * If purging an active vnode, it must be closed and
1906          * deactivated before being reclaimed. Note that the
1907          * VOP_INACTIVE will unlock the vnode.
1908          */
1909         if (active) {
1910                 if (flags & DOCLOSE)
1911                         VOP_CLOSE(vp, FNONBLOCK, td);
1912                 VOP_INACTIVE(vp, td);
1913         } else {
1914                 /*
1915                  * Any other processes trying to obtain this lock must first
1916                  * wait for VXLOCK to clear, then call the new lock operation.
1917                  */
1918                 VOP_UNLOCK(vp, 0, td);
1919         }
1920         /*
1921          * Reclaim the vnode.
1922          */
1923         if (VOP_RECLAIM(vp, td))
1924                 panic("vclean: cannot reclaim");
1925
1926         if (active) {
1927                 /*
1928                  * Inline copy of vrele() since VOP_INACTIVE
1929                  * has already been called.
1930                  */
1931                 lwkt_gettoken(&vp->v_interlock);
1932                 if (--vp->v_usecount <= 0) {
1933 #ifdef DIAGNOSTIC
1934                         if (vp->v_usecount < 0 || vp->v_writecount != 0) {
1935                                 vprint("vclean: bad ref count", vp);
1936                                 panic("vclean: ref cnt");
1937                         }
1938 #endif
1939                         vfree(vp);
1940                 }
1941                 lwkt_reltoken(&vp->v_interlock);
1942         }
1943
1944         cache_purge(vp);
1945         vp->v_vnlock = NULL;
1946
1947         if (VSHOULDFREE(vp))
1948                 vfree(vp);
1949         
1950         /*
1951          * Done with purge, notify sleepers of the grim news.
1952          */
1953         vp->v_op = dead_vnodeop_p;
1954         vn_pollgone(vp);
1955         vp->v_tag = VT_NON;
1956         vp->v_flag &= ~VXLOCK;
1957         vp->v_vxproc = NULL;
1958         if (vp->v_flag & VXWANT) {
1959                 vp->v_flag &= ~VXWANT;
1960                 wakeup((caddr_t) vp);
1961         }
1962 }
1963
1964 /*
1965  * Eliminate all activity associated with the requested vnode
1966  * and with all vnodes aliased to the requested vnode.
1967  */
1968 int
1969 vop_revoke(ap)
1970         struct vop_revoke_args /* {
1971                 struct vnode *a_vp;
1972                 int a_flags;
1973         } */ *ap;
1974 {
1975         struct vnode *vp, *vq;
1976         dev_t dev;
1977
1978         KASSERT((ap->a_flags & REVOKEALL) != 0, ("vop_revoke"));
1979
1980         vp = ap->a_vp;
1981         /*
1982          * If a vgone (or vclean) is already in progress,
1983          * wait until it is done and return.
1984          */
1985         if (vp->v_flag & VXLOCK) {
1986                 vp->v_flag |= VXWANT;
1987                 lwkt_reltoken(&vp->v_interlock);
1988                 tsleep((caddr_t)vp, 0, "vop_revokeall", 0);
1989                 return (0);
1990         }
1991         dev = vp->v_rdev;
1992         for (;;) {
1993                 lwkt_gettoken(&spechash_token);
1994                 vq = SLIST_FIRST(&dev->si_hlist);
1995                 lwkt_reltoken(&spechash_token);
1996                 if (!vq)
1997                         break;
1998                 vgone(vq);
1999         }
2000         return (0);
2001 }
2002
2003 /*
2004  * Recycle an unused vnode to the front of the free list.
2005  * Release the passed interlock if the vnode will be recycled.
2006  */
2007 int
2008 vrecycle(struct vnode *vp, struct lwkt_token *inter_lkp, struct thread *td)
2009 {
2010         lwkt_gettoken(&vp->v_interlock);
2011         if (vp->v_usecount == 0) {
2012                 if (inter_lkp) {
2013                         lwkt_reltoken(inter_lkp);
2014                 }
2015                 vgonel(vp, td);
2016                 return (1);
2017         }
2018         lwkt_reltoken(&vp->v_interlock);
2019         return (0);
2020 }
2021
2022 /*
2023  * Eliminate all activity associated with a vnode
2024  * in preparation for reuse.
2025  */
2026 void
2027 vgone(struct vnode *vp)
2028 {
2029         struct thread *td = curthread;  /* XXX */
2030
2031         lwkt_gettoken(&vp->v_interlock);
2032         vgonel(vp, td);
2033 }
2034
2035 /*
2036  * vgone, with the vp interlock held.
2037  */
2038 void
2039 vgonel(struct vnode *vp, struct thread *td)
2040 {
2041         int s;
2042
2043         /*
2044          * If a vgone (or vclean) is already in progress,
2045          * wait until it is done and return.
2046          */
2047         if (vp->v_flag & VXLOCK) {
2048                 vp->v_flag |= VXWANT;
2049                 lwkt_reltoken(&vp->v_interlock);
2050                 tsleep((caddr_t)vp, 0, "vgone", 0);
2051                 return;
2052         }
2053
2054         /*
2055          * Clean out the filesystem specific data.
2056          */
2057         vclean(vp, DOCLOSE, td);
2058         lwkt_gettoken(&vp->v_interlock);
2059
2060         /*
2061          * Delete from old mount point vnode list, if on one.
2062          */
2063         if (vp->v_mount != NULL)
2064                 insmntque(vp, (struct mount *)0);
2065         /*
2066          * If special device, remove it from special device alias list
2067          * if it is on one.
2068          */
2069         if ((vp->v_type == VBLK || vp->v_type == VCHR) && vp->v_rdev != NULL) {
2070                 lwkt_gettoken(&spechash_token);
2071                 SLIST_REMOVE(&vp->v_hashchain, vp, vnode, v_specnext);
2072                 freedev(vp->v_rdev);
2073                 lwkt_reltoken(&spechash_token);
2074                 vp->v_rdev = NULL;
2075         }
2076
2077         /*
2078          * If it is on the freelist and not already at the head,
2079          * move it to the head of the list. The test of the
2080          * VDOOMED flag and the reference count of zero is because
2081          * it will be removed from the free list by getnewvnode,
2082          * but will not have its reference count incremented until
2083          * after calling vgone. If the reference count were
2084          * incremented first, vgone would (incorrectly) try to
2085          * close the previous instance of the underlying object.
2086          */
2087         if (vp->v_usecount == 0 && !(vp->v_flag & VDOOMED)) {
2088                 s = splbio();
2089                 lwkt_gettoken(&vnode_free_list_token);
2090                 if (vp->v_flag & VFREE)
2091                         TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
2092                 else
2093                         freevnodes++;
2094                 vp->v_flag |= VFREE;
2095                 TAILQ_INSERT_HEAD(&vnode_free_list, vp, v_freelist);
2096                 lwkt_reltoken(&vnode_free_list_token);
2097                 splx(s);
2098         }
2099
2100         vp->v_type = VBAD;
2101         lwkt_reltoken(&vp->v_interlock);
2102 }
2103
2104 /*
2105  * Lookup a vnode by device number.
2106  */
2107 int
2108 vfinddev(dev, type, vpp)
2109         dev_t dev;
2110         enum vtype type;
2111         struct vnode **vpp;
2112 {
2113         struct vnode *vp;
2114
2115         lwkt_gettoken(&spechash_token);
2116         SLIST_FOREACH(vp, &dev->si_hlist, v_specnext) {
2117                 if (type == vp->v_type) {
2118                         *vpp = vp;
2119                         lwkt_reltoken(&spechash_token);
2120                         return (1);
2121                 }
2122         }
2123         lwkt_reltoken(&spechash_token);
2124         return (0);
2125 }
2126
2127 /*
2128  * Calculate the total number of references to a special device.
2129  */
2130 int
2131 vcount(vp)
2132         struct vnode *vp;
2133 {
2134         struct vnode *vq;
2135         int count;
2136
2137         count = 0;
2138         lwkt_gettoken(&spechash_token);
2139         SLIST_FOREACH(vq, &vp->v_hashchain, v_specnext)
2140                 count += vq->v_usecount;
2141         lwkt_reltoken(&spechash_token);
2142         return (count);
2143 }
2144
2145 /*
2146  * Same as above, but using the dev_t as argument
2147  */
2148
2149 int
2150 count_dev(dev)
2151         dev_t dev;
2152 {
2153         struct vnode *vp;
2154
2155         vp = SLIST_FIRST(&dev->si_hlist);
2156         if (vp == NULL)
2157                 return (0);
2158         return(vcount(vp));
2159 }
2160
2161 /*
2162  * Print out a description of a vnode.
2163  */
2164 static char *typename[] =
2165 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD"};
2166
2167 void
2168 vprint(label, vp)
2169         char *label;
2170         struct vnode *vp;
2171 {
2172         char buf[96];
2173
2174         if (label != NULL)
2175                 printf("%s: %p: ", label, (void *)vp);
2176         else
2177                 printf("%p: ", (void *)vp);
2178         printf("type %s, usecount %d, writecount %d, refcount %d,",
2179             typename[vp->v_type], vp->v_usecount, vp->v_writecount,
2180             vp->v_holdcnt);
2181         buf[0] = '\0';
2182         if (vp->v_flag & VROOT)
2183                 strcat(buf, "|VROOT");
2184         if (vp->v_flag & VTEXT)
2185                 strcat(buf, "|VTEXT");
2186         if (vp->v_flag & VSYSTEM)
2187                 strcat(buf, "|VSYSTEM");
2188         if (vp->v_flag & VXLOCK)
2189                 strcat(buf, "|VXLOCK");
2190         if (vp->v_flag & VXWANT)
2191                 strcat(buf, "|VXWANT");
2192         if (vp->v_flag & VBWAIT)
2193                 strcat(buf, "|VBWAIT");
2194         if (vp->v_flag & VDOOMED)
2195                 strcat(buf, "|VDOOMED");
2196         if (vp->v_flag & VFREE)
2197                 strcat(buf, "|VFREE");
2198         if (vp->v_flag & VOBJBUF)
2199                 strcat(buf, "|VOBJBUF");
2200         if (buf[0] != '\0')
2201                 printf(" flags (%s)", &buf[1]);
2202         if (vp->v_data == NULL) {
2203                 printf("\n");
2204         } else {
2205                 printf("\n\t");
2206                 VOP_PRINT(vp);
2207         }
2208 }
2209
2210 #ifdef DDB
2211 #include <ddb/ddb.h>
2212 /*
2213  * List all of the locked vnodes in the system.
2214  * Called when debugging the kernel.
2215  */
2216 DB_SHOW_COMMAND(lockedvnodes, lockedvnodes)
2217 {
2218         struct thread *td = curthread;  /* XXX */
2219         struct mount *mp, *nmp;
2220         struct vnode *vp;
2221
2222         printf("Locked vnodes\n");
2223         lwkt_gettoken(&mountlist_token);
2224         for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
2225                 if (vfs_busy(mp, LK_NOWAIT, &mountlist_token, td)) {
2226                         nmp = TAILQ_NEXT(mp, mnt_list);
2227                         continue;
2228                 }
2229                 TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
2230                         if (VOP_ISLOCKED(vp, NULL))
2231                                 vprint((char *)0, vp);
2232                 }
2233                 lwkt_gettoken(&mountlist_token);
2234                 nmp = TAILQ_NEXT(mp, mnt_list);
2235                 vfs_unbusy(mp, td);
2236         }
2237         lwkt_reltoken(&mountlist_token);
2238 }
2239 #endif
2240
2241 /*
2242  * Top level filesystem related information gathering.
2243  */
2244 static int      sysctl_ovfs_conf (SYSCTL_HANDLER_ARGS);
2245
2246 static int
2247 vfs_sysctl(SYSCTL_HANDLER_ARGS)
2248 {
2249         int *name = (int *)arg1 - 1;    /* XXX */
2250         u_int namelen = arg2 + 1;       /* XXX */
2251         struct vfsconf *vfsp;
2252
2253 #if 1 || defined(COMPAT_PRELITE2)
2254         /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
2255         if (namelen == 1)
2256                 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
2257 #endif
2258
2259 #ifdef notyet
2260         /* all sysctl names at this level are at least name and field */
2261         if (namelen < 2)
2262                 return (ENOTDIR);               /* overloaded */
2263         if (name[0] != VFS_GENERIC) {
2264                 for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next)
2265                         if (vfsp->vfc_typenum == name[0])
2266                                 break;
2267                 if (vfsp == NULL)
2268                         return (EOPNOTSUPP);
2269                 return ((*vfsp->vfc_vfsops->vfs_sysctl)(&name[1], namelen - 1,
2270                     oldp, oldlenp, newp, newlen, p));
2271         }
2272 #endif
2273         switch (name[1]) {
2274         case VFS_MAXTYPENUM:
2275                 if (namelen != 2)
2276                         return (ENOTDIR);
2277                 return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
2278         case VFS_CONF:
2279                 if (namelen != 3)
2280                         return (ENOTDIR);       /* overloaded */
2281                 for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next)
2282                         if (vfsp->vfc_typenum == name[2])
2283                                 break;
2284                 if (vfsp == NULL)
2285                         return (EOPNOTSUPP);
2286                 return (SYSCTL_OUT(req, vfsp, sizeof *vfsp));
2287         }
2288         return (EOPNOTSUPP);
2289 }
2290
2291 SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD, vfs_sysctl,
2292         "Generic filesystem");
2293
2294 #if 1 || defined(COMPAT_PRELITE2)
2295
2296 static int
2297 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
2298 {
2299         int error;
2300         struct vfsconf *vfsp;
2301         struct ovfsconf ovfs;
2302
2303         for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next) {
2304                 ovfs.vfc_vfsops = vfsp->vfc_vfsops;     /* XXX used as flag */
2305                 strcpy(ovfs.vfc_name, vfsp->vfc_name);
2306                 ovfs.vfc_index = vfsp->vfc_typenum;
2307                 ovfs.vfc_refcount = vfsp->vfc_refcount;
2308                 ovfs.vfc_flags = vfsp->vfc_flags;
2309                 error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
2310                 if (error)
2311                         return error;
2312         }
2313         return 0;
2314 }
2315
2316 #endif /* 1 || COMPAT_PRELITE2 */
2317
2318 #if 0
2319 #define KINFO_VNODESLOP 10
2320 /*
2321  * Dump vnode list (via sysctl).
2322  * Copyout address of vnode followed by vnode.
2323  */
2324 /* ARGSUSED */
2325 static int
2326 sysctl_vnode(SYSCTL_HANDLER_ARGS)
2327 {
2328         struct proc *p = curproc;       /* XXX */
2329         struct mount *mp, *nmp;
2330         struct vnode *nvp, *vp;
2331         int error;
2332
2333 #define VPTRSZ  sizeof (struct vnode *)
2334 #define VNODESZ sizeof (struct vnode)
2335
2336         req->lock = 0;
2337         if (!req->oldptr) /* Make an estimate */
2338                 return (SYSCTL_OUT(req, 0,
2339                         (numvnodes + KINFO_VNODESLOP) * (VPTRSZ + VNODESZ)));
2340
2341         lwkt_gettoken(&mountlist_token);
2342         for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
2343                 if (vfs_busy(mp, LK_NOWAIT, &mountlist_token, p)) {
2344                         nmp = TAILQ_NEXT(mp, mnt_list);
2345                         continue;
2346                 }
2347 again:
2348                 lwkt_gettoken(&mntvnode_token);
2349                 for (vp = TAILQ_FIRST(&mp->mnt_nvnodelist);
2350                      vp != NULL;
2351                      vp = nvp) {
2352                         /*
2353                          * Check that the vp is still associated with
2354                          * this filesystem.  RACE: could have been
2355                          * recycled onto the same filesystem.
2356                          */
2357                         if (vp->v_mount != mp) {
2358                                 lwkt_reltoken(&mntvnode_token);
2359                                 goto again;
2360                         }
2361                         nvp = TAILQ_NEXT(vp, v_nmntvnodes);
2362                         lwkt_reltoken(&mntvnode_token);
2363                         if ((error = SYSCTL_OUT(req, &vp, VPTRSZ)) ||
2364                             (error = SYSCTL_OUT(req, vp, VNODESZ)))
2365                                 return (error);
2366                         lwkt_gettoken(&mntvnode_token);
2367                 }
2368                 lwkt_reltoken(&mntvnode_token);
2369                 lwkt_gettoken(&mountlist_token);
2370                 nmp = TAILQ_NEXT(mp, mnt_list);
2371                 vfs_unbusy(mp, p);
2372         }
2373         lwkt_reltoken(&mountlist_token);
2374
2375         return (0);
2376 }
2377 #endif
2378
2379 /*
2380  * XXX
2381  * Exporting the vnode list on large systems causes them to crash.
2382  * Exporting the vnode list on medium systems causes sysctl to coredump.
2383  */
2384 #if 0
2385 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE|CTLFLAG_RD,
2386         0, 0, sysctl_vnode, "S,vnode", "");
2387 #endif
2388
2389 /*
2390  * Check to see if a filesystem is mounted on a block device.
2391  */
2392 int
2393 vfs_mountedon(vp)
2394         struct vnode *vp;
2395 {
2396
2397         if (vp->v_specmountpoint != NULL)
2398                 return (EBUSY);
2399         return (0);
2400 }
2401
2402 /*
2403  * Unmount all filesystems. The list is traversed in reverse order
2404  * of mounting to avoid dependencies.
2405  */
2406 void
2407 vfs_unmountall()
2408 {
2409         struct mount *mp;
2410         struct thread *td = curthread;
2411         int error;
2412
2413         if (td->td_proc == NULL)
2414                 td = initproc->p_thread;        /* XXX XXX use proc0 instead? */
2415
2416         /*
2417          * Since this only runs when rebooting, it is not interlocked.
2418          */
2419         while(!TAILQ_EMPTY(&mountlist)) {
2420                 mp = TAILQ_LAST(&mountlist, mntlist);
2421                 error = dounmount(mp, MNT_FORCE, td);
2422                 if (error) {
2423                         TAILQ_REMOVE(&mountlist, mp, mnt_list);
2424                         printf("unmount of %s failed (",
2425                             mp->mnt_stat.f_mntonname);
2426                         if (error == EBUSY)
2427                                 printf("BUSY)\n");
2428                         else
2429                                 printf("%d)\n", error);
2430                 } else {
2431                         /* The unmount has removed mp from the mountlist */
2432                 }
2433         }
2434 }
2435
2436 /*
2437  * Build hash lists of net addresses and hang them off the mount point.
2438  * Called by ufs_mount() to set up the lists of export addresses.
2439  */
2440 static int
2441 vfs_hang_addrlist(mp, nep, argp)
2442         struct mount *mp;
2443         struct netexport *nep;
2444         struct export_args *argp;
2445 {
2446         struct netcred *np;
2447         struct radix_node_head *rnh;
2448         int i;
2449         struct radix_node *rn;
2450         struct sockaddr *saddr, *smask = 0;
2451         struct domain *dom;
2452         int error;
2453
2454         if (argp->ex_addrlen == 0) {
2455                 if (mp->mnt_flag & MNT_DEFEXPORTED)
2456                         return (EPERM);
2457                 np = &nep->ne_defexported;
2458                 np->netc_exflags = argp->ex_flags;
2459                 np->netc_anon = argp->ex_anon;
2460                 np->netc_anon.cr_ref = 1;
2461                 mp->mnt_flag |= MNT_DEFEXPORTED;
2462                 return (0);
2463         }
2464
2465         if (argp->ex_addrlen < 0 || argp->ex_addrlen > MLEN)
2466                 return (EINVAL);
2467         if (argp->ex_masklen < 0 || argp->ex_masklen > MLEN)
2468                 return (EINVAL);
2469
2470         i = sizeof(struct netcred) + argp->ex_addrlen + argp->ex_masklen;
2471         np = (struct netcred *) malloc(i, M_NETADDR, M_WAITOK);
2472         bzero((caddr_t) np, i);
2473         saddr = (struct sockaddr *) (np + 1);
2474         if ((error = copyin(argp->ex_addr, (caddr_t) saddr, argp->ex_addrlen)))
2475                 goto out;
2476         if (saddr->sa_len > argp->ex_addrlen)
2477                 saddr->sa_len = argp->ex_addrlen;
2478         if (argp->ex_masklen) {
2479                 smask = (struct sockaddr *) ((caddr_t) saddr + argp->ex_addrlen);
2480                 error = copyin(argp->ex_mask, (caddr_t) smask, argp->ex_masklen);
2481                 if (error)
2482                         goto out;
2483                 if (smask->sa_len > argp->ex_masklen)
2484                         smask->sa_len = argp->ex_masklen;
2485         }
2486         i = saddr->sa_family;
2487         if ((rnh = nep->ne_rtable[i]) == 0) {
2488                 /*
2489                  * Seems silly to initialize every AF when most are not used,
2490                  * do so on demand here
2491                  */
2492                 for (dom = domains; dom; dom = dom->dom_next)
2493                         if (dom->dom_family == i && dom->dom_rtattach) {
2494                                 dom->dom_rtattach((void **) &nep->ne_rtable[i],
2495                                     dom->dom_rtoffset);
2496                                 break;
2497                         }
2498                 if ((rnh = nep->ne_rtable[i]) == 0) {
2499                         error = ENOBUFS;
2500                         goto out;
2501                 }
2502         }
2503         rn = (*rnh->rnh_addaddr) ((caddr_t) saddr, (caddr_t) smask, rnh,
2504             np->netc_rnodes);
2505         if (rn == 0 || np != (struct netcred *) rn) {   /* already exists */
2506                 error = EPERM;
2507                 goto out;
2508         }
2509         np->netc_exflags = argp->ex_flags;
2510         np->netc_anon = argp->ex_anon;
2511         np->netc_anon.cr_ref = 1;
2512         return (0);
2513 out:
2514         free(np, M_NETADDR);
2515         return (error);
2516 }
2517
2518 /* ARGSUSED */
2519 static int
2520 vfs_free_netcred(rn, w)
2521         struct radix_node *rn;
2522         void *w;
2523 {
2524         struct radix_node_head *rnh = (struct radix_node_head *) w;
2525
2526         (*rnh->rnh_deladdr) (rn->rn_key, rn->rn_mask, rnh);
2527         free((caddr_t) rn, M_NETADDR);
2528         return (0);
2529 }
2530
2531 /*
2532  * Free the net address hash lists that are hanging off the mount points.
2533  */
2534 static void
2535 vfs_free_addrlist(nep)
2536         struct netexport *nep;
2537 {
2538         int i;
2539         struct radix_node_head *rnh;
2540
2541         for (i = 0; i <= AF_MAX; i++)
2542                 if ((rnh = nep->ne_rtable[i])) {
2543                         (*rnh->rnh_walktree) (rnh, vfs_free_netcred,
2544                             (caddr_t) rnh);
2545                         free((caddr_t) rnh, M_RTABLE);
2546                         nep->ne_rtable[i] = 0;
2547                 }
2548 }
2549
2550 int
2551 vfs_export(mp, nep, argp)
2552         struct mount *mp;
2553         struct netexport *nep;
2554         struct export_args *argp;
2555 {
2556         int error;
2557
2558         if (argp->ex_flags & MNT_DELEXPORT) {
2559                 if (mp->mnt_flag & MNT_EXPUBLIC) {
2560                         vfs_setpublicfs(NULL, NULL, NULL);
2561                         mp->mnt_flag &= ~MNT_EXPUBLIC;
2562                 }
2563                 vfs_free_addrlist(nep);
2564                 mp->mnt_flag &= ~(MNT_EXPORTED | MNT_DEFEXPORTED);
2565         }
2566         if (argp->ex_flags & MNT_EXPORTED) {
2567                 if (argp->ex_flags & MNT_EXPUBLIC) {
2568                         if ((error = vfs_setpublicfs(mp, nep, argp)) != 0)
2569                                 return (error);
2570                         mp->mnt_flag |= MNT_EXPUBLIC;
2571                 }
2572                 if ((error = vfs_hang_addrlist(mp, nep, argp)))
2573                         return (error);
2574                 mp->mnt_flag |= MNT_EXPORTED;
2575         }
2576         return (0);
2577 }
2578
2579
2580 /*
2581  * Set the publicly exported filesystem (WebNFS). Currently, only
2582  * one public filesystem is possible in the spec (RFC 2054 and 2055)
2583  */
2584 int
2585 vfs_setpublicfs(mp, nep, argp)
2586         struct mount *mp;
2587         struct netexport *nep;
2588         struct export_args *argp;
2589 {
2590         int error;
2591         struct vnode *rvp;
2592         char *cp;
2593
2594         /*
2595          * mp == NULL -> invalidate the current info, the FS is
2596          * no longer exported. May be called from either vfs_export
2597          * or unmount, so check if it hasn't already been done.
2598          */
2599         if (mp == NULL) {
2600                 if (nfs_pub.np_valid) {
2601                         nfs_pub.np_valid = 0;
2602                         if (nfs_pub.np_index != NULL) {
2603                                 FREE(nfs_pub.np_index, M_TEMP);
2604                                 nfs_pub.np_index = NULL;
2605                         }
2606                 }
2607                 return (0);
2608         }
2609
2610         /*
2611          * Only one allowed at a time.
2612          */
2613         if (nfs_pub.np_valid != 0 && mp != nfs_pub.np_mount)
2614                 return (EBUSY);
2615
2616         /*
2617          * Get real filehandle for root of exported FS.
2618          */
2619         bzero((caddr_t)&nfs_pub.np_handle, sizeof(nfs_pub.np_handle));
2620         nfs_pub.np_handle.fh_fsid = mp->mnt_stat.f_fsid;
2621
2622         if ((error = VFS_ROOT(mp, &rvp)))
2623                 return (error);
2624
2625         if ((error = VFS_VPTOFH(rvp, &nfs_pub.np_handle.fh_fid)))
2626                 return (error);
2627
2628         vput(rvp);
2629
2630         /*
2631          * If an indexfile was specified, pull it in.
2632          */
2633         if (argp->ex_indexfile != NULL) {
2634                 MALLOC(nfs_pub.np_index, char *, MAXNAMLEN + 1, M_TEMP,
2635                     M_WAITOK);
2636                 error = copyinstr(argp->ex_indexfile, nfs_pub.np_index,
2637                     MAXNAMLEN, (size_t *)0);
2638                 if (!error) {
2639                         /*
2640                          * Check for illegal filenames.
2641                          */
2642                         for (cp = nfs_pub.np_index; *cp; cp++) {
2643                                 if (*cp == '/') {
2644                                         error = EINVAL;
2645                                         break;
2646                                 }
2647                         }
2648                 }
2649                 if (error) {
2650                         FREE(nfs_pub.np_index, M_TEMP);
2651                         return (error);
2652                 }
2653         }
2654
2655         nfs_pub.np_mount = mp;
2656         nfs_pub.np_valid = 1;
2657         return (0);
2658 }
2659
2660 struct netcred *
2661 vfs_export_lookup(mp, nep, nam)
2662         struct mount *mp;
2663         struct netexport *nep;
2664         struct sockaddr *nam;
2665 {
2666         struct netcred *np;
2667         struct radix_node_head *rnh;
2668         struct sockaddr *saddr;
2669
2670         np = NULL;
2671         if (mp->mnt_flag & MNT_EXPORTED) {
2672                 /*
2673                  * Lookup in the export list first.
2674                  */
2675                 if (nam != NULL) {
2676                         saddr = nam;
2677                         rnh = nep->ne_rtable[saddr->sa_family];
2678                         if (rnh != NULL) {
2679                                 np = (struct netcred *)
2680                                         (*rnh->rnh_matchaddr)((caddr_t)saddr,
2681                                                               rnh);
2682                                 if (np && np->netc_rnodes->rn_flags & RNF_ROOT)
2683                                         np = NULL;
2684                         }
2685                 }
2686                 /*
2687                  * If no address match, use the default if it exists.
2688                  */
2689                 if (np == NULL && mp->mnt_flag & MNT_DEFEXPORTED)
2690                         np = &nep->ne_defexported;
2691         }
2692         return (np);
2693 }
2694
2695 /*
2696  * perform msync on all vnodes under a mount point
2697  * the mount point must be locked.
2698  */
2699 void
2700 vfs_msync(struct mount *mp, int flags) 
2701 {
2702         struct thread *td = curthread;  /* XXX */
2703         struct vnode *vp, *nvp;
2704         struct vm_object *obj;
2705         int tries;
2706
2707         tries = 5;
2708         lwkt_gettoken(&mntvnode_token);
2709 loop:
2710         for (vp = TAILQ_FIRST(&mp->mnt_nvnodelist); vp != NULL; vp = nvp) {
2711                 if (vp->v_mount != mp) {
2712                         if (--tries > 0)
2713                                 goto loop;
2714                         break;
2715                 }
2716                 nvp = TAILQ_NEXT(vp, v_nmntvnodes);
2717
2718                 if (vp->v_flag & VXLOCK)        /* XXX: what if MNT_WAIT? */
2719                         continue;
2720
2721                 /*
2722                  * There could be hundreds of thousands of vnodes, we cannot
2723                  * afford to do anything heavy-weight until we have a fairly
2724                  * good indication that there is something to do.
2725                  */
2726                 if ((vp->v_flag & VOBJDIRTY) &&
2727                     (flags == MNT_WAIT || VOP_ISLOCKED(vp, NULL) == 0)) {
2728                         lwkt_reltoken(&mntvnode_token);
2729                         if (!vget(vp,
2730                             LK_EXCLUSIVE | LK_RETRY | LK_NOOBJ, td)) {
2731                                 if (VOP_GETVOBJECT(vp, &obj) == 0) {
2732                                         vm_object_page_clean(obj, 0, 0, flags == MNT_WAIT ? OBJPC_SYNC : OBJPC_NOSYNC);
2733                                 }
2734                                 vput(vp);
2735                         }
2736                         lwkt_gettoken(&mntvnode_token);
2737                         if (TAILQ_NEXT(vp, v_nmntvnodes) != nvp) {
2738                                 if (--tries > 0)
2739                                         goto loop;
2740                                 break;
2741                         }
2742                 }
2743         }
2744         lwkt_reltoken(&mntvnode_token);
2745 }
2746
2747 /*
2748  * Create the VM object needed for VMIO and mmap support.  This
2749  * is done for all VREG files in the system.  Some filesystems might
2750  * afford the additional metadata buffering capability of the
2751  * VMIO code by making the device node be VMIO mode also.
2752  *
2753  * vp must be locked when vfs_object_create is called.
2754  */
2755 int
2756 vfs_object_create(struct vnode *vp, struct thread *td)
2757 {
2758         return (VOP_CREATEVOBJECT(vp, td));
2759 }
2760
2761 void
2762 vfree(vp)
2763         struct vnode *vp;
2764 {
2765         int s;
2766
2767         s = splbio();
2768         lwkt_gettoken(&vnode_free_list_token);
2769         KASSERT((vp->v_flag & VFREE) == 0, ("vnode already free"));
2770         if (vp->v_flag & VAGE) {
2771                 TAILQ_INSERT_HEAD(&vnode_free_list, vp, v_freelist);
2772         } else {
2773                 TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
2774         }
2775         freevnodes++;
2776         lwkt_reltoken(&vnode_free_list_token);
2777         vp->v_flag &= ~VAGE;
2778         vp->v_flag |= VFREE;
2779         splx(s);
2780 }
2781
2782 void
2783 vbusy(vp)
2784         struct vnode *vp;
2785 {
2786         int s;
2787
2788         s = splbio();
2789         lwkt_gettoken(&vnode_free_list_token);
2790         KASSERT((vp->v_flag & VFREE) != 0, ("vnode not free"));
2791         TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
2792         freevnodes--;
2793         lwkt_reltoken(&vnode_free_list_token);
2794         vp->v_flag &= ~(VFREE|VAGE);
2795         splx(s);
2796 }
2797
2798 /*
2799  * Record a process's interest in events which might happen to
2800  * a vnode.  Because poll uses the historic select-style interface
2801  * internally, this routine serves as both the ``check for any
2802  * pending events'' and the ``record my interest in future events''
2803  * functions.  (These are done together, while the lock is held,
2804  * to avoid race conditions.)
2805  */
2806 int
2807 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
2808 {
2809         lwkt_gettoken(&vp->v_pollinfo.vpi_token);
2810         if (vp->v_pollinfo.vpi_revents & events) {
2811                 /*
2812                  * This leaves events we are not interested
2813                  * in available for the other process which
2814                  * which presumably had requested them
2815                  * (otherwise they would never have been
2816                  * recorded).
2817                  */
2818                 events &= vp->v_pollinfo.vpi_revents;
2819                 vp->v_pollinfo.vpi_revents &= ~events;
2820
2821                 lwkt_reltoken(&vp->v_pollinfo.vpi_token);
2822                 return events;
2823         }
2824         vp->v_pollinfo.vpi_events |= events;
2825         selrecord(td, &vp->v_pollinfo.vpi_selinfo);
2826         lwkt_reltoken(&vp->v_pollinfo.vpi_token);
2827         return 0;
2828 }
2829
2830 /*
2831  * Note the occurrence of an event.  If the VN_POLLEVENT macro is used,
2832  * it is possible for us to miss an event due to race conditions, but
2833  * that condition is expected to be rare, so for the moment it is the
2834  * preferred interface.
2835  */
2836 void
2837 vn_pollevent(vp, events)
2838         struct vnode *vp;
2839         short events;
2840 {
2841         lwkt_gettoken(&vp->v_pollinfo.vpi_token);
2842         if (vp->v_pollinfo.vpi_events & events) {
2843                 /*
2844                  * We clear vpi_events so that we don't
2845                  * call selwakeup() twice if two events are
2846                  * posted before the polling process(es) is
2847                  * awakened.  This also ensures that we take at
2848                  * most one selwakeup() if the polling process
2849                  * is no longer interested.  However, it does
2850                  * mean that only one event can be noticed at
2851                  * a time.  (Perhaps we should only clear those
2852                  * event bits which we note?) XXX
2853                  */
2854                 vp->v_pollinfo.vpi_events = 0;  /* &= ~events ??? */
2855                 vp->v_pollinfo.vpi_revents |= events;
2856                 selwakeup(&vp->v_pollinfo.vpi_selinfo);
2857         }
2858         lwkt_reltoken(&vp->v_pollinfo.vpi_token);
2859 }
2860
2861 /*
2862  * Wake up anyone polling on vp because it is being revoked.
2863  * This depends on dead_poll() returning POLLHUP for correct
2864  * behavior.
2865  */
2866 void
2867 vn_pollgone(vp)
2868         struct vnode *vp;
2869 {
2870         lwkt_gettoken(&vp->v_pollinfo.vpi_token);
2871         if (vp->v_pollinfo.vpi_events) {
2872                 vp->v_pollinfo.vpi_events = 0;
2873                 selwakeup(&vp->v_pollinfo.vpi_selinfo);
2874         }
2875         lwkt_reltoken(&vp->v_pollinfo.vpi_token);
2876 }
2877
2878
2879
2880 /*
2881  * Routine to create and manage a filesystem syncer vnode.
2882  */
2883 #define sync_close ((int (*) (struct  vop_close_args *))nullop)
2884 static int      sync_fsync (struct  vop_fsync_args *);
2885 static int      sync_inactive (struct  vop_inactive_args *);
2886 static int      sync_reclaim  (struct  vop_reclaim_args *);
2887 #define sync_lock ((int (*) (struct  vop_lock_args *))vop_nolock)
2888 #define sync_unlock ((int (*) (struct  vop_unlock_args *))vop_nounlock)
2889 static int      sync_print (struct vop_print_args *);
2890 #define sync_islocked ((int(*) (struct vop_islocked_args *))vop_noislocked)
2891
2892 static vop_t **sync_vnodeop_p;
2893 static struct vnodeopv_entry_desc sync_vnodeop_entries[] = {
2894         { &vop_default_desc,    (vop_t *) vop_eopnotsupp },
2895         { &vop_close_desc,      (vop_t *) sync_close },         /* close */
2896         { &vop_fsync_desc,      (vop_t *) sync_fsync },         /* fsync */
2897         { &vop_inactive_desc,   (vop_t *) sync_inactive },      /* inactive */
2898         { &vop_reclaim_desc,    (vop_t *) sync_reclaim },       /* reclaim */
2899         { &vop_lock_desc,       (vop_t *) sync_lock },          /* lock */
2900         { &vop_unlock_desc,     (vop_t *) sync_unlock },        /* unlock */
2901         { &vop_print_desc,      (vop_t *) sync_print },         /* print */
2902         { &vop_islocked_desc,   (vop_t *) sync_islocked },      /* islocked */
2903         { NULL, NULL }
2904 };
2905 static struct vnodeopv_desc sync_vnodeop_opv_desc =
2906         { &sync_vnodeop_p, sync_vnodeop_entries };
2907
2908 VNODEOP_SET(sync_vnodeop_opv_desc);
2909
2910 /*
2911  * Create a new filesystem syncer vnode for the specified mount point.
2912  */
2913 int
2914 vfs_allocate_syncvnode(mp)
2915         struct mount *mp;
2916 {
2917         struct vnode *vp;
2918         static long start, incr, next;
2919         int error;
2920
2921         /* Allocate a new vnode */
2922         if ((error = getnewvnode(VT_VFS, mp, sync_vnodeop_p, &vp)) != 0) {
2923                 mp->mnt_syncer = NULL;
2924                 return (error);
2925         }
2926         vp->v_type = VNON;
2927         /*
2928          * Place the vnode onto the syncer worklist. We attempt to
2929          * scatter them about on the list so that they will go off
2930          * at evenly distributed times even if all the filesystems
2931          * are mounted at once.
2932          */
2933         next += incr;
2934         if (next == 0 || next > syncer_maxdelay) {
2935                 start /= 2;
2936                 incr /= 2;
2937                 if (start == 0) {
2938                         start = syncer_maxdelay / 2;
2939                         incr = syncer_maxdelay;
2940                 }
2941                 next = start;
2942         }
2943         vn_syncer_add_to_worklist(vp, syncdelay > 0 ? next % syncdelay : 0);
2944         mp->mnt_syncer = vp;
2945         return (0);
2946 }
2947
2948 /*
2949  * Do a lazy sync of the filesystem.
2950  */
2951 static int
2952 sync_fsync(ap)
2953         struct vop_fsync_args /* {
2954                 struct vnode *a_vp;
2955                 struct ucred *a_cred;
2956                 int a_waitfor;
2957                 struct thread *a_td;
2958         } */ *ap;
2959 {
2960         struct vnode *syncvp = ap->a_vp;
2961         struct mount *mp = syncvp->v_mount;
2962         struct thread *td = ap->a_td;
2963         int asyncflag;
2964
2965         /*
2966          * We only need to do something if this is a lazy evaluation.
2967          */
2968         if (ap->a_waitfor != MNT_LAZY)
2969                 return (0);
2970
2971         /*
2972          * Move ourselves to the back of the sync list.
2973          */
2974         vn_syncer_add_to_worklist(syncvp, syncdelay);
2975
2976         /*
2977          * Walk the list of vnodes pushing all that are dirty and
2978          * not already on the sync list.
2979          */
2980         lwkt_gettoken(&mountlist_token);
2981         if (vfs_busy(mp, LK_EXCLUSIVE | LK_NOWAIT, &mountlist_token, td) != 0) {
2982                 lwkt_reltoken(&mountlist_token);
2983                 return (0);
2984         }
2985         asyncflag = mp->mnt_flag & MNT_ASYNC;
2986         mp->mnt_flag &= ~MNT_ASYNC;
2987         vfs_msync(mp, MNT_NOWAIT);
2988         VFS_SYNC(mp, MNT_LAZY, td);
2989         if (asyncflag)
2990                 mp->mnt_flag |= MNT_ASYNC;
2991         vfs_unbusy(mp, td);
2992         return (0);
2993 }
2994
2995 /*
2996  * The syncer vnode is no referenced.
2997  */
2998 static int
2999 sync_inactive(ap)
3000         struct vop_inactive_args /* {
3001                 struct vnode *a_vp;
3002                 struct proc *a_p;
3003         } */ *ap;
3004 {
3005
3006         vgone(ap->a_vp);
3007         return (0);
3008 }
3009
3010 /*
3011  * The syncer vnode is no longer needed and is being decommissioned.
3012  *
3013  * Modifications to the worklist must be protected at splbio().
3014  */
3015 static int
3016 sync_reclaim(ap)
3017         struct vop_reclaim_args /* {
3018                 struct vnode *a_vp;
3019         } */ *ap;
3020 {
3021         struct vnode *vp = ap->a_vp;
3022         int s;
3023
3024         s = splbio();
3025         vp->v_mount->mnt_syncer = NULL;
3026         if (vp->v_flag & VONWORKLST) {
3027                 LIST_REMOVE(vp, v_synclist);
3028                 vp->v_flag &= ~VONWORKLST;
3029         }
3030         splx(s);
3031
3032         return (0);
3033 }
3034
3035 /*
3036  * Print out a syncer vnode.
3037  */
3038 static int
3039 sync_print(ap)
3040         struct vop_print_args /* {
3041                 struct vnode *a_vp;
3042         } */ *ap;
3043 {
3044         struct vnode *vp = ap->a_vp;
3045
3046         printf("syncer vnode");
3047         if (vp->v_vnlock != NULL)
3048                 lockmgr_printinfo(vp->v_vnlock);
3049         printf("\n");
3050         return (0);
3051 }
3052
3053 /*
3054  * extract the dev_t from a VBLK or VCHR
3055  */
3056 dev_t
3057 vn_todev(vp)
3058         struct vnode *vp;
3059 {
3060         if (vp->v_type != VBLK && vp->v_type != VCHR)
3061                 return (NODEV);
3062         return (vp->v_rdev);
3063 }
3064
3065 /*
3066  * Check if vnode represents a disk device
3067  */
3068 int
3069 vn_isdisk(vp, errp)
3070         struct vnode *vp;
3071         int *errp;
3072 {
3073         if (vp->v_type != VBLK && vp->v_type != VCHR) {
3074                 if (errp != NULL)
3075                         *errp = ENOTBLK;
3076                 return (0);
3077         }
3078         if (vp->v_rdev == NULL) {
3079                 if (errp != NULL)
3080                         *errp = ENXIO;
3081                 return (0);
3082         }
3083         if (!dev_dport(vp->v_rdev)) {
3084                 if (errp != NULL)
3085                         *errp = ENXIO;
3086                 return (0);
3087         }
3088         if (!(dev_dflags(vp->v_rdev) & D_DISK)) {
3089                 if (errp != NULL)
3090                         *errp = ENOTBLK;
3091                 return (0);
3092         }
3093         if (errp != NULL)
3094                 *errp = 0;
3095         return (1);
3096 }
3097
3098 void
3099 NDFREE(ndp, flags)
3100      struct nameidata *ndp;
3101      const uint flags;
3102 {
3103         if (!(flags & NDF_NO_FREE_PNBUF) &&
3104             (ndp->ni_cnd.cn_flags & CNP_HASBUF)) {
3105                 zfree(namei_zone, ndp->ni_cnd.cn_pnbuf);
3106                 ndp->ni_cnd.cn_flags &= ~CNP_HASBUF;
3107         }
3108         if (!(flags & NDF_NO_DNCP_RELE) &&
3109             (ndp->ni_cnd.cn_flags & CNP_WANTDNCP) &&
3110             ndp->ni_dncp) {
3111                 cache_drop(ndp->ni_dncp);
3112                 ndp->ni_dncp = NULL;
3113         }
3114         if (!(flags & NDF_NO_NCP_RELE) &&
3115             (ndp->ni_cnd.cn_flags & CNP_WANTNCP) &&
3116             ndp->ni_ncp) {
3117                 cache_drop(ndp->ni_ncp);
3118                 ndp->ni_ncp = NULL;
3119         }
3120         if (!(flags & NDF_NO_DVP_UNLOCK) &&
3121             (ndp->ni_cnd.cn_flags & CNP_LOCKPARENT) &&
3122             ndp->ni_dvp != ndp->ni_vp) {
3123                 VOP_UNLOCK(ndp->ni_dvp, 0, ndp->ni_cnd.cn_td);
3124         }
3125         if (!(flags & NDF_NO_DVP_RELE) &&
3126             (ndp->ni_cnd.cn_flags & (CNP_LOCKPARENT|CNP_WANTPARENT))) {
3127                 vrele(ndp->ni_dvp);
3128                 ndp->ni_dvp = NULL;
3129         }
3130         if (!(flags & NDF_NO_VP_UNLOCK) &&
3131             (ndp->ni_cnd.cn_flags & CNP_LOCKLEAF) && ndp->ni_vp) {
3132                 VOP_UNLOCK(ndp->ni_vp, 0, ndp->ni_cnd.cn_td);
3133         }
3134         if (!(flags & NDF_NO_VP_RELE) &&
3135             ndp->ni_vp) {
3136                 vrele(ndp->ni_vp);
3137                 ndp->ni_vp = NULL;
3138         }
3139         if (!(flags & NDF_NO_STARTDIR_RELE) &&
3140             (ndp->ni_cnd.cn_flags & CNP_SAVESTART)) {
3141                 vrele(ndp->ni_startdir);
3142                 ndp->ni_startdir = NULL;
3143         }
3144 }
3145