Merge branch 'vendor/FILE'
[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.118 2008/09/17 21:44:18 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/file.h>
57 #include <sys/kernel.h>
58 #include <sys/kthread.h>
59 #include <sys/malloc.h>
60 #include <sys/mbuf.h>
61 #include <sys/mount.h>
62 #include <sys/priv.h>
63 #include <sys/proc.h>
64 #include <sys/reboot.h>
65 #include <sys/socket.h>
66 #include <sys/stat.h>
67 #include <sys/sysctl.h>
68 #include <sys/syslog.h>
69 #include <sys/unistd.h>
70 #include <sys/vmmeter.h>
71 #include <sys/vnode.h>
72
73 #include <machine/limits.h>
74
75 #include <vm/vm.h>
76 #include <vm/vm_object.h>
77 #include <vm/vm_extern.h>
78 #include <vm/vm_kern.h>
79 #include <vm/pmap.h>
80 #include <vm/vm_map.h>
81 #include <vm/vm_page.h>
82 #include <vm/vm_pager.h>
83 #include <vm/vnode_pager.h>
84 #include <vm/vm_zone.h>
85
86 #include <sys/buf2.h>
87 #include <sys/thread2.h>
88 #include <sys/sysref2.h>
89 #include <sys/mplock2.h>
90
91 static MALLOC_DEFINE(M_NETADDR, "Export Host", "Export host address structure");
92
93 int numvnodes;
94 SYSCTL_INT(_debug, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0, "");
95 int vfs_fastdev = 1;
96 SYSCTL_INT(_vfs, OID_AUTO, fastdev, CTLFLAG_RW, &vfs_fastdev, 0, "");
97
98 enum vtype iftovt_tab[16] = {
99         VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
100         VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VBAD,
101 };
102 int vttoif_tab[9] = {
103         0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
104         S_IFSOCK, S_IFIFO, S_IFMT,
105 };
106
107 static int reassignbufcalls;
108 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW,
109                 &reassignbufcalls, 0, "");
110 static int reassignbufloops;
111 SYSCTL_INT(_vfs, OID_AUTO, reassignbufloops, CTLFLAG_RW,
112                 &reassignbufloops, 0, "");
113 static int reassignbufsortgood;
114 SYSCTL_INT(_vfs, OID_AUTO, reassignbufsortgood, CTLFLAG_RW,
115                 &reassignbufsortgood, 0, "");
116 static int reassignbufsortbad;
117 SYSCTL_INT(_vfs, OID_AUTO, reassignbufsortbad, CTLFLAG_RW,
118                 &reassignbufsortbad, 0, "");
119 static int reassignbufmethod = 1;
120 SYSCTL_INT(_vfs, OID_AUTO, reassignbufmethod, CTLFLAG_RW,
121                 &reassignbufmethod, 0, "");
122
123 int     nfs_mount_type = -1;
124 static struct lwkt_token spechash_token;
125 struct nfs_public nfs_pub;      /* publicly exported FS */
126
127 int desiredvnodes;
128 SYSCTL_INT(_kern, KERN_MAXVNODES, maxvnodes, CTLFLAG_RW, 
129                 &desiredvnodes, 0, "Maximum number of vnodes");
130
131 static void     vfs_free_addrlist (struct netexport *nep);
132 static int      vfs_free_netcred (struct radix_node *rn, void *w);
133 static int      vfs_hang_addrlist (struct mount *mp, struct netexport *nep,
134                                        const struct export_args *argp);
135
136 /*
137  * Red black tree functions
138  */
139 static int rb_buf_compare(struct buf *b1, struct buf *b2);
140 RB_GENERATE2(buf_rb_tree, buf, b_rbnode, rb_buf_compare, off_t, b_loffset);
141 RB_GENERATE2(buf_rb_hash, buf, b_rbhash, rb_buf_compare, off_t, b_loffset);
142
143 static int
144 rb_buf_compare(struct buf *b1, struct buf *b2)
145 {
146         if (b1->b_loffset < b2->b_loffset)
147                 return(-1);
148         if (b1->b_loffset > b2->b_loffset)
149                 return(1);
150         return(0);
151 }
152
153 /*
154  * Returns non-zero if the vnode is a candidate for lazy msyncing.
155  */
156 static __inline int
157 vshouldmsync(struct vnode *vp)
158 {
159         if (vp->v_auxrefs != 0 || vp->v_sysref.refcnt > 0)
160                 return (0);             /* other holders */
161         if (vp->v_object &&
162             (vp->v_object->ref_count || vp->v_object->resident_page_count)) {
163                 return (0);
164         }
165         return (1);
166 }
167
168 /*
169  * Initialize the vnode management data structures. 
170  *
171  * Called from vfsinit()
172  */
173 void
174 vfs_subr_init(void)
175 {
176         /*
177          * Desiredvnodes is kern.maxvnodes.  We want to scale it 
178          * according to available system memory but we may also have
179          * to limit it based on available KVM, which is capped on 32 bit
180          * systems.
181          *
182          * WARNING!  For machines with 64-256M of ram we have to be sure
183          *           that the default limit scales down well due to HAMMER
184          *           taking up significantly more memory per-vnode vs UFS.
185          *           We want around ~5800 on a 128M machine.
186          */
187         desiredvnodes = min(maxproc + vmstats.v_page_count / 6,
188                             KvaSize / (20 * 
189                             (sizeof(struct vm_object) + sizeof(struct vnode))));
190
191         lwkt_token_init(&spechash_token);
192 }
193
194 /*
195  * Knob to control the precision of file timestamps:
196  *
197  *   0 = seconds only; nanoseconds zeroed.
198  *   1 = seconds and nanoseconds, accurate within 1/HZ.
199  *   2 = seconds and nanoseconds, truncated to microseconds.
200  * >=3 = seconds and nanoseconds, maximum precision.
201  */
202 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
203
204 static int timestamp_precision = TSP_SEC;
205 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
206                 &timestamp_precision, 0, "");
207
208 /*
209  * Get a current timestamp.
210  *
211  * MPSAFE
212  */
213 void
214 vfs_timestamp(struct timespec *tsp)
215 {
216         struct timeval tv;
217
218         switch (timestamp_precision) {
219         case TSP_SEC:
220                 tsp->tv_sec = time_second;
221                 tsp->tv_nsec = 0;
222                 break;
223         case TSP_HZ:
224                 getnanotime(tsp);
225                 break;
226         case TSP_USEC:
227                 microtime(&tv);
228                 TIMEVAL_TO_TIMESPEC(&tv, tsp);
229                 break;
230         case TSP_NSEC:
231         default:
232                 nanotime(tsp);
233                 break;
234         }
235 }
236
237 /*
238  * Set vnode attributes to VNOVAL
239  */
240 void
241 vattr_null(struct vattr *vap)
242 {
243         vap->va_type = VNON;
244         vap->va_size = VNOVAL;
245         vap->va_bytes = VNOVAL;
246         vap->va_mode = VNOVAL;
247         vap->va_nlink = VNOVAL;
248         vap->va_uid = VNOVAL;
249         vap->va_gid = VNOVAL;
250         vap->va_fsid = VNOVAL;
251         vap->va_fileid = VNOVAL;
252         vap->va_blocksize = VNOVAL;
253         vap->va_rmajor = VNOVAL;
254         vap->va_rminor = VNOVAL;
255         vap->va_atime.tv_sec = VNOVAL;
256         vap->va_atime.tv_nsec = VNOVAL;
257         vap->va_mtime.tv_sec = VNOVAL;
258         vap->va_mtime.tv_nsec = VNOVAL;
259         vap->va_ctime.tv_sec = VNOVAL;
260         vap->va_ctime.tv_nsec = VNOVAL;
261         vap->va_flags = VNOVAL;
262         vap->va_gen = VNOVAL;
263         vap->va_vaflags = 0;
264         /* va_*_uuid fields are only valid if related flags are set */
265 }
266
267 /*
268  * Flush out and invalidate all buffers associated with a vnode.
269  *
270  * vp must be locked.
271  */
272 static int vinvalbuf_bp(struct buf *bp, void *data);
273
274 struct vinvalbuf_bp_info {
275         struct vnode *vp;
276         int slptimeo;
277         int lkflags;
278         int flags;
279 };
280
281 int
282 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
283 {
284         struct vinvalbuf_bp_info info;
285         vm_object_t object;
286         lwkt_tokref vlock;
287         int error;
288
289         lwkt_gettoken(&vlock, &vp->v_token);
290
291         /*
292          * If we are being asked to save, call fsync to ensure that the inode
293          * is updated.
294          */
295         if (flags & V_SAVE) {
296                 error = bio_track_wait(&vp->v_track_write, slpflag, slptimeo);
297                 if (error)
298                         goto done;
299                 if (!RB_EMPTY(&vp->v_rbdirty_tree)) {
300                         if ((error = VOP_FSYNC(vp, MNT_WAIT, 0)) != 0)
301                                 goto done;
302
303                         /*
304                          * Dirty bufs may be left or generated via races
305                          * in circumstances where vinvalbuf() is called on
306                          * a vnode not undergoing reclamation.   Only
307                          * panic if we are trying to reclaim the vnode.
308                          */
309                         if ((vp->v_flag & VRECLAIMED) &&
310                             (bio_track_active(&vp->v_track_write) ||
311                             !RB_EMPTY(&vp->v_rbdirty_tree))) {
312                                 panic("vinvalbuf: dirty bufs");
313                         }
314                 }
315         }
316         info.slptimeo = slptimeo;
317         info.lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL;
318         if (slpflag & PCATCH)
319                 info.lkflags |= LK_PCATCH;
320         info.flags = flags;
321         info.vp = vp;
322
323         /*
324          * Flush the buffer cache until nothing is left.
325          */
326         while (!RB_EMPTY(&vp->v_rbclean_tree) || 
327                !RB_EMPTY(&vp->v_rbdirty_tree)) {
328                 error = RB_SCAN(buf_rb_tree, &vp->v_rbclean_tree, NULL,
329                                 vinvalbuf_bp, &info);
330                 if (error == 0) {
331                         error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
332                                         vinvalbuf_bp, &info);
333                 }
334         }
335
336         /*
337          * Wait for I/O completion.  We may block in the pip code so we have
338          * to re-check.
339          */
340         do {
341                 bio_track_wait(&vp->v_track_write, 0, 0);
342                 if ((object = vp->v_object) != NULL) {
343                         while (object->paging_in_progress)
344                                 vm_object_pip_sleep(object, "vnvlbx");
345                 }
346         } while (bio_track_active(&vp->v_track_write));
347
348         /*
349          * Destroy the copy in the VM cache, too.
350          */
351         if ((object = vp->v_object) != NULL) {
352                 vm_object_page_remove(object, 0, 0,
353                         (flags & V_SAVE) ? TRUE : FALSE);
354         }
355
356         if (!RB_EMPTY(&vp->v_rbdirty_tree) || !RB_EMPTY(&vp->v_rbclean_tree))
357                 panic("vinvalbuf: flush failed");
358         if (!RB_EMPTY(&vp->v_rbhash_tree))
359                 panic("vinvalbuf: flush failed, buffers still present");
360         error = 0;
361 done:
362         lwkt_reltoken(&vlock);
363         return (error);
364 }
365
366 static int
367 vinvalbuf_bp(struct buf *bp, void *data)
368 {
369         struct vinvalbuf_bp_info *info = data;
370         int error;
371
372         if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
373                 error = BUF_TIMELOCK(bp, info->lkflags,
374                                      "vinvalbuf", info->slptimeo);
375                 if (error == 0) {
376                         BUF_UNLOCK(bp);
377                         error = ENOLCK;
378                 }
379                 if (error == ENOLCK)
380                         return(0);
381                 return (-error);
382         }
383
384         KKASSERT(bp->b_vp == info->vp);
385
386         /*
387          * XXX Since there are no node locks for NFS, I
388          * believe there is a slight chance that a delayed
389          * write will occur while sleeping just above, so
390          * check for it.  Note that vfs_bio_awrite expects
391          * buffers to reside on a queue, while bwrite() and
392          * brelse() do not.
393          *
394          * NOTE:  NO B_LOCKED CHECK.  Also no buf_checkwrite()
395          * check.  This code will write out the buffer, period.
396          */
397         if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
398             (info->flags & V_SAVE)) {
399                 if (bp->b_vp == info->vp) {
400                         if (bp->b_flags & B_CLUSTEROK) {
401                                 vfs_bio_awrite(bp);
402                         } else {
403                                 bremfree(bp);
404                                 bawrite(bp);
405                         }
406                 } else {
407                         bremfree(bp);
408                         bwrite(bp);
409                 }
410         } else if (info->flags & V_SAVE) {
411                 /*
412                  * Cannot set B_NOCACHE on a clean buffer as this will
413                  * destroy the VM backing store which might actually
414                  * be dirty (and unsynchronized).
415                  */
416                 bremfree(bp);
417                 bp->b_flags |= (B_INVAL | B_RELBUF);
418                 brelse(bp);
419         } else {
420                 bremfree(bp);
421                 bp->b_flags |= (B_INVAL | B_NOCACHE | B_RELBUF);
422                 brelse(bp);
423         }
424         return(0);
425 }
426
427 /*
428  * Truncate a file's buffer and pages to a specified length.  This
429  * is in lieu of the old vinvalbuf mechanism, which performed unneeded
430  * sync activity.
431  *
432  * The vnode must be locked.
433  */
434 static int vtruncbuf_bp_trunc_cmp(struct buf *bp, void *data);
435 static int vtruncbuf_bp_trunc(struct buf *bp, void *data);
436 static int vtruncbuf_bp_metasync_cmp(struct buf *bp, void *data);
437 static int vtruncbuf_bp_metasync(struct buf *bp, void *data);
438
439 int
440 vtruncbuf(struct vnode *vp, off_t length, int blksize)
441 {
442         off_t truncloffset;
443         const char *filename;
444         lwkt_tokref vlock;
445         int count;
446
447         /*
448          * Round up to the *next* block, then destroy the buffers in question.  
449          * Since we are only removing some of the buffers we must rely on the
450          * scan count to determine whether a loop is necessary.
451          */
452         if ((count = (int)(length % blksize)) != 0)
453                 truncloffset = length + (blksize - count);
454         else
455                 truncloffset = length;
456
457         lwkt_gettoken(&vlock, &vp->v_token);
458         do {
459                 count = RB_SCAN(buf_rb_tree, &vp->v_rbclean_tree, 
460                                 vtruncbuf_bp_trunc_cmp,
461                                 vtruncbuf_bp_trunc, &truncloffset);
462                 count += RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
463                                 vtruncbuf_bp_trunc_cmp,
464                                 vtruncbuf_bp_trunc, &truncloffset);
465         } while(count);
466
467         /*
468          * For safety, fsync any remaining metadata if the file is not being
469          * truncated to 0.  Since the metadata does not represent the entire
470          * dirty list we have to rely on the hit count to ensure that we get
471          * all of it.
472          */
473         if (length > 0) {
474                 do {
475                         count = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
476                                         vtruncbuf_bp_metasync_cmp,
477                                         vtruncbuf_bp_metasync, vp);
478                 } while (count);
479         }
480
481         /*
482          * Clean out any left over VM backing store.
483          *
484          * It is possible to have in-progress I/O from buffers that were
485          * not part of the truncation.  This should not happen if we
486          * are truncating to 0-length.
487          */
488         vnode_pager_setsize(vp, length);
489         bio_track_wait(&vp->v_track_write, 0, 0);
490
491         /*
492          * Debugging only
493          */
494         spin_lock_wr(&vp->v_spinlock);
495         filename = TAILQ_FIRST(&vp->v_namecache) ?
496                    TAILQ_FIRST(&vp->v_namecache)->nc_name : "?";
497         spin_unlock_wr(&vp->v_spinlock);
498
499         /*
500          * Make sure no buffers were instantiated while we were trying
501          * to clean out the remaining VM pages.  This could occur due
502          * to busy dirty VM pages being flushed out to disk.
503          */
504         do {
505                 count = RB_SCAN(buf_rb_tree, &vp->v_rbclean_tree, 
506                                 vtruncbuf_bp_trunc_cmp,
507                                 vtruncbuf_bp_trunc, &truncloffset);
508                 count += RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree,
509                                 vtruncbuf_bp_trunc_cmp,
510                                 vtruncbuf_bp_trunc, &truncloffset);
511                 if (count) {
512                         kprintf("Warning: vtruncbuf():  Had to re-clean %d "
513                                "left over buffers in %s\n", count, filename);
514                 }
515         } while(count);
516
517         lwkt_reltoken(&vlock);
518
519         return (0);
520 }
521
522 /*
523  * The callback buffer is beyond the new file EOF and must be destroyed.
524  * Note that the compare function must conform to the RB_SCAN's requirements.
525  */
526 static
527 int
528 vtruncbuf_bp_trunc_cmp(struct buf *bp, void *data)
529 {
530         if (bp->b_loffset >= *(off_t *)data)
531                 return(0);
532         return(-1);
533 }
534
535 static 
536 int 
537 vtruncbuf_bp_trunc(struct buf *bp, void *data)
538 {
539         /*
540          * Do not try to use a buffer we cannot immediately lock, but sleep
541          * anyway to prevent a livelock.  The code will loop until all buffers
542          * can be acted upon.
543          */
544         if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
545                 if (BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL) == 0)
546                         BUF_UNLOCK(bp);
547         } else {
548                 bremfree(bp);
549                 bp->b_flags |= (B_INVAL | B_RELBUF | B_NOCACHE);
550                 brelse(bp);
551         }
552         return(1);
553 }
554
555 /*
556  * Fsync all meta-data after truncating a file to be non-zero.  Only metadata
557  * blocks (with a negative loffset) are scanned.
558  * Note that the compare function must conform to the RB_SCAN's requirements.
559  */
560 static int
561 vtruncbuf_bp_metasync_cmp(struct buf *bp, void *data)
562 {
563         if (bp->b_loffset < 0)
564                 return(0);
565         return(1);
566 }
567
568 static int
569 vtruncbuf_bp_metasync(struct buf *bp, void *data)
570 {
571         struct vnode *vp = data;
572
573         if (bp->b_flags & B_DELWRI) {
574                 /*
575                  * Do not try to use a buffer we cannot immediately lock,
576                  * but sleep anyway to prevent a livelock.  The code will
577                  * loop until all buffers can be acted upon.
578                  */
579                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
580                         if (BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL) == 0)
581                                 BUF_UNLOCK(bp);
582                 } else {
583                         bremfree(bp);
584                         if (bp->b_vp == vp)
585                                 bawrite(bp);
586                         else
587                                 bwrite(bp);
588                 }
589                 return(1);
590         } else {
591                 return(0);
592         }
593 }
594
595 /*
596  * vfsync - implements a multipass fsync on a file which understands
597  * dependancies and meta-data.  The passed vnode must be locked.  The 
598  * waitfor argument may be MNT_WAIT or MNT_NOWAIT, or MNT_LAZY.
599  *
600  * When fsyncing data asynchronously just do one consolidated pass starting
601  * with the most negative block number.  This may not get all the data due
602  * to dependancies.
603  *
604  * When fsyncing data synchronously do a data pass, then a metadata pass,
605  * then do additional data+metadata passes to try to get all the data out.
606  */
607 static int vfsync_wait_output(struct vnode *vp, 
608                             int (*waitoutput)(struct vnode *, struct thread *));
609 static int vfsync_data_only_cmp(struct buf *bp, void *data);
610 static int vfsync_meta_only_cmp(struct buf *bp, void *data);
611 static int vfsync_lazy_range_cmp(struct buf *bp, void *data);
612 static int vfsync_bp(struct buf *bp, void *data);
613
614 struct vfsync_info {
615         struct vnode *vp;
616         int synchronous;
617         int syncdeps;
618         int lazycount;
619         int lazylimit;
620         int skippedbufs;
621         int (*checkdef)(struct buf *);
622 };
623
624 int
625 vfsync(struct vnode *vp, int waitfor, int passes,
626         int (*checkdef)(struct buf *),
627         int (*waitoutput)(struct vnode *, struct thread *))
628 {
629         struct vfsync_info info;
630         lwkt_tokref vlock;
631         int error;
632
633         bzero(&info, sizeof(info));
634         info.vp = vp;
635         if ((info.checkdef = checkdef) == NULL)
636                 info.syncdeps = 1;
637
638         lwkt_gettoken(&vlock, &vp->v_token);
639
640         switch(waitfor) {
641         case MNT_LAZY:
642                 /*
643                  * Lazy (filesystem syncer typ) Asynchronous plus limit the
644                  * number of data (not meta) pages we try to flush to 1MB.
645                  * A non-zero return means that lazy limit was reached.
646                  */
647                 info.lazylimit = 1024 * 1024;
648                 info.syncdeps = 1;
649                 error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, 
650                                 vfsync_lazy_range_cmp, vfsync_bp, &info);
651                 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, 
652                                 vfsync_meta_only_cmp, vfsync_bp, &info);
653                 if (error == 0)
654                         vp->v_lazyw = 0;
655                 else if (!RB_EMPTY(&vp->v_rbdirty_tree))
656                         vn_syncer_add_to_worklist(vp, 1);
657                 error = 0;
658                 break;
659         case MNT_NOWAIT:
660                 /*
661                  * Asynchronous.  Do a data-only pass and a meta-only pass.
662                  */
663                 info.syncdeps = 1;
664                 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, vfsync_data_only_cmp, 
665                         vfsync_bp, &info);
666                 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, vfsync_meta_only_cmp, 
667                         vfsync_bp, &info);
668                 error = 0;
669                 break;
670         default:
671                 /*
672                  * Synchronous.  Do a data-only pass, then a meta-data+data
673                  * pass, then additional integrated passes to try to get
674                  * all the dependancies flushed.
675                  */
676                 RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, vfsync_data_only_cmp,
677                         vfsync_bp, &info);
678                 error = vfsync_wait_output(vp, waitoutput);
679                 if (error == 0) {
680                         info.skippedbufs = 0;
681                         RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
682                                 vfsync_bp, &info);
683                         error = vfsync_wait_output(vp, waitoutput);
684                         if (info.skippedbufs)
685                                 kprintf("Warning: vfsync skipped %d dirty bufs in pass2!\n", info.skippedbufs);
686                 }
687                 while (error == 0 && passes > 0 &&
688                        !RB_EMPTY(&vp->v_rbdirty_tree)
689                 ) {
690                         if (--passes == 0) {
691                                 info.synchronous = 1;
692                                 info.syncdeps = 1;
693                         }
694                         error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
695                                 vfsync_bp, &info);
696                         if (error < 0)
697                                 error = -error;
698                         info.syncdeps = 1;
699                         if (error == 0)
700                                 error = vfsync_wait_output(vp, waitoutput);
701                 }
702                 break;
703         }
704         lwkt_reltoken(&vlock);
705         return(error);
706 }
707
708 static int
709 vfsync_wait_output(struct vnode *vp,
710                    int (*waitoutput)(struct vnode *, struct thread *))
711 {
712         int error;
713
714         error = bio_track_wait(&vp->v_track_write, 0, 0);
715         if (waitoutput)
716                 error = waitoutput(vp, curthread);
717         return(error);
718 }
719
720 static int
721 vfsync_data_only_cmp(struct buf *bp, void *data)
722 {
723         if (bp->b_loffset < 0)
724                 return(-1);
725         return(0);
726 }
727
728 static int
729 vfsync_meta_only_cmp(struct buf *bp, void *data)
730 {
731         if (bp->b_loffset < 0)
732                 return(0);
733         return(1);
734 }
735
736 static int
737 vfsync_lazy_range_cmp(struct buf *bp, void *data)
738 {
739         struct vfsync_info *info = data;
740         if (bp->b_loffset < info->vp->v_lazyw)
741                 return(-1);
742         return(0);
743 }
744
745 static int
746 vfsync_bp(struct buf *bp, void *data)
747 {
748         struct vfsync_info *info = data;
749         struct vnode *vp = info->vp;
750         int error;
751
752         /*
753          * if syncdeps is not set we do not try to write buffers which have
754          * dependancies.
755          */
756         if (!info->synchronous && info->syncdeps == 0 && info->checkdef(bp))
757                 return(0);
758
759         /*
760          * Ignore buffers that we cannot immediately lock.  XXX
761          */
762         if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
763                 kprintf("Warning: vfsync_bp skipping dirty buffer %p\n", bp);
764                 ++info->skippedbufs;
765                 return(0);
766         }
767         if ((bp->b_flags & B_DELWRI) == 0)
768                 panic("vfsync_bp: buffer not dirty");
769         if (vp != bp->b_vp)
770                 panic("vfsync_bp: buffer vp mismatch");
771
772         /*
773          * B_NEEDCOMMIT (primarily used by NFS) is a state where the buffer
774          * has been written but an additional handshake with the device
775          * is required before we can dispose of the buffer.  We have no idea
776          * how to do this so we have to skip these buffers.
777          */
778         if (bp->b_flags & B_NEEDCOMMIT) {
779                 BUF_UNLOCK(bp);
780                 return(0);
781         }
782
783         /*
784          * Ask bioops if it is ok to sync 
785          */
786         if (LIST_FIRST(&bp->b_dep) != NULL && buf_checkwrite(bp)) {
787                 bremfree(bp);
788                 brelse(bp);
789                 return(0);
790         }
791
792         if (info->synchronous) {
793                 /*
794                  * Synchronous flushing.  An error may be returned.
795                  */
796                 bremfree(bp);
797                 error = bwrite(bp);
798         } else { 
799                 /*
800                  * Asynchronous flushing.  A negative return value simply
801                  * stops the scan and is not considered an error.  We use
802                  * this to support limited MNT_LAZY flushes.
803                  */
804                 vp->v_lazyw = bp->b_loffset;
805                 if ((vp->v_flag & VOBJBUF) && (bp->b_flags & B_CLUSTEROK)) {
806                         info->lazycount += vfs_bio_awrite(bp);
807                 } else {
808                         info->lazycount += bp->b_bufsize;
809                         bremfree(bp);
810                         bawrite(bp);
811                 }
812                 if (info->lazylimit && info->lazycount >= info->lazylimit)
813                         error = 1;
814                 else
815                         error = 0;
816         }
817         return(-error);
818 }
819
820 /*
821  * Associate a buffer with a vnode.
822  *
823  * MPSAFE
824  */
825 int
826 bgetvp(struct vnode *vp, struct buf *bp)
827 {
828         lwkt_tokref vlock;
829
830         KASSERT(bp->b_vp == NULL, ("bgetvp: not free"));
831         KKASSERT((bp->b_flags & (B_HASHED|B_DELWRI|B_VNCLEAN|B_VNDIRTY)) == 0);
832
833         /*
834          * Insert onto list for new vnode.
835          */
836         lwkt_gettoken(&vlock, &vp->v_token);
837         if (buf_rb_hash_RB_INSERT(&vp->v_rbhash_tree, bp)) {
838                 lwkt_reltoken(&vlock);
839                 return (EEXIST);
840         }
841         bp->b_vp = vp;
842         bp->b_flags |= B_HASHED;
843         bp->b_flags |= B_VNCLEAN;
844         if (buf_rb_tree_RB_INSERT(&vp->v_rbclean_tree, bp))
845                 panic("reassignbuf: dup lblk/clean vp %p bp %p", vp, bp);
846         vhold(vp);
847         lwkt_reltoken(&vlock);
848         return(0);
849 }
850
851 /*
852  * Disassociate a buffer from a vnode.
853  */
854 void
855 brelvp(struct buf *bp)
856 {
857         struct vnode *vp;
858         lwkt_tokref vlock;
859
860         KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
861
862         /*
863          * Delete from old vnode list, if on one.
864          */
865         vp = bp->b_vp;
866         lwkt_gettoken(&vlock, &vp->v_token);
867         if (bp->b_flags & (B_VNDIRTY | B_VNCLEAN)) {
868                 if (bp->b_flags & B_VNDIRTY)
869                         buf_rb_tree_RB_REMOVE(&vp->v_rbdirty_tree, bp);
870                 else
871                         buf_rb_tree_RB_REMOVE(&vp->v_rbclean_tree, bp);
872                 bp->b_flags &= ~(B_VNDIRTY | B_VNCLEAN);
873         }
874         if (bp->b_flags & B_HASHED) {
875                 buf_rb_hash_RB_REMOVE(&vp->v_rbhash_tree, bp);
876                 bp->b_flags &= ~B_HASHED;
877         }
878         if ((vp->v_flag & VONWORKLST) && RB_EMPTY(&vp->v_rbdirty_tree)) {
879                 vclrflags(vp, VONWORKLST);
880                 LIST_REMOVE(vp, v_synclist);
881         }
882         bp->b_vp = NULL;
883         lwkt_reltoken(&vlock);
884
885         vdrop(vp);
886 }
887
888 /*
889  * Reassign the buffer to the proper clean/dirty list based on B_DELWRI.
890  * This routine is called when the state of the B_DELWRI bit is changed.
891  *
892  * MPSAFE
893  */
894 void
895 reassignbuf(struct buf *bp)
896 {
897         struct vnode *vp = bp->b_vp;
898         lwkt_tokref vlock;
899         int delay;
900
901         KKASSERT(vp != NULL);
902         ++reassignbufcalls;
903
904         /*
905          * B_PAGING flagged buffers cannot be reassigned because their vp
906          * is not fully linked in.
907          */
908         if (bp->b_flags & B_PAGING)
909                 panic("cannot reassign paging buffer");
910
911         lwkt_gettoken(&vlock, &vp->v_token);
912         if (bp->b_flags & B_DELWRI) {
913                 /*
914                  * Move to the dirty list, add the vnode to the worklist
915                  */
916                 if (bp->b_flags & B_VNCLEAN) {
917                         buf_rb_tree_RB_REMOVE(&vp->v_rbclean_tree, bp);
918                         bp->b_flags &= ~B_VNCLEAN;
919                 }
920                 if ((bp->b_flags & B_VNDIRTY) == 0) {
921                         if (buf_rb_tree_RB_INSERT(&vp->v_rbdirty_tree, bp)) {
922                                 panic("reassignbuf: dup lblk vp %p bp %p",
923                                       vp, bp);
924                         }
925                         bp->b_flags |= B_VNDIRTY;
926                 }
927                 if ((vp->v_flag & VONWORKLST) == 0) {
928                         switch (vp->v_type) {
929                         case VDIR:
930                                 delay = dirdelay;
931                                 break;
932                         case VCHR:
933                         case VBLK:
934                                 if (vp->v_rdev && 
935                                     vp->v_rdev->si_mountpoint != NULL) {
936                                         delay = metadelay;
937                                         break;
938                                 }
939                                 /* fall through */
940                         default:
941                                 delay = filedelay;
942                         }
943                         vn_syncer_add_to_worklist(vp, delay);
944                 }
945         } else {
946                 /*
947                  * Move to the clean list, remove the vnode from the worklist
948                  * if no dirty blocks remain.
949                  */
950                 if (bp->b_flags & B_VNDIRTY) {
951                         buf_rb_tree_RB_REMOVE(&vp->v_rbdirty_tree, bp);
952                         bp->b_flags &= ~B_VNDIRTY;
953                 }
954                 if ((bp->b_flags & B_VNCLEAN) == 0) {
955                         if (buf_rb_tree_RB_INSERT(&vp->v_rbclean_tree, bp)) {
956                                 panic("reassignbuf: dup lblk vp %p bp %p",
957                                       vp, bp);
958                         }
959                         bp->b_flags |= B_VNCLEAN;
960                 }
961                 if ((vp->v_flag & VONWORKLST) &&
962                     RB_EMPTY(&vp->v_rbdirty_tree)) {
963                         vclrflags(vp, VONWORKLST);
964                         LIST_REMOVE(vp, v_synclist);
965                 }
966         }
967         lwkt_reltoken(&vlock);
968 }
969
970 /*
971  * Create a vnode for a block device.
972  * Used for mounting the root file system.
973  */
974 extern struct vop_ops *devfs_vnode_dev_vops_p;
975 int
976 bdevvp(cdev_t dev, struct vnode **vpp)
977 {
978         struct vnode *vp;
979         struct vnode *nvp;
980         int error;
981
982         if (dev == NULL) {
983                 *vpp = NULLVP;
984                 return (ENXIO);
985         }
986         error = getspecialvnode(VT_NON, NULL, &devfs_vnode_dev_vops_p,
987                                 &nvp, 0, 0);
988         if (error) {
989                 *vpp = NULLVP;
990                 return (error);
991         }
992         vp = nvp;
993         vp->v_type = VCHR;
994 #if 0
995         vp->v_rdev = dev;
996 #endif
997         v_associate_rdev(vp, dev);
998         vp->v_umajor = dev->si_umajor;
999         vp->v_uminor = dev->si_uminor;
1000         vx_unlock(vp);
1001         *vpp = vp;
1002         return (0);
1003 }
1004
1005 int
1006 v_associate_rdev(struct vnode *vp, cdev_t dev)
1007 {
1008         lwkt_tokref ilock;
1009
1010         if (dev == NULL)
1011                 return(ENXIO);
1012         if (dev_is_good(dev) == 0)
1013                 return(ENXIO);
1014         KKASSERT(vp->v_rdev == NULL);
1015         vp->v_rdev = reference_dev(dev);
1016         lwkt_gettoken(&ilock, &spechash_token);
1017         SLIST_INSERT_HEAD(&dev->si_hlist, vp, v_cdevnext);
1018         lwkt_reltoken(&ilock);
1019         return(0);
1020 }
1021
1022 void
1023 v_release_rdev(struct vnode *vp)
1024 {
1025         lwkt_tokref ilock;
1026         cdev_t dev;
1027
1028         if ((dev = vp->v_rdev) != NULL) {
1029                 lwkt_gettoken(&ilock, &spechash_token);
1030                 SLIST_REMOVE(&dev->si_hlist, vp, vnode, v_cdevnext);
1031                 vp->v_rdev = NULL;
1032                 release_dev(dev);
1033                 lwkt_reltoken(&ilock);
1034         }
1035 }
1036
1037 /*
1038  * Add a vnode to the alias list hung off the cdev_t.  We only associate
1039  * the device number with the vnode.  The actual device is not associated
1040  * until the vnode is opened (usually in spec_open()), and will be 
1041  * disassociated on last close.
1042  */
1043 void
1044 addaliasu(struct vnode *nvp, int x, int y)
1045 {
1046         if (nvp->v_type != VBLK && nvp->v_type != VCHR)
1047                 panic("addaliasu on non-special vnode");
1048         nvp->v_umajor = x;
1049         nvp->v_uminor = y;
1050 }
1051
1052 /*
1053  * Simple call that a filesystem can make to try to get rid of a
1054  * vnode.  It will fail if anyone is referencing the vnode (including
1055  * the caller).
1056  *
1057  * The filesystem can check whether its in-memory inode structure still
1058  * references the vp on return.
1059  */
1060 void
1061 vclean_unlocked(struct vnode *vp)
1062 {
1063         vx_get(vp);
1064         if (sysref_isactive(&vp->v_sysref) == 0)
1065                 vgone_vxlocked(vp);
1066         vx_put(vp);
1067 }
1068
1069 /*
1070  * Disassociate a vnode from its underlying filesystem. 
1071  *
1072  * The vnode must be VX locked and referenced.  In all normal situations
1073  * there are no active references.  If vclean_vxlocked() is called while
1074  * there are active references, the vnode is being ripped out and we have
1075  * to call VOP_CLOSE() as appropriate before we can reclaim it.
1076  */
1077 void
1078 vclean_vxlocked(struct vnode *vp, int flags)
1079 {
1080         int active;
1081         int n;
1082         vm_object_t object;
1083
1084         /*
1085          * If the vnode has already been reclaimed we have nothing to do.
1086          */
1087         if (vp->v_flag & VRECLAIMED)
1088                 return;
1089         vsetflags(vp, VRECLAIMED);
1090
1091         /*
1092          * Scrap the vfs cache
1093          */
1094         while (cache_inval_vp(vp, 0) != 0) {
1095                 kprintf("Warning: vnode %p clean/cache_resolution race detected\n", vp);
1096                 tsleep(vp, 0, "vclninv", 2);
1097         }
1098
1099         /*
1100          * Check to see if the vnode is in use. If so we have to reference it
1101          * before we clean it out so that its count cannot fall to zero and
1102          * generate a race against ourselves to recycle it.
1103          */
1104         active = sysref_isactive(&vp->v_sysref);
1105
1106         /*
1107          * Clean out any buffers associated with the vnode and destroy its
1108          * object, if it has one. 
1109          */
1110         vinvalbuf(vp, V_SAVE, 0, 0);
1111
1112         /*
1113          * If purging an active vnode (typically during a forced unmount
1114          * or reboot), it must be closed and deactivated before being
1115          * reclaimed.  This isn't really all that safe, but what can
1116          * we do? XXX.
1117          *
1118          * Note that neither of these routines unlocks the vnode.
1119          */
1120         if (active && (flags & DOCLOSE)) {
1121                 while ((n = vp->v_opencount) != 0) {
1122                         if (vp->v_writecount)
1123                                 VOP_CLOSE(vp, FWRITE|FNONBLOCK);
1124                         else
1125                                 VOP_CLOSE(vp, FNONBLOCK);
1126                         if (vp->v_opencount == n) {
1127                                 kprintf("Warning: unable to force-close"
1128                                        " vnode %p\n", vp);
1129                                 break;
1130                         }
1131                 }
1132         }
1133
1134         /*
1135          * If the vnode has not been deactivated, deactivated it.  Deactivation
1136          * can create new buffers and VM pages so we have to call vinvalbuf()
1137          * again to make sure they all get flushed.
1138          *
1139          * This can occur if a file with a link count of 0 needs to be
1140          * truncated.
1141          *
1142          * If the vnode is already dead don't try to deactivate it.
1143          */
1144         if ((vp->v_flag & VINACTIVE) == 0) {
1145                 vsetflags(vp, VINACTIVE);
1146                 if (vp->v_mount)
1147                         VOP_INACTIVE(vp);
1148                 vinvalbuf(vp, V_SAVE, 0, 0);
1149         }
1150
1151         /*
1152          * If the vnode has an object, destroy it.
1153          */
1154         if ((object = vp->v_object) != NULL) {
1155                 if (object->ref_count == 0) {
1156                         if ((object->flags & OBJ_DEAD) == 0)
1157                                 vm_object_terminate(object);
1158                 } else {
1159                         vm_pager_deallocate(object);
1160                 }
1161                 vclrflags(vp, VOBJBUF);
1162         }
1163         KKASSERT((vp->v_flag & VOBJBUF) == 0);
1164
1165         /*
1166          * Reclaim the vnode if not already dead.
1167          */
1168         if (vp->v_mount && VOP_RECLAIM(vp))
1169                 panic("vclean: cannot reclaim");
1170
1171         /*
1172          * Done with purge, notify sleepers of the grim news.
1173          */
1174         vp->v_ops = &dead_vnode_vops_p;
1175         vn_pollgone(vp);
1176         vp->v_tag = VT_NON;
1177
1178         /*
1179          * If we are destroying an active vnode, reactivate it now that
1180          * we have reassociated it with deadfs.  This prevents the system
1181          * from crashing on the vnode due to it being unexpectedly marked
1182          * as inactive or reclaimed.
1183          */
1184         if (active && (flags & DOCLOSE)) {
1185                 vclrflags(vp, VINACTIVE | VRECLAIMED);
1186         }
1187 }
1188
1189 /*
1190  * Eliminate all activity associated with the requested vnode
1191  * and with all vnodes aliased to the requested vnode.
1192  *
1193  * The vnode must be referenced but should not be locked.
1194  */
1195 int
1196 vrevoke(struct vnode *vp, struct ucred *cred)
1197 {
1198         struct vnode *vq;
1199         struct vnode *vqn;
1200         lwkt_tokref ilock;
1201         cdev_t dev;
1202         int error;
1203
1204         /*
1205          * If the vnode has a device association, scrap all vnodes associated
1206          * with the device.  Don't let the device disappear on us while we
1207          * are scrapping the vnodes.
1208          *
1209          * The passed vp will probably show up in the list, do not VX lock
1210          * it twice!
1211          *
1212          * Releasing the vnode's rdev here can mess up specfs's call to
1213          * device close, so don't do it.  The vnode has been disassociated
1214          * and the device will be closed after the last ref on the related
1215          * fp goes away (if not still open by e.g. the kernel).
1216          */
1217         if (vp->v_type != VCHR) {
1218                 error = fdrevoke(vp, DTYPE_VNODE, cred);
1219                 return (error);
1220         }
1221         if ((dev = vp->v_rdev) == NULL) {
1222                 return(0);
1223         }
1224         reference_dev(dev);
1225         lwkt_gettoken(&ilock, &spechash_token);
1226
1227         vqn = SLIST_FIRST(&dev->si_hlist);
1228         if (vqn)
1229                 vref(vqn);
1230         while ((vq = vqn) != NULL) {
1231                 vqn = SLIST_NEXT(vqn, v_cdevnext);
1232                 if (vqn)
1233                         vref(vqn);
1234                 fdrevoke(vq, DTYPE_VNODE, cred);
1235                 /*v_release_rdev(vq);*/
1236                 vrele(vq);
1237         }
1238         lwkt_reltoken(&ilock);
1239         dev_drevoke(dev);
1240         release_dev(dev);
1241         return (0);
1242 }
1243
1244 /*
1245  * This is called when the object underlying a vnode is being destroyed,
1246  * such as in a remove().  Try to recycle the vnode immediately if the
1247  * only active reference is our reference.
1248  *
1249  * Directory vnodes in the namecache with children cannot be immediately
1250  * recycled because numerous VOP_N*() ops require them to be stable.
1251  */
1252 int
1253 vrecycle(struct vnode *vp)
1254 {
1255         if (vp->v_sysref.refcnt <= 1) {
1256                 if (cache_inval_vp_nonblock(vp))
1257                         return(0);
1258                 vgone_vxlocked(vp);
1259                 return (1);
1260         }
1261         return (0);
1262 }
1263
1264 /*
1265  * Return the maximum I/O size allowed for strategy calls on VP.
1266  *
1267  * If vp is VCHR or VBLK we dive the device, otherwise we use
1268  * the vp's mount info.
1269  */
1270 int
1271 vmaxiosize(struct vnode *vp)
1272 {
1273         if (vp->v_type == VBLK || vp->v_type == VCHR) {
1274                 return(vp->v_rdev->si_iosize_max);
1275         } else {
1276                 return(vp->v_mount->mnt_iosize_max);
1277         }
1278 }
1279
1280 /*
1281  * Eliminate all activity associated with a vnode in preparation for reuse.
1282  *
1283  * The vnode must be VX locked and refd and will remain VX locked and refd
1284  * on return.  This routine may be called with the vnode in any state, as
1285  * long as it is VX locked.  The vnode will be cleaned out and marked
1286  * VRECLAIMED but will not actually be reused until all existing refs and
1287  * holds go away.
1288  *
1289  * NOTE: This routine may be called on a vnode which has not yet been
1290  * already been deactivated (VOP_INACTIVE), or on a vnode which has
1291  * already been reclaimed.
1292  *
1293  * This routine is not responsible for placing us back on the freelist. 
1294  * Instead, it happens automatically when the caller releases the VX lock
1295  * (assuming there aren't any other references).
1296  */
1297 void
1298 vgone_vxlocked(struct vnode *vp)
1299 {
1300         /*
1301          * assert that the VX lock is held.  This is an absolute requirement
1302          * now for vgone_vxlocked() to be called.
1303          */
1304         KKASSERT(vp->v_lock.lk_exclusivecount == 1);
1305
1306         get_mplock();
1307
1308         /*
1309          * Clean out the filesystem specific data and set the VRECLAIMED
1310          * bit.  Also deactivate the vnode if necessary. 
1311          */
1312         vclean_vxlocked(vp, DOCLOSE);
1313
1314         /*
1315          * Delete from old mount point vnode list, if on one.
1316          */
1317         if (vp->v_mount != NULL)
1318                 insmntque(vp, NULL);
1319
1320         /*
1321          * If special device, remove it from special device alias list
1322          * if it is on one.  This should normally only occur if a vnode is
1323          * being revoked as the device should otherwise have been released
1324          * naturally.
1325          */
1326         if ((vp->v_type == VBLK || vp->v_type == VCHR) && vp->v_rdev != NULL) {
1327                 v_release_rdev(vp);
1328         }
1329
1330         /*
1331          * Set us to VBAD
1332          */
1333         vp->v_type = VBAD;
1334         rel_mplock();
1335 }
1336
1337 /*
1338  * Lookup a vnode by device number.
1339  *
1340  * Returns non-zero and *vpp set to a vref'd vnode on success.
1341  * Returns zero on failure.
1342  */
1343 int
1344 vfinddev(cdev_t dev, enum vtype type, struct vnode **vpp)
1345 {
1346         lwkt_tokref ilock;
1347         struct vnode *vp;
1348
1349         lwkt_gettoken(&ilock, &spechash_token);
1350         SLIST_FOREACH(vp, &dev->si_hlist, v_cdevnext) {
1351                 if (type == vp->v_type) {
1352                         *vpp = vp;
1353                         vref(vp);
1354                         lwkt_reltoken(&ilock);
1355                         return (1);
1356                 }
1357         }
1358         lwkt_reltoken(&ilock);
1359         return (0);
1360 }
1361
1362 /*
1363  * Calculate the total number of references to a special device.  This
1364  * routine may only be called for VBLK and VCHR vnodes since v_rdev is
1365  * an overloaded field.  Since udev2dev can now return NULL, we have
1366  * to check for a NULL v_rdev.
1367  */
1368 int
1369 count_dev(cdev_t dev)
1370 {
1371         lwkt_tokref ilock;
1372         struct vnode *vp;
1373         int count = 0;
1374
1375         if (SLIST_FIRST(&dev->si_hlist)) {
1376                 lwkt_gettoken(&ilock, &spechash_token);
1377                 SLIST_FOREACH(vp, &dev->si_hlist, v_cdevnext) {
1378                         count += vp->v_opencount;
1379                 }
1380                 lwkt_reltoken(&ilock);
1381         }
1382         return(count);
1383 }
1384
1385 int
1386 vcount(struct vnode *vp)
1387 {
1388         if (vp->v_rdev == NULL)
1389                 return(0);
1390         return(count_dev(vp->v_rdev));
1391 }
1392
1393 /*
1394  * Initialize VMIO for a vnode.  This routine MUST be called before a
1395  * VFS can issue buffer cache ops on a vnode.  It is typically called
1396  * when a vnode is initialized from its inode.
1397  */
1398 int
1399 vinitvmio(struct vnode *vp, off_t filesize)
1400 {
1401         vm_object_t object;
1402         int error = 0;
1403
1404 retry:
1405         if ((object = vp->v_object) == NULL) {
1406                 object = vnode_pager_alloc(vp, filesize, 0, 0);
1407                 /*
1408                  * Dereference the reference we just created.  This assumes
1409                  * that the object is associated with the vp.
1410                  */
1411                 object->ref_count--;
1412                 vrele(vp);
1413         } else {
1414                 if (object->flags & OBJ_DEAD) {
1415                         vn_unlock(vp);
1416                         vm_object_dead_sleep(object, "vodead");
1417                         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1418                         goto retry;
1419                 }
1420         }
1421         KASSERT(vp->v_object != NULL, ("vinitvmio: NULL object"));
1422         vsetflags(vp, VOBJBUF);
1423         return (error);
1424 }
1425
1426
1427 /*
1428  * Print out a description of a vnode.
1429  */
1430 static char *typename[] =
1431 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD"};
1432
1433 void
1434 vprint(char *label, struct vnode *vp)
1435 {
1436         char buf[96];
1437
1438         if (label != NULL)
1439                 kprintf("%s: %p: ", label, (void *)vp);
1440         else
1441                 kprintf("%p: ", (void *)vp);
1442         kprintf("type %s, sysrefs %d, writecount %d, holdcnt %d,",
1443                 typename[vp->v_type],
1444                 vp->v_sysref.refcnt, vp->v_writecount, vp->v_auxrefs);
1445         buf[0] = '\0';
1446         if (vp->v_flag & VROOT)
1447                 strcat(buf, "|VROOT");
1448         if (vp->v_flag & VPFSROOT)
1449                 strcat(buf, "|VPFSROOT");
1450         if (vp->v_flag & VTEXT)
1451                 strcat(buf, "|VTEXT");
1452         if (vp->v_flag & VSYSTEM)
1453                 strcat(buf, "|VSYSTEM");
1454         if (vp->v_flag & VFREE)
1455                 strcat(buf, "|VFREE");
1456         if (vp->v_flag & VOBJBUF)
1457                 strcat(buf, "|VOBJBUF");
1458         if (buf[0] != '\0')
1459                 kprintf(" flags (%s)", &buf[1]);
1460         if (vp->v_data == NULL) {
1461                 kprintf("\n");
1462         } else {
1463                 kprintf("\n\t");
1464                 VOP_PRINT(vp);
1465         }
1466 }
1467
1468 /*
1469  * Do the usual access checking.
1470  * file_mode, uid and gid are from the vnode in question,
1471  * while acc_mode and cred are from the VOP_ACCESS parameter list
1472  */
1473 int
1474 vaccess(enum vtype type, mode_t file_mode, uid_t uid, gid_t gid,
1475     mode_t acc_mode, struct ucred *cred)
1476 {
1477         mode_t mask;
1478         int ismember;
1479
1480         /*
1481          * Super-user always gets read/write access, but execute access depends
1482          * on at least one execute bit being set.
1483          */
1484         if (priv_check_cred(cred, PRIV_ROOT, 0) == 0) {
1485                 if ((acc_mode & VEXEC) && type != VDIR &&
1486                     (file_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0)
1487                         return (EACCES);
1488                 return (0);
1489         }
1490
1491         mask = 0;
1492
1493         /* Otherwise, check the owner. */
1494         if (cred->cr_uid == uid) {
1495                 if (acc_mode & VEXEC)
1496                         mask |= S_IXUSR;
1497                 if (acc_mode & VREAD)
1498                         mask |= S_IRUSR;
1499                 if (acc_mode & VWRITE)
1500                         mask |= S_IWUSR;
1501                 return ((file_mode & mask) == mask ? 0 : EACCES);
1502         }
1503
1504         /* Otherwise, check the groups. */
1505         ismember = groupmember(gid, cred);
1506         if (cred->cr_svgid == gid || ismember) {
1507                 if (acc_mode & VEXEC)
1508                         mask |= S_IXGRP;
1509                 if (acc_mode & VREAD)
1510                         mask |= S_IRGRP;
1511                 if (acc_mode & VWRITE)
1512                         mask |= S_IWGRP;
1513                 return ((file_mode & mask) == mask ? 0 : EACCES);
1514         }
1515
1516         /* Otherwise, check everyone else. */
1517         if (acc_mode & VEXEC)
1518                 mask |= S_IXOTH;
1519         if (acc_mode & VREAD)
1520                 mask |= S_IROTH;
1521         if (acc_mode & VWRITE)
1522                 mask |= S_IWOTH;
1523         return ((file_mode & mask) == mask ? 0 : EACCES);
1524 }
1525
1526 #ifdef DDB
1527 #include <ddb/ddb.h>
1528
1529 static int db_show_locked_vnodes(struct mount *mp, void *data);
1530
1531 /*
1532  * List all of the locked vnodes in the system.
1533  * Called when debugging the kernel.
1534  */
1535 DB_SHOW_COMMAND(lockedvnodes, lockedvnodes)
1536 {
1537         kprintf("Locked vnodes\n");
1538         mountlist_scan(db_show_locked_vnodes, NULL, 
1539                         MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
1540 }
1541
1542 static int
1543 db_show_locked_vnodes(struct mount *mp, void *data __unused)
1544 {
1545         struct vnode *vp;
1546
1547         TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
1548                 if (vn_islocked(vp))
1549                         vprint(NULL, vp);
1550         }
1551         return(0);
1552 }
1553 #endif
1554
1555 /*
1556  * Top level filesystem related information gathering.
1557  */
1558 static int      sysctl_ovfs_conf (SYSCTL_HANDLER_ARGS);
1559
1560 static int
1561 vfs_sysctl(SYSCTL_HANDLER_ARGS)
1562 {
1563         int *name = (int *)arg1 - 1;    /* XXX */
1564         u_int namelen = arg2 + 1;       /* XXX */
1565         struct vfsconf *vfsp;
1566         int maxtypenum;
1567
1568 #if 1 || defined(COMPAT_PRELITE2)
1569         /* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
1570         if (namelen == 1)
1571                 return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
1572 #endif
1573
1574 #ifdef notyet
1575         /* all sysctl names at this level are at least name and field */
1576         if (namelen < 2)
1577                 return (ENOTDIR);               /* overloaded */
1578         if (name[0] != VFS_GENERIC) {
1579                 vfsp = vfsconf_find_by_typenum(name[0]);
1580                 if (vfsp == NULL)
1581                         return (EOPNOTSUPP);
1582                 return ((*vfsp->vfc_vfsops->vfs_sysctl)(&name[1], namelen - 1,
1583                     oldp, oldlenp, newp, newlen, p));
1584         }
1585 #endif
1586         switch (name[1]) {
1587         case VFS_MAXTYPENUM:
1588                 if (namelen != 2)
1589                         return (ENOTDIR);
1590                 maxtypenum = vfsconf_get_maxtypenum();
1591                 return (SYSCTL_OUT(req, &maxtypenum, sizeof(maxtypenum)));
1592         case VFS_CONF:
1593                 if (namelen != 3)
1594                         return (ENOTDIR);       /* overloaded */
1595                 vfsp = vfsconf_find_by_typenum(name[2]);
1596                 if (vfsp == NULL)
1597                         return (EOPNOTSUPP);
1598                 return (SYSCTL_OUT(req, vfsp, sizeof *vfsp));
1599         }
1600         return (EOPNOTSUPP);
1601 }
1602
1603 SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD, vfs_sysctl,
1604         "Generic filesystem");
1605
1606 #if 1 || defined(COMPAT_PRELITE2)
1607
1608 static int
1609 sysctl_ovfs_conf_iter(struct vfsconf *vfsp, void *data)
1610 {
1611         int error;
1612         struct ovfsconf ovfs;
1613         struct sysctl_req *req = (struct sysctl_req*) data;
1614
1615         bzero(&ovfs, sizeof(ovfs));
1616         ovfs.vfc_vfsops = vfsp->vfc_vfsops;     /* XXX used as flag */
1617         strcpy(ovfs.vfc_name, vfsp->vfc_name);
1618         ovfs.vfc_index = vfsp->vfc_typenum;
1619         ovfs.vfc_refcount = vfsp->vfc_refcount;
1620         ovfs.vfc_flags = vfsp->vfc_flags;
1621         error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
1622         if (error)
1623                 return error; /* abort iteration with error code */
1624         else
1625                 return 0; /* continue iterating with next element */
1626 }
1627
1628 static int
1629 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
1630 {
1631         return vfsconf_each(sysctl_ovfs_conf_iter, (void*)req);
1632 }
1633
1634 #endif /* 1 || COMPAT_PRELITE2 */
1635
1636 /*
1637  * Check to see if a filesystem is mounted on a block device.
1638  */
1639 int
1640 vfs_mountedon(struct vnode *vp)
1641 {
1642         cdev_t dev;
1643
1644         if ((dev = vp->v_rdev) == NULL) {
1645 /*              if (vp->v_type != VBLK)
1646                         dev = get_dev(vp->v_uminor, vp->v_umajor); */
1647         }
1648         if (dev != NULL && dev->si_mountpoint)
1649                 return (EBUSY);
1650         return (0);
1651 }
1652
1653 /*
1654  * Unmount all filesystems. The list is traversed in reverse order
1655  * of mounting to avoid dependencies.
1656  */
1657
1658 static int vfs_umountall_callback(struct mount *mp, void *data);
1659
1660 void
1661 vfs_unmountall(void)
1662 {
1663         int count;
1664
1665         do {
1666                 count = mountlist_scan(vfs_umountall_callback, 
1667                                         NULL, MNTSCAN_REVERSE|MNTSCAN_NOBUSY);
1668         } while (count);
1669 }
1670
1671 static
1672 int
1673 vfs_umountall_callback(struct mount *mp, void *data)
1674 {
1675         int error;
1676
1677         error = dounmount(mp, MNT_FORCE);
1678         if (error) {
1679                 mountlist_remove(mp);
1680                 kprintf("unmount of filesystem mounted from %s failed (", 
1681                         mp->mnt_stat.f_mntfromname);
1682                 if (error == EBUSY)
1683                         kprintf("BUSY)\n");
1684                 else
1685                         kprintf("%d)\n", error);
1686         }
1687         return(1);
1688 }
1689
1690 /*
1691  * Checks the mount flags for parameter mp and put the names comma-separated
1692  * into a string buffer buf with a size limit specified by len.
1693  *
1694  * It returns the number of bytes written into buf, and (*errorp) will be
1695  * set to 0, EINVAL (if passed length is 0), or ENOSPC (supplied buffer was
1696  * not large enough).  The buffer will be 0-terminated if len was not 0.
1697  */
1698 size_t
1699 vfs_flagstostr(int flags, const struct mountctl_opt *optp,
1700                char *buf, size_t len, int *errorp)
1701 {
1702         static const struct mountctl_opt optnames[] = {
1703                 { MNT_ASYNC,            "asynchronous" },
1704                 { MNT_EXPORTED,         "NFS exported" },
1705                 { MNT_LOCAL,            "local" },
1706                 { MNT_NOATIME,          "noatime" },
1707                 { MNT_NODEV,            "nodev" },
1708                 { MNT_NOEXEC,           "noexec" },
1709                 { MNT_NOSUID,           "nosuid" },
1710                 { MNT_NOSYMFOLLOW,      "nosymfollow" },
1711                 { MNT_QUOTA,            "with-quotas" },
1712                 { MNT_RDONLY,           "read-only" },
1713                 { MNT_SYNCHRONOUS,      "synchronous" },
1714                 { MNT_UNION,            "union" },
1715                 { MNT_NOCLUSTERR,       "noclusterr" },
1716                 { MNT_NOCLUSTERW,       "noclusterw" },
1717                 { MNT_SUIDDIR,          "suiddir" },
1718                 { MNT_SOFTDEP,          "soft-updates" },
1719                 { MNT_IGNORE,           "ignore" },
1720                 { 0,                    NULL}
1721         };
1722         int bwritten;
1723         int bleft;
1724         int optlen;
1725         int actsize;
1726
1727         *errorp = 0;
1728         bwritten = 0;
1729         bleft = len - 1;        /* leave room for trailing \0 */
1730
1731         /*
1732          * Checks the size of the string. If it contains
1733          * any data, then we will append the new flags to
1734          * it.
1735          */
1736         actsize = strlen(buf);
1737         if (actsize > 0)
1738                 buf += actsize;
1739
1740         /* Default flags if no flags passed */
1741         if (optp == NULL)
1742                 optp = optnames;
1743
1744         if (bleft < 0) {        /* degenerate case, 0-length buffer */
1745                 *errorp = EINVAL;
1746                 return(0);
1747         }
1748
1749         for (; flags && optp->o_opt; ++optp) {
1750                 if ((flags & optp->o_opt) == 0)
1751                         continue;
1752                 optlen = strlen(optp->o_name);
1753                 if (bwritten || actsize > 0) {
1754                         if (bleft < 2) {
1755                                 *errorp = ENOSPC;
1756                                 break;
1757                         }
1758                         buf[bwritten++] = ',';
1759                         buf[bwritten++] = ' ';
1760                         bleft -= 2;
1761                 }
1762                 if (bleft < optlen) {
1763                         *errorp = ENOSPC;
1764                         break;
1765                 }
1766                 bcopy(optp->o_name, buf + bwritten, optlen);
1767                 bwritten += optlen;
1768                 bleft -= optlen;
1769                 flags &= ~optp->o_opt;
1770         }
1771
1772         /*
1773          * Space already reserved for trailing \0
1774          */
1775         buf[bwritten] = 0;
1776         return (bwritten);
1777 }
1778
1779 /*
1780  * Build hash lists of net addresses and hang them off the mount point.
1781  * Called by ufs_mount() to set up the lists of export addresses.
1782  */
1783 static int
1784 vfs_hang_addrlist(struct mount *mp, struct netexport *nep,
1785                 const struct export_args *argp)
1786 {
1787         struct netcred *np;
1788         struct radix_node_head *rnh;
1789         int i;
1790         struct radix_node *rn;
1791         struct sockaddr *saddr, *smask = 0;
1792         struct domain *dom;
1793         int error;
1794
1795         if (argp->ex_addrlen == 0) {
1796                 if (mp->mnt_flag & MNT_DEFEXPORTED)
1797                         return (EPERM);
1798                 np = &nep->ne_defexported;
1799                 np->netc_exflags = argp->ex_flags;
1800                 np->netc_anon = argp->ex_anon;
1801                 np->netc_anon.cr_ref = 1;
1802                 mp->mnt_flag |= MNT_DEFEXPORTED;
1803                 return (0);
1804         }
1805
1806         if (argp->ex_addrlen < 0 || argp->ex_addrlen > MLEN)
1807                 return (EINVAL);
1808         if (argp->ex_masklen < 0 || argp->ex_masklen > MLEN)
1809                 return (EINVAL);
1810
1811         i = sizeof(struct netcred) + argp->ex_addrlen + argp->ex_masklen;
1812         np = (struct netcred *) kmalloc(i, M_NETADDR, M_WAITOK | M_ZERO);
1813         saddr = (struct sockaddr *) (np + 1);
1814         if ((error = copyin(argp->ex_addr, (caddr_t) saddr, argp->ex_addrlen)))
1815                 goto out;
1816         if (saddr->sa_len > argp->ex_addrlen)
1817                 saddr->sa_len = argp->ex_addrlen;
1818         if (argp->ex_masklen) {
1819                 smask = (struct sockaddr *)((caddr_t)saddr + argp->ex_addrlen);
1820                 error = copyin(argp->ex_mask, (caddr_t)smask, argp->ex_masklen);
1821                 if (error)
1822                         goto out;
1823                 if (smask->sa_len > argp->ex_masklen)
1824                         smask->sa_len = argp->ex_masklen;
1825         }
1826         i = saddr->sa_family;
1827         if ((rnh = nep->ne_rtable[i]) == 0) {
1828                 /*
1829                  * Seems silly to initialize every AF when most are not used,
1830                  * do so on demand here
1831                  */
1832                 SLIST_FOREACH(dom, &domains, dom_next)
1833                         if (dom->dom_family == i && dom->dom_rtattach) {
1834                                 dom->dom_rtattach((void **) &nep->ne_rtable[i],
1835                                     dom->dom_rtoffset);
1836                                 break;
1837                         }
1838                 if ((rnh = nep->ne_rtable[i]) == 0) {
1839                         error = ENOBUFS;
1840                         goto out;
1841                 }
1842         }
1843         rn = (*rnh->rnh_addaddr) ((char *) saddr, (char *) smask, rnh,
1844             np->netc_rnodes);
1845         if (rn == 0 || np != (struct netcred *) rn) {   /* already exists */
1846                 error = EPERM;
1847                 goto out;
1848         }
1849         np->netc_exflags = argp->ex_flags;
1850         np->netc_anon = argp->ex_anon;
1851         np->netc_anon.cr_ref = 1;
1852         return (0);
1853 out:
1854         kfree(np, M_NETADDR);
1855         return (error);
1856 }
1857
1858 /* ARGSUSED */
1859 static int
1860 vfs_free_netcred(struct radix_node *rn, void *w)
1861 {
1862         struct radix_node_head *rnh = (struct radix_node_head *) w;
1863
1864         (*rnh->rnh_deladdr) (rn->rn_key, rn->rn_mask, rnh);
1865         kfree((caddr_t) rn, M_NETADDR);
1866         return (0);
1867 }
1868
1869 /*
1870  * Free the net address hash lists that are hanging off the mount points.
1871  */
1872 static void
1873 vfs_free_addrlist(struct netexport *nep)
1874 {
1875         int i;
1876         struct radix_node_head *rnh;
1877
1878         for (i = 0; i <= AF_MAX; i++)
1879                 if ((rnh = nep->ne_rtable[i])) {
1880                         (*rnh->rnh_walktree) (rnh, vfs_free_netcred,
1881                             (caddr_t) rnh);
1882                         kfree((caddr_t) rnh, M_RTABLE);
1883                         nep->ne_rtable[i] = 0;
1884                 }
1885 }
1886
1887 int
1888 vfs_export(struct mount *mp, struct netexport *nep,
1889            const struct export_args *argp)
1890 {
1891         int error;
1892
1893         if (argp->ex_flags & MNT_DELEXPORT) {
1894                 if (mp->mnt_flag & MNT_EXPUBLIC) {
1895                         vfs_setpublicfs(NULL, NULL, NULL);
1896                         mp->mnt_flag &= ~MNT_EXPUBLIC;
1897                 }
1898                 vfs_free_addrlist(nep);
1899                 mp->mnt_flag &= ~(MNT_EXPORTED | MNT_DEFEXPORTED);
1900         }
1901         if (argp->ex_flags & MNT_EXPORTED) {
1902                 if (argp->ex_flags & MNT_EXPUBLIC) {
1903                         if ((error = vfs_setpublicfs(mp, nep, argp)) != 0)
1904                                 return (error);
1905                         mp->mnt_flag |= MNT_EXPUBLIC;
1906                 }
1907                 if ((error = vfs_hang_addrlist(mp, nep, argp)))
1908                         return (error);
1909                 mp->mnt_flag |= MNT_EXPORTED;
1910         }
1911         return (0);
1912 }
1913
1914
1915 /*
1916  * Set the publicly exported filesystem (WebNFS). Currently, only
1917  * one public filesystem is possible in the spec (RFC 2054 and 2055)
1918  */
1919 int
1920 vfs_setpublicfs(struct mount *mp, struct netexport *nep,
1921                 const struct export_args *argp)
1922 {
1923         int error;
1924         struct vnode *rvp;
1925         char *cp;
1926
1927         /*
1928          * mp == NULL -> invalidate the current info, the FS is
1929          * no longer exported. May be called from either vfs_export
1930          * or unmount, so check if it hasn't already been done.
1931          */
1932         if (mp == NULL) {
1933                 if (nfs_pub.np_valid) {
1934                         nfs_pub.np_valid = 0;
1935                         if (nfs_pub.np_index != NULL) {
1936                                 FREE(nfs_pub.np_index, M_TEMP);
1937                                 nfs_pub.np_index = NULL;
1938                         }
1939                 }
1940                 return (0);
1941         }
1942
1943         /*
1944          * Only one allowed at a time.
1945          */
1946         if (nfs_pub.np_valid != 0 && mp != nfs_pub.np_mount)
1947                 return (EBUSY);
1948
1949         /*
1950          * Get real filehandle for root of exported FS.
1951          */
1952         bzero((caddr_t)&nfs_pub.np_handle, sizeof(nfs_pub.np_handle));
1953         nfs_pub.np_handle.fh_fsid = mp->mnt_stat.f_fsid;
1954
1955         if ((error = VFS_ROOT(mp, &rvp)))
1956                 return (error);
1957
1958         if ((error = VFS_VPTOFH(rvp, &nfs_pub.np_handle.fh_fid)))
1959                 return (error);
1960
1961         vput(rvp);
1962
1963         /*
1964          * If an indexfile was specified, pull it in.
1965          */
1966         if (argp->ex_indexfile != NULL) {
1967                 int namelen;
1968
1969                 error = vn_get_namelen(rvp, &namelen);
1970                 if (error)
1971                         return (error);
1972                 MALLOC(nfs_pub.np_index, char *, namelen, M_TEMP,
1973                     M_WAITOK);
1974                 error = copyinstr(argp->ex_indexfile, nfs_pub.np_index,
1975                     namelen, NULL);
1976                 if (!error) {
1977                         /*
1978                          * Check for illegal filenames.
1979                          */
1980                         for (cp = nfs_pub.np_index; *cp; cp++) {
1981                                 if (*cp == '/') {
1982                                         error = EINVAL;
1983                                         break;
1984                                 }
1985                         }
1986                 }
1987                 if (error) {
1988                         FREE(nfs_pub.np_index, M_TEMP);
1989                         return (error);
1990                 }
1991         }
1992
1993         nfs_pub.np_mount = mp;
1994         nfs_pub.np_valid = 1;
1995         return (0);
1996 }
1997
1998 struct netcred *
1999 vfs_export_lookup(struct mount *mp, struct netexport *nep,
2000                 struct sockaddr *nam)
2001 {
2002         struct netcred *np;
2003         struct radix_node_head *rnh;
2004         struct sockaddr *saddr;
2005
2006         np = NULL;
2007         if (mp->mnt_flag & MNT_EXPORTED) {
2008                 /*
2009                  * Lookup in the export list first.
2010                  */
2011                 if (nam != NULL) {
2012                         saddr = nam;
2013                         rnh = nep->ne_rtable[saddr->sa_family];
2014                         if (rnh != NULL) {
2015                                 np = (struct netcred *)
2016                                         (*rnh->rnh_matchaddr)((char *)saddr,
2017                                                               rnh);
2018                                 if (np && np->netc_rnodes->rn_flags & RNF_ROOT)
2019                                         np = NULL;
2020                         }
2021                 }
2022                 /*
2023                  * If no address match, use the default if it exists.
2024                  */
2025                 if (np == NULL && mp->mnt_flag & MNT_DEFEXPORTED)
2026                         np = &nep->ne_defexported;
2027         }
2028         return (np);
2029 }
2030
2031 /*
2032  * perform msync on all vnodes under a mount point.  The mount point must
2033  * be locked.  This code is also responsible for lazy-freeing unreferenced
2034  * vnodes whos VM objects no longer contain pages.
2035  *
2036  * NOTE: MNT_WAIT still skips vnodes in the VXLOCK state.
2037  *
2038  * NOTE: XXX VOP_PUTPAGES and friends requires that the vnode be locked,
2039  * but vnode_pager_putpages() doesn't lock the vnode.  We have to do it
2040  * way up in this high level function.
2041  */
2042 static int vfs_msync_scan1(struct mount *mp, struct vnode *vp, void *data);
2043 static int vfs_msync_scan2(struct mount *mp, struct vnode *vp, void *data);
2044
2045 void
2046 vfs_msync(struct mount *mp, int flags) 
2047 {
2048         int vmsc_flags;
2049
2050         vmsc_flags = VMSC_GETVP;
2051         if (flags != MNT_WAIT)
2052                 vmsc_flags |= VMSC_NOWAIT;
2053         vmntvnodescan(mp, vmsc_flags, vfs_msync_scan1, vfs_msync_scan2,
2054                         (void *)(intptr_t)flags);
2055 }
2056
2057 /*
2058  * scan1 is a fast pre-check.  There could be hundreds of thousands of
2059  * vnodes, we cannot afford to do anything heavy weight until we have a
2060  * fairly good indication that there is work to do.
2061  */
2062 static
2063 int
2064 vfs_msync_scan1(struct mount *mp, struct vnode *vp, void *data)
2065 {
2066         int flags = (int)(intptr_t)data;
2067
2068         if ((vp->v_flag & VRECLAIMED) == 0) {
2069                 if (vshouldmsync(vp))
2070                         return(0);      /* call scan2 */
2071                 if ((mp->mnt_flag & MNT_RDONLY) == 0 &&
2072                     (vp->v_flag & VOBJDIRTY) &&
2073                     (flags == MNT_WAIT || vn_islocked(vp) == 0)) {
2074                         return(0);      /* call scan2 */
2075                 }
2076         }
2077
2078         /*
2079          * do not call scan2, continue the loop
2080          */
2081         return(-1);
2082 }
2083
2084 /*
2085  * This callback is handed a locked vnode.
2086  */
2087 static
2088 int
2089 vfs_msync_scan2(struct mount *mp, struct vnode *vp, void *data)
2090 {
2091         vm_object_t obj;
2092         int flags = (int)(intptr_t)data;
2093
2094         if (vp->v_flag & VRECLAIMED)
2095                 return(0);
2096
2097         if ((mp->mnt_flag & MNT_RDONLY) == 0 && (vp->v_flag & VOBJDIRTY)) {
2098                 if ((obj = vp->v_object) != NULL) {
2099                         vm_object_page_clean(obj, 0, 0, 
2100                          flags == MNT_WAIT ? OBJPC_SYNC : OBJPC_NOSYNC);
2101                 }
2102         }
2103         return(0);
2104 }
2105
2106 /*
2107  * Record a process's interest in events which might happen to
2108  * a vnode.  Because poll uses the historic select-style interface
2109  * internally, this routine serves as both the ``check for any
2110  * pending events'' and the ``record my interest in future events''
2111  * functions.  (These are done together, while the lock is held,
2112  * to avoid race conditions.)
2113  */
2114 int
2115 vn_pollrecord(struct vnode *vp, int events)
2116 {
2117         lwkt_tokref vlock;
2118
2119         KKASSERT(curthread->td_proc != NULL);
2120
2121         lwkt_gettoken(&vlock, &vp->v_token);
2122         if (vp->v_pollinfo.vpi_revents & events) {
2123                 /*
2124                  * This leaves events we are not interested
2125                  * in available for the other process which
2126                  * which presumably had requested them
2127                  * (otherwise they would never have been
2128                  * recorded).
2129                  */
2130                 events &= vp->v_pollinfo.vpi_revents;
2131                 vp->v_pollinfo.vpi_revents &= ~events;
2132
2133                 lwkt_reltoken(&vlock);
2134                 return events;
2135         }
2136         vp->v_pollinfo.vpi_events |= events;
2137         selrecord(curthread, &vp->v_pollinfo.vpi_selinfo);
2138         lwkt_reltoken(&vlock);
2139         return 0;
2140 }
2141
2142 /*
2143  * Note the occurrence of an event.  If the VN_POLLEVENT macro is used,
2144  * it is possible for us to miss an event due to race conditions, but
2145  * that condition is expected to be rare, so for the moment it is the
2146  * preferred interface.
2147  */
2148 void
2149 vn_pollevent(struct vnode *vp, int events)
2150 {
2151         lwkt_tokref vlock;
2152
2153         lwkt_gettoken(&vlock, &vp->v_token);
2154         if (vp->v_pollinfo.vpi_events & events) {
2155                 /*
2156                  * We clear vpi_events so that we don't
2157                  * call selwakeup() twice if two events are
2158                  * posted before the polling process(es) is
2159                  * awakened.  This also ensures that we take at
2160                  * most one selwakeup() if the polling process
2161                  * is no longer interested.  However, it does
2162                  * mean that only one event can be noticed at
2163                  * a time.  (Perhaps we should only clear those
2164                  * event bits which we note?) XXX
2165                  */
2166                 vp->v_pollinfo.vpi_events = 0;  /* &= ~events ??? */
2167                 vp->v_pollinfo.vpi_revents |= events;
2168                 selwakeup(&vp->v_pollinfo.vpi_selinfo);
2169         }
2170         lwkt_reltoken(&vlock);
2171 }
2172
2173 /*
2174  * Wake up anyone polling on vp because it is being revoked.
2175  * This depends on dead_poll() returning POLLHUP for correct
2176  * behavior.
2177  */
2178 void
2179 vn_pollgone(struct vnode *vp)
2180 {
2181         lwkt_tokref vlock;
2182
2183         lwkt_gettoken(&vlock, &vp->v_token);
2184         if (vp->v_pollinfo.vpi_events) {
2185                 vp->v_pollinfo.vpi_events = 0;
2186                 selwakeup(&vp->v_pollinfo.vpi_selinfo);
2187         }
2188         lwkt_reltoken(&vlock);
2189 }
2190
2191 /*
2192  * extract the cdev_t from a VBLK or VCHR.  The vnode must have been opened
2193  * (or v_rdev might be NULL).
2194  */
2195 cdev_t
2196 vn_todev(struct vnode *vp)
2197 {
2198         if (vp->v_type != VBLK && vp->v_type != VCHR)
2199                 return (NULL);
2200         KKASSERT(vp->v_rdev != NULL);
2201         return (vp->v_rdev);
2202 }
2203
2204 /*
2205  * Check if vnode represents a disk device.  The vnode does not need to be
2206  * opened.
2207  *
2208  * MPALMOSTSAFE
2209  */
2210 int
2211 vn_isdisk(struct vnode *vp, int *errp)
2212 {
2213         cdev_t dev;
2214
2215         if (vp->v_type != VCHR) {
2216                 if (errp != NULL)
2217                         *errp = ENOTBLK;
2218                 return (0);
2219         }
2220
2221         dev = vp->v_rdev;
2222
2223         if (dev == NULL) {
2224                 if (errp != NULL)
2225                         *errp = ENXIO;
2226                 return (0);
2227         }
2228         if (dev_is_good(dev) == 0) {
2229                 if (errp != NULL)
2230                         *errp = ENXIO;
2231                 return (0);
2232         }
2233         if ((dev_dflags(dev) & D_DISK) == 0) {
2234                 if (errp != NULL)
2235                         *errp = ENOTBLK;
2236                 return (0);
2237         }
2238         if (errp != NULL)
2239                 *errp = 0;
2240         return (1);
2241 }
2242
2243 int
2244 vn_get_namelen(struct vnode *vp, int *namelen)
2245 {
2246         int error;
2247         register_t retval[2];
2248
2249         error = VOP_PATHCONF(vp, _PC_NAME_MAX, retval);
2250         if (error)
2251                 return (error);
2252         *namelen = (int)retval[0];
2253         return (0);
2254 }
2255
2256 int
2257 vop_write_dirent(int *error, struct uio *uio, ino_t d_ino, uint8_t d_type, 
2258                 uint16_t d_namlen, const char *d_name)
2259 {
2260         struct dirent *dp;
2261         size_t len;
2262
2263         len = _DIRENT_RECLEN(d_namlen);
2264         if (len > uio->uio_resid)
2265                 return(1);
2266
2267         dp = kmalloc(len, M_TEMP, M_WAITOK | M_ZERO);
2268
2269         dp->d_ino = d_ino;
2270         dp->d_namlen = d_namlen;
2271         dp->d_type = d_type;
2272         bcopy(d_name, dp->d_name, d_namlen);
2273
2274         *error = uiomove((caddr_t)dp, len, uio);
2275
2276         kfree(dp, M_TEMP);
2277
2278         return(0);
2279 }
2280
2281 void
2282 vn_mark_atime(struct vnode *vp, struct thread *td)
2283 {
2284         struct proc *p = td->td_proc;
2285         struct ucred *cred = p ? p->p_ucred : proc0.p_ucred;
2286
2287         if ((vp->v_mount->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0) {
2288                 VOP_MARKATIME(vp, cred);
2289         }
2290 }