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