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