DEVFS - Factor out recursive code into iterate_topology
[dragonfly.git] / sys / vfs / devfs / devfs_core.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/kernel.h>
37 #include <sys/mount.h>
38 #include <sys/vnode.h>
39 #include <sys/types.h>
40 #include <sys/lock.h>
41 #include <sys/msgport.h>
42 #include <sys/msgport2.h>
43 #include <sys/spinlock2.h>
44 #include <sys/sysctl.h>
45 #include <sys/ucred.h>
46 #include <sys/param.h>
47 #include <sys/sysref2.h>
48 #include <sys/systm.h>
49 #include <vfs/devfs/devfs.h>
50 #include <vfs/devfs/devfs_rules.h>
51
52 MALLOC_DEFINE(M_DEVFS, "devfs", "Device File System (devfs) allocations");
53 DEVFS_DECLARE_CLONE_BITMAP(ops_id);
54 /*
55  * SYSREF Integration - reference counting, allocation,
56  * sysid and syslink integration.
57  */
58 static void devfs_cdev_terminate(cdev_t dev);
59 static struct sysref_class     cdev_sysref_class = {
60         .name =         "cdev",
61         .mtype =        M_DEVFS,
62         .proto =        SYSREF_PROTO_DEV,
63         .offset =       offsetof(struct cdev, si_sysref),
64         .objsize =      sizeof(struct cdev),
65         .mag_capacity = 32,
66         .flags =        0,
67         .ops =  {
68                 .terminate = (sysref_terminate_func_t)devfs_cdev_terminate
69         }
70 };
71
72 static struct objcache  *devfs_node_cache;
73 static struct objcache  *devfs_msg_cache;
74 static struct objcache  *devfs_dev_cache;
75
76 static struct objcache_malloc_args devfs_node_malloc_args = {
77         sizeof(struct devfs_node), M_DEVFS };
78 struct objcache_malloc_args devfs_msg_malloc_args = {
79         sizeof(struct devfs_msg), M_DEVFS };
80 struct objcache_malloc_args devfs_dev_malloc_args = {
81         sizeof(struct cdev), M_DEVFS };
82
83 static struct devfs_dev_head devfs_dev_list =
84                 TAILQ_HEAD_INITIALIZER(devfs_dev_list);
85 static struct devfs_mnt_head devfs_mnt_list =
86                 TAILQ_HEAD_INITIALIZER(devfs_mnt_list);
87 static struct devfs_chandler_head devfs_chandler_list =
88                 TAILQ_HEAD_INITIALIZER(devfs_chandler_list);
89 static struct devfs_alias_head devfs_alias_list =
90                 TAILQ_HEAD_INITIALIZER(devfs_alias_list);
91
92 struct lock             devfs_lock;
93 static struct lwkt_port devfs_dispose_port;
94 static struct lwkt_port devfs_msg_port;
95 static struct thread    *td_core;
96
97 static struct spinlock  ino_lock;
98 static ino_t    d_ino;
99 static int      devfs_debug_enable;
100 static int      devfs_run;
101
102 static ino_t devfs_fetch_ino(void);
103 static int devfs_create_all_dev_worker(struct devfs_node *);
104 static int devfs_create_dev_worker(cdev_t, uid_t, gid_t, int);
105 static int devfs_destroy_dev_worker(cdev_t);
106 static int devfs_destroy_subnames_worker(char *);
107 static int devfs_destroy_dev_by_ops_worker(struct dev_ops *, int);
108 static int devfs_propagate_dev(cdev_t, int);
109 static int devfs_unlink_dev(cdev_t dev);
110 static void devfs_msg_exec(devfs_msg_t msg);
111
112 static int devfs_chandler_add_worker(char *, d_clone_t *);
113 static int devfs_chandler_del_worker(char *);
114
115 static void devfs_msg_autofree_reply(lwkt_port_t, lwkt_msg_t);
116 static void devfs_msg_core(void *);
117
118 static int devfs_find_device_by_name_worker(devfs_msg_t);
119 static int devfs_find_device_by_udev_worker(devfs_msg_t);
120
121 static int devfs_apply_reset_rules_caller(char *, int);
122
123 static int devfs_scan_callback_worker(devfs_scan_t *);
124
125 static struct devfs_node *devfs_resolve_or_create_dir(struct devfs_node *,
126                 char *, size_t, int);
127
128 static int devfs_make_alias_worker(struct devfs_alias *);
129 static int devfs_alias_remove(cdev_t);
130 static int devfs_alias_reap(void);
131 static int devfs_alias_propagate(struct devfs_alias *);
132 static int devfs_alias_apply(struct devfs_node *, struct devfs_alias *);
133 static int devfs_alias_check_create(struct devfs_node *);
134
135 static int devfs_clr_subnames_flag_worker(char *, uint32_t);
136 static int devfs_destroy_subnames_without_flag_worker(char *, uint32_t);
137
138 static void *devfs_reaperp_callback(struct devfs_node *, void *);
139 static void *devfs_gc_dirs_callback(struct devfs_node *, void *);
140 static void *devfs_gc_links_callback(struct devfs_node *, struct devfs_node *);
141 static void *
142 devfs_inode_to_vnode_worker_callback(struct devfs_node *, ino_t *);
143
144 /*
145  * devfs_debug() is a SYSCTL and TUNABLE controlled debug output function
146  * using kvprintf
147  */
148 int
149 devfs_debug(int level, char *fmt, ...)
150 {
151         __va_list ap;
152
153         __va_start(ap, fmt);
154         if (level <= devfs_debug_enable)
155                 kvprintf(fmt, ap);
156         __va_end(ap);
157
158         return 0;
159 }
160
161 /*
162  * devfs_allocp() Allocates a new devfs node with the specified
163  * parameters. The node is also automatically linked into the topology
164  * if a parent is specified. It also calls the rule and alias stuff to
165  * be applied on the new node
166  */
167 struct devfs_node *
168 devfs_allocp(devfs_nodetype devfsnodetype, char *name,
169              struct devfs_node *parent, struct mount *mp, cdev_t dev)
170 {
171         struct devfs_node *node = NULL;
172         size_t namlen = strlen(name);
173
174         node = objcache_get(devfs_node_cache, M_WAITOK);
175         bzero(node, sizeof(*node));
176
177         atomic_add_int(&(DEVFS_MNTDATA(mp)->leak_count), 1);
178
179         node->d_dev = NULL;
180         node->nchildren = 1;
181         node->mp = mp;
182         node->d_dir.d_ino = devfs_fetch_ino();
183
184         /*
185          * Cookie jar for children. Leave 0 and 1 for '.' and '..' entries
186          * respectively.
187          */
188         node->cookie_jar = 2;
189
190         /*
191          * Access Control members
192          */
193         node->mode = DEVFS_DEFAULT_MODE;
194         node->uid = DEVFS_DEFAULT_UID;
195         node->gid = DEVFS_DEFAULT_GID;
196
197         switch (devfsnodetype) {
198         case Proot:
199                 /*
200                  * Ensure that we don't recycle the root vnode by marking it as
201                  * linked into the topology.
202                  */
203                 node->flags |= DEVFS_NODE_LINKED;
204         case Pdir:
205                 TAILQ_INIT(DEVFS_DENODE_HEAD(node));
206                 node->d_dir.d_type = DT_DIR;
207                 node->nchildren = 2;
208                 break;
209
210         case Plink:
211                 node->d_dir.d_type = DT_LNK;
212                 break;
213
214         case Preg:
215                 node->d_dir.d_type = DT_REG;
216                 break;
217
218         case Pdev:
219                 if (dev != NULL) {
220                         node->d_dir.d_type = DT_CHR;
221                         node->d_dev = dev;
222
223                         node->mode = dev->si_perms;
224                         node->uid = dev->si_uid;
225                         node->gid = dev->si_gid;
226
227                         devfs_alias_check_create(node);
228                 }
229                 break;
230
231         default:
232                 panic("devfs_allocp: unknown node type");
233         }
234
235         node->v_node = NULL;
236         node->node_type = devfsnodetype;
237
238         /* Initialize the dirent structure of each devfs vnode */
239         KKASSERT(namlen < 256);
240         node->d_dir.d_namlen = namlen;
241         node->d_dir.d_name = kmalloc(namlen+1, M_DEVFS, M_WAITOK);
242         memcpy(node->d_dir.d_name, name, namlen);
243         node->d_dir.d_name[namlen] = '\0';
244
245         /* Initialize the parent node element */
246         node->parent = parent;
247
248         /* Apply rules */
249         devfs_rule_check_apply(node, NULL);
250
251         /* Initialize *time members */
252         nanotime(&node->atime);
253         node->mtime = node->ctime = node->atime;
254
255         /*
256          * Associate with parent as last step, clean out namecache
257          * reference.
258          */
259         if ((parent != NULL) &&
260             ((parent->node_type == Proot) || (parent->node_type == Pdir))) {
261                 parent->nchildren++;
262                 node->cookie = parent->cookie_jar++;
263                 node->flags |= DEVFS_NODE_LINKED;
264                 TAILQ_INSERT_TAIL(DEVFS_DENODE_HEAD(parent), node, link);
265
266                 /* This forces negative namecache lookups to clear */
267                 ++mp->mnt_namecache_gen;
268         }
269
270         return node;
271 }
272
273 /*
274  * devfs_allocv() allocates a new vnode based on a devfs node.
275  */
276 int
277 devfs_allocv(struct vnode **vpp, struct devfs_node *node)
278 {
279         struct vnode *vp;
280         int error = 0;
281
282         KKASSERT(node);
283
284 try_again:
285         while ((vp = node->v_node) != NULL) {
286                 error = vget(vp, LK_EXCLUSIVE);
287                 if (error != ENOENT) {
288                         *vpp = vp;
289                         goto out;
290                 }
291         }
292
293         if ((error = getnewvnode(VT_DEVFS, node->mp, vpp, 0, 0)) != 0)
294                 goto out;
295
296         vp = *vpp;
297
298         if (node->v_node != NULL) {
299                 vp->v_type = VBAD;
300                 vx_put(vp);
301                 goto try_again;
302         }
303
304         vp->v_data = node;
305         node->v_node = vp;
306
307         switch (node->node_type) {
308         case Proot:
309                 vp->v_flag |= VROOT;
310         case Pdir:
311                 vp->v_type = VDIR;
312                 break;
313
314         case Plink:
315                 vp->v_type = VLNK;
316                 break;
317
318         case Preg:
319                 vp->v_type = VREG;
320                 break;
321
322         case Pdev:
323                 vp->v_type = VCHR;
324                 KKASSERT(node->d_dev);
325
326                 vp->v_uminor = node->d_dev->si_uminor;
327                 vp->v_umajor = 0;
328
329                 v_associate_rdev(vp, node->d_dev);
330                 vp->v_ops = &node->mp->mnt_vn_spec_ops;
331                 break;
332
333         default:
334                 panic("devfs_allocv: unknown node type");
335         }
336
337 out:
338         return error;
339 }
340
341 /*
342  * devfs_allocvp allocates both a devfs node (with the given settings) and a vnode
343  * based on the newly created devfs node.
344  */
345 int
346 devfs_allocvp(struct mount *mp, struct vnode **vpp, devfs_nodetype devfsnodetype,
347                 char *name, struct devfs_node *parent, cdev_t dev)
348 {
349         struct devfs_node *node;
350
351         node = devfs_allocp(devfsnodetype, name, parent, mp, dev);
352
353         if (node != NULL)
354                 devfs_allocv(vpp, node);
355         else
356                 *vpp = NULL;
357
358         return 0;
359 }
360
361 /*
362  * Destroy the devfs_node.  The node must be unlinked from the topology.
363  *
364  * This function will also destroy any vnode association with the node
365  * and device.
366  *
367  * The cdev_t itself remains intact.
368  */
369 int
370 devfs_freep(struct devfs_node *node)
371 {
372         struct vnode *vp;
373
374         KKASSERT(node);
375         KKASSERT(((node->flags & DEVFS_NODE_LINKED) == 0) ||
376                  (node->node_type == Proot));
377         KKASSERT((node->flags & DEVFS_DESTROYED) == 0);
378
379         atomic_subtract_int(&(DEVFS_MNTDATA(node->mp)->leak_count), 1);
380         if (node->symlink_name) {
381                 kfree(node->symlink_name, M_DEVFS);
382                 node->symlink_name = NULL;
383         }
384
385         /*
386          * Remove the node from the orphan list if it is still on it.
387          */
388         if (node->flags & DEVFS_ORPHANED)
389                 devfs_tracer_del_orphan(node);
390
391         /*
392          * Disassociate the vnode from the node.  This also prevents the
393          * vnode's reclaim code from double-freeing the node.
394          *
395          * The vget is needed to safely modify the vp.  It also serves
396          * to cycle the refs and terminate the vnode if it happens to
397          * be inactive, otherwise namecache references may not get cleared.
398          */
399         while ((vp = node->v_node) != NULL) {
400                 if (vget(vp, LK_EXCLUSIVE | LK_RETRY) != 0)
401                         break;
402                 v_release_rdev(vp);
403                 vp->v_data = NULL;
404                 node->v_node = NULL;
405                 vput(vp);
406         }
407         if (node->d_dir.d_name)
408                 kfree(node->d_dir.d_name, M_DEVFS);
409         node->flags |= DEVFS_DESTROYED;
410
411         objcache_put(devfs_node_cache, node);
412
413         return 0;
414 }
415
416 /*
417  * Unlink the devfs node from the topology and add it to the orphan list.
418  * The node will later be destroyed by freep.
419  *
420  * Any vnode association, including the v_rdev and v_data, remains intact
421  * until the freep.
422  */
423 int
424 devfs_unlinkp(struct devfs_node *node)
425 {
426         struct devfs_node *parent;
427         KKASSERT(node);
428
429         /*
430          * Add the node to the orphan list, so it is referenced somewhere, to
431          * so we don't leak it.
432          */
433         devfs_tracer_add_orphan(node);
434
435         parent = node->parent;
436
437         /*
438          * If the parent is known we can unlink the node out of the topology
439          */
440         if (parent)     {
441                 TAILQ_REMOVE(DEVFS_DENODE_HEAD(parent), node, link);
442                 parent->nchildren--;
443                 KKASSERT((parent->nchildren >= 0));
444                 node->flags &= ~DEVFS_NODE_LINKED;
445         }
446         node->parent = NULL;
447         return 0;
448 }
449
450 void *
451 devfs_iterate_topology(struct devfs_node *node,
452                 devfs_iterate_callback_t *callback, void *arg1)
453 {
454         struct devfs_node *node1, *node2;
455         void *ret = NULL;
456
457         if ((node->node_type == Proot) || (node->node_type == Pdir)) {
458                 if (node->nchildren > 2) {
459                         TAILQ_FOREACH_MUTABLE(node1, DEVFS_DENODE_HEAD(node),
460                                                         link, node2) {
461                                 if ((ret = devfs_iterate_topology(node1, callback, arg1)))
462                                         return ret;
463                         }
464                 }
465         }
466
467         ret = callback(node, arg1);
468         return ret;
469 }
470
471 /*
472  * devfs_reaperp() is a recursive function that iterates through all the
473  * topology, unlinking and freeing all devfs nodes.
474  */
475 static void *
476 devfs_reaperp_callback(struct devfs_node *node, void *unused)
477 {
478         devfs_unlinkp(node);
479         devfs_freep(node);
480
481         return NULL;
482 }
483
484 static void *
485 devfs_gc_dirs_callback(struct devfs_node *node, void *unused)
486 {
487         if (node->node_type == Pdir) {
488                 if (node->nchildren == 2) {
489                         devfs_unlinkp(node);
490                         devfs_freep(node);
491                 }
492         }
493
494         return NULL;
495 }
496
497 static void *
498 devfs_gc_links_callback(struct devfs_node *node, struct devfs_node *target)
499 {
500         if ((node->node_type == Plink) && (node->link_target == target)) {
501                 devfs_unlinkp(node);
502                 devfs_freep(node);
503         }
504
505         return NULL;
506 }
507
508 /*
509  * devfs_gc() is devfs garbage collector. It takes care of unlinking and
510  * freeing a node, but also removes empty directories and links that link
511  * via devfs auto-link mechanism to the node being deleted.
512  */
513 int
514 devfs_gc(struct devfs_node *node)
515 {
516         struct devfs_node *root_node = DEVFS_MNTDATA(node->mp)->root_node;
517
518         if (node->nlinks > 0)
519                 devfs_iterate_topology(root_node,
520                                 (devfs_iterate_callback_t *)devfs_gc_links_callback, node);
521
522         devfs_unlinkp(node);
523         devfs_iterate_topology(root_node,
524                         (devfs_iterate_callback_t *)devfs_gc_dirs_callback, NULL);
525
526         devfs_freep(node);
527
528         return 0;
529 }
530
531 /*
532  * devfs_create_dev() is the asynchronous entry point for device creation.
533  * It just sends a message with the relevant details to the devfs core.
534  *
535  * This function will reference the passed device.  The reference is owned
536  * by devfs and represents all of the device's node associations.
537  */
538 int
539 devfs_create_dev(cdev_t dev, uid_t uid, gid_t gid, int perms)
540 {
541         reference_dev(dev);
542         devfs_msg_send_dev(DEVFS_DEVICE_CREATE, dev, uid, gid, perms);
543
544         return 0;
545 }
546
547 /*
548  * devfs_destroy_dev() is the asynchronous entry point for device destruction.
549  * It just sends a message with the relevant details to the devfs core.
550  */
551 int
552 devfs_destroy_dev(cdev_t dev)
553 {
554         devfs_msg_send_dev(DEVFS_DEVICE_DESTROY, dev, 0, 0, 0);
555         return 0;
556 }
557
558 /*
559  * devfs_mount_add() is the synchronous entry point for adding a new devfs
560  * mount.  It sends a synchronous message with the relevant details to the
561  * devfs core.
562  */
563 int
564 devfs_mount_add(struct devfs_mnt_data *mnt)
565 {
566         devfs_msg_t msg;
567
568         msg = devfs_msg_get();
569         msg->mdv_mnt = mnt;
570         msg = devfs_msg_send_sync(DEVFS_MOUNT_ADD, msg);
571         devfs_msg_put(msg);
572
573         return 0;
574 }
575
576 /*
577  * devfs_mount_del() is the synchronous entry point for removing a devfs mount.
578  * It sends a synchronous message with the relevant details to the devfs core.
579  */
580 int
581 devfs_mount_del(struct devfs_mnt_data *mnt)
582 {
583         devfs_msg_t msg;
584
585         msg = devfs_msg_get();
586         msg->mdv_mnt = mnt;
587         msg = devfs_msg_send_sync(DEVFS_MOUNT_DEL, msg);
588         devfs_msg_put(msg);
589
590         return 0;
591 }
592
593 /*
594  * devfs_destroy_subnames() is the synchronous entry point for device
595  * destruction by subname. It just sends a message with the relevant details to
596  * the devfs core.
597  */
598 int
599 devfs_destroy_subnames(char *name)
600 {
601         devfs_msg_t msg;
602
603         msg = devfs_msg_get();
604         msg->mdv_load = name;
605         msg = devfs_msg_send_sync(DEVFS_DESTROY_SUBNAMES, msg);
606         devfs_msg_put(msg);
607         return 0;
608 }
609
610 int
611 devfs_clr_subnames_flag(char *name, uint32_t flag)
612 {
613         devfs_msg_t msg;
614
615         msg = devfs_msg_get();
616         msg->mdv_flags.name = name;
617         msg->mdv_flags.flag = flag;
618         msg = devfs_msg_send_sync(DEVFS_CLR_SUBNAMES_FLAG, msg);
619         devfs_msg_put(msg);
620
621         return 0;
622 }
623
624 int
625 devfs_destroy_subnames_without_flag(char *name, uint32_t flag)
626 {
627         devfs_msg_t msg;
628
629         msg = devfs_msg_get();
630         msg->mdv_flags.name = name;
631         msg->mdv_flags.flag = flag;
632         msg = devfs_msg_send_sync(DEVFS_DESTROY_SUBNAMES_WO_FLAG, msg);
633         devfs_msg_put(msg);
634
635         return 0;
636 }
637
638 /*
639  * devfs_create_all_dev is the asynchronous entry point to trigger device
640  * node creation.  It just sends a message with the relevant details to
641  * the devfs core.
642  */
643 int
644 devfs_create_all_dev(struct devfs_node *root)
645 {
646         devfs_msg_send_generic(DEVFS_CREATE_ALL_DEV, root);
647         return 0;
648 }
649
650 /*
651  * devfs_destroy_dev_by_ops is the asynchronous entry point to destroy all
652  * devices with a specific set of dev_ops and minor.  It just sends a
653  * message with the relevant details to the devfs core.
654  */
655 int
656 devfs_destroy_dev_by_ops(struct dev_ops *ops, int minor)
657 {
658         devfs_msg_send_ops(DEVFS_DESTROY_DEV_BY_OPS, ops, minor);
659         return 0;
660 }
661
662 /*
663  * devfs_clone_handler_add is the synchronous entry point to add a new
664  * clone handler.  It just sends a message with the relevant details to
665  * the devfs core.
666  */
667 int
668 devfs_clone_handler_add(char *name, d_clone_t *nhandler)
669 {
670         devfs_msg_t msg;
671
672         msg = devfs_msg_get();
673         msg->mdv_chandler.name = name;
674         msg->mdv_chandler.nhandler = nhandler;
675         msg = devfs_msg_send_sync(DEVFS_CHANDLER_ADD, msg);
676         devfs_msg_put(msg);
677         return 0;
678 }
679
680 /*
681  * devfs_clone_handler_del is the synchronous entry point to remove a
682  * clone handler.  It just sends a message with the relevant details to
683  * the devfs core.
684  */
685 int
686 devfs_clone_handler_del(char *name)
687 {
688         devfs_msg_t msg;
689
690         msg = devfs_msg_get();
691         msg->mdv_chandler.name = name;
692         msg->mdv_chandler.nhandler = NULL;
693         msg = devfs_msg_send_sync(DEVFS_CHANDLER_DEL, msg);
694         devfs_msg_put(msg);
695         return 0;
696 }
697
698 /*
699  * devfs_find_device_by_name is the synchronous entry point to find a
700  * device given its name.  It sends a synchronous message with the
701  * relevant details to the devfs core and returns the answer.
702  */
703 cdev_t
704 devfs_find_device_by_name(const char *fmt, ...)
705 {
706         cdev_t found = NULL;
707         devfs_msg_t msg;
708         char target[PATH_MAX+1];
709         __va_list ap;
710         int i;
711
712         if (fmt == NULL)
713                 return NULL;
714
715         __va_start(ap, fmt);
716         i = kvcprintf(fmt, NULL, target, 10, ap);
717         target[i] = '\0';
718         __va_end(ap);
719
720         msg = devfs_msg_get();
721         msg->mdv_name = target;
722         msg = devfs_msg_send_sync(DEVFS_FIND_DEVICE_BY_NAME, msg);
723         found = msg->mdv_cdev;
724         devfs_msg_put(msg);
725
726         return found;
727 }
728
729 /*
730  * devfs_find_device_by_udev is the synchronous entry point to find a
731  * device given its udev number.  It sends a synchronous message with
732  * the relevant details to the devfs core and returns the answer.
733  */
734 cdev_t
735 devfs_find_device_by_udev(udev_t udev)
736 {
737         cdev_t found = NULL;
738         devfs_msg_t msg;
739
740         msg = devfs_msg_get();
741         msg->mdv_udev = udev;
742         msg = devfs_msg_send_sync(DEVFS_FIND_DEVICE_BY_UDEV, msg);
743         found = msg->mdv_cdev;
744         devfs_msg_put(msg);
745
746         devfs_debug(DEVFS_DEBUG_DEBUG,
747                     "devfs_find_device_by_udev found? %s  -end:3-\n",
748                     ((found) ? found->si_name:"NO"));
749         return found;
750 }
751
752 struct vnode *
753 devfs_inode_to_vnode(struct mount *mp, ino_t target)
754 {
755         struct vnode *vp = NULL;
756         devfs_msg_t msg;
757
758         if (mp == NULL)
759                 return NULL;
760
761         msg = devfs_msg_get();
762         msg->mdv_ino.mp = mp;
763         msg->mdv_ino.ino = target;
764         msg = devfs_msg_send_sync(DEVFS_INODE_TO_VNODE, msg);
765         vp = msg->mdv_ino.vp;
766         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
767         devfs_msg_put(msg);
768
769         return vp;
770 }
771
772 /*
773  * devfs_make_alias is the asynchronous entry point to register an alias
774  * for a device.  It just sends a message with the relevant details to the
775  * devfs core.
776  */
777 int
778 devfs_make_alias(char *name, cdev_t dev_target)
779 {
780         struct devfs_alias *alias;
781         size_t len;
782
783         len = strlen(name);
784
785         alias = kmalloc(sizeof(struct devfs_alias), M_DEVFS, M_WAITOK);
786         alias->name = kmalloc(len + 1, M_DEVFS, M_WAITOK);
787         memcpy(alias->name, name, len + 1);
788         alias->namlen = len;
789         alias->dev_target = dev_target;
790
791         devfs_msg_send_generic(DEVFS_MAKE_ALIAS, alias);
792         return 0;
793 }
794
795 /*
796  * devfs_apply_rules is the asynchronous entry point to trigger application
797  * of all rules.  It just sends a message with the relevant details to the
798  * devfs core.
799  */
800 int
801 devfs_apply_rules(char *mntto)
802 {
803         char *new_name;
804         size_t  namelen;
805
806         namelen = strlen(mntto) + 1;
807         new_name = kmalloc(namelen, M_DEVFS, M_WAITOK);
808         memcpy(new_name, mntto, namelen);
809         devfs_msg_send_name(DEVFS_APPLY_RULES, new_name);
810
811         return 0;
812 }
813
814 /*
815  * devfs_reset_rules is the asynchronous entry point to trigger reset of all
816  * rules. It just sends a message with the relevant details to the devfs core.
817  */
818 int
819 devfs_reset_rules(char *mntto)
820 {
821         char *new_name;
822         size_t  namelen;
823
824         namelen = strlen(mntto) + 1;
825         new_name = kmalloc(namelen, M_DEVFS, M_WAITOK);
826         memcpy(new_name, mntto, namelen);
827         devfs_msg_send_name(DEVFS_RESET_RULES, new_name);
828
829         return 0;
830 }
831
832
833 /*
834  * devfs_scan_callback is the asynchronous entry point to call a callback
835  * on all cdevs.
836  * It just sends a message with the relevant details to the devfs core.
837  */
838 int
839 devfs_scan_callback(devfs_scan_t *callback)
840 {
841         devfs_msg_t msg;
842
843         KKASSERT(sizeof(callback) == sizeof(void *));
844
845         msg = devfs_msg_get();
846         msg->mdv_load = callback;
847         msg = devfs_msg_send_sync(DEVFS_SCAN_CALLBACK, msg);
848         devfs_msg_put(msg);
849
850         return 0;
851 }
852
853
854 /*
855  * Acts as a message drain. Any message that is replied to here gets destroyed
856  * and the memory freed.
857  */
858 static void
859 devfs_msg_autofree_reply(lwkt_port_t port, lwkt_msg_t msg)
860 {
861         devfs_msg_put((devfs_msg_t)msg);
862 }
863
864 /*
865  * devfs_msg_get allocates a new devfs msg and returns it.
866  */
867 devfs_msg_t
868 devfs_msg_get()
869 {
870         return objcache_get(devfs_msg_cache, M_WAITOK);
871 }
872
873 /*
874  * devfs_msg_put deallocates a given devfs msg.
875  */
876 int
877 devfs_msg_put(devfs_msg_t msg)
878 {
879         objcache_put(devfs_msg_cache, msg);
880         return 0;
881 }
882
883 /*
884  * devfs_msg_send is the generic asynchronous message sending facility
885  * for devfs. By default the reply port is the automatic disposal port.
886  *
887  * If the current thread is the devfs_msg_port thread we execute the
888  * operation synchronously.
889  */
890 void
891 devfs_msg_send(uint32_t cmd, devfs_msg_t devfs_msg)
892 {
893         lwkt_port_t port = &devfs_msg_port;
894
895         lwkt_initmsg(&devfs_msg->hdr, &devfs_dispose_port, 0);
896
897         devfs_msg->hdr.u.ms_result = cmd;
898
899         if (port->mpu_td == curthread) {
900                 devfs_msg_exec(devfs_msg);
901                 lwkt_replymsg(&devfs_msg->hdr, 0);
902         } else {
903                 lwkt_sendmsg(port, (lwkt_msg_t)devfs_msg);
904         }
905 }
906
907 /*
908  * devfs_msg_send_sync is the generic synchronous message sending
909  * facility for devfs. It initializes a local reply port and waits
910  * for the core's answer. This answer is then returned.
911  */
912 devfs_msg_t
913 devfs_msg_send_sync(uint32_t cmd, devfs_msg_t devfs_msg)
914 {
915         struct lwkt_port rep_port;
916         devfs_msg_t     msg_incoming;
917         lwkt_port_t port = &devfs_msg_port;
918
919         lwkt_initport_thread(&rep_port, curthread);
920         lwkt_initmsg(&devfs_msg->hdr, &rep_port, 0);
921
922         devfs_msg->hdr.u.ms_result = cmd;
923
924         lwkt_sendmsg(port, (lwkt_msg_t)devfs_msg);
925         msg_incoming = lwkt_waitport(&rep_port, 0);
926
927         return msg_incoming;
928 }
929
930 /*
931  * sends a message with a generic argument.
932  */
933 void
934 devfs_msg_send_generic(uint32_t cmd, void *load)
935 {
936         devfs_msg_t devfs_msg = devfs_msg_get();
937
938         devfs_msg->mdv_load = load;
939         devfs_msg_send(cmd, devfs_msg);
940 }
941
942 /*
943  * sends a message with a name argument.
944  */
945 void
946 devfs_msg_send_name(uint32_t cmd, char *name)
947 {
948         devfs_msg_t devfs_msg = devfs_msg_get();
949
950         devfs_msg->mdv_name = name;
951         devfs_msg_send(cmd, devfs_msg);
952 }
953
954 /*
955  * sends a message with a mount argument.
956  */
957 void
958 devfs_msg_send_mount(uint32_t cmd, struct devfs_mnt_data *mnt)
959 {
960         devfs_msg_t devfs_msg = devfs_msg_get();
961
962         devfs_msg->mdv_mnt = mnt;
963         devfs_msg_send(cmd, devfs_msg);
964 }
965
966 /*
967  * sends a message with an ops argument.
968  */
969 void
970 devfs_msg_send_ops(uint32_t cmd, struct dev_ops *ops, int minor)
971 {
972         devfs_msg_t devfs_msg = devfs_msg_get();
973
974         devfs_msg->mdv_ops.ops = ops;
975         devfs_msg->mdv_ops.minor = minor;
976         devfs_msg_send(cmd, devfs_msg);
977 }
978
979 /*
980  * sends a message with a clone handler argument.
981  */
982 void
983 devfs_msg_send_chandler(uint32_t cmd, char *name, d_clone_t handler)
984 {
985         devfs_msg_t devfs_msg = devfs_msg_get();
986
987         devfs_msg->mdv_chandler.name = name;
988         devfs_msg->mdv_chandler.nhandler = handler;
989         devfs_msg_send(cmd, devfs_msg);
990 }
991
992 /*
993  * sends a message with a device argument.
994  */
995 void
996 devfs_msg_send_dev(uint32_t cmd, cdev_t dev, uid_t uid, gid_t gid, int perms)
997 {
998         devfs_msg_t devfs_msg = devfs_msg_get();
999
1000         devfs_msg->mdv_dev.dev = dev;
1001         devfs_msg->mdv_dev.uid = uid;
1002         devfs_msg->mdv_dev.gid = gid;
1003         devfs_msg->mdv_dev.perms = perms;
1004
1005         devfs_msg_send(cmd, devfs_msg);
1006 }
1007
1008 /*
1009  * sends a message with a link argument.
1010  */
1011 void
1012 devfs_msg_send_link(uint32_t cmd, char *name, char *target, struct mount *mp)
1013 {
1014         devfs_msg_t devfs_msg = devfs_msg_get();
1015
1016         devfs_msg->mdv_link.name = name;
1017         devfs_msg->mdv_link.target = target;
1018         devfs_msg->mdv_link.mp = mp;
1019         devfs_msg_send(cmd, devfs_msg);
1020 }
1021
1022 /*
1023  * devfs_msg_core is the main devfs thread. It handles all incoming messages
1024  * and calls the relevant worker functions. By using messages it's assured
1025  * that events occur in the correct order.
1026  */
1027 static void
1028 devfs_msg_core(void *arg)
1029 {
1030         devfs_msg_t msg;
1031
1032         devfs_run = 1;
1033         lwkt_initport_thread(&devfs_msg_port, curthread);
1034         wakeup(td_core);
1035
1036         while (devfs_run) {
1037                 msg = (devfs_msg_t)lwkt_waitport(&devfs_msg_port, 0);
1038                 devfs_debug(DEVFS_DEBUG_DEBUG,
1039                                 "devfs_msg_core, new msg: %x\n",
1040                                 (unsigned int)msg->hdr.u.ms_result);
1041                 devfs_msg_exec(msg);
1042                 lwkt_replymsg(&msg->hdr, 0);
1043         }
1044         wakeup(td_core);
1045         lwkt_exit();
1046 }
1047
1048 static void
1049 devfs_msg_exec(devfs_msg_t msg)
1050 {
1051         struct devfs_mnt_data *mnt;
1052         struct devfs_node *node;
1053         cdev_t  dev;
1054
1055         /*
1056          * Acquire the devfs lock to ensure safety of all called functions
1057          */
1058         lockmgr(&devfs_lock, LK_EXCLUSIVE);
1059
1060         switch (msg->hdr.u.ms_result) {
1061         case DEVFS_DEVICE_CREATE:
1062                 dev = msg->mdv_dev.dev;
1063                 devfs_create_dev_worker(dev,
1064                                         msg->mdv_dev.uid,
1065                                         msg->mdv_dev.gid,
1066                                         msg->mdv_dev.perms);
1067                 break;
1068         case DEVFS_DEVICE_DESTROY:
1069                 dev = msg->mdv_dev.dev;
1070                 devfs_destroy_dev_worker(dev);
1071                 break;
1072         case DEVFS_DESTROY_SUBNAMES:
1073                 devfs_destroy_subnames_worker(msg->mdv_load);
1074                 break;
1075         case DEVFS_DESTROY_DEV_BY_OPS:
1076                 devfs_destroy_dev_by_ops_worker(msg->mdv_ops.ops,
1077                                                 msg->mdv_ops.minor);
1078                 break;
1079         case DEVFS_CREATE_ALL_DEV:
1080                 node = (struct devfs_node *)msg->mdv_load;
1081                 devfs_create_all_dev_worker(node);
1082                 break;
1083         case DEVFS_MOUNT_ADD:
1084                 mnt = msg->mdv_mnt;
1085                 TAILQ_INSERT_TAIL(&devfs_mnt_list, mnt, link);
1086                 devfs_create_all_dev_worker(mnt->root_node);
1087                 break;
1088         case DEVFS_MOUNT_DEL:
1089                 mnt = msg->mdv_mnt;
1090                 TAILQ_REMOVE(&devfs_mnt_list, mnt, link);
1091                 devfs_iterate_topology(mnt->root_node, devfs_reaperp_callback,
1092                                        NULL);
1093                 if (mnt->leak_count) {
1094                         devfs_debug(DEVFS_DEBUG_SHOW,
1095                                     "Leaked %d devfs_node elements!\n",
1096                                     mnt->leak_count);
1097                 }
1098                 break;
1099         case DEVFS_CHANDLER_ADD:
1100                 devfs_chandler_add_worker(msg->mdv_chandler.name,
1101                                 msg->mdv_chandler.nhandler);
1102                 break;
1103         case DEVFS_CHANDLER_DEL:
1104                 devfs_chandler_del_worker(msg->mdv_chandler.name);
1105                 break;
1106         case DEVFS_FIND_DEVICE_BY_NAME:
1107                 devfs_find_device_by_name_worker(msg);
1108                 break;
1109         case DEVFS_FIND_DEVICE_BY_UDEV:
1110                 devfs_find_device_by_udev_worker(msg);
1111                 break;
1112         case DEVFS_MAKE_ALIAS:
1113                 devfs_make_alias_worker((struct devfs_alias *)msg->mdv_load);
1114                 break;
1115         case DEVFS_APPLY_RULES:
1116                 devfs_apply_reset_rules_caller(msg->mdv_name, 1);
1117                 break;
1118         case DEVFS_RESET_RULES:
1119                 devfs_apply_reset_rules_caller(msg->mdv_name, 0);
1120                 break;
1121         case DEVFS_SCAN_CALLBACK:
1122                 devfs_scan_callback_worker((devfs_scan_t *)msg->mdv_load);
1123                 break;
1124         case DEVFS_CLR_SUBNAMES_FLAG:
1125                 devfs_clr_subnames_flag_worker(msg->mdv_flags.name,
1126                                 msg->mdv_flags.flag);
1127                 break;
1128         case DEVFS_DESTROY_SUBNAMES_WO_FLAG:
1129                 devfs_destroy_subnames_without_flag_worker(msg->mdv_flags.name,
1130                                 msg->mdv_flags.flag);
1131                 break;
1132         case DEVFS_INODE_TO_VNODE:
1133                 msg->mdv_ino.vp = devfs_iterate_topology(
1134                         DEVFS_MNTDATA(msg->mdv_ino.mp)->root_node,
1135                         (devfs_iterate_callback_t *)devfs_inode_to_vnode_worker_callback,
1136                         &msg->mdv_ino.ino);
1137                 break;
1138         case DEVFS_TERMINATE_CORE:
1139                 devfs_run = 0;
1140                 break;
1141         case DEVFS_SYNC:
1142                 break;
1143         default:
1144                 devfs_debug(DEVFS_DEBUG_WARNING,
1145                             "devfs_msg_core: unknown message "
1146                             "received at core\n");
1147                 break;
1148         }
1149         lockmgr(&devfs_lock, LK_RELEASE);
1150 }
1151
1152 /*
1153  * Worker function to insert a new dev into the dev list and initialize its
1154  * permissions. It also calls devfs_propagate_dev which in turn propagates
1155  * the change to all mount points.
1156  *
1157  * The passed dev is already referenced.  This reference is eaten by this
1158  * function and represents the dev's linkage into devfs_dev_list.
1159  */
1160 static int
1161 devfs_create_dev_worker(cdev_t dev, uid_t uid, gid_t gid, int perms)
1162 {
1163         KKASSERT(dev);
1164
1165         dev->si_uid = uid;
1166         dev->si_gid = gid;
1167         dev->si_perms = perms;
1168
1169         devfs_link_dev(dev);
1170         devfs_propagate_dev(dev, 1);
1171
1172         return 0;
1173 }
1174
1175 /*
1176  * Worker function to delete a dev from the dev list and free the cdev.
1177  * It also calls devfs_propagate_dev which in turn propagates the change
1178  * to all mount points.
1179  */
1180 static int
1181 devfs_destroy_dev_worker(cdev_t dev)
1182 {
1183         int error;
1184
1185         KKASSERT(dev);
1186         KKASSERT((lockstatus(&devfs_lock, curthread)) == LK_EXCLUSIVE);
1187
1188         error = devfs_unlink_dev(dev);
1189         devfs_propagate_dev(dev, 0);
1190         if (error == 0)
1191                 release_dev(dev);       /* link ref */
1192         release_dev(dev);
1193         release_dev(dev);
1194
1195         return 0;
1196 }
1197
1198 /*
1199  * Worker function to destroy all devices with a certain basename.
1200  * Calls devfs_destroy_dev_worker for the actual destruction.
1201  */
1202 static int
1203 devfs_destroy_subnames_worker(char *name)
1204 {
1205         cdev_t dev, dev1;
1206         size_t len = strlen(name);
1207
1208         TAILQ_FOREACH_MUTABLE(dev, &devfs_dev_list, link, dev1) {
1209                 if ((!strncmp(dev->si_name, name, len)) &&
1210                                 (dev->si_name[len] != '\0')) {
1211                         devfs_destroy_dev_worker(dev);
1212                 }
1213         }
1214         return 0;
1215 }
1216
1217 static int
1218 devfs_clr_subnames_flag_worker(char *name, uint32_t flag)
1219 {
1220         cdev_t dev, dev1;
1221         size_t len = strlen(name);
1222
1223         TAILQ_FOREACH_MUTABLE(dev, &devfs_dev_list, link, dev1) {
1224                 if ((!strncmp(dev->si_name, name, len)) &&
1225                                 (dev->si_name[len] != '\0')) {
1226                         dev->si_flags &= ~flag;
1227                 }
1228         }
1229
1230         return 0;
1231 }
1232
1233 static int
1234 devfs_destroy_subnames_without_flag_worker(char *name, uint32_t flag)
1235 {
1236         cdev_t dev, dev1;
1237         size_t len = strlen(name);
1238
1239         TAILQ_FOREACH_MUTABLE(dev, &devfs_dev_list, link, dev1) {
1240                 if ((!strncmp(dev->si_name, name, len)) &&
1241                                 (dev->si_name[len] != '\0')) {
1242                         if (!(dev->si_flags & flag)) {
1243                                 devfs_destroy_dev_worker(dev);
1244                         }
1245                 }
1246         }
1247
1248         return 0;
1249 }
1250
1251 /*
1252  * Worker function that creates all device nodes on top of a devfs
1253  * root node.
1254  */
1255 static int
1256 devfs_create_all_dev_worker(struct devfs_node *root)
1257 {
1258         cdev_t dev;
1259
1260         KKASSERT(root);
1261
1262         TAILQ_FOREACH(dev, &devfs_dev_list, link) {
1263                 devfs_create_device_node(root, dev, NULL, NULL);
1264         }
1265
1266         return 0;
1267 }
1268
1269 /*
1270  * Worker function that destroys all devices that match a specific
1271  * dev_ops and/or minor. If minor is less than 0, it is not matched
1272  * against. It also propagates all changes.
1273  */
1274 static int
1275 devfs_destroy_dev_by_ops_worker(struct dev_ops *ops, int minor)
1276 {
1277         cdev_t dev, dev1;
1278
1279         KKASSERT(ops);
1280
1281         TAILQ_FOREACH_MUTABLE(dev, &devfs_dev_list, link, dev1) {
1282                 if (dev->si_ops != ops)
1283                         continue;
1284                 if ((minor < 0) || (dev->si_uminor == minor)) {
1285                         devfs_destroy_dev_worker(dev);
1286                 }
1287         }
1288
1289         return 0;
1290 }
1291
1292 /*
1293  * Worker function that registers a new clone handler in devfs.
1294  */
1295 static int
1296 devfs_chandler_add_worker(char *name, d_clone_t *nhandler)
1297 {
1298         struct devfs_clone_handler *chandler = NULL;
1299         u_char len = strlen(name);
1300
1301         if (len == 0)
1302                 return 1;
1303
1304         TAILQ_FOREACH(chandler, &devfs_chandler_list, link) {
1305                 if (chandler->namlen != len)
1306                         continue;
1307
1308                 if (!memcmp(chandler->name, name, len)) {
1309                         /* Clonable basename already exists */
1310                         return 1;
1311                 }
1312         }
1313
1314         chandler = kmalloc(sizeof(*chandler), M_DEVFS, M_WAITOK | M_ZERO);
1315         chandler->name = kmalloc(len+1, M_DEVFS, M_WAITOK);
1316         memcpy(chandler->name, name, len+1);
1317         chandler->namlen = len;
1318         chandler->nhandler = nhandler;
1319
1320         TAILQ_INSERT_TAIL(&devfs_chandler_list, chandler, link);
1321         return 0;
1322 }
1323
1324 /*
1325  * Worker function that removes a given clone handler from the
1326  * clone handler list.
1327  */
1328 static int
1329 devfs_chandler_del_worker(char *name)
1330 {
1331         struct devfs_clone_handler *chandler, *chandler2;
1332         u_char len = strlen(name);
1333
1334         if (len == 0)
1335                 return 1;
1336
1337         TAILQ_FOREACH_MUTABLE(chandler, &devfs_chandler_list, link, chandler2) {
1338                 if (chandler->namlen != len)
1339                         continue;
1340                 if (memcmp(chandler->name, name, len))
1341                         continue;
1342
1343                 TAILQ_REMOVE(&devfs_chandler_list, chandler, link);
1344                 kfree(chandler->name, M_DEVFS);
1345                 kfree(chandler, M_DEVFS);
1346                 break;
1347         }
1348
1349         return 0;
1350 }
1351
1352 /*
1353  * Worker function that finds a given device name and changes
1354  * the message received accordingly so that when replied to,
1355  * the answer is returned to the caller.
1356  */
1357 static int
1358 devfs_find_device_by_name_worker(devfs_msg_t devfs_msg)
1359 {
1360         struct devfs_alias *alias;
1361         cdev_t dev;
1362         cdev_t found = NULL;
1363
1364         TAILQ_FOREACH(dev, &devfs_dev_list, link) {
1365                 if (strcmp(devfs_msg->mdv_name, dev->si_name) == 0) {
1366                         found = dev;
1367                         break;
1368                 }
1369         }
1370         if (found == NULL) {
1371                 TAILQ_FOREACH(alias, &devfs_alias_list, link) {
1372                         if (strcmp(devfs_msg->mdv_name, alias->name) == 0) {
1373                                 found = alias->dev_target;
1374                                 break;
1375                         }
1376                 }
1377         }
1378         devfs_msg->mdv_cdev = found;
1379
1380         return 0;
1381 }
1382
1383 /*
1384  * Worker function that finds a given device udev and changes
1385  * the message received accordingly so that when replied to,
1386  * the answer is returned to the caller.
1387  */
1388 static int
1389 devfs_find_device_by_udev_worker(devfs_msg_t devfs_msg)
1390 {
1391         cdev_t dev, dev1;
1392         cdev_t found = NULL;
1393
1394         TAILQ_FOREACH_MUTABLE(dev, &devfs_dev_list, link, dev1) {
1395                 if (((udev_t)dev->si_inode) == devfs_msg->mdv_udev) {
1396                         found = dev;
1397                         break;
1398                 }
1399         }
1400         devfs_msg->mdv_cdev = found;
1401
1402         return 0;
1403 }
1404
1405 /*
1406  * Worker function that inserts a given alias into the
1407  * alias list, and propagates the alias to all mount
1408  * points.
1409  */
1410 static int
1411 devfs_make_alias_worker(struct devfs_alias *alias)
1412 {
1413         struct devfs_alias *alias2;
1414         size_t len = strlen(alias->name);
1415         int found = 0;
1416
1417         TAILQ_FOREACH(alias2, &devfs_alias_list, link) {
1418                 if (len != alias2->namlen)
1419                         continue;
1420
1421                 if (!memcmp(alias->name, alias2->name, len)) {
1422                         found = 1;
1423                         break;
1424                 }
1425         }
1426
1427         if (!found) {
1428                 /*
1429                  * The alias doesn't exist yet, so we add it to the alias list
1430                  */
1431                 TAILQ_INSERT_TAIL(&devfs_alias_list, alias, link);
1432                 devfs_alias_propagate(alias);
1433         } else {
1434                 devfs_debug(DEVFS_DEBUG_WARNING,
1435                             "Warning: duplicate devfs_make_alias for %s\n",
1436                             alias->name);
1437                 kfree(alias->name, M_DEVFS);
1438                 kfree(alias, M_DEVFS);
1439         }
1440
1441         return 0;
1442 }
1443
1444 /*
1445  * Function that removes and frees all aliases.
1446  */
1447 static int
1448 devfs_alias_reap(void)
1449 {
1450         struct devfs_alias *alias, *alias2;
1451
1452         TAILQ_FOREACH_MUTABLE(alias, &devfs_alias_list, link, alias2) {
1453                 TAILQ_REMOVE(&devfs_alias_list, alias, link);
1454                 kfree(alias, M_DEVFS);
1455         }
1456         return 0;
1457 }
1458
1459 /*
1460  * Function that removes an alias matching a specific cdev and frees
1461  * it accordingly.
1462  */
1463 static int
1464 devfs_alias_remove(cdev_t dev)
1465 {
1466         struct devfs_alias *alias, *alias2;
1467
1468         TAILQ_FOREACH_MUTABLE(alias, &devfs_alias_list, link, alias2) {
1469                 if (alias->dev_target == dev) {
1470                         TAILQ_REMOVE(&devfs_alias_list, alias, link);
1471                         kfree(alias, M_DEVFS);
1472                 }
1473         }
1474         return 0;
1475 }
1476
1477 /*
1478  * This function propagates a new alias to all mount points.
1479  */
1480 static int
1481 devfs_alias_propagate(struct devfs_alias *alias)
1482 {
1483         struct devfs_mnt_data *mnt;
1484
1485         TAILQ_FOREACH(mnt, &devfs_mnt_list, link) {
1486                 devfs_alias_apply(mnt->root_node, alias);
1487         }
1488         return 0;
1489 }
1490
1491 /*
1492  * This function is a recursive function iterating through
1493  * all device nodes in the topology and, if applicable,
1494  * creating the relevant alias for a device node.
1495  */
1496 static int
1497 devfs_alias_apply(struct devfs_node *node, struct devfs_alias *alias)
1498 {
1499         struct devfs_node *node1, *node2;
1500
1501         KKASSERT(alias != NULL);
1502
1503         if ((node->node_type == Proot) || (node->node_type == Pdir)) {
1504                 if (node->nchildren > 2) {
1505                         TAILQ_FOREACH_MUTABLE(node1, DEVFS_DENODE_HEAD(node), link, node2) {
1506                                 devfs_alias_apply(node1, alias);
1507                         }
1508                 }
1509         } else {
1510                 if (node->d_dev == alias->dev_target)
1511                         devfs_alias_create(alias->name, node, 0);
1512         }
1513         return 0;
1514 }
1515
1516 /*
1517  * This function checks if any alias possibly is applicable
1518  * to the given node. If so, the alias is created.
1519  */
1520 static int
1521 devfs_alias_check_create(struct devfs_node *node)
1522 {
1523         struct devfs_alias *alias;
1524
1525         TAILQ_FOREACH(alias, &devfs_alias_list, link) {
1526                 if (node->d_dev == alias->dev_target)
1527                         devfs_alias_create(alias->name, node, 0);
1528         }
1529         return 0;
1530 }
1531
1532 /*
1533  * This function creates an alias with a given name
1534  * linking to a given devfs node. It also increments
1535  * the link count on the target node.
1536  */
1537 int
1538 devfs_alias_create(char *name_orig, struct devfs_node *target, int rule_based)
1539 {
1540         struct mount *mp = target->mp;
1541         struct devfs_node *parent = DEVFS_MNTDATA(mp)->root_node;
1542         struct devfs_node *linknode;
1543         char *create_path = NULL;
1544         char *name, name_buf[PATH_MAX];
1545
1546         KKASSERT((lockstatus(&devfs_lock, curthread)) == LK_EXCLUSIVE);
1547
1548         devfs_resolve_name_path(name_orig, name_buf, &create_path, &name);
1549
1550         if (create_path)
1551                 parent = devfs_resolve_or_create_path(parent, create_path, 1);
1552
1553
1554         if (devfs_find_device_node_by_name(parent, name)) {
1555                 devfs_debug(DEVFS_DEBUG_WARNING,
1556                             "Node already exists: %s "
1557                             "(devfs_make_alias_worker)!\n",
1558                             name);
1559                 return 1;
1560         }
1561
1562
1563         linknode = devfs_allocp(Plink, name, parent, mp, NULL);
1564         if (linknode == NULL)
1565                 return 1;
1566
1567         linknode->link_target = target;
1568         target->nlinks++;
1569
1570         if (rule_based)
1571                 linknode->flags |= DEVFS_RULE_CREATED;
1572
1573         return 0;
1574 }
1575
1576 /*
1577  * This function is called by the core and handles mount point
1578  * strings. It either calls the relevant worker (devfs_apply_
1579  * reset_rules_worker) on all mountpoints or only a specific
1580  * one.
1581  */
1582 static int
1583 devfs_apply_reset_rules_caller(char *mountto, int apply)
1584 {
1585         struct devfs_mnt_data *mnt;
1586         size_t len = strlen(mountto);
1587
1588         if (mountto[0] == '*') {
1589                 TAILQ_FOREACH(mnt, &devfs_mnt_list, link) {
1590                         devfs_iterate_topology(mnt->root_node,
1591                                         (apply)?(devfs_rule_check_apply):(devfs_rule_reset_node),
1592                                         NULL);
1593                 }
1594         } else {
1595                 TAILQ_FOREACH(mnt, &devfs_mnt_list, link) {
1596                         if ((len != mnt->mntonnamelen))
1597                                 continue;
1598
1599                         if (!memcmp(mnt->mp->mnt_stat.f_mntonname, mountto, len)) {
1600                                 devfs_iterate_topology(mnt->root_node,
1601                                         (apply)?(devfs_rule_check_apply):(devfs_rule_reset_node),
1602                                         NULL);
1603                                 break;
1604                         }
1605                 }
1606         }
1607
1608         kfree(mountto, M_DEVFS);
1609         return 0;
1610 }
1611
1612 /*
1613  * This function calls a given callback function for
1614  * every dev node in the devfs dev list.
1615  */
1616 static int
1617 devfs_scan_callback_worker(devfs_scan_t *callback)
1618 {
1619         cdev_t dev, dev1;
1620
1621         TAILQ_FOREACH_MUTABLE(dev, &devfs_dev_list, link, dev1) {
1622                 callback(dev);
1623         }
1624
1625         return 0;
1626 }
1627
1628 /*
1629  * This function tries to resolve a given directory, or if not
1630  * found and creation requested, creates the given directory.
1631  */
1632 static struct devfs_node *
1633 devfs_resolve_or_create_dir(struct devfs_node *parent, char *dir_name,
1634                             size_t name_len, int create)
1635 {
1636         struct devfs_node *node, *found = NULL;
1637
1638         TAILQ_FOREACH(node, DEVFS_DENODE_HEAD(parent), link) {
1639                 if (name_len != node->d_dir.d_namlen)
1640                         continue;
1641
1642                 if (!memcmp(dir_name, node->d_dir.d_name, name_len)) {
1643                         found = node;
1644                         break;
1645                 }
1646         }
1647
1648         if ((found == NULL) && (create)) {
1649                 found = devfs_allocp(Pdir, dir_name, parent, parent->mp, NULL);
1650         }
1651
1652         return found;
1653 }
1654
1655 /*
1656  * This function tries to resolve a complete path. If creation is requested,
1657  * if a given part of the path cannot be resolved (because it doesn't exist),
1658  * it is created.
1659  */
1660 struct devfs_node *
1661 devfs_resolve_or_create_path(struct devfs_node *parent, char *path, int create)
1662 {
1663         struct devfs_node *node = parent;
1664         char buf[PATH_MAX];
1665         size_t idx = 0;
1666
1667
1668         if (path == NULL)
1669                 return parent;
1670
1671
1672         for (; *path != '\0' ; path++) {
1673                 if (*path != '/') {
1674                         buf[idx++] = *path;
1675                 } else {
1676                         buf[idx] = '\0';
1677                         node = devfs_resolve_or_create_dir(node, buf, idx, create);
1678                         if (node == NULL)
1679                                 return NULL;
1680                         idx = 0;
1681                 }
1682         }
1683         buf[idx] = '\0';
1684         return devfs_resolve_or_create_dir(node, buf, idx, create);
1685 }
1686
1687 /*
1688  * Takes a full path and strips it into a directory path and a name.
1689  * For a/b/c/foo, it returns foo in namep and a/b/c in pathp. It
1690  * requires a working buffer with enough size to keep the whole
1691  * fullpath.
1692  */
1693 int
1694 devfs_resolve_name_path(char *fullpath, char *buf, char **pathp, char **namep)
1695 {
1696         char *name = NULL;
1697         char *path = NULL;
1698         size_t len = strlen(fullpath) + 1;
1699         int i;
1700
1701         KKASSERT((fullpath != NULL) && (buf != NULL));
1702         KKASSERT((pathp != NULL) && (namep != NULL));
1703
1704         memcpy(buf, fullpath, len);
1705
1706         for (i = len-1; i>= 0; i--) {
1707                 if (buf[i] == '/') {
1708                         buf[i] = '\0';
1709                         name = &(buf[i+1]);
1710                         path = buf;
1711                         break;
1712                 }
1713         }
1714
1715         *pathp = path;
1716
1717         if (name) {
1718                 *namep = name;
1719         } else {
1720                 *namep = buf;
1721         }
1722
1723         return 0;
1724 }
1725
1726 /*
1727  * This function creates a new devfs node for a given device.  It can
1728  * handle a complete path as device name, and accordingly creates
1729  * the path and the final device node.
1730  *
1731  * The reference count on the passed dev remains unchanged.
1732  */
1733 struct devfs_node *
1734 devfs_create_device_node(struct devfs_node *root, cdev_t dev,
1735                          char *dev_name, char *path_fmt, ...)
1736 {
1737         struct devfs_node *parent, *node = NULL;
1738         char *path = NULL;
1739         char *name, name_buf[PATH_MAX];
1740         __va_list ap;
1741         int i, found;
1742
1743         char *create_path = NULL;
1744         char *names = "pqrsPQRS";
1745
1746         if (path_fmt != NULL) {
1747                 path = kmalloc(PATH_MAX+1, M_DEVFS, M_WAITOK);
1748
1749                 __va_start(ap, path_fmt);
1750                 i = kvcprintf(path_fmt, NULL, path, 10, ap);
1751                 path[i] = '\0';
1752                 __va_end(ap);
1753         }
1754
1755         parent = devfs_resolve_or_create_path(root, path, 1);
1756         KKASSERT(parent);
1757
1758         devfs_resolve_name_path(
1759                         ((dev_name == NULL) && (dev))?(dev->si_name):(dev_name),
1760                         name_buf, &create_path, &name);
1761
1762         if (create_path)
1763                 parent = devfs_resolve_or_create_path(parent, create_path, 1);
1764
1765
1766         if (devfs_find_device_node_by_name(parent, name)) {
1767                 devfs_debug(DEVFS_DEBUG_WARNING, "devfs_create_device_node: "
1768                         "DEVICE %s ALREADY EXISTS!!! Ignoring creation request.\n", name);
1769                 goto out;
1770         }
1771
1772         node = devfs_allocp(Pdev, name, parent, parent->mp, dev);
1773
1774 #if 0
1775         /*
1776          * Ugly unix98 pty magic, to hide pty master (ptm) devices and their
1777          * directory
1778          */
1779         if ((dev) && (strlen(dev->si_name) >= 4) &&
1780                         (!memcmp(dev->si_name, "ptm/", 4))) {
1781                 node->parent->flags |= DEVFS_HIDDEN;
1782                 node->flags |= DEVFS_HIDDEN;
1783         }
1784 #endif
1785
1786         /*
1787          * Ugly pty magic, to tag pty devices as such and hide them if needed.
1788          */
1789         if ((strlen(name) >= 3) && (!memcmp(name, "pty", 3)))
1790                 node->flags |= (DEVFS_PTY | DEVFS_INVISIBLE);
1791
1792         if ((strlen(name) >= 3) && (!memcmp(name, "tty", 3))) {
1793                 found = 0;
1794                 for (i = 0; i < strlen(names); i++) {
1795                         if (name[3] == names[i]) {
1796                                 found = 1;
1797                                 break;
1798                         }
1799                 }
1800                 if (found)
1801                         node->flags |= (DEVFS_PTY | DEVFS_INVISIBLE);
1802         }
1803
1804 out:
1805         if (path_fmt != NULL)
1806                 kfree(path, M_DEVFS);
1807
1808         return node;
1809 }
1810
1811 /*
1812  * This function finds a given device node in the topology with a given
1813  * cdev.
1814  */
1815 void *
1816 devfs_find_device_node_callback(struct devfs_node *node, cdev_t target)
1817 {
1818         if ((node->node_type == Pdev) && (node->d_dev == target)) {
1819                 return node;
1820         }
1821
1822         return NULL;
1823 }
1824
1825 /*
1826  * This function finds a device node in the given parent directory by its
1827  * name and returns it.
1828  */
1829 struct devfs_node *
1830 devfs_find_device_node_by_name(struct devfs_node *parent, char *target)
1831 {
1832         struct devfs_node *node, *found = NULL;
1833         size_t len = strlen(target);
1834
1835         TAILQ_FOREACH(node, DEVFS_DENODE_HEAD(parent), link) {
1836                 if (len != node->d_dir.d_namlen)
1837                         continue;
1838
1839                 if (!memcmp(node->d_dir.d_name, target, len)) {
1840                         found = node;
1841                         break;
1842                 }
1843         }
1844
1845         return found;
1846 }
1847
1848 static void *
1849 devfs_inode_to_vnode_worker_callback(struct devfs_node *node, ino_t *inop)
1850 {
1851         struct vnode *vp = NULL;
1852         ino_t target = *inop;
1853
1854         if (node->d_dir.d_ino == target) {
1855                 if (node->v_node) {
1856                         vp = node->v_node;
1857                         vget(vp, LK_EXCLUSIVE | LK_RETRY);
1858                         vn_unlock(vp);
1859                 } else {
1860                         devfs_allocv(&vp, node);
1861                         vn_unlock(vp);
1862                 }
1863         }
1864
1865         return vp;
1866 }
1867
1868 /*
1869  * This function takes a cdev and removes its devfs node in the
1870  * given topology.  The cdev remains intact.
1871  */
1872 int
1873 devfs_destroy_device_node(struct devfs_node *root, cdev_t target)
1874 {
1875         struct devfs_node *node, *parent;
1876         char *name, name_buf[PATH_MAX];
1877         char *create_path = NULL;
1878
1879         KKASSERT(target);
1880
1881         memcpy(name_buf, target->si_name, strlen(target->si_name)+1);
1882
1883         devfs_resolve_name_path(target->si_name, name_buf, &create_path, &name);
1884
1885         if (create_path)
1886                 parent = devfs_resolve_or_create_path(root, create_path, 0);
1887         else
1888                 parent = root;
1889
1890         if (parent == NULL)
1891                 return 1;
1892
1893         node = devfs_find_device_node_by_name(parent, name);
1894
1895         if (node)
1896                 devfs_gc(node);
1897
1898         return 0;
1899 }
1900
1901 /*
1902  * Just set perms and ownership for given node.
1903  */
1904 int
1905 devfs_set_perms(struct devfs_node *node, uid_t uid, gid_t gid,
1906                 u_short mode, u_long flags)
1907 {
1908         node->mode = mode;
1909         node->uid = uid;
1910         node->gid = gid;
1911
1912         return 0;
1913 }
1914
1915 /*
1916  * Propagates a device attach/detach to all mount
1917  * points. Also takes care of automatic alias removal
1918  * for a deleted cdev.
1919  */
1920 static int
1921 devfs_propagate_dev(cdev_t dev, int attach)
1922 {
1923         struct devfs_mnt_data *mnt;
1924
1925         TAILQ_FOREACH(mnt, &devfs_mnt_list, link) {
1926                 if (attach) {
1927                         /* Device is being attached */
1928                         devfs_create_device_node(mnt->root_node, dev,
1929                                                  NULL, NULL );
1930                 } else {
1931                         /* Device is being detached */
1932                         devfs_alias_remove(dev);
1933                         devfs_destroy_device_node(mnt->root_node, dev);
1934                 }
1935         }
1936         return 0;
1937 }
1938
1939 /*
1940  * devfs_node_to_path takes a node and a buffer of a size of
1941  * at least PATH_MAX, resolves the full path from the root
1942  * node and writes it in a humanly-readable format into the
1943  * buffer.
1944  * If DEVFS_STASH_DEPTH is less than the directory level up
1945  * to the root node, only the last DEVFS_STASH_DEPTH levels
1946  * of the path are resolved.
1947  */
1948 int
1949 devfs_node_to_path(struct devfs_node *node, char *buffer)
1950 {
1951 #define DEVFS_STASH_DEPTH       32
1952         struct devfs_node *node_stash[DEVFS_STASH_DEPTH];
1953         int i, offset;
1954         memset(buffer, 0, PATH_MAX);
1955
1956         for (i = 0; (i < DEVFS_STASH_DEPTH) && (node->node_type != Proot); i++) {
1957                 node_stash[i] = node;
1958                 node = node->parent;
1959         }
1960         i--;
1961
1962         for (offset = 0; i >= 0; i--) {
1963                 memcpy(buffer+offset, node_stash[i]->d_dir.d_name,
1964                                 node_stash[i]->d_dir.d_namlen);
1965                 offset += node_stash[i]->d_dir.d_namlen;
1966                 if (i > 0) {
1967                         *(buffer+offset) = '/';
1968                         offset++;
1969                 }
1970         }
1971 #undef DEVFS_STASH_DEPTH
1972         return 0;
1973 }
1974
1975 /*
1976  * devfs_clone either returns a basename from a complete name by
1977  * returning the length of the name without trailing digits, or,
1978  * if clone != 0, calls the device's clone handler to get a new
1979  * device, which in turn is returned in devp.
1980  */
1981 int
1982 devfs_clone(char *name, size_t *namlenp, cdev_t *devp, int clone,
1983                 struct ucred *cred)
1984 {
1985         KKASSERT(namlenp);
1986
1987         size_t len = *namlenp;
1988         int error = 1;
1989         struct devfs_clone_handler *chandler;
1990         struct dev_clone_args ap;
1991
1992         if (!clone) {
1993                 for (; (len > 0) && (DEVFS_ISDIGIT(name[len-1])); len--);
1994         }
1995
1996         TAILQ_FOREACH(chandler, &devfs_chandler_list, link) {
1997                 if ((chandler->namlen == len) &&
1998                     (!memcmp(chandler->name, name, len)) &&
1999                     (chandler->nhandler)) {
2000                         if (clone) {
2001                                 ap.a_dev = NULL;
2002                                 ap.a_name = name;
2003                                 ap.a_namelen = len;
2004                                 ap.a_cred = cred;
2005                                 error = (chandler->nhandler)(&ap);
2006                                 KKASSERT(devp);
2007                                 *devp = ap.a_dev;
2008                         } else {
2009                                 *namlenp = len;
2010                                 error = 0;
2011                         }
2012
2013                         break;
2014                 }
2015         }
2016
2017         return error;
2018 }
2019
2020
2021 /*
2022  * Registers a new orphan in the orphan list.
2023  */
2024 void
2025 devfs_tracer_add_orphan(struct devfs_node *node)
2026 {
2027         struct devfs_orphan *orphan;
2028
2029         KKASSERT(node);
2030         orphan = kmalloc(sizeof(struct devfs_orphan), M_DEVFS, M_WAITOK);
2031         orphan->node = node;
2032
2033         KKASSERT((node->flags & DEVFS_ORPHANED) == 0);
2034         node->flags |= DEVFS_ORPHANED;
2035         TAILQ_INSERT_TAIL(DEVFS_ORPHANLIST(node->mp), orphan, link);
2036 }
2037
2038 /*
2039  * Removes an orphan from the orphan list.
2040  */
2041 void
2042 devfs_tracer_del_orphan(struct devfs_node *node)
2043 {
2044         struct devfs_orphan *orphan;
2045
2046         KKASSERT(node);
2047
2048         TAILQ_FOREACH(orphan, DEVFS_ORPHANLIST(node->mp), link) {
2049                 if (orphan->node == node) {
2050                         node->flags &= ~DEVFS_ORPHANED;
2051                         TAILQ_REMOVE(DEVFS_ORPHANLIST(node->mp), orphan, link);
2052                         kfree(orphan, M_DEVFS);
2053                         break;
2054                 }
2055         }
2056 }
2057
2058 /*
2059  * Counts the orphans in the orphan list, and if cleanup
2060  * is specified, also frees the orphan and removes it from
2061  * the list.
2062  */
2063 size_t
2064 devfs_tracer_orphan_count(struct mount *mp, int cleanup)
2065 {
2066         struct devfs_orphan *orphan, *orphan2;
2067         size_t count = 0;
2068
2069         TAILQ_FOREACH_MUTABLE(orphan, DEVFS_ORPHANLIST(mp), link, orphan2)      {
2070                 count++;
2071                 /*
2072                  * If we are instructed to clean up, we do so.
2073                  */
2074                 if (cleanup) {
2075                         TAILQ_REMOVE(DEVFS_ORPHANLIST(mp), orphan, link);
2076                         orphan->node->flags &= ~DEVFS_ORPHANED;
2077                         devfs_freep(orphan->node);
2078                         kfree(orphan, M_DEVFS);
2079                 }
2080         }
2081
2082         return count;
2083 }
2084
2085 /*
2086  * Fetch an ino_t from the global d_ino by increasing it
2087  * while spinlocked.
2088  */
2089 static ino_t
2090 devfs_fetch_ino(void)
2091 {
2092         ino_t   ret;
2093
2094         spin_lock_wr(&ino_lock);
2095         ret = d_ino++;
2096         spin_unlock_wr(&ino_lock);
2097
2098         return ret;
2099 }
2100
2101 /*
2102  * Allocates a new cdev and initializes it's most basic
2103  * fields.
2104  */
2105 cdev_t
2106 devfs_new_cdev(struct dev_ops *ops, int minor)
2107 {
2108         cdev_t dev = sysref_alloc(&cdev_sysref_class);
2109         sysref_activate(&dev->si_sysref);
2110         reference_dev(dev);
2111         memset(dev, 0, offsetof(struct cdev, si_sysref));
2112
2113         dev->si_uid = 0;
2114         dev->si_gid = 0;
2115         dev->si_perms = 0;
2116         dev->si_drv1 = NULL;
2117         dev->si_drv2 = NULL;
2118         dev->si_lastread = 0;           /* time_second */
2119         dev->si_lastwrite = 0;          /* time_second */
2120
2121         dev->si_ops = ops;
2122         dev->si_flags = 0;
2123         dev->si_umajor = 0;
2124         dev->si_uminor = minor;
2125         dev->si_inode = makeudev(devfs_reference_ops(ops), minor);
2126
2127         return dev;
2128 }
2129
2130 static void
2131 devfs_cdev_terminate(cdev_t dev)
2132 {
2133         int locked = 0;
2134
2135         /* Check if it is locked already. if not, we acquire the devfs lock */
2136         if (!(lockstatus(&devfs_lock, curthread)) == LK_EXCLUSIVE) {
2137                 lockmgr(&devfs_lock, LK_EXCLUSIVE);
2138                 locked = 1;
2139         }
2140
2141         /* Propagate destruction, just in case */
2142         devfs_propagate_dev(dev, 0);
2143
2144         /* If we acquired the lock, we also get rid of it */
2145         if (locked)
2146                 lockmgr(&devfs_lock, LK_RELEASE);
2147
2148         devfs_release_ops(dev->si_ops);
2149
2150         /* Finally destroy the device */
2151         sysref_put(&dev->si_sysref);
2152 }
2153
2154 /*
2155  * Links a given cdev into the dev list.
2156  */
2157 int
2158 devfs_link_dev(cdev_t dev)
2159 {
2160         KKASSERT((dev->si_flags & SI_DEVFS_LINKED) == 0);
2161         dev->si_flags |= SI_DEVFS_LINKED;
2162         TAILQ_INSERT_TAIL(&devfs_dev_list, dev, link);
2163
2164         return 0;
2165 }
2166
2167 /*
2168  * Removes a given cdev from the dev list.  The caller is responsible for
2169  * releasing the reference on the device associated with the linkage.
2170  *
2171  * Returns EALREADY if the dev has already been unlinked.
2172  */
2173 static int
2174 devfs_unlink_dev(cdev_t dev)
2175 {
2176         if ((dev->si_flags & SI_DEVFS_LINKED)) {
2177                 TAILQ_REMOVE(&devfs_dev_list, dev, link);
2178                 dev->si_flags &= ~SI_DEVFS_LINKED;
2179                 return (0);
2180         }
2181         return (EALREADY);
2182 }
2183
2184 int
2185 devfs_node_is_accessible(struct devfs_node *node)
2186 {
2187         if ((node) && (!(node->flags & DEVFS_HIDDEN)))
2188                 return 1;
2189         else
2190                 return 0;
2191 }
2192
2193 int
2194 devfs_reference_ops(struct dev_ops *ops)
2195 {
2196         int unit;
2197
2198         if (ops->head.refs == 0) {
2199                 ops->head.id = devfs_clone_bitmap_get(&DEVFS_CLONE_BITMAP(ops_id), 255);
2200                 if (ops->head.id == -1) {
2201                         /* Ran out of unique ids */
2202                         devfs_debug(DEVFS_DEBUG_WARNING,
2203                                         "devfs_reference_ops: WARNING: ran out of unique ids\n");
2204                 }
2205         }
2206         unit = ops->head.id;
2207         ++ops->head.refs;
2208
2209         return unit;
2210 }
2211
2212 void
2213 devfs_release_ops(struct dev_ops *ops)
2214 {
2215         --ops->head.refs;
2216
2217         if (ops->head.refs == 0) {
2218                 devfs_clone_bitmap_put(&DEVFS_CLONE_BITMAP(ops_id), ops->head.id);
2219         }
2220 }
2221
2222 void
2223 devfs_config(void)
2224 {
2225         devfs_msg_t msg;
2226
2227         msg = devfs_msg_get();
2228         msg = devfs_msg_send_sync(DEVFS_SYNC, msg);
2229         devfs_msg_put(msg);
2230 }
2231
2232 /*
2233  * Called on init of devfs; creates the objcaches and
2234  * spawns off the devfs core thread. Also initializes
2235  * locks.
2236  */
2237 static void
2238 devfs_init(void)
2239 {
2240         devfs_debug(DEVFS_DEBUG_DEBUG, "devfs_init() called\n");
2241         /* Create objcaches for nodes, msgs and devs */
2242         devfs_node_cache = objcache_create("devfs-node-cache", 0, 0,
2243                                            NULL, NULL, NULL,
2244                                            objcache_malloc_alloc,
2245                                            objcache_malloc_free,
2246                                            &devfs_node_malloc_args );
2247
2248         devfs_msg_cache = objcache_create("devfs-msg-cache", 0, 0,
2249                                           NULL, NULL, NULL,
2250                                           objcache_malloc_alloc,
2251                                           objcache_malloc_free,
2252                                           &devfs_msg_malloc_args );
2253
2254         devfs_dev_cache = objcache_create("devfs-dev-cache", 0, 0,
2255                                           NULL, NULL, NULL,
2256                                           objcache_malloc_alloc,
2257                                           objcache_malloc_free,
2258                                           &devfs_dev_malloc_args );
2259
2260         devfs_clone_bitmap_init(&DEVFS_CLONE_BITMAP(ops_id));
2261
2262         /* Initialize the reply-only port which acts as a message drain */
2263         lwkt_initport_replyonly(&devfs_dispose_port, devfs_msg_autofree_reply);
2264
2265         /* Initialize *THE* devfs lock */
2266         lockinit(&devfs_lock, "devfs_core lock", 0, 0);
2267
2268
2269         lwkt_create(devfs_msg_core, /*args*/NULL, &td_core, NULL,
2270                     0, 0, "devfs_msg_core");
2271
2272         tsleep(td_core/*devfs_id*/, 0, "devfsc", 0);
2273
2274         devfs_debug(DEVFS_DEBUG_DEBUG, "devfs_init finished\n");
2275 }
2276
2277 /*
2278  * Called on unload of devfs; takes care of destroying the core
2279  * and the objcaches. Also removes aliases that are no longer needed.
2280  */
2281 static void
2282 devfs_uninit(void)
2283 {
2284         devfs_debug(DEVFS_DEBUG_DEBUG, "devfs_uninit() called\n");
2285
2286         devfs_msg_send(DEVFS_TERMINATE_CORE, NULL);
2287
2288         tsleep(td_core/*devfs_id*/, 0, "devfsc", 0);
2289         tsleep(td_core/*devfs_id*/, 0, "devfsc", 10000);
2290
2291         devfs_clone_bitmap_uninit(&DEVFS_CLONE_BITMAP(ops_id));
2292
2293         /* Destroy the objcaches */
2294         objcache_destroy(devfs_msg_cache);
2295         objcache_destroy(devfs_node_cache);
2296         objcache_destroy(devfs_dev_cache);
2297
2298         devfs_alias_reap();
2299 }
2300
2301 /*
2302  * This is a sysctl handler to assist userland devname(3) to
2303  * find the device name for a given udev.
2304  */
2305 static int
2306 devfs_sysctl_devname_helper(SYSCTL_HANDLER_ARGS)
2307 {
2308         udev_t  udev;
2309         cdev_t  found;
2310         int             error;
2311
2312
2313         if ((error = SYSCTL_IN(req, &udev, sizeof(udev_t))))
2314                 return (error);
2315
2316         devfs_debug(DEVFS_DEBUG_DEBUG, "devfs sysctl, received udev: %d\n", udev);
2317
2318         if (udev == NOUDEV)
2319                 return(EINVAL);
2320
2321         if ((found = devfs_find_device_by_udev(udev)) == NULL)
2322                 return(ENOENT);
2323
2324         return(SYSCTL_OUT(req, found->si_name, strlen(found->si_name) + 1));
2325 }
2326
2327
2328 SYSCTL_PROC(_kern, OID_AUTO, devname, CTLTYPE_OPAQUE|CTLFLAG_RW|CTLFLAG_ANYBODY,
2329                         NULL, 0, devfs_sysctl_devname_helper, "", "helper for devname(3)");
2330
2331 static SYSCTL_NODE(_vfs, OID_AUTO, devfs, CTLFLAG_RW, 0, "devfs");
2332 TUNABLE_INT("vfs.devfs.debug", &devfs_debug_enable);
2333 SYSCTL_INT(_vfs_devfs, OID_AUTO, debug, CTLFLAG_RW, &devfs_debug_enable,
2334                 0, "Enable DevFS debugging");
2335
2336 SYSINIT(vfs_devfs_register, SI_SUB_PRE_DRIVERS, SI_ORDER_FIRST,
2337                 devfs_init, NULL);
2338 SYSUNINIT(vfs_devfs_register, SI_SUB_PRE_DRIVERS, SI_ORDER_ANY,
2339                 devfs_uninit, NULL);