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