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