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