MPSAFE - Add read() and write() path MPSAFE support, and more.
[dragonfly.git] / sys / vfs / specfs / spec_vnops.c
1 /*
2  * Copyright (c) 1989, 1993, 1995
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *      @(#)spec_vnops.c        8.14 (Berkeley) 5/21/95
34  * $FreeBSD: src/sys/miscfs/specfs/spec_vnops.c,v 1.131.2.4 2001/02/26 04:23:20 jlemon Exp $
35  * $DragonFly: src/sys/vfs/specfs/spec_vnops.c,v 1.58 2008/05/06 00:14:12 dillon Exp $
36  */
37
38 #include <sys/param.h>
39 #include <sys/proc.h>
40 #include <sys/systm.h>
41 #include <sys/kernel.h>
42 #include <sys/conf.h>
43 #include <sys/buf.h>
44 #include <sys/device.h>
45 #include <sys/mount.h>
46 #include <sys/vnode.h>
47 #include <sys/stat.h>
48 #include <sys/fcntl.h>
49 #include <sys/vmmeter.h>
50 #include <sys/bus.h>
51 #include <sys/tty.h>
52
53 #include <vm/vm.h>
54 #include <vm/vm_object.h>
55 #include <vm/vm_page.h>
56 #include <vm/vm_pager.h>
57
58 #include <machine/limits.h>
59
60 #include <sys/buf2.h>
61
62 #include <sys/thread2.h>
63
64 /*
65  * Specfs chained debugging (bitmask)
66  *
67  * 0 - disable debugging
68  * 1 - report chained I/Os
69  * 2 - force 4K chained I/Os
70  */
71 #define SPEC_CHAIN_DEBUG        0
72
73 static int      spec_advlock (struct vop_advlock_args *);  
74 static int      spec_bmap (struct vop_bmap_args *);
75 static int      spec_close (struct vop_close_args *);
76 static int      spec_freeblks (struct vop_freeblks_args *);
77 static int      spec_fsync (struct  vop_fsync_args *);
78 static int      spec_getpages (struct vop_getpages_args *);
79 static int      spec_inactive (struct  vop_inactive_args *);
80 static int      spec_ioctl (struct vop_ioctl_args *);
81 static int      spec_open (struct vop_open_args *);
82 static int      spec_poll (struct vop_poll_args *);
83 static int      spec_kqfilter (struct vop_kqfilter_args *);
84 static int      spec_print (struct vop_print_args *);
85 static int      spec_read (struct vop_read_args *);  
86 static int      spec_strategy (struct vop_strategy_args *);
87 static int      spec_write (struct vop_write_args *);
88 static void     spec_strategy_done(struct bio *nbio);
89 static int      spec_getattr (struct vop_getattr_args *);
90
91 struct vop_ops spec_vnode_vops = {
92         .vop_default =          vop_defaultop,
93         .vop_access =           (void *)vop_ebadf,
94         .vop_advlock =          spec_advlock,
95         .vop_bmap =             spec_bmap,
96         .vop_close =            spec_close,
97         .vop_old_create =       (void *)vop_panic,
98         .vop_freeblks =         spec_freeblks,
99         .vop_fsync =            spec_fsync,
100         .vop_getpages =         spec_getpages,
101         .vop_inactive =         spec_inactive,
102         .vop_ioctl =            spec_ioctl,
103         .vop_old_link =         (void *)vop_panic,
104         .vop_old_mkdir =        (void *)vop_panic,
105         .vop_old_mknod =        (void *)vop_panic,
106         .vop_open =             spec_open,
107         .vop_pathconf =         vop_stdpathconf,
108         .vop_poll =             spec_poll,
109         .vop_kqfilter =         spec_kqfilter,
110         .vop_print =            spec_print,
111         .vop_read =             spec_read,
112         .vop_readdir =          (void *)vop_panic,
113         .vop_readlink =         (void *)vop_panic,
114         .vop_reallocblks =      (void *)vop_panic,
115         .vop_reclaim =          (void *)vop_null,
116         .vop_old_remove =       (void *)vop_panic,
117         .vop_old_rename =       (void *)vop_panic,
118         .vop_old_rmdir =        (void *)vop_panic,
119         .vop_setattr =          (void *)vop_ebadf,
120         .vop_getattr =          spec_getattr,
121         .vop_strategy =         spec_strategy,
122         .vop_old_symlink =      (void *)vop_panic,
123         .vop_write =            spec_write
124 };
125
126 struct vop_ops *spec_vnode_vops_p = &spec_vnode_vops;
127
128 VNODEOP_SET(spec_vnode_vops);
129
130 extern int dev_ref_debug;
131
132 /*
133  * spec_vnoperate()
134  */
135 int
136 spec_vnoperate(struct vop_generic_args *ap)
137 {
138         return (VOCALL(&spec_vnode_vops, ap));
139 }
140
141 static void spec_getpages_iodone (struct bio *bio);
142
143 /*
144  * Open a special file.
145  *
146  * spec_open(struct vnode *a_vp, int a_mode, struct ucred *a_cred,
147  *           struct file *a_fp)
148  */
149 /* ARGSUSED */
150 static int
151 spec_open(struct vop_open_args *ap)
152 {
153         struct vnode *vp = ap->a_vp;
154         cdev_t dev;
155         int error;
156         const char *cp;
157
158         /*
159          * Don't allow open if fs is mounted -nodev.
160          */
161         if (vp->v_mount && (vp->v_mount->mnt_flag & MNT_NODEV))
162                 return (ENXIO);
163         if (vp->v_type == VBLK)
164                 return (ENXIO);
165
166         /*
167          * Resolve the device.  If the vnode is already open v_rdev may
168          * already be resolved.  However, if the device changes out from
169          * under us we report it (and, for now, we allow it).  Since
170          * v_release_rdev() zero's v_opencount, we have to save and restore
171          * it when replacing the rdev reference.
172          */
173         if (vp->v_rdev != NULL) {
174                 dev = get_dev(vp->v_umajor, vp->v_uminor);
175                 if (dev != vp->v_rdev) {
176                         int oc = vp->v_opencount;
177                         kprintf(
178                             "Warning: spec_open: dev %s was lost",
179                             vp->v_rdev->si_name);
180                         v_release_rdev(vp);
181                         error = v_associate_rdev(vp, 
182                                         get_dev(vp->v_umajor, vp->v_uminor));
183                         if (error) {
184                                 kprintf(", reacquisition failed\n");
185                         } else {
186                                 vp->v_opencount = oc;
187                                 kprintf(", reacquisition successful\n");
188                         }
189                 } else {
190                         error = 0;
191                 }
192         } else {
193                 error = v_associate_rdev(vp, get_dev(vp->v_umajor, vp->v_uminor));
194         }
195         if (error)
196                 return(error);
197
198         /*
199          * Prevent degenerate open/close sequences from nulling out rdev.
200          */
201         dev = vp->v_rdev;
202         KKASSERT(dev != NULL);
203
204         /*
205          * Make this field valid before any I/O in ->d_open.  XXX the
206          * device itself should probably be required to initialize
207          * this field in d_open.
208          */
209         if (!dev->si_iosize_max)
210                 dev->si_iosize_max = DFLTPHYS;
211
212         /*
213          * XXX: Disks get special billing here, but it is mostly wrong.
214          * XXX: diskpartitions can overlap and the real checks should
215          * XXX: take this into account, and consequently they need to
216          * XXX: live in the diskslicing code.  Some checks do.
217          */
218         if (vn_isdisk(vp, NULL) && ap->a_cred != FSCRED && 
219             (ap->a_mode & FWRITE)) {
220                 /*
221                  * Never allow opens for write if the device is mounted R/W
222                  */
223                 if (vp->v_rdev && vp->v_rdev->si_mountpoint &&
224                     !(vp->v_rdev->si_mountpoint->mnt_flag & MNT_RDONLY)) {
225                                 error = EBUSY;
226                                 goto done;
227                 }
228
229                 /*
230                  * When running in secure mode, do not allow opens
231                  * for writing if the device is mounted
232                  */
233                 if (securelevel >= 1 && vfs_mountedon(vp)) {
234                         error = EPERM;
235                         goto done;
236                 }
237
238                 /*
239                  * When running in very secure mode, do not allow
240                  * opens for writing of any devices.
241                  */
242                 if (securelevel >= 2) {
243                         error = EPERM;
244                         goto done;
245                 }
246         }
247
248         /* XXX: Special casing of ttys for deadfs.  Probably redundant */
249         if (dev_dflags(dev) & D_TTY)
250                 vp->v_flag |= VISTTY;
251         if ((dev_dflags(dev) & D_SEEKABLE) == 0)
252                 vp->v_flag |= VNOTSEEKABLE;
253
254         /*
255          * dev_dopen() is always called for each open.  dev_dclose() is
256          * only called for the last close unless D_TRACKCLOSE is set.
257          */
258         vn_unlock(vp);
259         error = dev_dopen(dev, ap->a_mode, S_IFCHR, ap->a_cred);
260         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
261
262         if (error)
263                 goto done;
264
265         if (dev_dflags(dev) & D_TTY) {
266                 if (dev->si_tty) {
267                         struct tty *tp;
268                         tp = dev->si_tty;
269                         if (!tp->t_stop) {
270                                 kprintf("Warning:%s: no t_stop, using nottystop\n", devtoname(dev));
271                                 tp->t_stop = nottystop;
272                         }
273                 }
274         }
275
276         /*
277          * If this is 'disk' or disk-like device, associate a VM object
278          * with it.
279          */
280         if (vn_isdisk(vp, NULL)) {
281                 if (!dev->si_bsize_phys)
282                         dev->si_bsize_phys = DEV_BSIZE;
283                 vinitvmio(vp, IDX_TO_OFF(INT_MAX));
284         }
285         if ((dev_dflags(dev) & D_DISK) == 0) {
286                 cp = devtoname(dev);
287                 if (*cp == '#') {
288                         kprintf("WARNING: driver %s should register devices with make_dev() (cdev_t = \"%s\")\n",
289                             dev_dname(dev), cp);
290                 }
291         }
292
293         /*
294          * If we were handed a file pointer we may be able to install a
295          * shortcut which issues device read and write operations directly
296          * from the fileops rather then having to go through spec_read()
297          * and spec_write().
298          */
299         if (ap->a_fp)
300                 vn_setspecops(ap->a_fp);
301
302         if (dev_ref_debug)
303                 kprintf("spec_open: %s %d\n", dev->si_name, vp->v_opencount);
304 done:
305         if (error) {
306                 if (vp->v_opencount == 0)
307                         v_release_rdev(vp);
308         } else {
309                 vop_stdopen(ap);
310         }
311         return (error);
312 }
313
314 /*
315  * Vnode op for read
316  *
317  * spec_read(struct vnode *a_vp, struct uio *a_uio, int a_ioflag,
318  *           struct ucred *a_cred)
319  */
320 /* ARGSUSED */
321 static int
322 spec_read(struct vop_read_args *ap)
323 {
324         struct vnode *vp;
325         struct thread *td;
326         struct uio *uio;
327         cdev_t dev;
328         int error;
329
330         vp = ap->a_vp;
331         dev = vp->v_rdev;
332         uio = ap->a_uio;
333         td = uio->uio_td;
334
335         if (dev == NULL)                /* device was revoked */
336                 return (EBADF);
337         if (uio->uio_resid == 0)
338                 return (0);
339
340         vn_unlock(vp);
341         error = dev_dread(dev, uio, ap->a_ioflag);
342         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
343         return (error);
344 }
345
346 /*
347  * Vnode op for write
348  *
349  * spec_write(struct vnode *a_vp, struct uio *a_uio, int a_ioflag,
350  *            struct ucred *a_cred)
351  */
352 /* ARGSUSED */
353 static int
354 spec_write(struct vop_write_args *ap)
355 {
356         struct vnode *vp;
357         struct thread *td;
358         struct uio *uio;
359         cdev_t dev;
360         int error;
361
362         vp = ap->a_vp;
363         dev = vp->v_rdev;
364         uio = ap->a_uio;
365         td = uio->uio_td;
366
367         KKASSERT(uio->uio_segflg != UIO_NOCOPY);
368
369         if (dev == NULL)                /* device was revoked */
370                 return (EBADF);
371
372         vn_unlock(vp);
373         error = dev_dwrite(dev, uio, ap->a_ioflag);
374         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
375         return (error);
376 }
377
378 /*
379  * This call modifying an upper layer filesystem's idea of the owner only.
380  * It does NOT replace the upper layer filesystem's getattr.
381  *
382  * XXX spec_getattr() - TEMPORARY - remove when devfs is fully installed.
383  *                      This is a horrible hack.  The code will get confused
384  *                      if root chown's a tty device and then fails to chown
385  *                      it back after finishing with it.  Non-root chowns are
386  *                      strictly stored in the device and don't have the issue.
387  */
388 static int
389 spec_getattr (struct vop_getattr_args *ap)
390 {
391         struct vattr *vap = ap->a_vap;
392         struct vnode *vp = ap->a_vp;
393         cdev_t dev;
394
395         if (vp->v_type != VCHR)
396                 return (0);
397         if ((dev = vp->v_rdev) == NULL) {
398                 if ((dev = vp->v_rdev) == NULL)
399                         dev = get_dev(vp->v_umajor, vp->v_uminor);
400                 if (dev == NULL)
401                         return (0);
402         }
403         if (vap->va_uid == 0) {
404                 vap->va_uid = dev->si_uid;
405         }
406         return (0);
407 }
408
409 /*
410  * Device ioctl operation.
411  *
412  * spec_ioctl(struct vnode *a_vp, int a_command, caddr_t a_data,
413  *            int a_fflag, struct ucred *a_cred)
414  */
415 /* ARGSUSED */
416 static int
417 spec_ioctl(struct vop_ioctl_args *ap)
418 {
419         cdev_t dev;
420
421         if ((dev = ap->a_vp->v_rdev) == NULL)
422                 return (EBADF);         /* device was revoked */
423
424         return (dev_dioctl(dev, ap->a_command, ap->a_data,
425                     ap->a_fflag, ap->a_cred));
426 }
427
428 /*
429  * spec_poll(struct vnode *a_vp, int a_events, struct ucred *a_cred)
430  */
431 /* ARGSUSED */
432 static int
433 spec_poll(struct vop_poll_args *ap)
434 {
435         cdev_t dev;
436
437         if ((dev = ap->a_vp->v_rdev) == NULL)
438                 return (EBADF);         /* device was revoked */
439         return (dev_dpoll(dev, ap->a_events));
440 }
441
442 /*
443  * spec_kqfilter(struct vnode *a_vp, struct knote *a_kn)
444  */
445 /* ARGSUSED */
446 static int
447 spec_kqfilter(struct vop_kqfilter_args *ap)
448 {
449         cdev_t dev;
450
451         if ((dev = ap->a_vp->v_rdev) == NULL)
452                 return (EBADF);         /* device was revoked */
453         return (dev_dkqfilter(dev, ap->a_kn));
454 }
455
456 /*
457  * Synch buffers associated with a block device
458  *
459  * spec_fsync(struct vnode *a_vp, int a_waitfor)
460  */
461 /* ARGSUSED */
462 static int
463 spec_fsync(struct vop_fsync_args *ap)
464 {
465         struct vnode *vp = ap->a_vp;
466         int error;
467
468         if (!vn_isdisk(vp, NULL))
469                 return (0);
470
471         /*
472          * Flush all dirty buffers associated with a block device.
473          */
474         error = vfsync(vp, ap->a_waitfor, 10000, NULL, NULL);
475         return (error);
476 }
477
478 /*
479  * spec_inactive(struct vnode *a_vp)
480  */
481 static int
482 spec_inactive(struct vop_inactive_args *ap)
483 {
484         return (0);
485 }
486
487 /*
488  * Convert a vnode strategy call into a device strategy call.  Vnode strategy
489  * calls are not limited to device DMA limits so we have to deal with the
490  * case.
491  *
492  * spec_strategy(struct vnode *a_vp, struct bio *a_bio)
493  */
494 static int
495 spec_strategy(struct vop_strategy_args *ap)
496 {
497         struct bio *bio = ap->a_bio;
498         struct buf *bp = bio->bio_buf;
499         struct buf *nbp;
500         struct vnode *vp;
501         struct mount *mp;
502         int chunksize;
503         int maxiosize;
504
505         if (bp->b_cmd != BUF_CMD_READ && LIST_FIRST(&bp->b_dep) != NULL)
506                 buf_start(bp);
507
508         /*
509          * Collect statistics on synchronous and asynchronous read
510          * and write counts for disks that have associated filesystems.
511          */
512         vp = ap->a_vp;
513         KKASSERT(vp->v_rdev != NULL);   /* XXX */
514         if (vn_isdisk(vp, NULL) && (mp = vp->v_rdev->si_mountpoint) != NULL) {
515                 if (bp->b_cmd == BUF_CMD_READ) {
516                         if (bp->b_flags & B_ASYNC)
517                                 mp->mnt_stat.f_asyncreads++;
518                         else
519                                 mp->mnt_stat.f_syncreads++;
520                 } else {
521                         if (bp->b_flags & B_ASYNC)
522                                 mp->mnt_stat.f_asyncwrites++;
523                         else
524                                 mp->mnt_stat.f_syncwrites++;
525                 }
526         }
527
528         /*
529          * Device iosize limitations only apply to read and write.  Shortcut
530          * the I/O if it fits.
531          */
532         if ((maxiosize = vp->v_rdev->si_iosize_max) == 0) {
533                 kprintf("%s: si_iosize_max not set!\n", dev_dname(vp->v_rdev));
534                 maxiosize = MAXPHYS;
535         }
536 #if SPEC_CHAIN_DEBUG & 2
537         maxiosize = 4096;
538 #endif
539         if (bp->b_bcount <= maxiosize ||
540             (bp->b_cmd != BUF_CMD_READ && bp->b_cmd != BUF_CMD_WRITE)) {
541                 dev_dstrategy_chain(vp->v_rdev, bio);
542                 return (0);
543         }
544
545         /*
546          * Clone the buffer and set up an I/O chain to chunk up the I/O.
547          */
548         nbp = kmalloc(sizeof(*bp), M_DEVBUF, M_INTWAIT|M_ZERO);
549         initbufbio(nbp);
550         buf_dep_init(nbp);
551         BUF_LOCKINIT(nbp);
552         BUF_LOCK(nbp, LK_EXCLUSIVE);
553         BUF_KERNPROC(nbp);
554         nbp->b_vp = vp;
555         nbp->b_flags = B_PAGING | (bp->b_flags & B_BNOCLIP);
556         nbp->b_data = bp->b_data;
557         nbp->b_bio1.bio_done = spec_strategy_done;
558         nbp->b_bio1.bio_offset = bio->bio_offset;
559         nbp->b_bio1.bio_caller_info1.ptr = bio;
560
561         /*
562          * Start the first transfer
563          */
564         if (vn_isdisk(vp, NULL))
565                 chunksize = vp->v_rdev->si_bsize_phys;
566         else
567                 chunksize = DEV_BSIZE;
568         chunksize = maxiosize / chunksize * chunksize;
569 #if SPEC_CHAIN_DEBUG & 1
570         kprintf("spec_strategy chained I/O chunksize=%d\n", chunksize);
571 #endif
572         nbp->b_cmd = bp->b_cmd;
573         nbp->b_bcount = chunksize;
574         nbp->b_bufsize = chunksize;     /* used to detect a short I/O */
575         nbp->b_bio1.bio_caller_info2.index = chunksize;
576
577 #if SPEC_CHAIN_DEBUG & 1
578         kprintf("spec_strategy: chain %p offset %d/%d bcount %d\n",
579                 bp, 0, bp->b_bcount, nbp->b_bcount);
580 #endif
581
582         dev_dstrategy(vp->v_rdev, &nbp->b_bio1);
583         return (0);
584 }
585
586 /*
587  * Chunked up transfer completion routine - chain transfers until done
588  */
589 static
590 void
591 spec_strategy_done(struct bio *nbio)
592 {
593         struct buf *nbp = nbio->bio_buf;
594         struct bio *bio = nbio->bio_caller_info1.ptr;   /* original bio */
595         struct buf *bp = bio->bio_buf;                  /* original bp */
596         int chunksize = nbio->bio_caller_info2.index;   /* chunking */
597         int boffset = nbp->b_data - bp->b_data;
598
599         if (nbp->b_flags & B_ERROR) {
600                 /*
601                  * An error terminates the chain, propogate the error back
602                  * to the original bp
603                  */
604                 bp->b_flags |= B_ERROR;
605                 bp->b_error = nbp->b_error;
606                 bp->b_resid = bp->b_bcount - boffset +
607                               (nbp->b_bcount - nbp->b_resid);
608 #if SPEC_CHAIN_DEBUG & 1
609                 kprintf("spec_strategy: chain %p error %d bcount %d/%d\n",
610                         bp, bp->b_error, bp->b_bcount,
611                         bp->b_bcount - bp->b_resid);
612 #endif
613                 kfree(nbp, M_DEVBUF);
614                 biodone(bio);
615         } else if (nbp->b_resid) {
616                 /*
617                  * A short read or write terminates the chain
618                  */
619                 bp->b_error = nbp->b_error;
620                 bp->b_resid = bp->b_bcount - boffset +
621                               (nbp->b_bcount - nbp->b_resid);
622 #if SPEC_CHAIN_DEBUG & 1
623                 kprintf("spec_strategy: chain %p short read(1) bcount %d/%d\n",
624                         bp, bp->b_bcount - bp->b_resid, bp->b_bcount);
625 #endif
626                 kfree(nbp, M_DEVBUF);
627                 biodone(bio);
628         } else if (nbp->b_bcount != nbp->b_bufsize) {
629                 /*
630                  * A short read or write can also occur by truncating b_bcount
631                  */
632 #if SPEC_CHAIN_DEBUG & 1
633                 kprintf("spec_strategy: chain %p short read(2) bcount %d/%d\n",
634                         bp, nbp->b_bcount + boffset, bp->b_bcount);
635 #endif
636                 bp->b_error = 0;
637                 bp->b_bcount = nbp->b_bcount + boffset; 
638                 bp->b_resid = nbp->b_resid;
639                 kfree(nbp, M_DEVBUF);
640                 biodone(bio);
641         } else if (nbp->b_bcount + boffset == bp->b_bcount) {
642                 /*
643                  * No more data terminates the chain
644                  */
645 #if SPEC_CHAIN_DEBUG & 1
646                 kprintf("spec_strategy: chain %p finished bcount %d\n",
647                         bp, bp->b_bcount);
648 #endif
649                 bp->b_error = 0;
650                 bp->b_resid = 0;
651                 kfree(nbp, M_DEVBUF);
652                 biodone(bio);
653         } else {
654                 /*
655                  * Continue the chain
656                  */
657                 boffset += nbp->b_bcount;
658                 nbp->b_data = bp->b_data + boffset;
659                 nbp->b_bcount = bp->b_bcount - boffset;
660                 if (nbp->b_bcount > chunksize)
661                         nbp->b_bcount = chunksize;
662                 nbp->b_bio1.bio_done = spec_strategy_done;
663                 nbp->b_bio1.bio_offset = bio->bio_offset + boffset;
664
665 #if SPEC_CHAIN_DEBUG & 1
666                 kprintf("spec_strategy: chain %p offset %d/%d bcount %d\n",
667                         bp, boffset, bp->b_bcount, nbp->b_bcount);
668 #endif
669
670                 dev_dstrategy(nbp->b_vp->v_rdev, &nbp->b_bio1);
671         }
672 }
673
674 /*
675  * spec_freeblks(struct vnode *a_vp, daddr_t a_addr, daddr_t a_length)
676  */
677 static int
678 spec_freeblks(struct vop_freeblks_args *ap)
679 {
680         struct buf *bp;
681
682         /*
683          * XXX: This assumes that strategy does the deed right away.
684          * XXX: this may not be TRTTD.
685          */
686         KKASSERT(ap->a_vp->v_rdev != NULL);
687         if ((dev_dflags(ap->a_vp->v_rdev) & D_CANFREE) == 0)
688                 return (0);
689         bp = geteblk(ap->a_length);
690         bp->b_cmd = BUF_CMD_FREEBLKS;
691         bp->b_bio1.bio_offset = ap->a_offset;
692         bp->b_bcount = ap->a_length;
693         dev_dstrategy(ap->a_vp->v_rdev, &bp->b_bio1);
694         return (0);
695 }
696
697 /*
698  * Implement degenerate case where the block requested is the block
699  * returned, and assume that the entire device is contiguous in regards
700  * to the contiguous block range (runp and runb).
701  *
702  * spec_bmap(struct vnode *a_vp, off_t a_loffset,
703  *           off_t *a_doffsetp, int *a_runp, int *a_runb)
704  */
705 static int
706 spec_bmap(struct vop_bmap_args *ap)
707 {
708         if (ap->a_doffsetp != NULL)
709                 *ap->a_doffsetp = ap->a_loffset;
710         if (ap->a_runp != NULL)
711                 *ap->a_runp = MAXBSIZE;
712         if (ap->a_runb != NULL) {
713                 if (ap->a_loffset < MAXBSIZE)
714                         *ap->a_runb = (int)ap->a_loffset;
715                 else
716                         *ap->a_runb = MAXBSIZE;
717         }
718         return (0);
719 }
720
721 /*
722  * Device close routine
723  *
724  * spec_close(struct vnode *a_vp, int a_fflag)
725  *
726  * NOTE: The vnode may or may not be locked on call.
727  */
728 /* ARGSUSED */
729 static int
730 spec_close(struct vop_close_args *ap)
731 {
732         struct proc *p = curproc;
733         struct vnode *vp = ap->a_vp;
734         cdev_t dev = vp->v_rdev;
735         int error;
736         int needrelock;
737
738         /*
739          * A couple of hacks for devices and tty devices.  The
740          * vnode ref count cannot be used to figure out the
741          * last close, but we can use v_opencount now that
742          * revoke works properly.
743          *
744          * Detect the last close on a controlling terminal and clear
745          * the session (half-close).
746          */
747         if (dev)
748                 reference_dev(dev);
749
750         if (p && vp->v_opencount <= 1 && vp == p->p_session->s_ttyvp) {
751                 p->p_session->s_ttyvp = NULL;
752                 vrele(vp);
753         }
754
755         /*
756          * Vnodes can be opened and closed multiple times.  Do not really
757          * close the device unless (1) it is being closed forcibly,
758          * (2) the device wants to track closes, or (3) this is the last
759          * vnode doing its last close on the device.
760          *
761          * XXX the VXLOCK (force close) case can leave vnodes referencing
762          * a closed device.  This might not occur now that our revoke is
763          * fixed.
764          */
765         if (dev && ((vp->v_flag & VRECLAIMED) ||
766             (dev_dflags(dev) & D_TRACKCLOSE) ||
767             (vp->v_opencount == 1))) {
768                 needrelock = 0;
769                 if (vn_islocked(vp)) {
770                         needrelock = 1;
771                         vn_unlock(vp);
772                 }
773                 error = dev_dclose(dev, ap->a_fflag, S_IFCHR);
774                 if (needrelock)
775                         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
776         } else {
777                 error = 0;
778         }
779
780         /*
781          * Track the actual opens and closes on the vnode.  The last close
782          * disassociates the rdev.  If the rdev is already disassociated or the
783          * opencount is already 0, the vnode might have been revoked and no
784          * further opencount tracking occurs.
785          */
786         if (dev) {
787                 if (dev_ref_debug) {
788                         kprintf("spec_close: %s %d\n",
789                                 dev->si_name, vp->v_opencount - 1);
790                 }
791                 if (vp->v_opencount == 1)
792                         v_release_rdev(vp);
793                 release_dev(dev);
794         }
795         if (vp->v_opencount > 0)
796                 vop_stdclose(ap);
797         return(error);
798 }
799
800 /*
801  * Print out the contents of a special device vnode.
802  *
803  * spec_print(struct vnode *a_vp)
804  */
805 static int
806 spec_print(struct vop_print_args *ap)
807 {
808         kprintf("tag VT_NON, dev %s\n", devtoname(ap->a_vp->v_rdev));
809         return (0);
810 }
811
812 /*
813  * Special device advisory byte-level locks.
814  *
815  * spec_advlock(struct vnode *a_vp, caddr_t a_id, int a_op,
816  *              struct flock *a_fl, int a_flags)
817  */
818 /* ARGSUSED */
819 static int
820 spec_advlock(struct vop_advlock_args *ap)
821 {
822         return ((ap->a_flags & F_POSIX) ? EINVAL : EOPNOTSUPP);
823 }
824
825 static void
826 spec_getpages_iodone(struct bio *bio)
827 {
828         bio->bio_buf->b_cmd = BUF_CMD_DONE;
829         wakeup(bio->bio_buf);
830 }
831
832 /*
833  * spec_getpages() - get pages associated with device vnode.
834  *
835  * Note that spec_read and spec_write do not use the buffer cache, so we
836  * must fully implement getpages here.
837  */
838 static int
839 spec_getpages(struct vop_getpages_args *ap)
840 {
841         vm_offset_t kva;
842         int error;
843         int i, pcount, size;
844         struct buf *bp;
845         vm_page_t m;
846         vm_ooffset_t offset;
847         int toff, nextoff, nread;
848         struct vnode *vp = ap->a_vp;
849         int blksiz;
850         int gotreqpage;
851
852         error = 0;
853         pcount = round_page(ap->a_count) / PAGE_SIZE;
854
855         /*
856          * Calculate the offset of the transfer and do sanity check.
857          */
858         offset = IDX_TO_OFF(ap->a_m[0]->pindex) + ap->a_offset;
859
860         /*
861          * Round up physical size for real devices.  We cannot round using
862          * v_mount's block size data because v_mount has nothing to do with
863          * the device.  i.e. it's usually '/dev'.  We need the physical block
864          * size for the device itself.
865          *
866          * We can't use v_rdev->si_mountpoint because it only exists when the
867          * block device is mounted.  However, we can use v_rdev.
868          */
869
870         if (vn_isdisk(vp, NULL))
871                 blksiz = vp->v_rdev->si_bsize_phys;
872         else
873                 blksiz = DEV_BSIZE;
874
875         size = (ap->a_count + blksiz - 1) & ~(blksiz - 1);
876
877         bp = getpbuf(NULL);
878         kva = (vm_offset_t)bp->b_data;
879
880         /*
881          * Map the pages to be read into the kva.
882          */
883         pmap_qenter(kva, ap->a_m, pcount);
884
885         /* Build a minimal buffer header. */
886         bp->b_cmd = BUF_CMD_READ;
887         bp->b_bcount = size;
888         bp->b_resid = 0;
889         bp->b_runningbufspace = size;
890         if (size) {
891                 runningbufspace += bp->b_runningbufspace;
892                 ++runningbufcount;
893         }
894
895         bp->b_bio1.bio_offset = offset;
896         bp->b_bio1.bio_done = spec_getpages_iodone;
897
898         mycpu->gd_cnt.v_vnodein++;
899         mycpu->gd_cnt.v_vnodepgsin += pcount;
900
901         /* Do the input. */
902         vn_strategy(ap->a_vp, &bp->b_bio1);
903
904         crit_enter();
905
906         /* We definitely need to be at splbio here. */
907         while (bp->b_cmd != BUF_CMD_DONE)
908                 tsleep(bp, 0, "spread", 0);
909
910         crit_exit();
911
912         if (bp->b_flags & B_ERROR) {
913                 if (bp->b_error)
914                         error = bp->b_error;
915                 else
916                         error = EIO;
917         }
918
919         /*
920          * If EOF is encountered we must zero-extend the result in order
921          * to ensure that the page does not contain garabge.  When no
922          * error occurs, an early EOF is indicated if b_bcount got truncated.
923          * b_resid is relative to b_bcount and should be 0, but some devices
924          * might indicate an EOF with b_resid instead of truncating b_bcount.
925          */
926         nread = bp->b_bcount - bp->b_resid;
927         if (nread < ap->a_count)
928                 bzero((caddr_t)kva + nread, ap->a_count - nread);
929         pmap_qremove(kva, pcount);
930
931         gotreqpage = 0;
932         for (i = 0, toff = 0; i < pcount; i++, toff = nextoff) {
933                 nextoff = toff + PAGE_SIZE;
934                 m = ap->a_m[i];
935
936                 m->flags &= ~PG_ZERO;
937
938                 if (nextoff <= nread) {
939                         m->valid = VM_PAGE_BITS_ALL;
940                         vm_page_undirty(m);
941                 } else if (toff < nread) {
942                         /*
943                          * Since this is a VM request, we have to supply the
944                          * unaligned offset to allow vm_page_set_validclean()
945                          * to zero sub-DEV_BSIZE'd portions of the page.
946                          */
947                         vm_page_set_validclean(m, 0, nread - toff);
948                 } else {
949                         m->valid = 0;
950                         vm_page_undirty(m);
951                 }
952
953                 if (i != ap->a_reqpage) {
954                         /*
955                          * Just in case someone was asking for this page we
956                          * now tell them that it is ok to use.
957                          */
958                         if (!error || (m->valid == VM_PAGE_BITS_ALL)) {
959                                 if (m->valid) {
960                                         if (m->flags & PG_WANTED) {
961                                                 vm_page_activate(m);
962                                         } else {
963                                                 vm_page_deactivate(m);
964                                         }
965                                         vm_page_wakeup(m);
966                                 } else {
967                                         vm_page_free(m);
968                                 }
969                         } else {
970                                 vm_page_free(m);
971                         }
972                 } else if (m->valid) {
973                         gotreqpage = 1;
974                         /*
975                          * Since this is a VM request, we need to make the
976                          * entire page presentable by zeroing invalid sections.
977                          */
978                         if (m->valid != VM_PAGE_BITS_ALL)
979                             vm_page_zero_invalid(m, FALSE);
980                 }
981         }
982         if (!gotreqpage) {
983                 m = ap->a_m[ap->a_reqpage];
984                 kprintf(
985             "spec_getpages:(%s) I/O read failure: (error=%d) bp %p vp %p\n",
986                         devtoname(vp->v_rdev), error, bp, bp->b_vp);
987                 kprintf(
988             "               size: %d, resid: %d, a_count: %d, valid: 0x%x\n",
989                     size, bp->b_resid, ap->a_count, m->valid);
990                 kprintf(
991             "               nread: %d, reqpage: %d, pindex: %lu, pcount: %d\n",
992                     nread, ap->a_reqpage, (u_long)m->pindex, pcount);
993                 /*
994                  * Free the buffer header back to the swap buffer pool.
995                  */
996                 relpbuf(bp, NULL);
997                 return VM_PAGER_ERROR;
998         }
999         /*
1000          * Free the buffer header back to the swap buffer pool.
1001          */
1002         relpbuf(bp, NULL);
1003         return VM_PAGER_OK;
1004 }