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