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