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