Merge branch 'master' of ssh://crater.dragonflybsd.org/repository/git/dragonfly
[dragonfly.git] / sys / vfs / devfs / devfs_vnops.c
1 /*
2  * Copyright (c) 2009 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Alex Hornung <ahornung@gmail.com>
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  * 3. Neither the name of The DragonFly Project nor the names of its
18  *    contributors may be used to endorse or promote products derived
19  *    from this software without specific, prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
24  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
25  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
26  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
27  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
28  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
31  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 #include <sys/param.h>
35 #include <sys/systm.h>
36 #include <sys/time.h>
37 #include <sys/kernel.h>
38 #include <sys/lock.h>
39 #include <sys/fcntl.h>
40 #include <sys/proc.h>
41 #include <sys/priv.h>
42 #include <sys/signalvar.h>
43 #include <sys/vnode.h>
44 #include <sys/uio.h>
45 #include <sys/mount.h>
46 #include <sys/file.h>
47 #include <sys/fcntl.h>
48 #include <sys/namei.h>
49 #include <sys/dirent.h>
50 #include <sys/malloc.h>
51 #include <sys/stat.h>
52 #include <sys/reg.h>
53 #include <sys/buf2.h>
54 #include <vm/vm_pager.h>
55 #include <vm/vm_zone.h>
56 #include <vm/vm_object.h>
57 #include <sys/filio.h>
58 #include <sys/ttycom.h>
59 #include <sys/sysref2.h>
60 #include <sys/tty.h>
61 #include <vfs/devfs/devfs.h>
62 #include <sys/pioctl.h>
63
64 #include <machine/limits.h>
65
66 MALLOC_DECLARE(M_DEVFS);
67 #define DEVFS_BADOP     (void *)devfs_badop
68
69 static int devfs_badop(struct vop_generic_args *);
70 static int devfs_access(struct vop_access_args *);
71 static int devfs_inactive(struct vop_inactive_args *);
72 static int devfs_reclaim(struct vop_reclaim_args *);
73 static int devfs_readdir(struct vop_readdir_args *);
74 static int devfs_getattr(struct vop_getattr_args *);
75 static int devfs_setattr(struct vop_setattr_args *);
76 static int devfs_readlink(struct vop_readlink_args *);
77 static int devfs_print(struct vop_print_args *);
78
79 static int devfs_nresolve(struct vop_nresolve_args *);
80 static int devfs_nlookupdotdot(struct vop_nlookupdotdot_args *);
81 static int devfs_nsymlink(struct vop_nsymlink_args *);
82 static int devfs_nremove(struct vop_nremove_args *);
83
84 static int devfs_spec_open(struct vop_open_args *);
85 static int devfs_spec_close(struct vop_close_args *);
86 static int devfs_spec_fsync(struct vop_fsync_args *);
87
88 static int devfs_spec_read(struct vop_read_args *);
89 static int devfs_spec_write(struct vop_write_args *);
90 static int devfs_spec_ioctl(struct vop_ioctl_args *);
91 static int devfs_spec_poll(struct vop_poll_args *);
92 static int devfs_spec_kqfilter(struct vop_kqfilter_args *);
93 static int devfs_spec_strategy(struct vop_strategy_args *);
94 static void devfs_spec_strategy_done(struct bio *);
95 static int devfs_spec_freeblks(struct vop_freeblks_args *);
96 static int devfs_spec_bmap(struct vop_bmap_args *);
97 static int devfs_spec_advlock(struct vop_advlock_args *);
98 static void devfs_spec_getpages_iodone(struct bio *);
99 static int devfs_spec_getpages(struct vop_getpages_args *);
100
101
102 static int devfs_specf_close(struct file *);
103 static int devfs_specf_read(struct file *, struct uio *, struct ucred *, int);
104 static int devfs_specf_write(struct file *, struct uio *, struct ucred *, int);
105 static int devfs_specf_stat(struct file *, struct stat *, struct ucred *);
106 static int devfs_specf_kqfilter(struct file *, struct knote *);
107 static int devfs_specf_poll(struct file *, int, struct ucred *);
108 static int devfs_specf_ioctl(struct file *, u_long, caddr_t, struct ucred *);
109
110
111 static __inline int sequential_heuristic(struct uio *, struct file *);
112 extern struct lock              devfs_lock;
113
114 /*
115  * devfs vnode operations for regular files
116  */
117 struct vop_ops devfs_vnode_norm_vops = {
118         .vop_default =          vop_defaultop,
119         .vop_access =           devfs_access,
120         .vop_advlock =          DEVFS_BADOP,
121         .vop_bmap =                     DEVFS_BADOP,
122         .vop_close =            vop_stdclose,
123         .vop_getattr =          devfs_getattr,
124         .vop_inactive =         devfs_inactive,
125         .vop_ncreate =          DEVFS_BADOP,
126         .vop_nresolve =         devfs_nresolve,
127         .vop_nlookupdotdot =    devfs_nlookupdotdot,
128         .vop_nlink =            DEVFS_BADOP,
129         .vop_nmkdir =           DEVFS_BADOP,
130         .vop_nmknod =           DEVFS_BADOP,
131         .vop_nremove =          devfs_nremove,
132         .vop_nrename =          DEVFS_BADOP,
133         .vop_nrmdir =           DEVFS_BADOP,
134         .vop_nsymlink =         devfs_nsymlink,
135         .vop_open =                     vop_stdopen,
136         .vop_pathconf =         vop_stdpathconf,
137         .vop_print =            devfs_print,
138         .vop_read =                     DEVFS_BADOP,
139         .vop_readdir =          devfs_readdir,
140         .vop_readlink =         devfs_readlink,
141         .vop_reclaim =          devfs_reclaim,
142         .vop_setattr =          devfs_setattr,
143         .vop_write =            DEVFS_BADOP,
144         .vop_ioctl =            DEVFS_BADOP
145 };
146
147 /*
148  * devfs vnode operations for character devices
149  */
150 struct vop_ops devfs_vnode_dev_vops = {
151         .vop_default =          vop_defaultop,
152         .vop_access =           devfs_access,
153         .vop_advlock =          devfs_spec_advlock,
154         .vop_bmap =                     devfs_spec_bmap,
155         .vop_close =            devfs_spec_close,
156         .vop_freeblks =         devfs_spec_freeblks,
157         .vop_fsync =            devfs_spec_fsync,
158         .vop_getattr =          devfs_getattr,
159         .vop_getpages =         devfs_spec_getpages,
160         .vop_inactive =         devfs_inactive,
161         .vop_open =                     devfs_spec_open,
162         .vop_pathconf =         vop_stdpathconf,
163         .vop_print =            devfs_print,
164         .vop_poll =                     devfs_spec_poll,
165         .vop_kqfilter =         devfs_spec_kqfilter,
166         .vop_read =                     devfs_spec_read,
167         .vop_readdir =          DEVFS_BADOP,
168         .vop_readlink =         DEVFS_BADOP,
169         .vop_reclaim =          devfs_reclaim,
170         .vop_setattr =          devfs_setattr,
171         .vop_strategy =         devfs_spec_strategy,
172         .vop_write =            devfs_spec_write,
173         .vop_ioctl =            devfs_spec_ioctl
174 };
175
176 struct vop_ops *devfs_vnode_dev_vops_p = &devfs_vnode_dev_vops;
177
178 struct fileops devfs_dev_fileops = {
179         .fo_read = devfs_specf_read,
180         .fo_write = devfs_specf_write,
181         .fo_ioctl = devfs_specf_ioctl,
182         .fo_poll = devfs_specf_poll,
183         .fo_kqfilter = devfs_specf_kqfilter,
184         .fo_stat = devfs_specf_stat,
185         .fo_close = devfs_specf_close,
186         .fo_shutdown = nofo_shutdown
187 };
188
189
190 /*
191  * generic entry point for unsupported operations
192  */
193 static int
194 devfs_badop(struct vop_generic_args *ap)
195 {
196         return (EIO);
197 }
198
199
200 static int
201 devfs_access(struct vop_access_args *ap)
202 {
203         struct devfs_node *node = DEVFS_NODE(ap->a_vp);
204         int error;
205
206         if (!devfs_node_is_accessible(node))
207                 return ENOENT;
208         error = vop_helper_access(ap, node->uid, node->gid,
209                                 node->mode, node->flags);
210
211         return error;
212 }
213
214
215 static int
216 devfs_inactive(struct vop_inactive_args *ap)
217 {
218         struct devfs_node *node = DEVFS_NODE(ap->a_vp);
219
220         if (node == NULL || (node->flags & DEVFS_NODE_LINKED) == 0)
221                 vrecycle(ap->a_vp);
222         return 0;
223 }
224
225
226 static int
227 devfs_reclaim(struct vop_reclaim_args *ap)
228 {
229         struct devfs_node *node;
230         struct vnode *vp;
231         int locked;
232
233         /*
234          * Check if it is locked already. if not, we acquire the devfs lock
235          */
236         if (!(lockstatus(&devfs_lock, curthread)) == LK_EXCLUSIVE) {
237                 lockmgr(&devfs_lock, LK_EXCLUSIVE);
238                 locked = 1;
239         } else {
240                 locked = 0;
241         }
242
243         /*
244          * Get rid of the devfs_node if it is no longer linked into the
245          * topology.
246          */
247         vp = ap->a_vp;
248         if ((node = DEVFS_NODE(vp)) != NULL) {
249                 if ((node->flags & DEVFS_NODE_LINKED) == 0) {
250                         devfs_freep(node);
251                         /* NOTE: v_data is NULLd out by freep */
252                 } else {
253                         node->v_node = NULL;
254                         /* vp->v_data = NULL; handled below */
255                 }
256         }
257
258         if (locked)
259                 lockmgr(&devfs_lock, LK_RELEASE);
260
261         /*
262          * v_rdev needs to be properly released using v_release_rdev
263          * Make sure v_data is NULL as well.
264          */
265         vp->v_data = NULL;
266         v_release_rdev(vp);
267         return 0;
268 }
269
270
271 static int
272 devfs_readdir(struct vop_readdir_args *ap)
273 {
274         struct devfs_node *dnode = DEVFS_NODE(ap->a_vp);
275         struct devfs_node *node;
276         int cookie_index;
277         int ncookies;
278         int error2;
279         int error;
280         int r;
281         off_t *cookies;
282         off_t saveoff;
283
284         devfs_debug(DEVFS_DEBUG_DEBUG, "devfs_readdir() called!\n");
285
286         if (ap->a_uio->uio_offset < 0 || ap->a_uio->uio_offset > INT_MAX)
287                 return (EINVAL);
288         if ((error = vn_lock(ap->a_vp, LK_EXCLUSIVE | LK_RETRY)) != 0)
289                 return (error);
290
291         if (!devfs_node_is_accessible(dnode))
292                 return ENOENT;
293
294         lockmgr(&devfs_lock, LK_EXCLUSIVE);
295
296         saveoff = ap->a_uio->uio_offset;
297
298         if (ap->a_ncookies) {
299                 ncookies = ap->a_uio->uio_resid / 16 + 1; /* Why / 16 ?? */
300                 if (ncookies > 256)
301                         ncookies = 256;
302                 cookies = kmalloc(256 * sizeof(off_t), M_TEMP, M_WAITOK);
303                 cookie_index = 0;
304         } else {
305                 ncookies = -1;
306                 cookies = NULL;
307                 cookie_index = 0;
308         }
309
310         nanotime(&dnode->atime);
311
312         if (saveoff == 0) {
313                 r = vop_write_dirent(&error, ap->a_uio, dnode->d_dir.d_ino,
314                                      DT_DIR, 1, ".");
315                 if (r)
316                         goto done;
317                 if (cookies)
318                         cookies[cookie_index] = saveoff;
319                 saveoff++;
320                 cookie_index++;
321                 if (cookie_index == ncookies)
322                         goto done;
323         }
324
325         if (saveoff == 1) {
326                 if (dnode->parent) {
327                         r = vop_write_dirent(&error, ap->a_uio,
328                                              dnode->parent->d_dir.d_ino,
329                                              DT_DIR, 2, "..");
330                 } else {
331                         r = vop_write_dirent(&error, ap->a_uio,
332                                              dnode->d_dir.d_ino,
333                                              DT_DIR, 2, "..");
334                 }
335                 if (r)
336                         goto done;
337                 if (cookies)
338                         cookies[cookie_index] = saveoff;
339                 saveoff++;
340                 cookie_index++;
341                 if (cookie_index == ncookies)
342                         goto done;
343         }
344
345         TAILQ_FOREACH(node, DEVFS_DENODE_HEAD(dnode), link) {
346                 if ((node->flags & DEVFS_HIDDEN) ||
347                     (node->flags & DEVFS_INVISIBLE)) {
348                         continue;
349                 }
350
351                 /*
352                  * If the node type is a valid devfs alias, then we make sure that the
353                  * target isn't hidden. If it is, we don't show the link in the
354                  * directory listing.
355                  */
356                 if ((node->node_type == Plink) && (node->link_target != NULL) &&
357                         (node->link_target->flags & DEVFS_HIDDEN))
358                         continue;
359
360                 if (node->cookie < saveoff)
361                         continue;
362
363                 saveoff = node->cookie;
364
365                 error2 = vop_write_dirent(&error, ap->a_uio, node->d_dir.d_ino,
366                                           node->d_dir.d_type,
367                                           node->d_dir.d_namlen,
368                                           node->d_dir.d_name);
369
370                 if (error2)
371                         break;
372
373                 saveoff++;
374
375                 if (cookies)
376                         cookies[cookie_index] = node->cookie;
377                 ++cookie_index;
378                 if (cookie_index == ncookies)
379                         break;
380         }
381
382 done:
383         lockmgr(&devfs_lock, LK_RELEASE);
384         vn_unlock(ap->a_vp);
385
386         ap->a_uio->uio_offset = saveoff;
387         if (error && cookie_index == 0) {
388                 if (cookies) {
389                         kfree(cookies, M_TEMP);
390                         *ap->a_ncookies = 0;
391                         *ap->a_cookies = NULL;
392                 }
393         } else {
394                 if (cookies) {
395                         *ap->a_ncookies = cookie_index;
396                         *ap->a_cookies = cookies;
397                 }
398         }
399         return (error);
400 }
401
402
403 static int
404 devfs_nresolve(struct vop_nresolve_args *ap)
405 {
406         struct devfs_node *dnode = DEVFS_NODE(ap->a_dvp);
407         struct devfs_node *node, *found = NULL;
408         struct namecache *ncp;
409         struct vnode *vp = NULL;
410         int error = 0;
411         int len;
412         int hidden = 0;
413
414         ncp = ap->a_nch->ncp;
415         len = ncp->nc_nlen;
416
417         if (!devfs_node_is_accessible(dnode))
418                 return ENOENT;
419
420         lockmgr(&devfs_lock, LK_EXCLUSIVE);
421
422         if ((dnode->node_type != Proot) && (dnode->node_type != Pdir)) {
423                 error = ENOENT;
424                 cache_setvp(ap->a_nch, NULL);
425                 goto out;
426         }
427
428         TAILQ_FOREACH(node, DEVFS_DENODE_HEAD(dnode), link) {
429                 if (len == node->d_dir.d_namlen) {
430                         if (!memcmp(ncp->nc_name, node->d_dir.d_name, len)) {
431                                 found = node;
432                                 break;
433                         }
434                 }
435         }
436
437         if (found) {
438                 if ((found->node_type == Plink) && (found->link_target))
439                         found = found->link_target;
440
441                 if (!(found->flags & DEVFS_HIDDEN))
442                         devfs_allocv(/*ap->a_dvp->v_mount, */ &vp, found);
443                 else
444                         hidden = 1;
445         }
446
447         if (vp == NULL) {
448                 error = ENOENT;
449                 cache_setvp(ap->a_nch, NULL);
450                 goto out;
451
452         }
453         KKASSERT(vp);
454         vn_unlock(vp);
455         cache_setvp(ap->a_nch, vp);
456         vrele(vp);
457 out:
458         lockmgr(&devfs_lock, LK_RELEASE);
459
460         return error;
461 }
462
463
464 static int
465 devfs_nlookupdotdot(struct vop_nlookupdotdot_args *ap)
466 {
467         struct devfs_node *dnode = DEVFS_NODE(ap->a_dvp);
468
469         *ap->a_vpp = NULL;
470         if (!devfs_node_is_accessible(dnode))
471                 return ENOENT;
472
473         lockmgr(&devfs_lock, LK_EXCLUSIVE);
474         if (dnode->parent != NULL) {
475                 devfs_allocv(ap->a_vpp, dnode->parent);
476                 vn_unlock(*ap->a_vpp);
477         }
478         lockmgr(&devfs_lock, LK_RELEASE);
479
480         return ((*ap->a_vpp == NULL) ? ENOENT : 0);
481 }
482
483
484 static int
485 devfs_getattr(struct vop_getattr_args *ap)
486 {
487         struct devfs_node *node = DEVFS_NODE(ap->a_vp);
488         struct vattr *vap = ap->a_vap;
489         int error = 0;
490
491         if (!devfs_node_is_accessible(node))
492                 return ENOENT;
493
494         lockmgr(&devfs_lock, LK_EXCLUSIVE);
495
496         /* start by zeroing out the attributes */
497         VATTR_NULL(vap);
498
499         /* next do all the common fields */
500         vap->va_type = ap->a_vp->v_type;
501         vap->va_mode = node->mode;
502         vap->va_fileid = DEVFS_NODE(ap->a_vp)->d_dir.d_ino ;
503         vap->va_flags = 0; /* XXX: what should this be? */
504         vap->va_blocksize = DEV_BSIZE;
505         vap->va_bytes = vap->va_size = sizeof(struct devfs_node);
506
507         vap->va_fsid = ap->a_vp->v_mount->mnt_stat.f_fsid.val[0];
508
509         vap->va_atime = node->atime;
510         vap->va_mtime = node->mtime;
511         vap->va_ctime = node->ctime;
512
513         vap->va_nlink = 1; /* number of references to file */
514
515         vap->va_uid = node->uid;
516         vap->va_gid = node->gid;
517
518         vap->va_rmajor = 0;
519         vap->va_rminor = 0;
520
521         if ((node->node_type == Pdev) && node->d_dev)  {
522                 reference_dev(node->d_dev);
523                 vap->va_rminor = node->d_dev->si_uminor;
524                 release_dev(node->d_dev);
525         }
526
527         /* For a softlink the va_size is the length of the softlink */
528         if (node->symlink_name != 0) {
529                 vap->va_size = node->symlink_namelen;
530         }
531         lockmgr(&devfs_lock, LK_RELEASE);
532
533         return (error);
534 }
535
536
537 static int
538 devfs_setattr(struct vop_setattr_args *ap)
539 {
540         struct devfs_node *node = DEVFS_NODE(ap->a_vp);
541         struct vattr *vap;
542         int error = 0;
543
544         if (!devfs_node_is_accessible(node))
545                 return ENOENT;
546
547         lockmgr(&devfs_lock, LK_EXCLUSIVE);
548
549         vap = ap->a_vap;
550
551         if (vap->va_uid != (uid_t)VNOVAL) {
552                 if ((ap->a_cred->cr_uid != node->uid) &&
553                     (!groupmember(node->gid, ap->a_cred))) {
554                         error = priv_check(curthread, PRIV_VFS_CHOWN);
555                         if (error)
556                                 goto out;
557                 }
558                 node->uid = vap->va_uid;
559         }
560
561         if (vap->va_gid != (uid_t)VNOVAL) {
562                 if ((ap->a_cred->cr_uid != node->uid) &&
563                     (!groupmember(node->gid, ap->a_cred))) {
564                         error = priv_check(curthread, PRIV_VFS_CHOWN);
565                         if (error)
566                                 goto out;
567                 }
568                 node->gid = vap->va_gid;
569         }
570
571         if (vap->va_mode != (mode_t)VNOVAL) {
572                 if (ap->a_cred->cr_uid != node->uid) {
573                         error = priv_check(curthread, PRIV_VFS_ADMIN);
574                         if (error)
575                                 goto out;
576                 }
577                 node->mode = vap->va_mode;
578         }
579
580 out:
581         nanotime(&node->ctime);
582         lockmgr(&devfs_lock, LK_RELEASE);
583
584         return error;
585 }
586
587
588 static int
589 devfs_readlink(struct vop_readlink_args *ap)
590 {
591         struct devfs_node *node = DEVFS_NODE(ap->a_vp);
592         int ret;
593
594         if (!devfs_node_is_accessible(node))
595                 return ENOENT;
596
597         lockmgr(&devfs_lock, LK_EXCLUSIVE);
598         ret = uiomove(node->symlink_name, node->symlink_namelen, ap->a_uio);
599         lockmgr(&devfs_lock, LK_RELEASE);
600
601         return ret;
602 }
603
604
605 static int
606 devfs_print(struct vop_print_args *ap)
607 {
608         return (0);
609 }
610
611
612 static int
613 devfs_nsymlink(struct vop_nsymlink_args *ap)
614 {
615         struct devfs_node *dnode = DEVFS_NODE(ap->a_dvp);
616         struct devfs_node *node;
617         size_t targetlen;
618
619         if (!devfs_node_is_accessible(dnode))
620                 return ENOENT;
621
622         ap->a_vap->va_type = VLNK;
623
624         if ((dnode->node_type != Proot) && (dnode->node_type != Pdir))
625                 goto out;
626
627         lockmgr(&devfs_lock, LK_EXCLUSIVE);
628         devfs_allocvp(ap->a_dvp->v_mount, ap->a_vpp, Plink,
629                       ap->a_nch->ncp->nc_name, dnode, NULL);
630
631         targetlen = strlen(ap->a_target);
632         if (*ap->a_vpp) {
633                 node = DEVFS_NODE(*ap->a_vpp);
634                 node->flags |= DEVFS_USER_CREATED;
635                 node->symlink_namelen = targetlen;
636                 node->symlink_name = kmalloc(targetlen + 1, M_DEVFS, M_WAITOK);
637                 memcpy(node->symlink_name, ap->a_target, targetlen);
638                 node->symlink_name[targetlen] = '\0';
639                 cache_setunresolved(ap->a_nch);
640                 cache_setvp(ap->a_nch, *ap->a_vpp);
641         }
642         lockmgr(&devfs_lock, LK_RELEASE);
643 out:
644         return ((*ap->a_vpp == NULL) ? ENOTDIR : 0);
645 }
646
647
648 static int
649 devfs_nremove(struct vop_nremove_args *ap)
650 {
651         struct devfs_node *dnode = DEVFS_NODE(ap->a_dvp);
652         struct devfs_node *node;
653         struct namecache *ncp;
654         int error = ENOENT;
655
656         ncp = ap->a_nch->ncp;
657
658         if (!devfs_node_is_accessible(dnode))
659                 return ENOENT;
660
661         lockmgr(&devfs_lock, LK_EXCLUSIVE);
662
663         if ((dnode->node_type != Proot) && (dnode->node_type != Pdir))
664                 goto out;
665
666         TAILQ_FOREACH(node, DEVFS_DENODE_HEAD(dnode), link) {
667                 if (ncp->nc_nlen != node->d_dir.d_namlen)
668                         continue;
669                 if (memcmp(ncp->nc_name, node->d_dir.d_name, ncp->nc_nlen))
670                         continue;
671
672                 /*
673                  * only allow removal of user created stuff (e.g. symlinks)
674                  */
675                 if ((node->flags & DEVFS_USER_CREATED) == 0) {
676                         error = EPERM;
677                         goto out;
678                 } else {
679                         if (node->v_node)
680                                 cache_inval_vp(node->v_node, CINV_DESTROY);
681                         devfs_unlinkp(node);
682                         error = 0;
683                         break;
684                 }
685         }
686
687         cache_setunresolved(ap->a_nch);
688         cache_setvp(ap->a_nch, NULL);
689
690 out:
691         lockmgr(&devfs_lock, LK_RELEASE);
692         return error;
693 }
694
695
696 static int
697 devfs_spec_open(struct vop_open_args *ap)
698 {
699         struct vnode *vp = ap->a_vp;
700         struct vnode *orig_vp = NULL;
701         struct devfs_node *node = DEVFS_NODE(vp);
702         struct devfs_node *newnode;
703         cdev_t dev, ndev = NULL;
704         int error = 0;
705
706         if (node) {
707                 if (node->d_dev == NULL)
708                         return ENXIO;
709                 if (!devfs_node_is_accessible(node))
710                         return ENOENT;
711         }
712
713         if ((dev = vp->v_rdev) == NULL)
714                 return ENXIO;
715
716         if (node && ap->a_fp) {
717                 devfs_debug(DEVFS_DEBUG_DEBUG, "devfs_spec_open: -1.1-\n");
718                 lockmgr(&devfs_lock, LK_EXCLUSIVE);
719
720                 ndev = devfs_clone(dev, node->d_dir.d_name, node->d_dir.d_namlen,
721                                                 ap->a_mode, ap->a_cred);
722                 if (ndev != NULL) {
723                         newnode = devfs_create_device_node(
724                                         DEVFS_MNTDATA(vp->v_mount)->root_node,
725                                         ndev, NULL, NULL);
726                         /* XXX: possibly destroy device if this happens */
727
728                         if (newnode != NULL) {
729                                 dev = ndev;
730                                 devfs_link_dev(dev);
731
732                                 devfs_debug(DEVFS_DEBUG_DEBUG,
733                                                 "parent here is: %s, node is: |%s|\n",
734                                                 ((node->parent->node_type == Proot) ?
735                                                 "ROOT!" : node->parent->d_dir.d_name),
736                                                 newnode->d_dir.d_name);
737                                 devfs_debug(DEVFS_DEBUG_DEBUG,
738                                                 "test: %s\n",
739                                                 ((struct devfs_node *)(TAILQ_LAST(DEVFS_DENODE_HEAD(node->parent), devfs_node_head)))->d_dir.d_name);
740
741                                 /*
742                                  * orig_vp is set to the original vp if we cloned.
743                                  */
744                                 /* node->flags |= DEVFS_CLONED; */
745                                 devfs_allocv(&vp, newnode);
746                                 orig_vp = ap->a_vp;
747                                 ap->a_vp = vp;
748                         }
749                 }
750                 lockmgr(&devfs_lock, LK_RELEASE);
751         }
752
753         devfs_debug(DEVFS_DEBUG_DEBUG,
754                     "devfs_spec_open() called on %s! \n",
755                     dev->si_name);
756
757         /*
758          * Make this field valid before any I/O in ->d_open
759          */
760         if (!dev->si_iosize_max)
761                 dev->si_iosize_max = DFLTPHYS;
762
763         if (dev_dflags(dev) & D_TTY)
764                 vp->v_flag |= VISTTY;
765
766         vn_unlock(vp);
767         error = dev_dopen(dev, ap->a_mode, S_IFCHR, ap->a_cred);
768         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
769
770         /*
771          * Clean up any cloned vp if we error out.
772          */
773         if (error) {
774                 if (orig_vp) {
775                         vput(vp);
776                         ap->a_vp = orig_vp;
777                         /* orig_vp = NULL; */
778                 }
779                 return error;
780         }
781
782
783         if (dev_dflags(dev) & D_TTY) {
784                 if (dev->si_tty) {
785                         struct tty *tp;
786                         tp = dev->si_tty;
787                         if (!tp->t_stop) {
788                                 devfs_debug(DEVFS_DEBUG_DEBUG,
789                                             "devfs: no t_stop\n");
790                                 tp->t_stop = nottystop;
791                         }
792                 }
793         }
794
795
796         if (vn_isdisk(vp, NULL)) {
797                 if (!dev->si_bsize_phys)
798                         dev->si_bsize_phys = DEV_BSIZE;
799                 vinitvmio(vp, IDX_TO_OFF(INT_MAX));
800         }
801
802         vop_stdopen(ap);
803 #if 0
804         if (node)
805                 nanotime(&node->atime);
806 #endif
807
808         if (orig_vp)
809                 vn_unlock(vp);
810
811         /* Ugly pty magic, to make pty devices appear once they are opened */
812         if (node && (node->flags & DEVFS_PTY) == DEVFS_PTY)
813                 node->flags &= ~DEVFS_INVISIBLE;
814
815         if (ap->a_fp) {
816                 ap->a_fp->f_type = DTYPE_VNODE;
817                 ap->a_fp->f_flag = ap->a_mode & FMASK;
818                 ap->a_fp->f_ops = &devfs_dev_fileops;
819                 ap->a_fp->f_data = vp;
820         }
821
822         return 0;
823 }
824
825
826 static int
827 devfs_spec_close(struct vop_close_args *ap)
828 {
829         struct devfs_node *node = DEVFS_NODE(ap->a_vp);
830         struct proc *p = curproc;
831         struct vnode *vp = ap->a_vp;
832         cdev_t dev = vp->v_rdev;
833         int error = 0;
834         int needrelock;
835
836         devfs_debug(DEVFS_DEBUG_DEBUG,
837                     "devfs_spec_close() called on %s! \n",
838                     dev->si_name);
839
840         /*
841          * A couple of hacks for devices and tty devices.  The
842          * vnode ref count cannot be used to figure out the
843          * last close, but we can use v_opencount now that
844          * revoke works properly.
845          *
846          * Detect the last close on a controlling terminal and clear
847          * the session (half-close).
848          */
849         if (dev)
850                 reference_dev(dev);
851
852         if (p && vp->v_opencount <= 1 && vp == p->p_session->s_ttyvp) {
853                 p->p_session->s_ttyvp = NULL;
854                 vrele(vp);
855         }
856
857         /*
858          * Vnodes can be opened and closed multiple times.  Do not really
859          * close the device unless (1) it is being closed forcibly,
860          * (2) the device wants to track closes, or (3) this is the last
861          * vnode doing its last close on the device.
862          *
863          * XXX the VXLOCK (force close) case can leave vnodes referencing
864          * a closed device.  This might not occur now that our revoke is
865          * fixed.
866          */
867         devfs_debug(DEVFS_DEBUG_DEBUG, "devfs_spec_close() -1- \n");
868         if (dev && ((vp->v_flag & VRECLAIMED) ||
869             (dev_dflags(dev) & D_TRACKCLOSE) ||
870             (vp->v_opencount == 1))) {
871                 /*
872                  * Unlock around dev_dclose()
873                  */
874                 needrelock = 0;
875                 if (vn_islocked(vp)) {
876                         needrelock = 1;
877                         vn_unlock(vp);
878                 }
879                 error = dev_dclose(dev, ap->a_fflag, S_IFCHR);
880
881                 /*
882                  * Ugly pty magic, to make pty devices disappear again once
883                  * they are closed
884                  */
885                 if (node && (node->flags & DEVFS_PTY) == DEVFS_PTY)
886                         node->flags |= DEVFS_INVISIBLE;
887
888                 if (needrelock)
889                         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
890         } else {
891                 error = 0;
892         }
893         devfs_debug(DEVFS_DEBUG_DEBUG, "devfs_spec_close() -2- \n");
894
895         /*
896          * Track the actual opens and closes on the vnode.  The last close
897          * disassociates the rdev.  If the rdev is already disassociated or
898          * the opencount is already 0, the vnode might have been revoked
899          * and no further opencount tracking occurs.
900          */
901         if (dev)
902                 release_dev(dev);
903         if (vp->v_opencount > 0)
904                 vop_stdclose(ap);
905         return(error);
906
907 }
908
909
910 static int
911 devfs_specf_close(struct file *fp)
912 {
913         struct vnode *vp = (struct vnode *)fp->f_data;
914         int error;
915
916         get_mplock();
917         fp->f_ops = &badfileops;
918         error = vn_close(vp, fp->f_flag);
919         rel_mplock();
920
921         return (error);
922 }
923
924
925 /*
926  * Device-optimized file table vnode read routine.
927  *
928  * This bypasses the VOP table and talks directly to the device.  Most
929  * filesystems just route to specfs and can make this optimization.
930  *
931  * MPALMOSTSAFE - acquires mplock
932  */
933 static int
934 devfs_specf_read(struct file *fp, struct uio *uio,
935                  struct ucred *cred, int flags)
936 {
937         struct devfs_node *node;
938         struct vnode *vp;
939         int ioflag;
940         int error;
941         cdev_t dev;
942
943         get_mplock();
944         KASSERT(uio->uio_td == curthread,
945                 ("uio_td %p is not td %p", uio->uio_td, curthread));
946
947         vp = (struct vnode *)fp->f_data;
948         if (vp == NULL || vp->v_type == VBAD) {
949                 error = EBADF;
950                 goto done;
951         }
952         node = DEVFS_NODE(vp);
953
954         if ((dev = vp->v_rdev) == NULL) {
955                 error = EBADF;
956                 goto done;
957         }
958
959         reference_dev(dev);
960
961         if (uio->uio_resid == 0) {
962                 error = 0;
963                 goto done;
964         }
965         if ((flags & O_FOFFSET) == 0)
966                 uio->uio_offset = fp->f_offset;
967
968         ioflag = 0;
969         if (flags & O_FBLOCKING) {
970                 /* ioflag &= ~IO_NDELAY; */
971         } else if (flags & O_FNONBLOCKING) {
972                 ioflag |= IO_NDELAY;
973         } else if (fp->f_flag & FNONBLOCK) {
974                 ioflag |= IO_NDELAY;
975         }
976         if (flags & O_FBUFFERED) {
977                 /* ioflag &= ~IO_DIRECT; */
978         } else if (flags & O_FUNBUFFERED) {
979                 ioflag |= IO_DIRECT;
980         } else if (fp->f_flag & O_DIRECT) {
981                 ioflag |= IO_DIRECT;
982         }
983         ioflag |= sequential_heuristic(uio, fp);
984
985         error = dev_dread(dev, uio, ioflag);
986
987         release_dev(dev);
988         if (node)
989                 nanotime(&node->atime);
990         if ((flags & O_FOFFSET) == 0)
991                 fp->f_offset = uio->uio_offset;
992         fp->f_nextoff = uio->uio_offset;
993 done:
994         rel_mplock();
995         return (error);
996 }
997
998
999 static int
1000 devfs_specf_write(struct file *fp, struct uio *uio,
1001                   struct ucred *cred, int flags)
1002 {
1003         struct devfs_node *node;
1004         struct vnode *vp;
1005         int ioflag;
1006         int error;
1007         cdev_t dev;
1008
1009         get_mplock();
1010         KASSERT(uio->uio_td == curthread,
1011                 ("uio_td %p is not p %p", uio->uio_td, curthread));
1012
1013         vp = (struct vnode *)fp->f_data;
1014         if (vp == NULL || vp->v_type == VBAD) {
1015                 error = EBADF;
1016                 goto done;
1017         }
1018         node = DEVFS_NODE(vp);
1019         if (vp->v_type == VREG)
1020                 bwillwrite(uio->uio_resid);
1021         vp = (struct vnode *)fp->f_data;
1022
1023         if ((dev = vp->v_rdev) == NULL) {
1024                 error = EBADF;
1025                 goto done;
1026         }
1027         reference_dev(dev);
1028
1029         if ((flags & O_FOFFSET) == 0)
1030                 uio->uio_offset = fp->f_offset;
1031
1032         ioflag = IO_UNIT;
1033         if (vp->v_type == VREG &&
1034            ((fp->f_flag & O_APPEND) || (flags & O_FAPPEND))) {
1035                 ioflag |= IO_APPEND;
1036         }
1037
1038         if (flags & O_FBLOCKING) {
1039                 /* ioflag &= ~IO_NDELAY; */
1040         } else if (flags & O_FNONBLOCKING) {
1041                 ioflag |= IO_NDELAY;
1042         } else if (fp->f_flag & FNONBLOCK) {
1043                 ioflag |= IO_NDELAY;
1044         }
1045         if (flags & O_FBUFFERED) {
1046                 /* ioflag &= ~IO_DIRECT; */
1047         } else if (flags & O_FUNBUFFERED) {
1048                 ioflag |= IO_DIRECT;
1049         } else if (fp->f_flag & O_DIRECT) {
1050                 ioflag |= IO_DIRECT;
1051         }
1052         if (flags & O_FASYNCWRITE) {
1053                 /* ioflag &= ~IO_SYNC; */
1054         } else if (flags & O_FSYNCWRITE) {
1055                 ioflag |= IO_SYNC;
1056         } else if (fp->f_flag & O_FSYNC) {
1057                 ioflag |= IO_SYNC;
1058         }
1059
1060         if (vp->v_mount && (vp->v_mount->mnt_flag & MNT_SYNCHRONOUS))
1061                 ioflag |= IO_SYNC;
1062         ioflag |= sequential_heuristic(uio, fp);
1063
1064         error = dev_dwrite(dev, uio, ioflag);
1065
1066         release_dev(dev);
1067         if (node) {
1068                 nanotime(&node->atime);
1069                 nanotime(&node->mtime);
1070         }
1071
1072         if ((flags & O_FOFFSET) == 0)
1073                 fp->f_offset = uio->uio_offset;
1074         fp->f_nextoff = uio->uio_offset;
1075 done:
1076         rel_mplock();
1077         return (error);
1078 }
1079
1080
1081 static int
1082 devfs_specf_stat(struct file *fp, struct stat *sb, struct ucred *cred)
1083 {
1084         struct vnode *vp;
1085         int error;
1086
1087         get_mplock();
1088         vp = (struct vnode *)fp->f_data;
1089         error = vn_stat(vp, sb, cred);
1090         if (error) {
1091                 rel_mplock();
1092                 return (error);
1093         }
1094
1095         struct vattr vattr;
1096         struct vattr *vap;
1097         u_short mode;
1098         cdev_t dev;
1099
1100         vap = &vattr;
1101         error = VOP_GETATTR(vp, vap);
1102         if (error) {
1103                 rel_mplock();
1104                 return (error);
1105         }
1106
1107         /*
1108          * Zero the spare stat fields
1109          */
1110         sb->st_lspare = 0;
1111         sb->st_qspare = 0;
1112
1113         /*
1114          * Copy from vattr table ... or not in case it's a cloned device
1115          */
1116         if (vap->va_fsid != VNOVAL)
1117                 sb->st_dev = vap->va_fsid;
1118         else
1119                 sb->st_dev = vp->v_mount->mnt_stat.f_fsid.val[0];
1120
1121         sb->st_ino = vap->va_fileid;
1122
1123         mode = vap->va_mode;
1124         mode |= S_IFCHR;
1125         sb->st_mode = mode;
1126
1127         if (vap->va_nlink > (nlink_t)-1)
1128                 sb->st_nlink = (nlink_t)-1;
1129         else
1130                 sb->st_nlink = vap->va_nlink;
1131         sb->st_uid = vap->va_uid;
1132         sb->st_gid = vap->va_gid;
1133         sb->st_rdev = dev2udev(DEVFS_NODE(vp)->d_dev);
1134         sb->st_size = vap->va_size;
1135         sb->st_atimespec = vap->va_atime;
1136         sb->st_mtimespec = vap->va_mtime;
1137         sb->st_ctimespec = vap->va_ctime;
1138
1139         /*
1140          * A VCHR and VBLK device may track the last access and last modified
1141          * time independantly of the filesystem.  This is particularly true
1142          * because device read and write calls may bypass the filesystem.
1143          */
1144         if (vp->v_type == VCHR || vp->v_type == VBLK) {
1145                 dev = vp->v_rdev;
1146                 if (dev != NULL) {
1147                         if (dev->si_lastread) {
1148                                 sb->st_atimespec.tv_sec = dev->si_lastread;
1149                                 sb->st_atimespec.tv_nsec = 0;
1150                         }
1151                         if (dev->si_lastwrite) {
1152                                 sb->st_atimespec.tv_sec = dev->si_lastwrite;
1153                                 sb->st_atimespec.tv_nsec = 0;
1154                         }
1155                 }
1156         }
1157
1158         /*
1159          * According to www.opengroup.org, the meaning of st_blksize is
1160          *   "a filesystem-specific preferred I/O block size for this
1161          *    object.  In some filesystem types, this may vary from file
1162          *    to file"
1163          * Default to PAGE_SIZE after much discussion.
1164          */
1165
1166         sb->st_blksize = PAGE_SIZE;
1167
1168         sb->st_flags = vap->va_flags;
1169
1170         error = priv_check_cred(cred, PRIV_VFS_GENERATION, 0);
1171         if (error)
1172                 sb->st_gen = 0;
1173         else
1174                 sb->st_gen = (u_int32_t)vap->va_gen;
1175
1176         sb->st_blocks = vap->va_bytes / S_BLKSIZE;
1177         sb->st_fsmid = vap->va_fsmid;
1178
1179         rel_mplock();
1180         return (0);
1181 }
1182
1183
1184 static int
1185 devfs_specf_kqfilter(struct file *fp, struct knote *kn)
1186 {
1187         struct devfs_node *node;
1188         struct vnode *vp;
1189         int error;
1190         cdev_t dev;
1191
1192         get_mplock();
1193
1194         vp = (struct vnode *)fp->f_data;
1195         if (vp == NULL || vp->v_type == VBAD) {
1196                 error = EBADF;
1197                 goto done;
1198         }
1199         node = DEVFS_NODE(vp);
1200
1201         if ((dev = vp->v_rdev) == NULL) {
1202                 error = EBADF;
1203                 goto done;
1204         }
1205         reference_dev(dev);
1206
1207         error = dev_dkqfilter(dev, kn);
1208
1209         release_dev(dev);
1210
1211 done:
1212         rel_mplock();
1213         return (error);
1214 }
1215
1216
1217 static int
1218 devfs_specf_poll(struct file *fp, int events, struct ucred *cred)
1219 {
1220         struct devfs_node *node;
1221         struct vnode *vp;
1222         int error;
1223         cdev_t dev;
1224
1225         get_mplock();
1226
1227         vp = (struct vnode *)fp->f_data;
1228         if (vp == NULL || vp->v_type == VBAD) {
1229                 error = EBADF;
1230                 goto done;
1231         }
1232         node = DEVFS_NODE(vp);
1233
1234         if ((dev = vp->v_rdev) == NULL) {
1235                 error = EBADF;
1236                 goto done;
1237         }
1238         reference_dev(dev);
1239         error = dev_dpoll(dev, events);
1240
1241         release_dev(dev);
1242
1243 #if 0
1244         if (node)
1245                 nanotime(&node->atime);
1246 #endif
1247 done:
1248         rel_mplock();
1249         return (error);
1250 }
1251
1252
1253 /*
1254  * MPALMOSTSAFE - acquires mplock
1255  */
1256 static int
1257 devfs_specf_ioctl(struct file *fp, u_long com, caddr_t data, struct ucred *ucred)
1258 {
1259         struct devfs_node *node;
1260         struct vnode *vp;
1261         struct vnode *ovp;
1262         cdev_t  dev;
1263         int error;
1264         struct fiodname_args *name_args;
1265         size_t namlen;
1266         const char *name;
1267
1268         get_mplock();
1269         vp = ((struct vnode *)fp->f_data);
1270         if ((dev = vp->v_rdev) == NULL) {
1271                 error = EBADF;          /* device was revoked */
1272                 goto out;
1273         }
1274
1275         node = DEVFS_NODE(vp);
1276
1277         devfs_debug(DEVFS_DEBUG_DEBUG,
1278                     "devfs_specf_ioctl() called! for dev %s\n",
1279                     dev->si_name);
1280
1281         if (com == FIODTYPE) {
1282                 *(int *)data = dev_dflags(dev) & D_TYPEMASK;
1283                 error = 0;
1284                 goto out;
1285         } else if (com == FIODNAME) {
1286                 name_args = (struct fiodname_args *)data;
1287                 name = dev->si_name;
1288                 namlen = strlen(name) + 1;
1289
1290                 devfs_debug(DEVFS_DEBUG_DEBUG,
1291                             "ioctl, got: FIODNAME for %s\n", name);
1292
1293                 if (namlen <= name_args->len)
1294                         error = copyout(dev->si_name, name_args->name, namlen);
1295                 else
1296                         error = EINVAL;
1297
1298                 devfs_debug(DEVFS_DEBUG_DEBUG,
1299                             "ioctl stuff: error: %d\n", error);
1300                 goto out;
1301         }
1302         reference_dev(dev);
1303         error = dev_dioctl(dev, com, data, fp->f_flag, ucred);
1304         release_dev(dev);
1305 #if 0
1306         if (node) {
1307                 nanotime(&node->atime);
1308                 nanotime(&node->mtime);
1309         }
1310 #endif
1311
1312         if (com == TIOCSCTTY) {
1313                 devfs_debug(DEVFS_DEBUG_DEBUG,
1314                             "devfs_specf_ioctl: got TIOCSCTTY on %s\n",
1315                             dev->si_name);
1316         }
1317         if (error == 0 && com == TIOCSCTTY) {
1318                 struct proc *p = curthread->td_proc;
1319                 struct session *sess;
1320
1321                 devfs_debug(DEVFS_DEBUG_DEBUG,
1322                             "devfs_specf_ioctl: dealing with TIOCSCTTY on %s\n",
1323                             dev->si_name);
1324                 if (p == NULL) {
1325                         error = ENOTTY;
1326                         goto out;
1327                 }
1328                 sess = p->p_session;
1329
1330                 /*
1331                  * Do nothing if reassigning same control tty
1332                  */
1333                 if (sess->s_ttyvp == vp) {
1334                         error = 0;
1335                         goto out;
1336                 }
1337
1338                 /*
1339                  * Get rid of reference to old control tty
1340                  */
1341                 ovp = sess->s_ttyvp;
1342                 vref(vp);
1343                 sess->s_ttyvp = vp;
1344                 if (ovp)
1345                         vrele(ovp);
1346         }
1347
1348 out:
1349         rel_mplock();
1350         devfs_debug(DEVFS_DEBUG_DEBUG, "devfs_specf_ioctl() finished! \n");
1351         return (error);
1352 }
1353
1354
1355 static int
1356 devfs_spec_fsync(struct vop_fsync_args *ap)
1357 {
1358         struct vnode *vp = ap->a_vp;
1359         int error;
1360
1361         if (!vn_isdisk(vp, NULL))
1362                 return (0);
1363
1364         /*
1365          * Flush all dirty buffers associated with a block device.
1366          */
1367         error = vfsync(vp, ap->a_waitfor, 10000, NULL, NULL);
1368         return (error);
1369 }
1370
1371 static int
1372 devfs_spec_read(struct vop_read_args *ap)
1373 {
1374         struct devfs_node *node;
1375         struct vnode *vp;
1376         struct uio *uio;
1377         cdev_t dev;
1378         int error;
1379
1380         vp = ap->a_vp;
1381         dev = vp->v_rdev;
1382         uio = ap->a_uio;
1383         node = DEVFS_NODE(vp);
1384
1385         if (dev == NULL)                /* device was revoked */
1386                 return (EBADF);
1387         if (uio->uio_resid == 0)
1388                 return (0);
1389
1390         vn_unlock(vp);
1391         error = dev_dread(dev, uio, ap->a_ioflag);
1392         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1393
1394         if (node)
1395                 nanotime(&node->atime);
1396
1397         return (error);
1398 }
1399
1400 /*
1401  * Vnode op for write
1402  *
1403  * spec_write(struct vnode *a_vp, struct uio *a_uio, int a_ioflag,
1404  *            struct ucred *a_cred)
1405  */
1406 static int
1407 devfs_spec_write(struct vop_write_args *ap)
1408 {
1409         struct devfs_node *node;
1410         struct vnode *vp;
1411         struct uio *uio;
1412         cdev_t dev;
1413         int error;
1414
1415         vp = ap->a_vp;
1416         dev = vp->v_rdev;
1417         uio = ap->a_uio;
1418         node = DEVFS_NODE(vp);
1419
1420         KKASSERT(uio->uio_segflg != UIO_NOCOPY);
1421
1422         if (dev == NULL)                /* device was revoked */
1423                 return (EBADF);
1424
1425         vn_unlock(vp);
1426         error = dev_dwrite(dev, uio, ap->a_ioflag);
1427         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1428
1429         if (node) {
1430                 nanotime(&node->atime);
1431                 nanotime(&node->mtime);
1432         }
1433
1434         return (error);
1435 }
1436
1437 /*
1438  * Device ioctl operation.
1439  *
1440  * spec_ioctl(struct vnode *a_vp, int a_command, caddr_t a_data,
1441  *            int a_fflag, struct ucred *a_cred)
1442  */
1443 static int
1444 devfs_spec_ioctl(struct vop_ioctl_args *ap)
1445 {
1446         struct vnode *vp = ap->a_vp;
1447         struct devfs_node *node;
1448         cdev_t dev;
1449
1450         if ((dev = vp->v_rdev) == NULL)
1451                 return (EBADF);         /* device was revoked */
1452         node = DEVFS_NODE(vp);
1453
1454 #if 0
1455         if (node) {
1456                 nanotime(&node->atime);
1457                 nanotime(&node->mtime);
1458         }
1459 #endif
1460
1461         return (dev_dioctl(dev, ap->a_command, ap->a_data,
1462                            ap->a_fflag, ap->a_cred));
1463 }
1464
1465 /*
1466  * spec_poll(struct vnode *a_vp, int a_events, struct ucred *a_cred)
1467  */
1468 /* ARGSUSED */
1469 static int
1470 devfs_spec_poll(struct vop_poll_args *ap)
1471 {
1472         struct vnode *vp = ap->a_vp;
1473         struct devfs_node *node;
1474         cdev_t dev;
1475
1476         if ((dev = vp->v_rdev) == NULL)
1477                 return (EBADF);         /* device was revoked */
1478         node = DEVFS_NODE(vp);
1479
1480 #if 0
1481         if (node)
1482                 nanotime(&node->atime);
1483 #endif
1484
1485         return (dev_dpoll(dev, ap->a_events));
1486 }
1487
1488 /*
1489  * spec_kqfilter(struct vnode *a_vp, struct knote *a_kn)
1490  */
1491 /* ARGSUSED */
1492 static int
1493 devfs_spec_kqfilter(struct vop_kqfilter_args *ap)
1494 {
1495         struct vnode *vp = ap->a_vp;
1496         struct devfs_node *node;
1497         cdev_t dev;
1498
1499         if ((dev = vp->v_rdev) == NULL)
1500                 return (EBADF);         /* device was revoked */
1501         node = DEVFS_NODE(vp);
1502
1503 #if 0
1504         if (node)
1505                 nanotime(&node->atime);
1506 #endif
1507
1508         return (dev_dkqfilter(dev, ap->a_kn));
1509 }
1510
1511 /*
1512  * Convert a vnode strategy call into a device strategy call.  Vnode strategy
1513  * calls are not limited to device DMA limits so we have to deal with the
1514  * case.
1515  *
1516  * spec_strategy(struct vnode *a_vp, struct bio *a_bio)
1517  */
1518 static int
1519 devfs_spec_strategy(struct vop_strategy_args *ap)
1520 {
1521         struct bio *bio = ap->a_bio;
1522         struct buf *bp = bio->bio_buf;
1523         struct buf *nbp;
1524         struct vnode *vp;
1525         struct mount *mp;
1526         int chunksize;
1527         int maxiosize;
1528
1529         if (bp->b_cmd != BUF_CMD_READ && LIST_FIRST(&bp->b_dep) != NULL)
1530                 buf_start(bp);
1531
1532         /*
1533          * Collect statistics on synchronous and asynchronous read
1534          * and write counts for disks that have associated filesystems.
1535          */
1536         vp = ap->a_vp;
1537         KKASSERT(vp->v_rdev != NULL);   /* XXX */
1538         if (vn_isdisk(vp, NULL) && (mp = vp->v_rdev->si_mountpoint) != NULL) {
1539                 if (bp->b_cmd == BUF_CMD_READ) {
1540                         if (bp->b_flags & BIO_SYNC)
1541                                 mp->mnt_stat.f_syncreads++;
1542                         else
1543                                 mp->mnt_stat.f_asyncreads++;
1544                 } else {
1545                         if (bp->b_flags & BIO_SYNC)
1546                                 mp->mnt_stat.f_syncwrites++;
1547                         else
1548                                 mp->mnt_stat.f_asyncwrites++;
1549                 }
1550         }
1551
1552         /*
1553          * Device iosize limitations only apply to read and write.  Shortcut
1554          * the I/O if it fits.
1555          */
1556         if ((maxiosize = vp->v_rdev->si_iosize_max) == 0) {
1557                 devfs_debug(DEVFS_DEBUG_DEBUG,
1558                             "%s: si_iosize_max not set!\n",
1559                             dev_dname(vp->v_rdev));
1560                 maxiosize = MAXPHYS;
1561         }
1562 #if SPEC_CHAIN_DEBUG & 2
1563         maxiosize = 4096;
1564 #endif
1565         if (bp->b_bcount <= maxiosize ||
1566             (bp->b_cmd != BUF_CMD_READ && bp->b_cmd != BUF_CMD_WRITE)) {
1567                 dev_dstrategy_chain(vp->v_rdev, bio);
1568                 return (0);
1569         }
1570
1571         /*
1572          * Clone the buffer and set up an I/O chain to chunk up the I/O.
1573          */
1574         nbp = kmalloc(sizeof(*bp), M_DEVBUF, M_INTWAIT|M_ZERO);
1575         initbufbio(nbp);
1576         buf_dep_init(nbp);
1577         BUF_LOCKINIT(nbp);
1578         BUF_LOCK(nbp, LK_EXCLUSIVE);
1579         BUF_KERNPROC(nbp);
1580         nbp->b_vp = vp;
1581         nbp->b_flags = B_PAGING | (bp->b_flags & B_BNOCLIP);
1582         nbp->b_data = bp->b_data;
1583         nbp->b_bio1.bio_done = devfs_spec_strategy_done;
1584         nbp->b_bio1.bio_offset = bio->bio_offset;
1585         nbp->b_bio1.bio_caller_info1.ptr = bio;
1586
1587         /*
1588          * Start the first transfer
1589          */
1590         if (vn_isdisk(vp, NULL))
1591                 chunksize = vp->v_rdev->si_bsize_phys;
1592         else
1593                 chunksize = DEV_BSIZE;
1594         chunksize = maxiosize / chunksize * chunksize;
1595 #if SPEC_CHAIN_DEBUG & 1
1596         devfs_debug(DEVFS_DEBUG_DEBUG,
1597                     "spec_strategy chained I/O chunksize=%d\n",
1598                     chunksize);
1599 #endif
1600         nbp->b_cmd = bp->b_cmd;
1601         nbp->b_bcount = chunksize;
1602         nbp->b_bufsize = chunksize;     /* used to detect a short I/O */
1603         nbp->b_bio1.bio_caller_info2.index = chunksize;
1604
1605 #if SPEC_CHAIN_DEBUG & 1
1606         devfs_debug(DEVFS_DEBUG_DEBUG,
1607                     "spec_strategy: chain %p offset %d/%d bcount %d\n",
1608                     bp, 0, bp->b_bcount, nbp->b_bcount);
1609 #endif
1610
1611         dev_dstrategy(vp->v_rdev, &nbp->b_bio1);
1612
1613         if (DEVFS_NODE(vp)) {
1614                 nanotime(&DEVFS_NODE(vp)->atime);
1615                 nanotime(&DEVFS_NODE(vp)->mtime);
1616         }
1617
1618         return (0);
1619 }
1620
1621 /*
1622  * Chunked up transfer completion routine - chain transfers until done
1623  */
1624 static
1625 void
1626 devfs_spec_strategy_done(struct bio *nbio)
1627 {
1628         struct buf *nbp = nbio->bio_buf;
1629         struct bio *bio = nbio->bio_caller_info1.ptr;   /* original bio */
1630         struct buf *bp = bio->bio_buf;                  /* original bp */
1631         int chunksize = nbio->bio_caller_info2.index;   /* chunking */
1632         int boffset = nbp->b_data - bp->b_data;
1633
1634         if (nbp->b_flags & B_ERROR) {
1635                 /*
1636                  * An error terminates the chain, propogate the error back
1637                  * to the original bp
1638                  */
1639                 bp->b_flags |= B_ERROR;
1640                 bp->b_error = nbp->b_error;
1641                 bp->b_resid = bp->b_bcount - boffset +
1642                               (nbp->b_bcount - nbp->b_resid);
1643 #if SPEC_CHAIN_DEBUG & 1
1644                 devfs_debug(DEVFS_DEBUG_DEBUG,
1645                             "spec_strategy: chain %p error %d bcount %d/%d\n",
1646                             bp, bp->b_error, bp->b_bcount,
1647                             bp->b_bcount - bp->b_resid);
1648 #endif
1649                 kfree(nbp, M_DEVBUF);
1650                 biodone(bio);
1651         } else if (nbp->b_resid) {
1652                 /*
1653                  * A short read or write terminates the chain
1654                  */
1655                 bp->b_error = nbp->b_error;
1656                 bp->b_resid = bp->b_bcount - boffset +
1657                               (nbp->b_bcount - nbp->b_resid);
1658 #if SPEC_CHAIN_DEBUG & 1
1659                 devfs_debug(DEVFS_DEBUG_DEBUG,
1660                             "spec_strategy: chain %p short read(1) "
1661                             "bcount %d/%d\n",
1662                             bp, bp->b_bcount - bp->b_resid, bp->b_bcount);
1663 #endif
1664                 kfree(nbp, M_DEVBUF);
1665                 biodone(bio);
1666         } else if (nbp->b_bcount != nbp->b_bufsize) {
1667                 /*
1668                  * A short read or write can also occur by truncating b_bcount
1669                  */
1670 #if SPEC_CHAIN_DEBUG & 1
1671                 devfs_debug(DEVFS_DEBUG_DEBUG,
1672                             "spec_strategy: chain %p short read(2) "
1673                             "bcount %d/%d\n",
1674                             bp, nbp->b_bcount + boffset, bp->b_bcount);
1675 #endif
1676                 bp->b_error = 0;
1677                 bp->b_bcount = nbp->b_bcount + boffset;
1678                 bp->b_resid = nbp->b_resid;
1679                 kfree(nbp, M_DEVBUF);
1680                 biodone(bio);
1681         } else if (nbp->b_bcount + boffset == bp->b_bcount) {
1682                 /*
1683                  * No more data terminates the chain
1684                  */
1685 #if SPEC_CHAIN_DEBUG & 1
1686                 devfs_debug(DEVFS_DEBUG_DEBUG,
1687                             "spec_strategy: chain %p finished bcount %d\n",
1688                             bp, bp->b_bcount);
1689 #endif
1690                 bp->b_error = 0;
1691                 bp->b_resid = 0;
1692                 kfree(nbp, M_DEVBUF);
1693                 biodone(bio);
1694         } else {
1695                 /*
1696                  * Continue the chain
1697                  */
1698                 boffset += nbp->b_bcount;
1699                 nbp->b_data = bp->b_data + boffset;
1700                 nbp->b_bcount = bp->b_bcount - boffset;
1701                 if (nbp->b_bcount > chunksize)
1702                         nbp->b_bcount = chunksize;
1703                 nbp->b_bio1.bio_done = devfs_spec_strategy_done;
1704                 nbp->b_bio1.bio_offset = bio->bio_offset + boffset;
1705
1706 #if SPEC_CHAIN_DEBUG & 1
1707                 devfs_debug(DEVFS_DEBUG_DEBUG,
1708                             "spec_strategy: chain %p offset %d/%d bcount %d\n",
1709                             bp, boffset, bp->b_bcount, nbp->b_bcount);
1710 #endif
1711
1712                 dev_dstrategy(nbp->b_vp->v_rdev, &nbp->b_bio1);
1713         }
1714 }
1715
1716 /*
1717  * spec_freeblks(struct vnode *a_vp, daddr_t a_addr, daddr_t a_length)
1718  */
1719 static int
1720 devfs_spec_freeblks(struct vop_freeblks_args *ap)
1721 {
1722         struct buf *bp;
1723
1724         /*
1725          * XXX: This assumes that strategy does the deed right away.
1726          * XXX: this may not be TRTTD.
1727          */
1728         KKASSERT(ap->a_vp->v_rdev != NULL);
1729         if ((dev_dflags(ap->a_vp->v_rdev) & D_CANFREE) == 0)
1730                 return (0);
1731         bp = geteblk(ap->a_length);
1732         bp->b_cmd = BUF_CMD_FREEBLKS;
1733         bp->b_bio1.bio_offset = ap->a_offset;
1734         bp->b_bcount = ap->a_length;
1735         dev_dstrategy(ap->a_vp->v_rdev, &bp->b_bio1);
1736         return (0);
1737 }
1738
1739 /*
1740  * Implement degenerate case where the block requested is the block
1741  * returned, and assume that the entire device is contiguous in regards
1742  * to the contiguous block range (runp and runb).
1743  *
1744  * spec_bmap(struct vnode *a_vp, off_t a_loffset,
1745  *           off_t *a_doffsetp, int *a_runp, int *a_runb)
1746  */
1747 static int
1748 devfs_spec_bmap(struct vop_bmap_args *ap)
1749 {
1750         if (ap->a_doffsetp != NULL)
1751                 *ap->a_doffsetp = ap->a_loffset;
1752         if (ap->a_runp != NULL)
1753                 *ap->a_runp = MAXBSIZE;
1754         if (ap->a_runb != NULL) {
1755                 if (ap->a_loffset < MAXBSIZE)
1756                         *ap->a_runb = (int)ap->a_loffset;
1757                 else
1758                         *ap->a_runb = MAXBSIZE;
1759         }
1760         return (0);
1761 }
1762
1763
1764 /*
1765  * Special device advisory byte-level locks.
1766  *
1767  * spec_advlock(struct vnode *a_vp, caddr_t a_id, int a_op,
1768  *              struct flock *a_fl, int a_flags)
1769  */
1770 /* ARGSUSED */
1771 static int
1772 devfs_spec_advlock(struct vop_advlock_args *ap)
1773 {
1774         return ((ap->a_flags & F_POSIX) ? EINVAL : EOPNOTSUPP);
1775 }
1776
1777 static void
1778 devfs_spec_getpages_iodone(struct bio *bio)
1779 {
1780         bio->bio_buf->b_cmd = BUF_CMD_DONE;
1781         wakeup(bio->bio_buf);
1782 }
1783
1784 /*
1785  * spec_getpages() - get pages associated with device vnode.
1786  *
1787  * Note that spec_read and spec_write do not use the buffer cache, so we
1788  * must fully implement getpages here.
1789  */
1790 static int
1791 devfs_spec_getpages(struct vop_getpages_args *ap)
1792 {
1793         vm_offset_t kva;
1794         int error;
1795         int i, pcount, size;
1796         struct buf *bp;
1797         vm_page_t m;
1798         vm_ooffset_t offset;
1799         int toff, nextoff, nread;
1800         struct vnode *vp = ap->a_vp;
1801         int blksiz;
1802         int gotreqpage;
1803
1804         error = 0;
1805         pcount = round_page(ap->a_count) / PAGE_SIZE;
1806
1807         /*
1808          * Calculate the offset of the transfer and do sanity check.
1809          */
1810         offset = IDX_TO_OFF(ap->a_m[0]->pindex) + ap->a_offset;
1811
1812         /*
1813          * Round up physical size for real devices.  We cannot round using
1814          * v_mount's block size data because v_mount has nothing to do with
1815          * the device.  i.e. it's usually '/dev'.  We need the physical block
1816          * size for the device itself.
1817          *
1818          * We can't use v_rdev->si_mountpoint because it only exists when the
1819          * block device is mounted.  However, we can use v_rdev.
1820          */
1821         if (vn_isdisk(vp, NULL))
1822                 blksiz = vp->v_rdev->si_bsize_phys;
1823         else
1824                 blksiz = DEV_BSIZE;
1825
1826         size = (ap->a_count + blksiz - 1) & ~(blksiz - 1);
1827
1828         bp = getpbuf(NULL);
1829         kva = (vm_offset_t)bp->b_data;
1830
1831         /*
1832          * Map the pages to be read into the kva.
1833          */
1834         pmap_qenter(kva, ap->a_m, pcount);
1835
1836         /* Build a minimal buffer header. */
1837         bp->b_cmd = BUF_CMD_READ;
1838         bp->b_bcount = size;
1839         bp->b_resid = 0;
1840         bp->b_runningbufspace = size;
1841         if (size) {
1842                 runningbufspace += bp->b_runningbufspace;
1843                 ++runningbufcount;
1844         }
1845
1846         bp->b_bio1.bio_offset = offset;
1847         bp->b_bio1.bio_done = devfs_spec_getpages_iodone;
1848
1849         mycpu->gd_cnt.v_vnodein++;
1850         mycpu->gd_cnt.v_vnodepgsin += pcount;
1851
1852         /* Do the input. */
1853         vn_strategy(ap->a_vp, &bp->b_bio1);
1854
1855         crit_enter();
1856
1857         /* We definitely need to be at splbio here. */
1858         while (bp->b_cmd != BUF_CMD_DONE)
1859                 tsleep(bp, 0, "spread", 0);
1860
1861         crit_exit();
1862
1863         if (bp->b_flags & B_ERROR) {
1864                 if (bp->b_error)
1865                         error = bp->b_error;
1866                 else
1867                         error = EIO;
1868         }
1869
1870         /*
1871          * If EOF is encountered we must zero-extend the result in order
1872          * to ensure that the page does not contain garabge.  When no
1873          * error occurs, an early EOF is indicated if b_bcount got truncated.
1874          * b_resid is relative to b_bcount and should be 0, but some devices
1875          * might indicate an EOF with b_resid instead of truncating b_bcount.
1876          */
1877         nread = bp->b_bcount - bp->b_resid;
1878         if (nread < ap->a_count)
1879                 bzero((caddr_t)kva + nread, ap->a_count - nread);
1880         pmap_qremove(kva, pcount);
1881
1882         gotreqpage = 0;
1883         for (i = 0, toff = 0; i < pcount; i++, toff = nextoff) {
1884                 nextoff = toff + PAGE_SIZE;
1885                 m = ap->a_m[i];
1886
1887                 m->flags &= ~PG_ZERO;
1888
1889                 if (nextoff <= nread) {
1890                         m->valid = VM_PAGE_BITS_ALL;
1891                         vm_page_undirty(m);
1892                 } else if (toff < nread) {
1893                         /*
1894                          * Since this is a VM request, we have to supply the
1895                          * unaligned offset to allow vm_page_set_validclean()
1896                          * to zero sub-DEV_BSIZE'd portions of the page.
1897                          */
1898                         vm_page_set_validclean(m, 0, nread - toff);
1899                 } else {
1900                         m->valid = 0;
1901                         vm_page_undirty(m);
1902                 }
1903
1904                 if (i != ap->a_reqpage) {
1905                         /*
1906                          * Just in case someone was asking for this page we
1907                          * now tell them that it is ok to use.
1908                          */
1909                         if (!error || (m->valid == VM_PAGE_BITS_ALL)) {
1910                                 if (m->valid) {
1911                                         if (m->flags & PG_WANTED) {
1912                                                 vm_page_activate(m);
1913                                         } else {
1914                                                 vm_page_deactivate(m);
1915                                         }
1916                                         vm_page_wakeup(m);
1917                                 } else {
1918                                         vm_page_free(m);
1919                                 }
1920                         } else {
1921                                 vm_page_free(m);
1922                         }
1923                 } else if (m->valid) {
1924                         gotreqpage = 1;
1925                         /*
1926                          * Since this is a VM request, we need to make the
1927                          * entire page presentable by zeroing invalid sections.
1928                          */
1929                         if (m->valid != VM_PAGE_BITS_ALL)
1930                             vm_page_zero_invalid(m, FALSE);
1931                 }
1932         }
1933         if (!gotreqpage) {
1934                 m = ap->a_m[ap->a_reqpage];
1935                 devfs_debug(DEVFS_DEBUG_WARNING,
1936             "spec_getpages:(%s) I/O read failure: (error=%d) bp %p vp %p\n",
1937                         devtoname(vp->v_rdev), error, bp, bp->b_vp);
1938                 devfs_debug(DEVFS_DEBUG_WARNING,
1939             "               size: %d, resid: %d, a_count: %d, valid: 0x%x\n",
1940                     size, bp->b_resid, ap->a_count, m->valid);
1941                 devfs_debug(DEVFS_DEBUG_WARNING,
1942             "               nread: %d, reqpage: %d, pindex: %lu, pcount: %d\n",
1943                     nread, ap->a_reqpage, (u_long)m->pindex, pcount);
1944                 /*
1945                  * Free the buffer header back to the swap buffer pool.
1946                  */
1947                 relpbuf(bp, NULL);
1948                 return VM_PAGER_ERROR;
1949         }
1950         /*
1951          * Free the buffer header back to the swap buffer pool.
1952          */
1953         relpbuf(bp, NULL);
1954         if (DEVFS_NODE(ap->a_vp))
1955                 nanotime(&DEVFS_NODE(ap->a_vp)->mtime);
1956         return VM_PAGER_OK;
1957 }
1958
1959 static __inline
1960 int
1961 sequential_heuristic(struct uio *uio, struct file *fp)
1962 {
1963         /*
1964          * Sequential heuristic - detect sequential operation
1965          */
1966         if ((uio->uio_offset == 0 && fp->f_seqcount > 0) ||
1967             uio->uio_offset == fp->f_nextoff) {
1968                 /*
1969                  * XXX we assume that the filesystem block size is
1970                  * the default.  Not true, but still gives us a pretty
1971                  * good indicator of how sequential the read operations
1972                  * are.
1973                  */
1974                 int tmpseq = fp->f_seqcount;
1975
1976                 tmpseq += (uio->uio_resid + BKVASIZE - 1) / BKVASIZE;
1977                 if (tmpseq > IO_SEQMAX)
1978                         tmpseq = IO_SEQMAX;
1979                 fp->f_seqcount = tmpseq;
1980                 return(fp->f_seqcount << IO_SEQSHIFT);
1981         }
1982
1983         /*
1984          * Not sequential, quick draw-down of seqcount
1985          */
1986         if (fp->f_seqcount > 1)
1987                 fp->f_seqcount = 1;
1988         else
1989                 fp->f_seqcount = 0;
1990         return(0);
1991 }