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