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