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