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