xref: /titanic_51/usr/src/uts/common/os/modctl.c (revision 074bb90d80fdbeb2d04a8450a55ecbc96de28785)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*
28  * modctl system call for loadable module support.
29  */
30 
31 #include <sys/param.h>
32 #include <sys/user.h>
33 #include <sys/systm.h>
34 #include <sys/exec.h>
35 #include <sys/file.h>
36 #include <sys/stat.h>
37 #include <sys/conf.h>
38 #include <sys/time.h>
39 #include <sys/reboot.h>
40 #include <sys/fs/ufs_fsdir.h>
41 #include <sys/kmem.h>
42 #include <sys/sysconf.h>
43 #include <sys/cmn_err.h>
44 #include <sys/ddi.h>
45 #include <sys/sunddi.h>
46 #include <sys/sunndi.h>
47 #include <sys/ndi_impldefs.h>
48 #include <sys/ddi_impldefs.h>
49 #include <sys/ddi_implfuncs.h>
50 #include <sys/bootconf.h>
51 #include <sys/dc_ki.h>
52 #include <sys/cladm.h>
53 #include <sys/dtrace.h>
54 #include <sys/kdi.h>
55 
56 #include <sys/devpolicy.h>
57 #include <sys/modctl.h>
58 #include <sys/kobj.h>
59 #include <sys/devops.h>
60 #include <sys/autoconf.h>
61 #include <sys/hwconf.h>
62 #include <sys/callb.h>
63 #include <sys/debug.h>
64 #include <sys/cpuvar.h>
65 #include <sys/sysmacros.h>
66 #include <sys/sysevent.h>
67 #include <sys/sysevent_impl.h>
68 #include <sys/instance.h>
69 #include <sys/modhash.h>
70 #include <sys/modhash_impl.h>
71 #include <sys/dacf_impl.h>
72 #include <sys/vfs.h>
73 #include <sys/pathname.h>
74 #include <sys/console.h>
75 #include <sys/policy.h>
76 #include <ipp/ipp_impl.h>
77 #include <sys/fs/dv_node.h>
78 #include <sys/strsubr.h>
79 #include <sys/fs/sdev_impl.h>
80 
81 static int		mod_circdep(struct modctl *);
82 static int		modinfo(modid_t, struct modinfo *);
83 
84 static void		mod_uninstall_all(void);
85 static int		mod_getinfo(struct modctl *, struct modinfo *);
86 static struct modctl	*allocate_modp(const char *, const char *);
87 
88 static int		mod_load(struct modctl *, int);
89 static void		mod_unload(struct modctl *);
90 static int		modinstall(struct modctl *);
91 static int		moduninstall(struct modctl *);
92 
93 static struct modctl	*mod_hold_by_name_common(struct modctl *, const char *);
94 static struct modctl	*mod_hold_next_by_id(modid_t);
95 static struct modctl	*mod_hold_loaded_mod(struct modctl *, char *, int *);
96 static struct modctl	*mod_hold_installed_mod(char *, int, int, int *);
97 
98 static void		mod_release(struct modctl *);
99 static void		mod_make_requisite(struct modctl *, struct modctl *);
100 static int		mod_install_requisites(struct modctl *);
101 static void		check_esc_sequences(char *, char *);
102 static struct modctl	*mod_hold_by_name_requisite(struct modctl *, char *);
103 
104 /*
105  * module loading thread control structure. Calls to kobj_load_module()() are
106  * handled off to a separate thead using this structure.
107  */
108 struct loadmt {
109 	ksema_t		sema;
110 	struct modctl	*mp;
111 	int		usepath;
112 	kthread_t	*owner;
113 	int		retval;
114 };
115 
116 static void	modload_thread(struct loadmt *);
117 
118 kcondvar_t	mod_cv;
119 kcondvar_t	mod_uninstall_cv;	/* Communication between swapper */
120 					/* and the uninstall daemon. */
121 kmutex_t	mod_lock;		/* protects &modules insert linkage, */
122 					/* mod_busy, mod_want, and mod_ref. */
123 					/* blocking operations while holding */
124 					/* mod_lock should be avoided */
125 kmutex_t	mod_uninstall_lock;	/* protects mod_uninstall_cv */
126 kthread_id_t	mod_aul_thread;
127 
128 int		modunload_wait;
129 kmutex_t	modunload_wait_mutex;
130 kcondvar_t	modunload_wait_cv;
131 int		modunload_active_count;
132 int		modunload_disable_count;
133 
134 int	isminiroot;		/* set if running as miniroot */
135 int	modrootloaded;		/* set after root driver and fs are loaded */
136 int	moddebug = 0x0;		/* debug flags for module writers */
137 int	swaploaded;		/* set after swap driver and fs are loaded */
138 int	bop_io_quiesced = 0;	/* set when BOP I/O can no longer be used */
139 int	last_module_id;
140 clock_t	mod_uninstall_interval = 0;
141 int	ddi_modclose_unload = 1;	/* 0 -> just decrement reference */
142 
143 struct devnames *devnamesp;
144 struct devnames orphanlist;
145 
146 krwlock_t	devinfo_tree_lock;	/* obsolete, to be removed */
147 
148 #define	MAJBINDFILE "/etc/name_to_major"
149 #define	SYSBINDFILE "/etc/name_to_sysnum"
150 
151 static char	majbind[] = MAJBINDFILE;
152 static char	sysbind[] = SYSBINDFILE;
153 static uint_t	mod_autounload_key;	/* for module autounload detection */
154 
155 extern int obpdebug;
156 
157 #define	DEBUGGER_PRESENT	((boothowto & RB_DEBUG) || (obpdebug != 0))
158 
159 static int minorperm_loaded = 0;
160 
161 void
162 mod_setup(void)
163 {
164 	struct sysent *callp;
165 	int callnum, exectype;
166 	int	num_devs;
167 	int	i;
168 
169 	/*
170 	 * Initialize the list of loaded driver dev_ops.
171 	 * XXX - This must be done before reading the system file so that
172 	 * forceloads of drivers will work.
173 	 */
174 	num_devs = read_binding_file(majbind, mb_hashtab, make_mbind);
175 	/*
176 	 * Since read_binding_file is common code, it doesn't enforce that all
177 	 * of the binding file entries have major numbers <= MAXMAJ32.	Thus,
178 	 * ensure that we don't allocate some massive amount of space due to a
179 	 * bad entry.  We can't have major numbers bigger than MAXMAJ32
180 	 * until file system support for larger major numbers exists.
181 	 */
182 
183 	/*
184 	 * Leave space for expansion, but not more than L_MAXMAJ32
185 	 */
186 	devcnt = MIN(num_devs + 30, L_MAXMAJ32);
187 	devopsp = kmem_alloc(devcnt * sizeof (struct dev_ops *), KM_SLEEP);
188 	for (i = 0; i < devcnt; i++)
189 		devopsp[i] = &mod_nodev_ops;
190 
191 	init_devnamesp(devcnt);
192 
193 	/*
194 	 * Sync up with the work that the stand-alone linker has already done.
195 	 */
196 	(void) kobj_sync();
197 
198 	if (boothowto & RB_DEBUG)
199 		kdi_dvec_modavail();
200 
201 	make_aliases(mb_hashtab);
202 
203 	/*
204 	 * Initialize streams device implementation structures.
205 	 */
206 	devimpl = kmem_zalloc(devcnt * sizeof (cdevsw_impl_t), KM_SLEEP);
207 
208 	/*
209 	 * If the cl_bootstrap module is present,
210 	 * we should be configured as a cluster. Loading this module
211 	 * will set "cluster_bootflags" to non-zero.
212 	 */
213 	(void) modload("misc", "cl_bootstrap");
214 
215 	(void) read_binding_file(sysbind, sb_hashtab, make_mbind);
216 	init_syscallnames(NSYSCALL);
217 
218 	/*
219 	 * Start up dynamic autoconfiguration framework (dacf).
220 	 */
221 	mod_hash_init();
222 	dacf_init();
223 
224 	/*
225 	 * Start up IP policy framework (ipp).
226 	 */
227 	ipp_init();
228 
229 	/*
230 	 * Allocate loadable native system call locks.
231 	 */
232 	for (callnum = 0, callp = sysent; callnum < NSYSCALL;
233 	    callnum++, callp++) {
234 		if (LOADABLE_SYSCALL(callp)) {
235 			if (mod_getsysname(callnum) != NULL) {
236 				callp->sy_lock =
237 				    kobj_zalloc(sizeof (krwlock_t), KM_SLEEP);
238 				rw_init(callp->sy_lock, NULL, RW_DEFAULT, NULL);
239 			} else {
240 				callp->sy_flags &= ~SE_LOADABLE;
241 				callp->sy_callc = nosys;
242 			}
243 #ifdef DEBUG
244 		} else {
245 			/*
246 			 * Do some sanity checks on the sysent table
247 			 */
248 			switch (callp->sy_flags & SE_RVAL_MASK) {
249 			case SE_32RVAL1:
250 				/* only r_val1 returned */
251 			case SE_32RVAL1 | SE_32RVAL2:
252 				/* r_val1 and r_val2 returned */
253 			case SE_64RVAL:
254 				/* 64-bit rval returned */
255 				break;
256 			default:
257 				cmn_err(CE_WARN, "sysent[%d]: bad flags %x",
258 				    callnum, callp->sy_flags);
259 			}
260 #endif
261 		}
262 	}
263 
264 #ifdef _SYSCALL32_IMPL
265 	/*
266 	 * Allocate loadable system call locks for 32-bit compat syscalls
267 	 */
268 	for (callnum = 0, callp = sysent32; callnum < NSYSCALL;
269 	    callnum++, callp++) {
270 		if (LOADABLE_SYSCALL(callp)) {
271 			if (mod_getsysname(callnum) != NULL) {
272 				callp->sy_lock =
273 				    kobj_zalloc(sizeof (krwlock_t), KM_SLEEP);
274 				rw_init(callp->sy_lock, NULL, RW_DEFAULT, NULL);
275 			} else {
276 				callp->sy_flags &= ~SE_LOADABLE;
277 				callp->sy_callc = nosys;
278 			}
279 #ifdef DEBUG
280 		} else {
281 			/*
282 			 * Do some sanity checks on the sysent table
283 			 */
284 			switch (callp->sy_flags & SE_RVAL_MASK) {
285 			case SE_32RVAL1:
286 				/* only r_val1 returned */
287 			case SE_32RVAL1 | SE_32RVAL2:
288 				/* r_val1 and r_val2 returned */
289 			case SE_64RVAL:
290 				/* 64-bit rval returned */
291 				break;
292 			default:
293 				cmn_err(CE_WARN, "sysent32[%d]: bad flags %x",
294 				    callnum, callp->sy_flags);
295 				goto skip;
296 			}
297 
298 			/*
299 			 * Cross-check the native and compatibility tables.
300 			 */
301 			if (callp->sy_callc == nosys ||
302 			    sysent[callnum].sy_callc == nosys)
303 				continue;
304 			/*
305 			 * If only one or the other slot is loadable, then
306 			 * there's an error -- they should match!
307 			 */
308 			if ((callp->sy_callc == loadable_syscall) ^
309 			    (sysent[callnum].sy_callc == loadable_syscall)) {
310 				cmn_err(CE_WARN, "sysent[%d] loadable?",
311 				    callnum);
312 			}
313 			/*
314 			 * This is more of a heuristic test -- if the
315 			 * system call returns two values in the 32-bit
316 			 * world, it should probably return two 32-bit
317 			 * values in the 64-bit world too.
318 			 */
319 			if (((callp->sy_flags & SE_32RVAL2) == 0) ^
320 			    ((sysent[callnum].sy_flags & SE_32RVAL2) == 0)) {
321 				cmn_err(CE_WARN, "sysent[%d] rval2 mismatch!",
322 				    callnum);
323 			}
324 skip:;
325 #endif	/* DEBUG */
326 		}
327 	}
328 #endif	/* _SYSCALL32_IMPL */
329 
330 	/*
331 	 * Allocate loadable exec locks.  (Assumes all execs are loadable)
332 	 */
333 	for (exectype = 0; exectype < nexectype; exectype++) {
334 		execsw[exectype].exec_lock =
335 		    kobj_zalloc(sizeof (krwlock_t), KM_SLEEP);
336 		rw_init(execsw[exectype].exec_lock, NULL, RW_DEFAULT, NULL);
337 	}
338 
339 	read_class_file();
340 
341 	/* init thread specific structure for mod_uninstall_all */
342 	tsd_create(&mod_autounload_key, NULL);
343 }
344 
345 static int
346 modctl_modload(int use_path, char *filename, int *rvp)
347 {
348 	struct modctl *modp;
349 	int retval = 0;
350 	char *filenamep;
351 	int modid;
352 
353 	filenamep = kmem_zalloc(MOD_MAXPATH, KM_SLEEP);
354 
355 	if (copyinstr(filename, filenamep, MOD_MAXPATH, 0)) {
356 		retval = EFAULT;
357 		goto out;
358 	}
359 
360 	filenamep[MOD_MAXPATH - 1] = 0;
361 	modp = mod_hold_installed_mod(filenamep, use_path, 0, &retval);
362 
363 	if (modp == NULL)
364 		goto out;
365 
366 	modp->mod_loadflags |= MOD_NOAUTOUNLOAD;
367 	modid = modp->mod_id;
368 	mod_release_mod(modp);
369 	CPU_STATS_ADDQ(CPU, sys, modload, 1);
370 	if (rvp != NULL && copyout(&modid, rvp, sizeof (modid)) != 0)
371 		retval = EFAULT;
372 out:
373 	kmem_free(filenamep, MOD_MAXPATH);
374 
375 	return (retval);
376 }
377 
378 static int
379 modctl_modunload(modid_t id)
380 {
381 	int rval = 0;
382 
383 	if (id == 0) {
384 #ifdef DEBUG
385 		/*
386 		 * Turn on mod_uninstall_daemon
387 		 */
388 		if (mod_uninstall_interval == 0) {
389 			mod_uninstall_interval = 60;
390 			modreap();
391 			return (rval);
392 		}
393 #endif
394 		mod_uninstall_all();
395 	} else {
396 		rval = modunload(id);
397 	}
398 	return (rval);
399 }
400 
401 static int
402 modctl_modinfo(modid_t id, struct modinfo *umodi)
403 {
404 	int retval;
405 	struct modinfo modi;
406 #if defined(_SYSCALL32_IMPL)
407 	int nobase;
408 	struct modinfo32 modi32;
409 #endif
410 
411 	if (get_udatamodel() == DATAMODEL_NATIVE) {
412 		if (copyin(umodi, &modi, sizeof (struct modinfo)) != 0)
413 			return (EFAULT);
414 	}
415 #ifdef _SYSCALL32_IMPL
416 	else {
417 		bzero(&modi, sizeof (modi));
418 		if (copyin(umodi, &modi32, sizeof (struct modinfo32)) != 0)
419 			return (EFAULT);
420 		modi.mi_info = modi32.mi_info;
421 		modi.mi_id = modi32.mi_id;
422 		modi.mi_nextid = modi32.mi_nextid;
423 		nobase = modi.mi_info & MI_INFO_NOBASE;
424 	}
425 #endif
426 	/*
427 	 * This flag is -only- for the kernels use.
428 	 */
429 	modi.mi_info &= ~MI_INFO_LINKAGE;
430 
431 	retval = modinfo(id, &modi);
432 	if (retval)
433 		return (retval);
434 
435 	if (get_udatamodel() == DATAMODEL_NATIVE) {
436 		if (copyout(&modi, umodi, sizeof (struct modinfo)) != 0)
437 			retval = EFAULT;
438 #ifdef _SYSCALL32_IMPL
439 	} else {
440 		int i;
441 
442 		if (!nobase && (uintptr_t)modi.mi_base > UINT32_MAX)
443 			return (EOVERFLOW);
444 
445 		modi32.mi_info = modi.mi_info;
446 		modi32.mi_state = modi.mi_state;
447 		modi32.mi_id = modi.mi_id;
448 		modi32.mi_nextid = modi.mi_nextid;
449 		modi32.mi_base = (caddr32_t)(uintptr_t)modi.mi_base;
450 		modi32.mi_size = modi.mi_size;
451 		modi32.mi_rev = modi.mi_rev;
452 		modi32.mi_loadcnt = modi.mi_loadcnt;
453 		bcopy(modi.mi_name, modi32.mi_name, sizeof (modi32.mi_name));
454 		for (i = 0; i < MODMAXLINK32; i++) {
455 			modi32.mi_msinfo[i].msi_p0 = modi.mi_msinfo[i].msi_p0;
456 			bcopy(modi.mi_msinfo[i].msi_linkinfo,
457 			    modi32.mi_msinfo[i].msi_linkinfo,
458 			    sizeof (modi32.mi_msinfo[0].msi_linkinfo));
459 		}
460 		if (copyout(&modi32, umodi, sizeof (struct modinfo32)) != 0)
461 			retval = EFAULT;
462 #endif
463 	}
464 
465 	return (retval);
466 }
467 
468 /*
469  * Return the last major number in the range of permissible major numbers.
470  */
471 /*ARGSUSED*/
472 static int
473 modctl_modreserve(modid_t id, int *data)
474 {
475 	if (copyout(&devcnt, data, sizeof (devcnt)) != 0)
476 		return (EFAULT);
477 	return (0);
478 }
479 
480 /* Add/Remove driver and binding aliases */
481 static int
482 modctl_update_driver_aliases(int add, int *data)
483 {
484 	struct modconfig	mc;
485 	int			i, n, rv = 0;
486 	struct aliases		alias;
487 	struct aliases		*ap;
488 	char			name[MAXMODCONFNAME];
489 	char			cname[MAXMODCONFNAME];
490 	char			*drvname;
491 	int			resid;
492 	struct alias_info {
493 		char	*alias_name;
494 		int	alias_resid;
495 	} *aliases, *aip;
496 
497 	bzero(&mc, sizeof (struct modconfig));
498 	if (get_udatamodel() == DATAMODEL_NATIVE) {
499 		if (copyin(data, &mc, sizeof (struct modconfig)) != 0)
500 			return (EFAULT);
501 	}
502 #ifdef _SYSCALL32_IMPL
503 	else {
504 		struct modconfig32 modc32;
505 		if (copyin(data, &modc32, sizeof (struct modconfig32)) != 0)
506 			return (EFAULT);
507 		else {
508 			bcopy(modc32.drvname, mc.drvname,
509 			    sizeof (modc32.drvname));
510 			bcopy(modc32.drvclass, mc.drvclass,
511 			    sizeof (modc32.drvclass));
512 			mc.major = modc32.major;
513 			mc.flags = modc32.flags;
514 			mc.num_aliases = modc32.num_aliases;
515 			mc.ap = (struct aliases *)(uintptr_t)modc32.ap;
516 		}
517 	}
518 #endif
519 
520 	/*
521 	 * If the driver is already in the mb_hashtab, and the name given
522 	 * doesn't match that driver's name, fail.  Otherwise, pass, since
523 	 * we may be adding aliases.
524 	 */
525 	drvname = mod_major_to_name(mc.major);
526 	if ((drvname != NULL) && strcmp(drvname, mc.drvname) != 0)
527 		return (EINVAL);
528 
529 	/*
530 	 * Precede alias removal by unbinding as many devices as possible.
531 	 */
532 	if (add == 0) {
533 		(void) i_ddi_unload_drvconf(mc.major);
534 		i_ddi_unbind_devs(mc.major);
535 	}
536 
537 	/*
538 	 * Add/remove each supplied driver alias to/from mb_hashtab
539 	 */
540 	ap = mc.ap;
541 	if (mc.num_aliases > 0)
542 		aliases = kmem_zalloc(
543 		    mc.num_aliases * sizeof (struct alias_info), KM_SLEEP);
544 	aip = aliases;
545 	for (i = 0; i < mc.num_aliases; i++) {
546 		bzero(&alias, sizeof (struct aliases));
547 		if (get_udatamodel() == DATAMODEL_NATIVE) {
548 			if (copyin(ap, &alias, sizeof (struct aliases)) != 0) {
549 				rv = EFAULT;
550 				goto error;
551 			}
552 			if (alias.a_len > MAXMODCONFNAME) {
553 				rv = EINVAL;
554 				goto error;
555 			}
556 			if (copyin(alias.a_name, name, alias.a_len) != 0) {
557 				rv = EFAULT;
558 				goto error;
559 			}
560 			if (name[alias.a_len - 1] != '\0') {
561 				rv = EINVAL;
562 				goto error;
563 			}
564 		}
565 #ifdef _SYSCALL32_IMPL
566 		else {
567 			struct aliases32 al32;
568 			bzero(&al32, sizeof (struct aliases32));
569 			if (copyin(ap, &al32, sizeof (struct aliases32)) != 0) {
570 				rv = EFAULT;
571 				goto error;
572 			}
573 			if (al32.a_len > MAXMODCONFNAME) {
574 				rv = EINVAL;
575 				goto error;
576 			}
577 			if (copyin((void *)(uintptr_t)al32.a_name,
578 			    name, al32.a_len) != 0) {
579 				rv = EFAULT;
580 				goto error;
581 			}
582 			if (name[al32.a_len - 1] != '\0') {
583 				rv = EINVAL;
584 				goto error;
585 			}
586 			alias.a_next = (void *)(uintptr_t)al32.a_next;
587 		}
588 #endif
589 		check_esc_sequences(name, cname);
590 		aip->alias_name = strdup(cname);
591 		ap = alias.a_next;
592 		aip++;
593 	}
594 
595 	if (add == 0) {
596 		ap = mc.ap;
597 		resid = 0;
598 		aip = aliases;
599 		/* attempt to unbind all devices bound to each alias */
600 		for (i = 0; i < mc.num_aliases; i++) {
601 			n = i_ddi_unbind_devs_by_alias(
602 			    mc.major, aip->alias_name);
603 			resid += n;
604 			aip->alias_resid = n;
605 		}
606 
607 		/*
608 		 * If some device bound to an alias remains in use,
609 		 * and override wasn't specified, no change is made to
610 		 * the binding state and we fail the operation.
611 		 */
612 		if (resid > 0 && ((mc.flags & MOD_UNBIND_OVERRIDE) == 0)) {
613 			rv = EBUSY;
614 			goto error;
615 		}
616 
617 		/*
618 		 * No device remains bound of any of the aliases,
619 		 * or force was requested.  Mark each alias as
620 		 * inactive via delete_mbind so no future binds
621 		 * to this alias take place and that a new
622 		 * binding can be established.
623 		 */
624 		aip = aliases;
625 		for (i = 0; i < mc.num_aliases; i++) {
626 			if (moddebug & MODDEBUG_BINDING)
627 				cmn_err(CE_CONT, "Removing binding for %s "
628 				    "(%d active references)\n",
629 				    aip->alias_name, aip->alias_resid);
630 			delete_mbind(aip->alias_name, mb_hashtab);
631 			aip++;
632 		}
633 		rv = 0;
634 	} else {
635 		aip = aliases;
636 		for (i = 0; i < mc.num_aliases; i++) {
637 			if (moddebug & MODDEBUG_BINDING)
638 				cmn_err(CE_NOTE, "Adding binding for '%s'\n",
639 				    aip->alias_name);
640 			(void) make_mbind(aip->alias_name,
641 			    mc.major, NULL, mb_hashtab);
642 			aip++;
643 		}
644 		/*
645 		 * Try to establish an mbinding for mc.drvname, and add it to
646 		 * devnames. Add class if any after establishing the major
647 		 * number.
648 		 */
649 		(void) make_mbind(mc.drvname, mc.major, NULL, mb_hashtab);
650 		if ((rv = make_devname(mc.drvname, mc.major,
651 		    (mc.flags & MOD_ADDMAJBIND_UPDATE) ?
652 		    DN_DRIVER_INACTIVE : 0)) != 0) {
653 			goto error;
654 		}
655 
656 		if (mc.drvclass[0] != '\0')
657 			add_class(mc.drvname, mc.drvclass);
658 		if ((mc.flags & MOD_ADDMAJBIND_UPDATE) == 0) {
659 			(void) i_ddi_load_drvconf(mc.major);
660 		}
661 	}
662 
663 	/*
664 	 * Ensure that all nodes are bound to the most appropriate driver
665 	 * possible, attempting demotion and rebind when a more appropriate
666 	 * driver now exists.  But not when adding a driver update-only.
667 	 */
668 	if ((add == 0) || ((mc.flags & MOD_ADDMAJBIND_UPDATE) == 0)) {
669 		i_ddi_bind_devs();
670 		i_ddi_di_cache_invalidate();
671 	}
672 
673 error:
674 	if (mc.num_aliases > 0) {
675 		aip = aliases;
676 		for (i = 0; i < mc.num_aliases; i++) {
677 			if (aip->alias_name != NULL)
678 				strfree(aip->alias_name);
679 			aip++;
680 		}
681 		kmem_free(aliases, mc.num_aliases * sizeof (struct alias_info));
682 	}
683 	return (rv);
684 }
685 
686 static int
687 modctl_add_driver_aliases(int *data)
688 {
689 	return (modctl_update_driver_aliases(1, data));
690 }
691 
692 static int
693 modctl_remove_driver_aliases(int *data)
694 {
695 	return (modctl_update_driver_aliases(0, data));
696 }
697 
698 static int
699 modctl_rem_major(major_t major)
700 {
701 	struct devnames *dnp;
702 
703 	if (major >= devcnt)
704 		return (EINVAL);
705 
706 	/* mark devnames as removed */
707 	dnp = &devnamesp[major];
708 	LOCK_DEV_OPS(&dnp->dn_lock);
709 	if (dnp->dn_name == NULL ||
710 	    (dnp->dn_flags & (DN_DRIVER_REMOVED | DN_TAKEN_GETUDEV))) {
711 		UNLOCK_DEV_OPS(&dnp->dn_lock);
712 		return (EINVAL);
713 	}
714 	dnp->dn_flags |= DN_DRIVER_REMOVED;
715 	pm_driver_removed(major);
716 	UNLOCK_DEV_OPS(&dnp->dn_lock);
717 
718 	(void) i_ddi_unload_drvconf(major);
719 	i_ddi_unbind_devs(major);
720 	i_ddi_bind_devs();
721 	i_ddi_di_cache_invalidate();
722 
723 	/* purge all the bindings to this driver */
724 	purge_mbind(major, mb_hashtab);
725 	return (0);
726 }
727 
728 static struct vfs *
729 path_to_vfs(char *name)
730 {
731 	vnode_t *vp;
732 	struct vfs *vfsp;
733 
734 	if (lookupname(name, UIO_SYSSPACE, FOLLOW, NULLVPP, &vp))
735 		return (NULL);
736 
737 	vfsp = vp->v_vfsp;
738 	VN_RELE(vp);
739 	return (vfsp);
740 }
741 
742 static int
743 new_vfs_in_modpath()
744 {
745 	static int n_modpath = 0;
746 	static char *modpath_copy;
747 	static struct pathvfs {
748 		char *path;
749 		struct vfs *vfsp;
750 	} *pathvfs;
751 
752 	int i, new_vfs = 0;
753 	char *tmp, *tmp1;
754 	struct vfs *vfsp;
755 
756 	if (n_modpath != 0) {
757 		for (i = 0; i < n_modpath; i++) {
758 			vfsp = path_to_vfs(pathvfs[i].path);
759 			if (vfsp != pathvfs[i].vfsp) {
760 				pathvfs[i].vfsp = vfsp;
761 				if (vfsp)
762 					new_vfs = 1;
763 			}
764 		}
765 		return (new_vfs);
766 	}
767 
768 	/*
769 	 * First call, initialize the pathvfs structure
770 	 */
771 	modpath_copy = i_ddi_strdup(default_path, KM_SLEEP);
772 	tmp = modpath_copy;
773 	n_modpath = 1;
774 	tmp1 = strchr(tmp, ' ');
775 	while (tmp1) {
776 		*tmp1 = '\0';
777 		n_modpath++;
778 		tmp = tmp1 + 1;
779 		tmp1 = strchr(tmp, ' ');
780 	}
781 
782 	pathvfs = kmem_zalloc(n_modpath * sizeof (struct pathvfs), KM_SLEEP);
783 	tmp = modpath_copy;
784 	for (i = 0; i < n_modpath; i++) {
785 		pathvfs[i].path = tmp;
786 		vfsp = path_to_vfs(tmp);
787 		pathvfs[i].vfsp = vfsp;
788 		tmp += strlen(tmp) + 1;
789 	}
790 	return (1);	/* always reread driver.conf the first time */
791 }
792 
793 static int
794 modctl_load_drvconf(major_t major, int flags)
795 {
796 	int ret;
797 
798 	/*
799 	 * devfsadm -u - read all new driver.conf files
800 	 * and bind and configure devices for new drivers.
801 	 */
802 	if (flags & MOD_LOADDRVCONF_RECONF) {
803 		(void) i_ddi_load_drvconf(DDI_MAJOR_T_NONE);
804 		i_ddi_bind_devs();
805 		i_ddi_di_cache_invalidate();
806 		return (0);
807 	}
808 
809 	/*
810 	 * update_drv <drv> - reload driver.conf for the specified driver
811 	 */
812 	if (major != DDI_MAJOR_T_NONE) {
813 		ret = i_ddi_load_drvconf(major);
814 		if (ret == 0)
815 			i_ddi_bind_devs();
816 		return (ret);
817 	}
818 
819 	/*
820 	 * We are invoked to rescan new driver.conf files. It is
821 	 * only necessary if a new file system was mounted in the
822 	 * module_path. Because rescanning driver.conf files can
823 	 * take some time on older platforms (sun4m), the following
824 	 * code skips unnecessary driver.conf rescans to optimize
825 	 * boot performance.
826 	 */
827 	if (new_vfs_in_modpath()) {
828 		(void) i_ddi_load_drvconf(DDI_MAJOR_T_NONE);
829 		/*
830 		 * If we are still initializing io subsystem,
831 		 * load drivers with ddi-forceattach property
832 		 */
833 		if (!i_ddi_io_initialized())
834 			i_ddi_forceattach_drivers();
835 	}
836 	return (0);
837 }
838 
839 /*
840  * Unload driver.conf file and follow up by attempting
841  * to rebind devices to more appropriate driver.
842  */
843 static int
844 modctl_unload_drvconf(major_t major)
845 {
846 	int ret;
847 
848 	if (major >= devcnt)
849 		return (EINVAL);
850 
851 	ret = i_ddi_unload_drvconf(major);
852 	if (ret != 0)
853 		return (ret);
854 	(void) i_ddi_unbind_devs(major);
855 	i_ddi_bind_devs();
856 
857 	return (0);
858 }
859 
860 static void
861 check_esc_sequences(char *str, char *cstr)
862 {
863 	int i;
864 	size_t len;
865 	char *p;
866 
867 	len = strlen(str);
868 	for (i = 0; i < len; i++, str++, cstr++) {
869 		if (*str != '\\') {
870 			*cstr = *str;
871 		} else {
872 			p = str + 1;
873 			/*
874 			 * we only handle octal escape sequences for SPACE
875 			 */
876 			if (*p++ == '0' && *p++ == '4' && *p == '0') {
877 				*cstr = ' ';
878 				str += 3;
879 			} else {
880 				*cstr = *str;
881 			}
882 		}
883 	}
884 	*cstr = 0;
885 }
886 
887 static int
888 modctl_getmodpathlen(int *data)
889 {
890 	int len;
891 	len = strlen(default_path);
892 	if (copyout(&len, data, sizeof (len)) != 0)
893 		return (EFAULT);
894 	return (0);
895 }
896 
897 static int
898 modctl_getmodpath(char *data)
899 {
900 	if (copyout(default_path, data, strlen(default_path) + 1) != 0)
901 		return (EFAULT);
902 	return (0);
903 }
904 
905 static int
906 modctl_read_sysbinding_file(void)
907 {
908 	(void) read_binding_file(sysbind, sb_hashtab, make_mbind);
909 	return (0);
910 }
911 
912 static int
913 modctl_getmaj(char *uname, uint_t ulen, int *umajorp)
914 {
915 	char name[256];
916 	int retval;
917 	major_t major;
918 
919 	if (ulen == 0)
920 		return (EINVAL);
921 	if ((retval = copyinstr(uname, name,
922 	    (ulen < 256) ? ulen : 256, 0)) != 0)
923 		return (retval);
924 	if ((major = mod_name_to_major(name)) == DDI_MAJOR_T_NONE)
925 		return (ENODEV);
926 	if (copyout(&major, umajorp, sizeof (major_t)) != 0)
927 		return (EFAULT);
928 	return (0);
929 }
930 
931 static char **
932 convert_constraint_string(char *constraints, size_t len)
933 {
934 	int	i;
935 	int	n;
936 	char	*p;
937 	char	**array;
938 
939 	ASSERT(constraints != NULL);
940 	ASSERT(len > 0);
941 
942 	for (i = 0, p = constraints; strlen(p) > 0; i++, p += strlen(p) + 1)
943 		;
944 
945 	n = i;
946 
947 	if (n == 0) {
948 		kmem_free(constraints, len);
949 		return (NULL);
950 	}
951 
952 	array = kmem_alloc((n + 1) * sizeof (char *), KM_SLEEP);
953 
954 	for (i = 0, p = constraints; i < n; i++, p += strlen(p) + 1) {
955 		array[i] = i_ddi_strdup(p, KM_SLEEP);
956 	}
957 	array[n] = NULL;
958 
959 	kmem_free(constraints, len);
960 
961 	return (array);
962 }
963 /*ARGSUSED*/
964 static int
965 modctl_retire(char *path, char *uconstraints, size_t ulen)
966 {
967 	char	*pathbuf;
968 	char	*devpath;
969 	size_t	pathsz;
970 	int	retval;
971 	char	*constraints;
972 	char	**cons_array;
973 
974 	if (path == NULL)
975 		return (EINVAL);
976 
977 	if ((uconstraints == NULL) ^ (ulen == 0))
978 		return (EINVAL);
979 
980 	pathbuf = kmem_alloc(MAXPATHLEN, KM_SLEEP);
981 	retval = copyinstr(path, pathbuf, MAXPATHLEN, &pathsz);
982 	if (retval != 0) {
983 		kmem_free(pathbuf, MAXPATHLEN);
984 		return (retval);
985 	}
986 	devpath = i_ddi_strdup(pathbuf, KM_SLEEP);
987 	kmem_free(pathbuf, MAXPATHLEN);
988 
989 	/*
990 	 * First check if the device is already retired.
991 	 * If it is, this becomes a NOP
992 	 */
993 	if (e_ddi_device_retired(devpath)) {
994 		cmn_err(CE_NOTE, "Device: already retired: %s", devpath);
995 		kmem_free(devpath, strlen(devpath) + 1);
996 		return (0);
997 	}
998 
999 	cons_array = NULL;
1000 	if (uconstraints) {
1001 		constraints = kmem_alloc(ulen, KM_SLEEP);
1002 		if (copyin(uconstraints, constraints, ulen)) {
1003 			kmem_free(constraints, ulen);
1004 			kmem_free(devpath, strlen(devpath) + 1);
1005 			return (EFAULT);
1006 		}
1007 		cons_array = convert_constraint_string(constraints, ulen);
1008 	}
1009 
1010 	/*
1011 	 * Try to retire the device first. The following
1012 	 * routine will return an error only if the device
1013 	 * is not retireable i.e. retire constraints forbid
1014 	 * a retire. A return of success from this routine
1015 	 * indicates that device is retireable.
1016 	 */
1017 	retval = e_ddi_retire_device(devpath, cons_array);
1018 	if (retval != DDI_SUCCESS) {
1019 		cmn_err(CE_WARN, "constraints forbid retire: %s", devpath);
1020 		kmem_free(devpath, strlen(devpath) + 1);
1021 		return (ENOTSUP);
1022 	}
1023 
1024 	/*
1025 	 * Ok, the retire succeeded. Persist the retire.
1026 	 * If retiring a nexus, we need to only persist the
1027 	 * nexus retire. Any children of a retired nexus
1028 	 * are automatically covered by the retire store
1029 	 * code.
1030 	 */
1031 	retval = e_ddi_retire_persist(devpath);
1032 	if (retval != 0) {
1033 		cmn_err(CE_WARN, "Failed to persist device retire: error %d: "
1034 		    "%s", retval, devpath);
1035 		kmem_free(devpath, strlen(devpath) + 1);
1036 		return (retval);
1037 	}
1038 	if (moddebug & MODDEBUG_RETIRE)
1039 		cmn_err(CE_NOTE, "Persisted retire of device: %s", devpath);
1040 
1041 	kmem_free(devpath, strlen(devpath) + 1);
1042 	return (0);
1043 }
1044 
1045 static int
1046 modctl_is_retired(char *path, int *statep)
1047 {
1048 	char	*pathbuf;
1049 	char	*devpath;
1050 	size_t	pathsz;
1051 	int	error;
1052 	int	status;
1053 
1054 	if (path == NULL || statep == NULL)
1055 		return (EINVAL);
1056 
1057 	pathbuf = kmem_alloc(MAXPATHLEN, KM_SLEEP);
1058 	error = copyinstr(path, pathbuf, MAXPATHLEN, &pathsz);
1059 	if (error != 0) {
1060 		kmem_free(pathbuf, MAXPATHLEN);
1061 		return (error);
1062 	}
1063 	devpath = i_ddi_strdup(pathbuf, KM_SLEEP);
1064 	kmem_free(pathbuf, MAXPATHLEN);
1065 
1066 	if (e_ddi_device_retired(devpath))
1067 		status = 1;
1068 	else
1069 		status = 0;
1070 	kmem_free(devpath, strlen(devpath) + 1);
1071 
1072 	return (copyout(&status, statep, sizeof (status)) ? EFAULT : 0);
1073 }
1074 
1075 static int
1076 modctl_unretire(char *path)
1077 {
1078 	char	*pathbuf;
1079 	char	*devpath;
1080 	size_t	pathsz;
1081 	int	retired;
1082 	int	retval;
1083 
1084 	if (path == NULL)
1085 		return (EINVAL);
1086 
1087 	pathbuf = kmem_alloc(MAXPATHLEN, KM_SLEEP);
1088 	retval = copyinstr(path, pathbuf, MAXPATHLEN, &pathsz);
1089 	if (retval != 0) {
1090 		kmem_free(pathbuf, MAXPATHLEN);
1091 		return (retval);
1092 	}
1093 	devpath = i_ddi_strdup(pathbuf, KM_SLEEP);
1094 	kmem_free(pathbuf, MAXPATHLEN);
1095 
1096 	/*
1097 	 * We check if a device is retired (first) before
1098 	 * unpersisting the retire, because we use the
1099 	 * retire store to determine if a device is retired.
1100 	 * If we unpersist first, the device will always appear
1101 	 * to be unretired. For the rationale behind unpersisting
1102 	 * a device that is not retired, see the next comment.
1103 	 */
1104 	retired = e_ddi_device_retired(devpath);
1105 
1106 	/*
1107 	 * We call unpersist unconditionally because the lookup
1108 	 * for retired devices (e_ddi_device_retired()), skips "bypassed"
1109 	 * devices. We still want to be able remove "bypassed" entries
1110 	 * from the persistent store, so we unpersist unconditionally
1111 	 * i.e. whether or not the entry is found on a lookup.
1112 	 *
1113 	 * e_ddi_retire_unpersist() returns 1 if it found and cleared
1114 	 * an entry from the retire store or 0 otherwise.
1115 	 */
1116 	if (e_ddi_retire_unpersist(devpath))
1117 		if (moddebug & MODDEBUG_RETIRE) {
1118 			cmn_err(CE_NOTE, "Unpersisted retire of device: %s",
1119 			    devpath);
1120 		}
1121 
1122 	/*
1123 	 * Check if the device is already unretired. If so,
1124 	 * the unretire becomes a NOP
1125 	 */
1126 	if (!retired) {
1127 		cmn_err(CE_NOTE, "Not retired: %s", devpath);
1128 		kmem_free(devpath, strlen(devpath) + 1);
1129 		return (0);
1130 	}
1131 
1132 	retval = e_ddi_unretire_device(devpath);
1133 	if (retval != 0) {
1134 		cmn_err(CE_WARN, "cannot unretire device: error %d, path %s\n",
1135 		    retval, devpath);
1136 	}
1137 
1138 	kmem_free(devpath, strlen(devpath) + 1);
1139 
1140 	return (retval);
1141 }
1142 
1143 static int
1144 modctl_getname(char *uname, uint_t ulen, int *umajorp)
1145 {
1146 	char *name;
1147 	major_t major;
1148 
1149 	if (copyin(umajorp, &major, sizeof (major)) != 0)
1150 		return (EFAULT);
1151 	if ((name = mod_major_to_name(major)) == NULL)
1152 		return (ENODEV);
1153 	if ((strlen(name) + 1) > ulen)
1154 		return (ENOSPC);
1155 	return (copyoutstr(name, uname, ulen, NULL));
1156 }
1157 
1158 static int
1159 modctl_devt2instance(dev_t dev, int *uinstancep)
1160 {
1161 	int	instance;
1162 
1163 	if ((instance = dev_to_instance(dev)) == -1)
1164 		return (EINVAL);
1165 
1166 	return (copyout(&instance, uinstancep, sizeof (int)));
1167 }
1168 
1169 /*
1170  * Return the sizeof of the device id.
1171  */
1172 static int
1173 modctl_sizeof_devid(dev_t dev, uint_t *len)
1174 {
1175 	uint_t		sz;
1176 	ddi_devid_t	devid;
1177 
1178 	/* get device id */
1179 	if (ddi_lyr_get_devid(dev, &devid) == DDI_FAILURE)
1180 		return (EINVAL);
1181 
1182 	sz = ddi_devid_sizeof(devid);
1183 	ddi_devid_free(devid);
1184 
1185 	/* copyout device id size */
1186 	if (copyout(&sz, len, sizeof (sz)) != 0)
1187 		return (EFAULT);
1188 
1189 	return (0);
1190 }
1191 
1192 /*
1193  * Return a copy of the device id.
1194  */
1195 static int
1196 modctl_get_devid(dev_t dev, uint_t len, ddi_devid_t udevid)
1197 {
1198 	uint_t		sz;
1199 	ddi_devid_t	devid;
1200 	int		err = 0;
1201 
1202 	/* get device id */
1203 	if (ddi_lyr_get_devid(dev, &devid) == DDI_FAILURE)
1204 		return (EINVAL);
1205 
1206 	sz = ddi_devid_sizeof(devid);
1207 
1208 	/* Error if device id is larger than space allocated */
1209 	if (sz > len) {
1210 		ddi_devid_free(devid);
1211 		return (ENOSPC);
1212 	}
1213 
1214 	/* copy out device id */
1215 	if (copyout(devid, udevid, sz) != 0)
1216 		err = EFAULT;
1217 	ddi_devid_free(devid);
1218 	return (err);
1219 }
1220 
1221 /*
1222  * return the /devices paths associated with the specified devid and
1223  * minor name.
1224  */
1225 /*ARGSUSED*/
1226 static int
1227 modctl_devid2paths(ddi_devid_t udevid, char *uminor_name, uint_t flag,
1228 	size_t *ulensp, char *upaths)
1229 {
1230 	ddi_devid_t	devid = NULL;
1231 	int		devid_len;
1232 	char		*minor_name = NULL;
1233 	dev_info_t	*dip = NULL;
1234 	int		circ;
1235 	struct ddi_minor_data	*dmdp;
1236 	char		*path = NULL;
1237 	int		ulens;
1238 	int		lens;
1239 	int		len;
1240 	dev_t		*devlist = NULL;
1241 	int		ndevs;
1242 	int		i;
1243 	int		ret = 0;
1244 
1245 	/*
1246 	 * If upaths is NULL then we are only computing the amount of space
1247 	 * needed to hold the paths and returning the value in *ulensp. If we
1248 	 * are copying out paths then we get the amount of space allocated by
1249 	 * the caller. If the actual space needed for paths is larger, or
1250 	 * things are changing out from under us, then we return EAGAIN.
1251 	 */
1252 	if (upaths) {
1253 		if (ulensp == NULL)
1254 			return (EINVAL);
1255 		if (copyin(ulensp, &ulens, sizeof (ulens)) != 0)
1256 			return (EFAULT);
1257 	}
1258 
1259 	/*
1260 	 * copyin enough of the devid to determine the length then
1261 	 * reallocate and copy in the entire devid.
1262 	 */
1263 	devid_len = ddi_devid_sizeof(NULL);
1264 	devid = kmem_alloc(devid_len, KM_SLEEP);
1265 	if (copyin(udevid, devid, devid_len)) {
1266 		ret = EFAULT;
1267 		goto out;
1268 	}
1269 	len = devid_len;
1270 	devid_len = ddi_devid_sizeof(devid);
1271 	kmem_free(devid, len);
1272 	devid = kmem_alloc(devid_len, KM_SLEEP);
1273 	if (copyin(udevid, devid, devid_len)) {
1274 		ret = EFAULT;
1275 		goto out;
1276 	}
1277 
1278 	/* copyin the minor name if specified. */
1279 	minor_name = uminor_name;
1280 	if ((minor_name != DEVID_MINOR_NAME_ALL) &&
1281 	    (minor_name != DEVID_MINOR_NAME_ALL_CHR) &&
1282 	    (minor_name != DEVID_MINOR_NAME_ALL_BLK)) {
1283 		minor_name = kmem_alloc(MAXPATHLEN, KM_SLEEP);
1284 		if (copyinstr(uminor_name, minor_name, MAXPATHLEN, 0)) {
1285 			ret = EFAULT;
1286 			goto out;
1287 		}
1288 	}
1289 
1290 	/*
1291 	 * Use existing function to resolve the devid into a devlist.
1292 	 *
1293 	 * NOTE: there is a loss of spectype information in the current
1294 	 * ddi_lyr_devid_to_devlist implementation. We work around this by not
1295 	 * passing down DEVID_MINOR_NAME_ALL here, but reproducing all minor
1296 	 * node forms in the loop processing the devlist below. It would be
1297 	 * best if at some point the use of this interface here was replaced
1298 	 * with a path oriented call.
1299 	 */
1300 	if (ddi_lyr_devid_to_devlist(devid,
1301 	    (minor_name == DEVID_MINOR_NAME_ALL) ?
1302 	    DEVID_MINOR_NAME_ALL_CHR : minor_name,
1303 	    &ndevs, &devlist) != DDI_SUCCESS) {
1304 		ret = EINVAL;
1305 		goto out;
1306 	}
1307 
1308 	/*
1309 	 * loop over the devlist, converting each devt to a path and doing
1310 	 * a copyout of the path and computation of the amount of space
1311 	 * needed to hold all the paths
1312 	 */
1313 	path = kmem_alloc(MAXPATHLEN, KM_SLEEP);
1314 	for (i = 0, lens = 0; i < ndevs; i++) {
1315 
1316 		/* find the dip associated with the dev_t */
1317 		if ((dip = e_ddi_hold_devi_by_dev(devlist[i], 0)) == NULL)
1318 			continue;
1319 
1320 		/* loop over all the minor nodes, skipping ones we don't want */
1321 		ndi_devi_enter(dip, &circ);
1322 		for (dmdp = DEVI(dip)->devi_minor; dmdp; dmdp = dmdp->next) {
1323 			if ((dmdp->ddm_dev != devlist[i]) ||
1324 			    (dmdp->type != DDM_MINOR))
1325 				continue;
1326 
1327 			if ((minor_name != DEVID_MINOR_NAME_ALL) &&
1328 			    (minor_name != DEVID_MINOR_NAME_ALL_CHR) &&
1329 			    (minor_name != DEVID_MINOR_NAME_ALL_BLK) &&
1330 			    strcmp(minor_name, dmdp->ddm_name))
1331 				continue;
1332 			else {
1333 				if ((minor_name == DEVID_MINOR_NAME_ALL_CHR) &&
1334 				    (dmdp->ddm_spec_type != S_IFCHR))
1335 					continue;
1336 				if ((minor_name == DEVID_MINOR_NAME_ALL_BLK) &&
1337 				    (dmdp->ddm_spec_type != S_IFBLK))
1338 					continue;
1339 			}
1340 
1341 			(void) ddi_pathname_minor(dmdp, path);
1342 			len = strlen(path) + 1;
1343 			*(path + len) = '\0';	/* set double termination */
1344 			lens += len;
1345 
1346 			/* copyout the path with double terminations */
1347 			if (upaths) {
1348 				if (lens > ulens) {
1349 					ret = EAGAIN;
1350 					goto out;
1351 				}
1352 				if (copyout(path, upaths, len + 1)) {
1353 					ret = EFAULT;
1354 					goto out;
1355 				}
1356 				upaths += len;
1357 			}
1358 		}
1359 		ndi_devi_exit(dip, circ);
1360 		ddi_release_devi(dip);
1361 		dip = NULL;
1362 	}
1363 	lens++;		/* add one for double termination */
1364 
1365 	/* copy out the amount of space needed to hold the paths */
1366 	if (ulensp && copyout(&lens, ulensp, sizeof (lens))) {
1367 		ret = EFAULT;
1368 		goto out;
1369 	}
1370 	ret = 0;
1371 
1372 out:	if (dip) {
1373 		ndi_devi_exit(dip, circ);
1374 		ddi_release_devi(dip);
1375 	}
1376 	if (path)
1377 		kmem_free(path, MAXPATHLEN);
1378 	if (devlist)
1379 		ddi_lyr_free_devlist(devlist, ndevs);
1380 	if (minor_name &&
1381 	    (minor_name != DEVID_MINOR_NAME_ALL) &&
1382 	    (minor_name != DEVID_MINOR_NAME_ALL_CHR) &&
1383 	    (minor_name != DEVID_MINOR_NAME_ALL_BLK))
1384 		kmem_free(minor_name, MAXPATHLEN);
1385 	if (devid)
1386 		kmem_free(devid, devid_len);
1387 	return (ret);
1388 }
1389 
1390 /*
1391  * Return the size of the minor name.
1392  */
1393 static int
1394 modctl_sizeof_minorname(dev_t dev, int spectype, uint_t *len)
1395 {
1396 	uint_t	sz;
1397 	char	*name;
1398 
1399 	/* get the minor name */
1400 	if (ddi_lyr_get_minor_name(dev, spectype, &name) == DDI_FAILURE)
1401 		return (EINVAL);
1402 
1403 	sz = strlen(name) + 1;
1404 	kmem_free(name, sz);
1405 
1406 	/* copy out the size of the minor name */
1407 	if (copyout(&sz, len, sizeof (sz)) != 0)
1408 		return (EFAULT);
1409 
1410 	return (0);
1411 }
1412 
1413 /*
1414  * Return the minor name.
1415  */
1416 static int
1417 modctl_get_minorname(dev_t dev, int spectype, uint_t len, char *uname)
1418 {
1419 	uint_t	sz;
1420 	char	*name;
1421 	int	err = 0;
1422 
1423 	/* get the minor name */
1424 	if (ddi_lyr_get_minor_name(dev, spectype, &name) == DDI_FAILURE)
1425 		return (EINVAL);
1426 
1427 	sz = strlen(name) + 1;
1428 
1429 	/* Error if the minor name is larger than the space allocated */
1430 	if (sz > len) {
1431 		kmem_free(name, sz);
1432 		return (ENOSPC);
1433 	}
1434 
1435 	/* copy out the minor name */
1436 	if (copyout(name, uname, sz) != 0)
1437 		err = EFAULT;
1438 	kmem_free(name, sz);
1439 	return (err);
1440 }
1441 
1442 /*
1443  * Return the size of the (dev_t,spectype) devfspath name.
1444  */
1445 static int
1446 modctl_devfspath_len(dev_t dev, int spectype, uint_t *len)
1447 {
1448 	uint_t	sz;
1449 	char	*name;
1450 
1451 	/* get the path name */
1452 	name = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
1453 	if (ddi_dev_pathname(dev, spectype, name) == DDI_FAILURE) {
1454 		kmem_free(name, MAXPATHLEN);
1455 		return (EINVAL);
1456 	}
1457 
1458 	sz = strlen(name) + 1;
1459 	kmem_free(name, MAXPATHLEN);
1460 
1461 	/* copy out the size of the path name */
1462 	if (copyout(&sz, len, sizeof (sz)) != 0)
1463 		return (EFAULT);
1464 
1465 	return (0);
1466 }
1467 
1468 /*
1469  * Return the (dev_t,spectype) devfspath name.
1470  */
1471 static int
1472 modctl_devfspath(dev_t dev, int spectype, uint_t len, char *uname)
1473 {
1474 	uint_t	sz;
1475 	char	*name;
1476 	int	err = 0;
1477 
1478 	/* get the path name */
1479 	name = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
1480 	if (ddi_dev_pathname(dev, spectype, name) == DDI_FAILURE) {
1481 		kmem_free(name, MAXPATHLEN);
1482 		return (EINVAL);
1483 	}
1484 
1485 	sz = strlen(name) + 1;
1486 
1487 	/* Error if the path name is larger than the space allocated */
1488 	if (sz > len) {
1489 		kmem_free(name, MAXPATHLEN);
1490 		return (ENOSPC);
1491 	}
1492 
1493 	/* copy out the path name */
1494 	if (copyout(name, uname, sz) != 0)
1495 		err = EFAULT;
1496 	kmem_free(name, MAXPATHLEN);
1497 	return (err);
1498 }
1499 
1500 /*
1501  * Return the size of the (major,instance) devfspath name.
1502  */
1503 static int
1504 modctl_devfspath_mi_len(major_t major, int instance, uint_t *len)
1505 {
1506 	uint_t	sz;
1507 	char	*name;
1508 
1509 	/* get the path name */
1510 	name = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
1511 	if (e_ddi_majorinstance_to_path(major, instance, name) != DDI_SUCCESS) {
1512 		kmem_free(name, MAXPATHLEN);
1513 		return (EINVAL);
1514 	}
1515 
1516 	sz = strlen(name) + 1;
1517 	kmem_free(name, MAXPATHLEN);
1518 
1519 	/* copy out the size of the path name */
1520 	if (copyout(&sz, len, sizeof (sz)) != 0)
1521 		return (EFAULT);
1522 
1523 	return (0);
1524 }
1525 
1526 /*
1527  * Return the (major_instance) devfspath name.
1528  * NOTE: e_ddi_majorinstance_to_path does not require the device to attach to
1529  * return a path - it uses the instance tree.
1530  */
1531 static int
1532 modctl_devfspath_mi(major_t major, int instance, uint_t len, char *uname)
1533 {
1534 	uint_t	sz;
1535 	char	*name;
1536 	int	err = 0;
1537 
1538 	/* get the path name */
1539 	name = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
1540 	if (e_ddi_majorinstance_to_path(major, instance, name) != DDI_SUCCESS) {
1541 		kmem_free(name, MAXPATHLEN);
1542 		return (EINVAL);
1543 	}
1544 
1545 	sz = strlen(name) + 1;
1546 
1547 	/* Error if the path name is larger than the space allocated */
1548 	if (sz > len) {
1549 		kmem_free(name, MAXPATHLEN);
1550 		return (ENOSPC);
1551 	}
1552 
1553 	/* copy out the path name */
1554 	if (copyout(name, uname, sz) != 0)
1555 		err = EFAULT;
1556 	kmem_free(name, MAXPATHLEN);
1557 	return (err);
1558 }
1559 
1560 static int
1561 modctl_get_fbname(char *path)
1562 {
1563 	extern dev_t fbdev;
1564 	char *pathname = NULL;
1565 	int rval = 0;
1566 
1567 	/* make sure fbdev is set before we plunge in */
1568 	if (fbdev == NODEV)
1569 		return (ENODEV);
1570 
1571 	pathname = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
1572 	if ((rval = ddi_dev_pathname(fbdev, S_IFCHR,
1573 	    pathname)) == DDI_SUCCESS) {
1574 		if (copyout(pathname, path, strlen(pathname)+1) != 0) {
1575 			rval = EFAULT;
1576 		}
1577 	}
1578 	kmem_free(pathname, MAXPATHLEN);
1579 	return (rval);
1580 }
1581 
1582 /*
1583  * modctl_reread_dacf()
1584  *	Reread the dacf rules database from the named binding file.
1585  *	If NULL is specified, pass along the NULL, it means 'use the default'.
1586  */
1587 static int
1588 modctl_reread_dacf(char *path)
1589 {
1590 	int rval = 0;
1591 	char *filename, *filenamep;
1592 
1593 	filename = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
1594 
1595 	if (path == NULL) {
1596 		filenamep = NULL;
1597 	} else {
1598 		if (copyinstr(path, filename, MAXPATHLEN, 0) != 0) {
1599 			rval = EFAULT;
1600 			goto out;
1601 		}
1602 		filenamep = filename;
1603 		filenamep[MAXPATHLEN - 1] = '\0';
1604 	}
1605 
1606 	rval = read_dacf_binding_file(filenamep);
1607 out:
1608 	kmem_free(filename, MAXPATHLEN);
1609 	return (rval);
1610 }
1611 
1612 /*ARGSUSED*/
1613 static int
1614 modctl_modevents(int subcmd, uintptr_t a2, uintptr_t a3, uintptr_t a4,
1615     uint_t flag)
1616 {
1617 	int error = 0;
1618 	char *filenamep;
1619 
1620 	switch (subcmd) {
1621 
1622 	case MODEVENTS_FLUSH:
1623 		/* flush all currently queued events */
1624 		log_sysevent_flushq(subcmd, flag);
1625 		break;
1626 
1627 	case MODEVENTS_SET_DOOR_UPCALL_FILENAME:
1628 		/*
1629 		 * bind door_upcall to filename
1630 		 * this should only be done once per invocation
1631 		 * of the event daemon.
1632 		 */
1633 
1634 		filenamep = kmem_zalloc(MOD_MAXPATH, KM_SLEEP);
1635 
1636 		if (copyinstr((char *)a2, filenamep, MOD_MAXPATH, 0)) {
1637 			error = EFAULT;
1638 		} else {
1639 			error = log_sysevent_filename(filenamep);
1640 		}
1641 		kmem_free(filenamep, MOD_MAXPATH);
1642 		break;
1643 
1644 	case MODEVENTS_GETDATA:
1645 		error = log_sysevent_copyout_data((sysevent_id_t *)a2,
1646 		    (size_t)a3, (caddr_t)a4);
1647 		break;
1648 
1649 	case MODEVENTS_FREEDATA:
1650 		error = log_sysevent_free_data((sysevent_id_t *)a2);
1651 		break;
1652 	case MODEVENTS_POST_EVENT:
1653 		error = log_usr_sysevent((sysevent_t *)a2, (uint32_t)a3,
1654 		    (sysevent_id_t *)a4);
1655 		break;
1656 	case MODEVENTS_REGISTER_EVENT:
1657 		error = log_sysevent_register((char *)a2, (char *)a3,
1658 		    (se_pubsub_t *)a4);
1659 		break;
1660 	default:
1661 		error = EINVAL;
1662 	}
1663 
1664 	return (error);
1665 }
1666 
1667 static void
1668 free_mperm(mperm_t *mp)
1669 {
1670 	int len;
1671 
1672 	if (mp->mp_minorname) {
1673 		len = strlen(mp->mp_minorname) + 1;
1674 		kmem_free(mp->mp_minorname, len);
1675 	}
1676 	kmem_free(mp, sizeof (mperm_t));
1677 }
1678 
1679 #define	MP_NO_DRV_ERR	\
1680 	"/etc/minor_perm: no driver for %s\n"
1681 
1682 #define	MP_EMPTY_MINOR	\
1683 	"/etc/minor_perm: empty minor name for driver %s\n"
1684 
1685 #define	MP_NO_MINOR	\
1686 	"/etc/minor_perm: no minor matching %s for driver %s\n"
1687 
1688 /*
1689  * Remove mperm entry with matching minorname
1690  */
1691 static void
1692 rem_minorperm(major_t major, char *drvname, mperm_t *mp, int is_clone)
1693 {
1694 	mperm_t **mp_head;
1695 	mperm_t *freemp = NULL;
1696 	struct devnames *dnp = &devnamesp[major];
1697 	mperm_t **wildmp;
1698 
1699 	ASSERT(mp->mp_minorname && strlen(mp->mp_minorname) > 0);
1700 
1701 	LOCK_DEV_OPS(&dnp->dn_lock);
1702 	if (strcmp(mp->mp_minorname, "*") == 0) {
1703 		wildmp = ((is_clone == 0) ?
1704 		    &dnp->dn_mperm_wild : &dnp->dn_mperm_clone);
1705 		if (*wildmp)
1706 			freemp = *wildmp;
1707 		*wildmp = NULL;
1708 	} else {
1709 		mp_head = &dnp->dn_mperm;
1710 		while (*mp_head) {
1711 			if (strcmp((*mp_head)->mp_minorname,
1712 			    mp->mp_minorname) != 0) {
1713 				mp_head = &(*mp_head)->mp_next;
1714 				continue;
1715 			}
1716 			/* remove the entry */
1717 			freemp = *mp_head;
1718 			*mp_head = freemp->mp_next;
1719 			break;
1720 		}
1721 	}
1722 	if (freemp) {
1723 		if (moddebug & MODDEBUG_MINORPERM) {
1724 			cmn_err(CE_CONT, "< %s %s 0%o %d %d\n",
1725 			    drvname, freemp->mp_minorname,
1726 			    freemp->mp_mode & 0777,
1727 			    freemp->mp_uid, freemp->mp_gid);
1728 		}
1729 		free_mperm(freemp);
1730 	} else {
1731 		if (moddebug & MODDEBUG_MINORPERM) {
1732 			cmn_err(CE_CONT, MP_NO_MINOR,
1733 			    drvname, mp->mp_minorname);
1734 		}
1735 	}
1736 
1737 	UNLOCK_DEV_OPS(&dnp->dn_lock);
1738 }
1739 
1740 /*
1741  * Add minor perm entry
1742  */
1743 static void
1744 add_minorperm(major_t major, char *drvname, mperm_t *mp, int is_clone)
1745 {
1746 	mperm_t **mp_head;
1747 	mperm_t *freemp = NULL;
1748 	struct devnames *dnp = &devnamesp[major];
1749 	mperm_t **wildmp;
1750 
1751 	ASSERT(mp->mp_minorname && strlen(mp->mp_minorname) > 0);
1752 
1753 	/*
1754 	 * Note that update_drv replace semantics require
1755 	 * replacing matching entries with the new permissions.
1756 	 */
1757 	LOCK_DEV_OPS(&dnp->dn_lock);
1758 	if (strcmp(mp->mp_minorname, "*") == 0) {
1759 		wildmp = ((is_clone == 0) ?
1760 		    &dnp->dn_mperm_wild : &dnp->dn_mperm_clone);
1761 		if (*wildmp)
1762 			freemp = *wildmp;
1763 		*wildmp = mp;
1764 	} else {
1765 		mperm_t *p, *v = NULL;
1766 		for (p = dnp->dn_mperm; p; v = p, p = p->mp_next) {
1767 			if (strcmp(p->mp_minorname, mp->mp_minorname) == 0) {
1768 				if (v == NULL)
1769 					dnp->dn_mperm = mp;
1770 				else
1771 					v->mp_next = mp;
1772 				mp->mp_next = p->mp_next;
1773 				freemp = p;
1774 				goto replaced;
1775 			}
1776 		}
1777 		if (p == NULL) {
1778 			mp_head = &dnp->dn_mperm;
1779 			if (*mp_head == NULL) {
1780 				*mp_head = mp;
1781 			} else {
1782 				mp->mp_next = *mp_head;
1783 				*mp_head = mp;
1784 			}
1785 		}
1786 	}
1787 replaced:
1788 	if (freemp) {
1789 		if (moddebug & MODDEBUG_MINORPERM) {
1790 			cmn_err(CE_CONT, "< %s %s 0%o %d %d\n",
1791 			    drvname, freemp->mp_minorname,
1792 			    freemp->mp_mode & 0777,
1793 			    freemp->mp_uid, freemp->mp_gid);
1794 		}
1795 		free_mperm(freemp);
1796 	}
1797 	if (moddebug & MODDEBUG_MINORPERM) {
1798 		cmn_err(CE_CONT, "> %s %s 0%o %d %d\n",
1799 		    drvname, mp->mp_minorname, mp->mp_mode & 0777,
1800 		    mp->mp_uid, mp->mp_gid);
1801 	}
1802 	UNLOCK_DEV_OPS(&dnp->dn_lock);
1803 }
1804 
1805 
1806 static int
1807 process_minorperm(int cmd, nvlist_t *nvl)
1808 {
1809 	char *minor;
1810 	major_t major;
1811 	mperm_t *mp;
1812 	nvpair_t *nvp;
1813 	char *name;
1814 	int is_clone;
1815 	major_t minmaj;
1816 
1817 	ASSERT(cmd == MODLOADMINORPERM ||
1818 	    cmd == MODADDMINORPERM || cmd == MODREMMINORPERM);
1819 
1820 	nvp = NULL;
1821 	while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
1822 		name = nvpair_name(nvp);
1823 
1824 		is_clone = 0;
1825 		(void) nvpair_value_string(nvp, &minor);
1826 		major = ddi_name_to_major(name);
1827 		if (major != DDI_MAJOR_T_NONE) {
1828 			mp = kmem_zalloc(sizeof (*mp), KM_SLEEP);
1829 			if (minor == NULL || strlen(minor) == 0) {
1830 				if (moddebug & MODDEBUG_MINORPERM) {
1831 					cmn_err(CE_CONT, MP_EMPTY_MINOR, name);
1832 				}
1833 				minor = "*";
1834 			}
1835 
1836 			/*
1837 			 * The minor name of a node using the clone
1838 			 * driver must be the driver name.  To avoid
1839 			 * multiple searches, we map entries in the form
1840 			 * clone:<driver> to <driver>:*.  This also allows us
1841 			 * to filter out some of the litter in /etc/minor_perm.
1842 			 * Minor perm alias entries where the name is not
1843 			 * the driver kept on the clone list itself.
1844 			 * This all seems very fragile as a driver could
1845 			 * be introduced with an existing alias name.
1846 			 */
1847 			if (strcmp(name, "clone") == 0) {
1848 				minmaj = ddi_name_to_major(minor);
1849 				if (minmaj != DDI_MAJOR_T_NONE) {
1850 					if (moddebug & MODDEBUG_MINORPERM) {
1851 						cmn_err(CE_CONT,
1852 						    "mapping %s:%s to %s:*\n",
1853 						    name, minor, minor);
1854 					}
1855 					major = minmaj;
1856 					name = minor;
1857 					minor = "*";
1858 					is_clone = 1;
1859 				}
1860 			}
1861 
1862 			if (mp) {
1863 				mp->mp_minorname =
1864 				    i_ddi_strdup(minor, KM_SLEEP);
1865 			}
1866 		} else {
1867 			mp = NULL;
1868 			if (moddebug & MODDEBUG_MINORPERM) {
1869 				cmn_err(CE_CONT, MP_NO_DRV_ERR, name);
1870 			}
1871 		}
1872 
1873 		/* mode */
1874 		nvp = nvlist_next_nvpair(nvl, nvp);
1875 		ASSERT(strcmp(nvpair_name(nvp), "mode") == 0);
1876 		if (mp)
1877 			(void) nvpair_value_int32(nvp, (int *)&mp->mp_mode);
1878 		/* uid */
1879 		nvp = nvlist_next_nvpair(nvl, nvp);
1880 		ASSERT(strcmp(nvpair_name(nvp), "uid") == 0);
1881 		if (mp)
1882 			(void) nvpair_value_uint32(nvp, &mp->mp_uid);
1883 		/* gid */
1884 		nvp = nvlist_next_nvpair(nvl, nvp);
1885 		ASSERT(strcmp(nvpair_name(nvp), "gid") == 0);
1886 		if (mp) {
1887 			(void) nvpair_value_uint32(nvp, &mp->mp_gid);
1888 
1889 			if (cmd == MODREMMINORPERM) {
1890 				rem_minorperm(major, name, mp, is_clone);
1891 				free_mperm(mp);
1892 			} else {
1893 				add_minorperm(major, name, mp, is_clone);
1894 			}
1895 		}
1896 	}
1897 
1898 	if (cmd == MODLOADMINORPERM)
1899 		minorperm_loaded = 1;
1900 
1901 	/*
1902 	 * Reset permissions of cached dv_nodes
1903 	 */
1904 	(void) devfs_reset_perm(DV_RESET_PERM);
1905 
1906 	return (0);
1907 }
1908 
1909 static int
1910 modctl_minorperm(int cmd, char *usrbuf, size_t buflen)
1911 {
1912 	int error;
1913 	nvlist_t *nvl;
1914 	char *buf = kmem_alloc(buflen, KM_SLEEP);
1915 
1916 	if ((error = ddi_copyin(usrbuf, buf, buflen, 0)) != 0) {
1917 		kmem_free(buf, buflen);
1918 		return (error);
1919 	}
1920 
1921 	error = nvlist_unpack(buf, buflen, &nvl, KM_SLEEP);
1922 	kmem_free(buf, buflen);
1923 	if (error)
1924 		return (error);
1925 
1926 	error = process_minorperm(cmd, nvl);
1927 	nvlist_free(nvl);
1928 	return (error);
1929 }
1930 
1931 struct walk_args {
1932 	char		*wa_drvname;
1933 	list_t		wa_pathlist;
1934 };
1935 
1936 struct path_elem {
1937 	char		*pe_dir;
1938 	char		*pe_nodename;
1939 	list_node_t	pe_node;
1940 	int		pe_dirlen;
1941 };
1942 
1943 /*ARGSUSED*/
1944 static int
1945 modctl_inst_walker(const char *path, in_node_t *np, in_drv_t *dp, void *arg)
1946 {
1947 	struct walk_args *wargs = (struct walk_args *)arg;
1948 	struct path_elem *pe;
1949 	char *nodename;
1950 
1951 	/*
1952 	 * Search may be restricted to a single driver in the case of rem_drv
1953 	 */
1954 	if (wargs->wa_drvname &&
1955 	    strcmp(dp->ind_driver_name, wargs->wa_drvname) != 0)
1956 		return (INST_WALK_CONTINUE);
1957 
1958 	pe = kmem_zalloc(sizeof (*pe), KM_SLEEP);
1959 	pe->pe_dir = i_ddi_strdup((char *)path, KM_SLEEP);
1960 	pe->pe_dirlen = strlen(pe->pe_dir) + 1;
1961 	ASSERT(strrchr(pe->pe_dir, '/') != NULL);
1962 	nodename = strrchr(pe->pe_dir, '/');
1963 	*nodename++ = 0;
1964 	pe->pe_nodename = nodename;
1965 	list_insert_tail(&wargs->wa_pathlist, pe);
1966 
1967 	return (INST_WALK_CONTINUE);
1968 }
1969 
1970 /*
1971  * /devices attribute nodes clean-up optionally performed
1972  * when removing a driver (rem_drv -C).
1973  *
1974  * Removing attribute nodes allows a machine to be reprovisioned
1975  * without the side-effect of inadvertently picking up stale
1976  * device node ownership or permissions.
1977  *
1978  * Preserving attributes (not performing cleanup) allows devices
1979  * attribute changes to be preserved across upgrades, as
1980  * upgrade rather heavy-handedly does a rem_drv/add_drv cycle.
1981  */
1982 static int
1983 modctl_remdrv_cleanup(const char *u_drvname)
1984 {
1985 	struct walk_args *wargs;
1986 	struct path_elem *pe;
1987 	char *drvname;
1988 	int err, rval = 0;
1989 
1990 	drvname = kmem_alloc(MAXMODCONFNAME, KM_SLEEP);
1991 	if ((err = copyinstr(u_drvname, drvname, MAXMODCONFNAME, 0))) {
1992 		kmem_free(drvname, MAXMODCONFNAME);
1993 		return (err);
1994 	}
1995 
1996 	/*
1997 	 * First go through the instance database.  For each
1998 	 * instance of a device bound to the driver being
1999 	 * removed, remove any underlying devfs attribute nodes.
2000 	 *
2001 	 * This is a two-step process.	First we go through
2002 	 * the instance data itself, constructing a list of
2003 	 * the nodes discovered.  The second step is then
2004 	 * to find and remove any devfs attribute nodes
2005 	 * for the instances discovered in the first step.
2006 	 * The two-step process avoids any difficulties
2007 	 * which could arise by holding the instance data
2008 	 * lock with simultaneous devfs operations.
2009 	 */
2010 	wargs = kmem_zalloc(sizeof (*wargs), KM_SLEEP);
2011 
2012 	wargs->wa_drvname = drvname;
2013 	list_create(&wargs->wa_pathlist,
2014 	    sizeof (struct path_elem), offsetof(struct path_elem, pe_node));
2015 
2016 	(void) e_ddi_walk_instances(modctl_inst_walker, (void *)wargs);
2017 
2018 	for (pe = list_head(&wargs->wa_pathlist); pe != NULL;
2019 	    pe = list_next(&wargs->wa_pathlist, pe)) {
2020 		err = devfs_remdrv_cleanup((const char *)pe->pe_dir,
2021 		    (const char *)pe->pe_nodename);
2022 		if (rval == 0)
2023 			rval = err;
2024 	}
2025 
2026 	while ((pe = list_head(&wargs->wa_pathlist)) != NULL) {
2027 		list_remove(&wargs->wa_pathlist, pe);
2028 		kmem_free(pe->pe_dir, pe->pe_dirlen);
2029 		kmem_free(pe, sizeof (*pe));
2030 	}
2031 	kmem_free(wargs, sizeof (*wargs));
2032 
2033 	/*
2034 	 * Pseudo nodes aren't recorded in the instance database
2035 	 * so any such nodes need to be handled separately.
2036 	 */
2037 	err = devfs_remdrv_cleanup("pseudo", (const char *)drvname);
2038 	if (rval == 0)
2039 		rval = err;
2040 
2041 	kmem_free(drvname, MAXMODCONFNAME);
2042 	return (rval);
2043 }
2044 
2045 /*
2046  * Perform a cleanup of non-existent /devices attribute nodes,
2047  * similar to rem_drv -C, but for all drivers/devices.
2048  * This is also optional, performed as part of devfsadm -C.
2049  */
2050 void
2051 dev_devices_cleanup()
2052 {
2053 	struct walk_args *wargs;
2054 	struct path_elem *pe;
2055 	dev_info_t *devi;
2056 	char *path;
2057 	int err;
2058 
2059 	/*
2060 	 * It's expected that all drivers have been loaded and
2061 	 * module unloading disabled while performing cleanup.
2062 	 */
2063 	ASSERT(modunload_disable_count > 0);
2064 
2065 	wargs = kmem_zalloc(sizeof (*wargs), KM_SLEEP);
2066 	wargs->wa_drvname = NULL;
2067 	list_create(&wargs->wa_pathlist,
2068 	    sizeof (struct path_elem), offsetof(struct path_elem, pe_node));
2069 
2070 	(void) e_ddi_walk_instances(modctl_inst_walker, (void *)wargs);
2071 
2072 	path = kmem_alloc(MAXPATHLEN, KM_SLEEP);
2073 
2074 	for (pe = list_head(&wargs->wa_pathlist); pe != NULL;
2075 	    pe = list_next(&wargs->wa_pathlist, pe)) {
2076 		(void) snprintf(path, MAXPATHLEN, "%s/%s",
2077 		    pe->pe_dir, pe->pe_nodename);
2078 		devi = e_ddi_hold_devi_by_path(path, 0);
2079 		if (devi != NULL) {
2080 			ddi_release_devi(devi);
2081 		} else {
2082 			err = devfs_remdrv_cleanup((const char *)pe->pe_dir,
2083 			    (const char *)pe->pe_nodename);
2084 			if (err) {
2085 				cmn_err(CE_CONT,
2086 				    "devfs: %s: clean-up error %d\n",
2087 				    path, err);
2088 			}
2089 		}
2090 	}
2091 
2092 	while ((pe = list_head(&wargs->wa_pathlist)) != NULL) {
2093 		list_remove(&wargs->wa_pathlist, pe);
2094 		kmem_free(pe->pe_dir, pe->pe_dirlen);
2095 		kmem_free(pe, sizeof (*pe));
2096 	}
2097 	kmem_free(wargs, sizeof (*wargs));
2098 	kmem_free(path, MAXPATHLEN);
2099 }
2100 
2101 static int
2102 modctl_allocpriv(const char *name)
2103 {
2104 	char *pstr = kmem_alloc(PRIVNAME_MAX, KM_SLEEP);
2105 	int error;
2106 
2107 	if ((error = copyinstr(name, pstr, PRIVNAME_MAX, 0))) {
2108 		kmem_free(pstr, PRIVNAME_MAX);
2109 		return (error);
2110 	}
2111 	error = priv_getbyname(pstr, PRIV_ALLOC);
2112 	if (error < 0)
2113 		error = -error;
2114 	else
2115 		error = 0;
2116 	kmem_free(pstr, PRIVNAME_MAX);
2117 	return (error);
2118 }
2119 
2120 static int
2121 modctl_devexists(const char *upath, int pathlen)
2122 {
2123 	char	*path;
2124 	int	ret;
2125 
2126 	/*
2127 	 * copy in the path, including the terminating null
2128 	 */
2129 	pathlen++;
2130 	if (pathlen <= 1 || pathlen > MAXPATHLEN)
2131 		return (EINVAL);
2132 	path = kmem_zalloc(pathlen + 1, KM_SLEEP);
2133 	if ((ret = copyinstr(upath, path, pathlen, NULL)) == 0) {
2134 		ret = sdev_modctl_devexists(path);
2135 	}
2136 
2137 	kmem_free(path, pathlen + 1);
2138 	return (ret);
2139 }
2140 
2141 static int
2142 modctl_devreaddir(const char *udir, int udirlen,
2143     char *upaths, int64_t *ulensp)
2144 {
2145 	char	*paths = NULL;
2146 	char	**dirlist = NULL;
2147 	char	*dir;
2148 	int64_t	ulens;
2149 	int64_t	lens;
2150 	int	i, n;
2151 	int	ret = 0;
2152 	char	*p;
2153 	int	npaths;
2154 	int	npaths_alloc;
2155 
2156 	/*
2157 	 * If upaths is NULL then we are only computing the amount of space
2158 	 * needed to return the paths, with the value returned in *ulensp. If we
2159 	 * are copying out paths then we get the amount of space allocated by
2160 	 * the caller. If the actual space needed for paths is larger, or
2161 	 * things are changing out from under us, then we return EAGAIN.
2162 	 */
2163 	if (upaths) {
2164 		if (ulensp == NULL)
2165 			return (EINVAL);
2166 		if (copyin(ulensp, &ulens, sizeof (ulens)) != 0)
2167 			return (EFAULT);
2168 	}
2169 
2170 	/*
2171 	 * copyin the /dev path including terminating null
2172 	 */
2173 	udirlen++;
2174 	if (udirlen <= 1 || udirlen > MAXPATHLEN)
2175 		return (EINVAL);
2176 	dir = kmem_zalloc(udirlen + 1, KM_SLEEP);
2177 	if ((ret = copyinstr(udir, dir, udirlen, NULL)) != 0)
2178 		goto err;
2179 
2180 	if ((ret = sdev_modctl_readdir(dir, &dirlist,
2181 	    &npaths, &npaths_alloc, 0)) != 0) {
2182 		ASSERT(dirlist == NULL);
2183 		goto err;
2184 	}
2185 
2186 	lens = 0;
2187 	for (i = 0; i < npaths; i++) {
2188 		lens += strlen(dirlist[i]) + 1;
2189 	}
2190 	lens++;		/* add one for double termination */
2191 
2192 	if (upaths) {
2193 		if (lens > ulens) {
2194 			ret = EAGAIN;
2195 			goto out;
2196 		}
2197 
2198 		paths = kmem_alloc(lens, KM_SLEEP);
2199 
2200 		p = paths;
2201 		for (i = 0; i < npaths; i++) {
2202 			n = strlen(dirlist[i]) + 1;
2203 			bcopy(dirlist[i], p, n);
2204 			p += n;
2205 		}
2206 		*p = 0;
2207 
2208 		if (copyout(paths, upaths, lens)) {
2209 			ret = EFAULT;
2210 			goto err;
2211 		}
2212 	}
2213 
2214 out:
2215 	/* copy out the amount of space needed to hold the paths */
2216 	if (copyout(&lens, ulensp, sizeof (lens)))
2217 		ret = EFAULT;
2218 
2219 err:
2220 	if (dirlist)
2221 		sdev_modctl_readdir_free(dirlist, npaths, npaths_alloc);
2222 	if (paths)
2223 		kmem_free(paths, lens);
2224 	kmem_free(dir, udirlen + 1);
2225 	return (ret);
2226 }
2227 
2228 static int
2229 modctl_devemptydir(const char *udir, int udirlen, int *uempty)
2230 {
2231 	char	*dir;
2232 	int	ret;
2233 	char	**dirlist = NULL;
2234 	int	npaths;
2235 	int	npaths_alloc;
2236 	int	empty;
2237 
2238 	/*
2239 	 * copyin the /dev path including terminating null
2240 	 */
2241 	udirlen++;
2242 	if (udirlen <= 1 || udirlen > MAXPATHLEN)
2243 		return (EINVAL);
2244 	dir = kmem_zalloc(udirlen + 1, KM_SLEEP);
2245 	if ((ret = copyinstr(udir, dir, udirlen, NULL)) != 0)
2246 		goto err;
2247 
2248 	if ((ret = sdev_modctl_readdir(dir, &dirlist,
2249 	    &npaths, &npaths_alloc, 1)) != 0) {
2250 		goto err;
2251 	}
2252 
2253 	empty = npaths ? 0 : 1;
2254 	if (copyout(&empty, uempty, sizeof (empty)))
2255 		ret = EFAULT;
2256 
2257 err:
2258 	if (dirlist)
2259 		sdev_modctl_readdir_free(dirlist, npaths, npaths_alloc);
2260 	kmem_free(dir, udirlen + 1);
2261 	return (ret);
2262 }
2263 
2264 static int
2265 modctl_hp(int subcmd, const char *path, char *cn_name, uintptr_t arg,
2266     uintptr_t rval)
2267 {
2268 	int error = 0;
2269 	size_t pathsz, namesz;
2270 	char *devpath, *cn_name_str;
2271 
2272 	if (path == NULL)
2273 		return (EINVAL);
2274 
2275 	devpath = kmem_zalloc(MAXPATHLEN, KM_SLEEP);
2276 	error = copyinstr(path, devpath, MAXPATHLEN, &pathsz);
2277 	if (error != 0) {
2278 		kmem_free(devpath, MAXPATHLEN);
2279 		return (EFAULT);
2280 	}
2281 
2282 	cn_name_str = kmem_zalloc(MAXNAMELEN, KM_SLEEP);
2283 	error = copyinstr(cn_name, cn_name_str, MAXNAMELEN, &namesz);
2284 	if (error != 0) {
2285 		kmem_free(devpath, MAXPATHLEN);
2286 		kmem_free(cn_name_str, MAXNAMELEN);
2287 
2288 		return (EFAULT);
2289 	}
2290 
2291 	switch (subcmd) {
2292 	case MODHPOPS_CHANGE_STATE:
2293 		error = ddihp_modctl(DDI_HPOP_CN_CHANGE_STATE, devpath,
2294 		    cn_name_str, arg, NULL);
2295 		break;
2296 	case MODHPOPS_CREATE_PORT:
2297 		/* Create an empty PORT */
2298 		error = ddihp_modctl(DDI_HPOP_CN_CREATE_PORT, devpath,
2299 		    cn_name_str, NULL, NULL);
2300 		break;
2301 	case MODHPOPS_REMOVE_PORT:
2302 		/* Remove an empty PORT */
2303 		error = ddihp_modctl(DDI_HPOP_CN_REMOVE_PORT, devpath,
2304 		    cn_name_str, NULL, NULL);
2305 		break;
2306 	case MODHPOPS_BUS_GET:
2307 		error = ddihp_modctl(DDI_HPOP_CN_GET_PROPERTY, devpath,
2308 		    cn_name_str, arg, rval);
2309 		break;
2310 	case MODHPOPS_BUS_SET:
2311 		error = ddihp_modctl(DDI_HPOP_CN_SET_PROPERTY, devpath,
2312 		    cn_name_str, arg, rval);
2313 		break;
2314 	default:
2315 		error = ENOTSUP;
2316 		break;
2317 	}
2318 
2319 	kmem_free(devpath, MAXPATHLEN);
2320 	kmem_free(cn_name_str, MAXNAMELEN);
2321 
2322 	return (error);
2323 }
2324 
2325 int
2326 modctl_moddevname(int subcmd, uintptr_t a1, uintptr_t a2)
2327 {
2328 	int error = 0;
2329 
2330 	switch (subcmd) {
2331 	case MODDEVNAME_LOOKUPDOOR:
2332 		error = devname_filename_register((char *)a1);
2333 		break;
2334 	case MODDEVNAME_PROFILE:
2335 		error = devname_profile_update((char *)a1, (size_t)a2);
2336 		break;
2337 	case MODDEVNAME_RECONFIG:
2338 		i_ddi_set_reconfig();
2339 		break;
2340 	case MODDEVNAME_SYSAVAIL:
2341 		i_ddi_set_sysavail();
2342 		break;
2343 	default:
2344 		error = EINVAL;
2345 		break;
2346 	}
2347 
2348 	return (error);
2349 }
2350 
2351 /*ARGSUSED5*/
2352 int
2353 modctl(int cmd, uintptr_t a1, uintptr_t a2, uintptr_t a3, uintptr_t a4,
2354     uintptr_t a5)
2355 {
2356 	int	error = EINVAL;
2357 	dev_t	dev;
2358 
2359 	if (secpolicy_modctl(CRED(), cmd) != 0)
2360 		return (set_errno(EPERM));
2361 
2362 	switch (cmd) {
2363 	case MODLOAD:		/* load a module */
2364 		error = modctl_modload((int)a1, (char *)a2, (int *)a3);
2365 		break;
2366 
2367 	case MODUNLOAD:		/* unload a module */
2368 		error = modctl_modunload((modid_t)a1);
2369 		break;
2370 
2371 	case MODINFO:		/* get module status */
2372 		error = modctl_modinfo((modid_t)a1, (struct modinfo *)a2);
2373 		break;
2374 
2375 	case MODRESERVED:	/* get last major number in range */
2376 		error = modctl_modreserve((modid_t)a1, (int *)a2);
2377 		break;
2378 
2379 	case MODSETMINIROOT:	/* we are running in miniroot */
2380 		isminiroot = 1;
2381 		error = 0;
2382 		break;
2383 
2384 	case MODADDMAJBIND:	/* add major / driver alias bindings */
2385 		error = modctl_add_driver_aliases((int *)a2);
2386 		break;
2387 
2388 	case MODGETPATHLEN:	/* get modpath length */
2389 		error = modctl_getmodpathlen((int *)a2);
2390 		break;
2391 
2392 	case MODGETPATH:	/* get modpath */
2393 		error = modctl_getmodpath((char *)a2);
2394 		break;
2395 
2396 	case MODREADSYSBIND:	/* read system call binding file */
2397 		error = modctl_read_sysbinding_file();
2398 		break;
2399 
2400 	case MODGETMAJBIND:	/* get major number for named device */
2401 		error = modctl_getmaj((char *)a1, (uint_t)a2, (int *)a3);
2402 		break;
2403 
2404 	case MODGETNAME:	/* get name of device given major number */
2405 		error = modctl_getname((char *)a1, (uint_t)a2, (int *)a3);
2406 		break;
2407 
2408 	case MODDEVT2INSTANCE:
2409 		if (get_udatamodel() == DATAMODEL_NATIVE) {
2410 			dev = (dev_t)a1;
2411 		}
2412 #ifdef _SYSCALL32_IMPL
2413 		else {
2414 			dev = expldev(a1);
2415 		}
2416 #endif
2417 		error = modctl_devt2instance(dev, (int *)a2);
2418 		break;
2419 
2420 	case MODSIZEOF_DEVID:	/* sizeof device id of device given dev_t */
2421 		if (get_udatamodel() == DATAMODEL_NATIVE) {
2422 			dev = (dev_t)a1;
2423 		}
2424 #ifdef _SYSCALL32_IMPL
2425 		else {
2426 			dev = expldev(a1);
2427 		}
2428 #endif
2429 		error = modctl_sizeof_devid(dev, (uint_t *)a2);
2430 		break;
2431 
2432 	case MODGETDEVID:	/* get device id of device given dev_t */
2433 		if (get_udatamodel() == DATAMODEL_NATIVE) {
2434 			dev = (dev_t)a1;
2435 		}
2436 #ifdef _SYSCALL32_IMPL
2437 		else {
2438 			dev = expldev(a1);
2439 		}
2440 #endif
2441 		error = modctl_get_devid(dev, (uint_t)a2, (ddi_devid_t)a3);
2442 		break;
2443 
2444 	case MODSIZEOF_MINORNAME:	/* sizeof minor nm (dev_t,spectype) */
2445 		if (get_udatamodel() == DATAMODEL_NATIVE) {
2446 			error = modctl_sizeof_minorname((dev_t)a1, (int)a2,
2447 			    (uint_t *)a3);
2448 		}
2449 #ifdef _SYSCALL32_IMPL
2450 		else {
2451 			error = modctl_sizeof_minorname(expldev(a1), (int)a2,
2452 			    (uint_t *)a3);
2453 		}
2454 
2455 #endif
2456 		break;
2457 
2458 	case MODGETMINORNAME:		/* get minor name of (dev_t,spectype) */
2459 		if (get_udatamodel() == DATAMODEL_NATIVE) {
2460 			error = modctl_get_minorname((dev_t)a1, (int)a2,
2461 			    (uint_t)a3, (char *)a4);
2462 		}
2463 #ifdef _SYSCALL32_IMPL
2464 		else {
2465 			error = modctl_get_minorname(expldev(a1), (int)a2,
2466 			    (uint_t)a3, (char *)a4);
2467 		}
2468 #endif
2469 		break;
2470 
2471 	case MODGETDEVFSPATH_LEN:	/* sizeof path nm of (dev_t,spectype) */
2472 		if (get_udatamodel() == DATAMODEL_NATIVE) {
2473 			error = modctl_devfspath_len((dev_t)a1, (int)a2,
2474 			    (uint_t *)a3);
2475 		}
2476 #ifdef _SYSCALL32_IMPL
2477 		else {
2478 			error = modctl_devfspath_len(expldev(a1), (int)a2,
2479 			    (uint_t *)a3);
2480 		}
2481 
2482 #endif
2483 		break;
2484 
2485 	case MODGETDEVFSPATH:		/* get path name of (dev_t,spec) type */
2486 		if (get_udatamodel() == DATAMODEL_NATIVE) {
2487 			error = modctl_devfspath((dev_t)a1, (int)a2,
2488 			    (uint_t)a3, (char *)a4);
2489 		}
2490 #ifdef _SYSCALL32_IMPL
2491 		else {
2492 			error = modctl_devfspath(expldev(a1), (int)a2,
2493 			    (uint_t)a3, (char *)a4);
2494 		}
2495 #endif
2496 		break;
2497 
2498 	case MODGETDEVFSPATH_MI_LEN:	/* sizeof path nm of (major,instance) */
2499 		error = modctl_devfspath_mi_len((major_t)a1, (int)a2,
2500 		    (uint_t *)a3);
2501 		break;
2502 
2503 	case MODGETDEVFSPATH_MI:	/* get path name of (major,instance) */
2504 		error = modctl_devfspath_mi((major_t)a1, (int)a2,
2505 		    (uint_t)a3, (char *)a4);
2506 		break;
2507 
2508 
2509 	case MODEVENTS:
2510 		error = modctl_modevents((int)a1, a2, a3, a4, (uint_t)a5);
2511 		break;
2512 
2513 	case MODGETFBNAME:	/* get the framebuffer name */
2514 		error = modctl_get_fbname((char *)a1);
2515 		break;
2516 
2517 	case MODREREADDACF:	/* reread dacf rule database from given file */
2518 		error = modctl_reread_dacf((char *)a1);
2519 		break;
2520 
2521 	case MODLOADDRVCONF:	/* load driver.conf file for major */
2522 		error = modctl_load_drvconf((major_t)a1, (int)a2);
2523 		break;
2524 
2525 	case MODUNLOADDRVCONF:	/* unload driver.conf file for major */
2526 		error = modctl_unload_drvconf((major_t)a1);
2527 		break;
2528 
2529 	case MODREMMAJBIND:	/* remove a major binding */
2530 		error = modctl_rem_major((major_t)a1);
2531 		break;
2532 
2533 	case MODREMDRVALIAS:	/* remove a major/alias binding */
2534 		error = modctl_remove_driver_aliases((int *)a2);
2535 		break;
2536 
2537 	case MODDEVID2PATHS:	/* get paths given devid */
2538 		error = modctl_devid2paths((ddi_devid_t)a1, (char *)a2,
2539 		    (uint_t)a3, (size_t *)a4, (char *)a5);
2540 		break;
2541 
2542 	case MODSETDEVPOLICY:	/* establish device policy */
2543 		error = devpolicy_load((int)a1, (size_t)a2, (devplcysys_t *)a3);
2544 		break;
2545 
2546 	case MODGETDEVPOLICY:	/* get device policy */
2547 		error = devpolicy_get((int *)a1, (size_t)a2,
2548 		    (devplcysys_t *)a3);
2549 		break;
2550 
2551 	case MODALLOCPRIV:
2552 		error = modctl_allocpriv((const char *)a1);
2553 		break;
2554 
2555 	case MODGETDEVPOLICYBYNAME:
2556 		error = devpolicy_getbyname((size_t)a1,
2557 		    (devplcysys_t *)a2, (char *)a3);
2558 		break;
2559 
2560 	case MODLOADMINORPERM:
2561 	case MODADDMINORPERM:
2562 	case MODREMMINORPERM:
2563 		error = modctl_minorperm(cmd, (char *)a1, (size_t)a2);
2564 		break;
2565 
2566 	case MODREMDRVCLEANUP:
2567 		error = modctl_remdrv_cleanup((const char *)a1);
2568 		break;
2569 
2570 	case MODDEVEXISTS:	/* non-reconfiguring /dev lookup */
2571 		error = modctl_devexists((const char *)a1, (size_t)a2);
2572 		break;
2573 
2574 	case MODDEVREADDIR:	/* non-reconfiguring /dev readdir */
2575 		error = modctl_devreaddir((const char *)a1, (size_t)a2,
2576 		    (char *)a3, (int64_t *)a4);
2577 		break;
2578 
2579 	case MODDEVEMPTYDIR:	/* non-reconfiguring /dev emptydir */
2580 		error = modctl_devemptydir((const char *)a1, (size_t)a2,
2581 		    (int *)a3);
2582 		break;
2583 
2584 	case MODDEVNAME:
2585 		error = modctl_moddevname((int)a1, a2, a3);
2586 		break;
2587 
2588 	case MODRETIRE:	/* retire device named by physpath a1 */
2589 		error = modctl_retire((char *)a1, (char *)a2, (size_t)a3);
2590 		break;
2591 
2592 	case MODISRETIRED:  /* check if a device is retired. */
2593 		error = modctl_is_retired((char *)a1, (int *)a2);
2594 		break;
2595 
2596 	case MODUNRETIRE:	/* unretire device named by physpath a1 */
2597 		error = modctl_unretire((char *)a1);
2598 		break;
2599 
2600 	case MODHPOPS:	/* hotplug operations */
2601 		/* device named by physpath a2 and Connection name a3 */
2602 		error = modctl_hp((int)a1, (char *)a2, (char *)a3, a4, a5);
2603 		break;
2604 
2605 	default:
2606 		error = EINVAL;
2607 		break;
2608 	}
2609 
2610 	return (error ? set_errno(error) : 0);
2611 }
2612 
2613 /*
2614  * Calls to kobj_load_module()() are handled off to this routine in a
2615  * separate thread.
2616  */
2617 static void
2618 modload_thread(struct loadmt *ltp)
2619 {
2620 	/* load the module and signal the creator of this thread */
2621 	kmutex_t	cpr_lk;
2622 	callb_cpr_t	cpr_i;
2623 
2624 	mutex_init(&cpr_lk, NULL, MUTEX_DEFAULT, NULL);
2625 	CALLB_CPR_INIT(&cpr_i, &cpr_lk, callb_generic_cpr, "modload");
2626 	/* borrow the devi lock from thread which invoked us */
2627 	pm_borrow_lock(ltp->owner);
2628 	ltp->retval = kobj_load_module(ltp->mp, ltp->usepath);
2629 	pm_return_lock();
2630 	sema_v(&ltp->sema);
2631 	mutex_enter(&cpr_lk);
2632 	CALLB_CPR_EXIT(&cpr_i);
2633 	mutex_destroy(&cpr_lk);
2634 	thread_exit();
2635 }
2636 
2637 /*
2638  * load a module, adding a reference if caller specifies rmodp.  If rmodp
2639  * is specified then an errno is returned, otherwise a module index is
2640  * returned (-1 on error).
2641  */
2642 static int
2643 modrload(const char *subdir, const char *filename, struct modctl **rmodp)
2644 {
2645 	struct modctl *modp;
2646 	size_t size;
2647 	char *fullname;
2648 	int retval = EINVAL;
2649 	int id = -1;
2650 
2651 	if (rmodp)
2652 		*rmodp = NULL;			/* avoid garbage */
2653 
2654 	if (subdir != NULL) {
2655 		/*
2656 		 * refuse / in filename to prevent "../" escapes.
2657 		 */
2658 		if (strchr(filename, '/') != NULL)
2659 			return (rmodp ? retval : id);
2660 
2661 		/*
2662 		 * allocate enough space for <subdir>/<filename><NULL>
2663 		 */
2664 		size = strlen(subdir) + strlen(filename) + 2;
2665 		fullname = kmem_zalloc(size, KM_SLEEP);
2666 		(void) sprintf(fullname, "%s/%s", subdir, filename);
2667 	} else {
2668 		fullname = (char *)filename;
2669 	}
2670 
2671 	modp = mod_hold_installed_mod(fullname, 1, 0, &retval);
2672 	if (modp != NULL) {
2673 		id = modp->mod_id;
2674 		if (rmodp) {
2675 			/* add mod_ref and return *rmodp */
2676 			mutex_enter(&mod_lock);
2677 			modp->mod_ref++;
2678 			mutex_exit(&mod_lock);
2679 			*rmodp = modp;
2680 		}
2681 		mod_release_mod(modp);
2682 		CPU_STATS_ADDQ(CPU, sys, modload, 1);
2683 	}
2684 
2685 done:	if (subdir != NULL)
2686 		kmem_free(fullname, size);
2687 	return (rmodp ? retval : id);
2688 }
2689 
2690 /*
2691  * This is the primary kernel interface to load a module. It loads and
2692  * installs the named module.  It does not hold mod_ref of the module, so
2693  * a module unload attempt can occur at any time - it is up to the
2694  * _fini/mod_remove implementation to determine if unload will succeed.
2695  */
2696 int
2697 modload(const char *subdir, const char *filename)
2698 {
2699 	return (modrload(subdir, filename, NULL));
2700 }
2701 
2702 /*
2703  * Load a module using a series of qualified names from most specific to least
2704  * specific, e.g. for subdir "foo", p1 "bar", p2 "baz", we might try:
2705  *			Value returned in *chosen
2706  * foo/bar.baz.1.2.3	3
2707  * foo/bar.baz.1.2	2
2708  * foo/bar.baz.1	1
2709  * foo/bar.baz		0
2710  *
2711  * Return the module ID on success; -1 if no module was loaded.  On success
2712  * and if 'chosen' is not NULL we also return the number of suffices that
2713  * were in the module we chose to load.
2714  */
2715 int
2716 modload_qualified(const char *subdir, const char *p1,
2717     const char *p2, const char *delim, uint_t suffv[], int suffc, int *chosen)
2718 {
2719 	char path[MOD_MAXPATH];
2720 	size_t n, resid = sizeof (path);
2721 	char *p = path;
2722 
2723 	char **dotv;
2724 	int i, rc, id;
2725 	modctl_t *mp;
2726 
2727 	if (p2 != NULL)
2728 		n = snprintf(p, resid, "%s/%s%s%s", subdir, p1, delim, p2);
2729 	else
2730 		n = snprintf(p, resid, "%s/%s", subdir, p1);
2731 
2732 	if (n >= resid)
2733 		return (-1);
2734 
2735 	p += n;
2736 	resid -= n;
2737 	dotv = kmem_alloc(sizeof (char *) * (suffc + 1), KM_SLEEP);
2738 
2739 	for (i = 0; i < suffc; i++) {
2740 		dotv[i] = p;
2741 		n = snprintf(p, resid, "%s%u", delim, suffv[i]);
2742 
2743 		if (n >= resid) {
2744 			kmem_free(dotv, sizeof (char *) * (suffc + 1));
2745 			return (-1);
2746 		}
2747 
2748 		p += n;
2749 		resid -= n;
2750 	}
2751 
2752 	dotv[suffc] = p;
2753 
2754 	for (i = suffc; i >= 0; i--) {
2755 		dotv[i][0] = '\0';
2756 		mp = mod_hold_installed_mod(path, 1, 1, &rc);
2757 
2758 		if (mp != NULL) {
2759 			kmem_free(dotv, sizeof (char *) * (suffc + 1));
2760 			id = mp->mod_id;
2761 			mod_release_mod(mp);
2762 			if (chosen != NULL)
2763 				*chosen = i;
2764 			return (id);
2765 		}
2766 	}
2767 
2768 	kmem_free(dotv, sizeof (char *) * (suffc + 1));
2769 	return (-1);
2770 }
2771 
2772 /*
2773  * Load a module.
2774  */
2775 int
2776 modloadonly(const char *subdir, const char *filename)
2777 {
2778 	struct modctl *modp;
2779 	char *fullname;
2780 	size_t size;
2781 	int id, retval;
2782 
2783 	if (subdir != NULL) {
2784 		/*
2785 		 * allocate enough space for <subdir>/<filename><NULL>
2786 		 */
2787 		size = strlen(subdir) + strlen(filename) + 2;
2788 		fullname = kmem_zalloc(size, KM_SLEEP);
2789 		(void) sprintf(fullname, "%s/%s", subdir, filename);
2790 	} else {
2791 		fullname = (char *)filename;
2792 	}
2793 
2794 	modp = mod_hold_loaded_mod(NULL, fullname, &retval);
2795 	if (modp) {
2796 		id = modp->mod_id;
2797 		mod_release_mod(modp);
2798 	}
2799 
2800 	if (subdir != NULL)
2801 		kmem_free(fullname, size);
2802 
2803 	if (retval == 0)
2804 		return (id);
2805 	return (-1);
2806 }
2807 
2808 /*
2809  * Try to uninstall and unload a module, removing a reference if caller
2810  * specifies rmodp.
2811  */
2812 static int
2813 modunrload(modid_t id, struct modctl **rmodp, int unload)
2814 {
2815 	struct modctl	*modp;
2816 	int		retval;
2817 
2818 	if (rmodp)
2819 		*rmodp = NULL;			/* avoid garbage */
2820 
2821 	if ((modp = mod_hold_by_id((modid_t)id)) == NULL)
2822 		return (EINVAL);
2823 
2824 	if (rmodp) {
2825 		mutex_enter(&mod_lock);
2826 		modp->mod_ref--;
2827 		mutex_exit(&mod_lock);
2828 		*rmodp = modp;
2829 	}
2830 
2831 	if (unload) {
2832 		retval = moduninstall(modp);
2833 		if (retval == 0) {
2834 			mod_unload(modp);
2835 			CPU_STATS_ADDQ(CPU, sys, modunload, 1);
2836 		} else if (retval == EALREADY)
2837 			retval = 0;	/* already unloaded, not an error */
2838 	} else
2839 		retval = 0;
2840 
2841 	mod_release_mod(modp);
2842 	return (retval);
2843 }
2844 
2845 /*
2846  * Uninstall and unload a module.
2847  */
2848 int
2849 modunload(modid_t id)
2850 {
2851 	int		retval;
2852 
2853 	/* synchronize with any active modunload_disable() */
2854 	modunload_begin();
2855 	if (ddi_root_node())
2856 		(void) devfs_clean(ddi_root_node(), NULL, 0);
2857 	retval = modunrload(id, NULL, 1);
2858 	modunload_end();
2859 	return (retval);
2860 }
2861 
2862 /*
2863  * Return status of a loaded module.
2864  */
2865 static int
2866 modinfo(modid_t id, struct modinfo *modinfop)
2867 {
2868 	struct modctl	*modp;
2869 	modid_t		mid;
2870 	int		i;
2871 
2872 	mid = modinfop->mi_id;
2873 	if (modinfop->mi_info & MI_INFO_ALL) {
2874 		while ((modp = mod_hold_next_by_id(mid++)) != NULL) {
2875 			if ((modinfop->mi_info & MI_INFO_CNT) ||
2876 			    modp->mod_installed)
2877 				break;
2878 			mod_release_mod(modp);
2879 		}
2880 		if (modp == NULL)
2881 			return (EINVAL);
2882 	} else {
2883 		modp = mod_hold_by_id(id);
2884 		if (modp == NULL)
2885 			return (EINVAL);
2886 		if (!(modinfop->mi_info & MI_INFO_CNT) &&
2887 		    (modp->mod_installed == 0)) {
2888 			mod_release_mod(modp);
2889 			return (EINVAL);
2890 		}
2891 	}
2892 
2893 	modinfop->mi_rev = 0;
2894 	modinfop->mi_state = 0;
2895 	for (i = 0; i < MODMAXLINK; i++) {
2896 		modinfop->mi_msinfo[i].msi_p0 = -1;
2897 		modinfop->mi_msinfo[i].msi_linkinfo[0] = 0;
2898 	}
2899 	if (modp->mod_loaded) {
2900 		modinfop->mi_state = MI_LOADED;
2901 		kobj_getmodinfo(modp->mod_mp, modinfop);
2902 	}
2903 	if (modp->mod_installed) {
2904 		modinfop->mi_state |= MI_INSTALLED;
2905 
2906 		(void) mod_getinfo(modp, modinfop);
2907 	}
2908 
2909 	modinfop->mi_id = modp->mod_id;
2910 	modinfop->mi_loadcnt = modp->mod_loadcnt;
2911 	(void) strcpy(modinfop->mi_name, modp->mod_modname);
2912 
2913 	mod_release_mod(modp);
2914 	return (0);
2915 }
2916 
2917 static char mod_stub_err[] = "mod_hold_stub: Couldn't load stub module %s";
2918 static char no_err[] = "No error function for weak stub %s";
2919 
2920 /*
2921  * used by the stubs themselves to load and hold a module.
2922  * Returns  0 if the module is successfully held;
2923  *	    the stub needs to call mod_release_stub().
2924  *	    -1 if the stub should just call the err_fcn.
2925  * Note that this code is stretched out so that we avoid subroutine calls
2926  * and optimize for the most likely case.  That is, the case where the
2927  * module is loaded and installed and not held.  In that case we just inc
2928  * the mod_ref count and continue.
2929  */
2930 int
2931 mod_hold_stub(struct mod_stub_info *stub)
2932 {
2933 	struct modctl *mp;
2934 	struct mod_modinfo *mip;
2935 
2936 	mip = stub->mods_modinfo;
2937 
2938 	mutex_enter(&mod_lock);
2939 
2940 	/* we do mod_hold_by_modctl inline for speed */
2941 
2942 mod_check_again:
2943 	if ((mp = mip->mp) != NULL) {
2944 		if (mp->mod_busy == 0) {
2945 			if (mp->mod_installed) {
2946 				/* increment the reference count */
2947 				mp->mod_ref++;
2948 				ASSERT(mp->mod_ref && mp->mod_installed);
2949 				mutex_exit(&mod_lock);
2950 				return (0);
2951 			} else {
2952 				mp->mod_busy = 1;
2953 				mp->mod_inprogress_thread =
2954 				    (curthread == NULL ?
2955 				    (kthread_id_t)-1 : curthread);
2956 			}
2957 		} else {
2958 			/*
2959 			 * wait one time and then go see if someone
2960 			 * else has resolved the stub (set mip->mp).
2961 			 */
2962 			if (mod_hold_by_modctl(mp,
2963 			    MOD_WAIT_ONCE | MOD_LOCK_HELD))
2964 				goto mod_check_again;
2965 
2966 			/*
2967 			 * what we have now may have been unloaded!, in
2968 			 * that case, mip->mp will be NULL, we'll hit this
2969 			 * module and load again..
2970 			 */
2971 			cmn_err(CE_PANIC, "mod_hold_stub should have blocked");
2972 		}
2973 		mutex_exit(&mod_lock);
2974 	} else {
2975 		/* first time we've hit this module */
2976 		mutex_exit(&mod_lock);
2977 		mp = mod_hold_by_name(mip->modm_module_name);
2978 		mip->mp = mp;
2979 	}
2980 
2981 	/*
2982 	 * If we are here, it means that the following conditions
2983 	 * are satisfied.
2984 	 *
2985 	 * mip->mp != NULL
2986 	 * this thread has set the mp->mod_busy = 1
2987 	 * mp->mod_installed = 0
2988 	 *
2989 	 */
2990 	ASSERT(mp != NULL);
2991 	ASSERT(mp->mod_busy == 1);
2992 
2993 	if (mp->mod_installed == 0) {
2994 		/* Module not loaded, if weak stub don't load it */
2995 		if (stub->mods_flag & MODS_WEAK) {
2996 			if (stub->mods_errfcn == NULL) {
2997 				mod_release_mod(mp);
2998 				cmn_err(CE_PANIC, no_err,
2999 				    mip->modm_module_name);
3000 			}
3001 		} else {
3002 			/* Not a weak stub so load the module */
3003 
3004 			if (mod_load(mp, 1) != 0 || modinstall(mp) != 0) {
3005 				/*
3006 				 * If mod_load() was successful
3007 				 * and modinstall() failed, then
3008 				 * unload the module.
3009 				 */
3010 				if (mp->mod_loaded)
3011 					mod_unload(mp);
3012 
3013 				mod_release_mod(mp);
3014 				if (stub->mods_errfcn == NULL) {
3015 					cmn_err(CE_PANIC, mod_stub_err,
3016 					    mip->modm_module_name);
3017 				} else {
3018 					return (-1);
3019 				}
3020 			}
3021 		}
3022 	}
3023 
3024 	/*
3025 	 * At this point module is held and loaded. Release
3026 	 * the mod_busy and mod_inprogress_thread before
3027 	 * returning. We actually call mod_release() here so
3028 	 * that if another stub wants to access this module,
3029 	 * it can do so. mod_ref is incremented before mod_release()
3030 	 * is called to prevent someone else from snatching the
3031 	 * module from this thread.
3032 	 */
3033 	mutex_enter(&mod_lock);
3034 	mp->mod_ref++;
3035 	ASSERT(mp->mod_ref &&
3036 	    (mp->mod_loaded || (stub->mods_flag & MODS_WEAK)));
3037 	mod_release(mp);
3038 	mutex_exit(&mod_lock);
3039 	return (0);
3040 }
3041 
3042 void
3043 mod_release_stub(struct mod_stub_info *stub)
3044 {
3045 	struct modctl *mp = stub->mods_modinfo->mp;
3046 
3047 	/* inline mod_release_mod */
3048 	mutex_enter(&mod_lock);
3049 	ASSERT(mp->mod_ref &&
3050 	    (mp->mod_loaded || (stub->mods_flag & MODS_WEAK)));
3051 	mp->mod_ref--;
3052 	if (mp->mod_want) {
3053 		mp->mod_want = 0;
3054 		cv_broadcast(&mod_cv);
3055 	}
3056 	mutex_exit(&mod_lock);
3057 }
3058 
3059 static struct modctl *
3060 mod_hold_loaded_mod(struct modctl *dep, char *filename, int *status)
3061 {
3062 	struct modctl *modp;
3063 	int retval;
3064 
3065 	/*
3066 	 * Hold the module.
3067 	 */
3068 	modp = mod_hold_by_name_requisite(dep, filename);
3069 	if (modp) {
3070 		retval = mod_load(modp, 1);
3071 		if (retval != 0) {
3072 			mod_release_mod(modp);
3073 			modp = NULL;
3074 		}
3075 		*status = retval;
3076 	} else {
3077 		*status = ENOSPC;
3078 	}
3079 
3080 	/*
3081 	 * if dep is not NULL, clear the module dependency information.
3082 	 * This information is set in mod_hold_by_name_common().
3083 	 */
3084 	if (dep != NULL && dep->mod_requisite_loading != NULL) {
3085 		ASSERT(dep->mod_busy);
3086 		dep->mod_requisite_loading = NULL;
3087 	}
3088 
3089 	return (modp);
3090 }
3091 
3092 /*
3093  * hold, load, and install the named module
3094  */
3095 static struct modctl *
3096 mod_hold_installed_mod(char *name, int usepath, int forcecheck, int *r)
3097 {
3098 	struct modctl *modp;
3099 	int retval;
3100 
3101 	/*
3102 	 * Verify that that module in question actually exists on disk
3103 	 * before allocation of module structure by mod_hold_by_name.
3104 	 */
3105 	if (modrootloaded && swaploaded || forcecheck) {
3106 		if (!kobj_path_exists(name, usepath)) {
3107 			*r = ENOENT;
3108 			return (NULL);
3109 		}
3110 	}
3111 
3112 	/*
3113 	 * Hold the module.
3114 	 */
3115 	modp = mod_hold_by_name(name);
3116 	if (modp) {
3117 		retval = mod_load(modp, usepath);
3118 		if (retval != 0) {
3119 			mod_release_mod(modp);
3120 			modp = NULL;
3121 			*r = retval;
3122 		} else {
3123 			if ((*r = modinstall(modp)) != 0) {
3124 				/*
3125 				 * We loaded it, but failed to _init() it.
3126 				 * Be kind to developers -- force it
3127 				 * out of memory now so that the next
3128 				 * attempt to use the module will cause
3129 				 * a reload.  See 1093793.
3130 				 */
3131 				mod_unload(modp);
3132 				mod_release_mod(modp);
3133 				modp = NULL;
3134 			}
3135 		}
3136 	} else {
3137 		*r = ENOSPC;
3138 	}
3139 	return (modp);
3140 }
3141 
3142 static char mod_excl_msg[] =
3143 	"module %s(%s) is EXCLUDED and will not be loaded\n";
3144 static char mod_init_msg[] = "loadmodule:%s(%s): _init() error %d\n";
3145 
3146 /*
3147  * This routine is needed for dependencies.  Users specify dependencies
3148  * by declaring a character array initialized to filenames of dependents.
3149  * So the code that handles dependents deals with filenames (and not
3150  * module names) because that's all it has.  We load by filename and once
3151  * we've loaded a file we can get the module name.
3152  * Unfortunately there isn't a single unified filename/modulename namespace.
3153  * C'est la vie.
3154  *
3155  * We allow the name being looked up to be prepended by an optional
3156  * subdirectory e.g. we can lookup (NULL, "fs/ufs") or ("fs", "ufs")
3157  */
3158 struct modctl *
3159 mod_find_by_filename(char *subdir, char *filename)
3160 {
3161 	struct modctl	*mp;
3162 	size_t		sublen;
3163 
3164 	ASSERT(!MUTEX_HELD(&mod_lock));
3165 	if (subdir != NULL)
3166 		sublen = strlen(subdir);
3167 	else
3168 		sublen = 0;
3169 
3170 	mutex_enter(&mod_lock);
3171 	mp = &modules;
3172 	do {
3173 		if (sublen) {
3174 			char *mod_filename = mp->mod_filename;
3175 
3176 			if (strncmp(subdir, mod_filename, sublen) == 0 &&
3177 			    mod_filename[sublen] == '/' &&
3178 			    strcmp(filename, &mod_filename[sublen + 1]) == 0) {
3179 				mutex_exit(&mod_lock);
3180 				return (mp);
3181 			}
3182 		} else if (strcmp(filename, mp->mod_filename) == 0) {
3183 			mutex_exit(&mod_lock);
3184 			return (mp);
3185 		}
3186 	} while ((mp = mp->mod_next) != &modules);
3187 	mutex_exit(&mod_lock);
3188 	return (NULL);
3189 }
3190 
3191 /*
3192  * Check for circular dependencies.  This is called from do_dependents()
3193  * in kobj.c.  If we are the thread already loading this module, then
3194  * we're trying to load a dependent that we're already loading which
3195  * means the user specified circular dependencies.
3196  */
3197 static int
3198 mod_circdep(struct modctl *modp)
3199 {
3200 	struct modctl	*rmod;
3201 
3202 	ASSERT(MUTEX_HELD(&mod_lock));
3203 
3204 	/*
3205 	 * Check the mod_inprogress_thread first.
3206 	 * mod_inprogress_thread is used in mod_hold_stub()
3207 	 * directly to improve performance.
3208 	 */
3209 	if (modp->mod_inprogress_thread == curthread)
3210 		return (1);
3211 
3212 	/*
3213 	 * Check the module circular dependencies.
3214 	 */
3215 	for (rmod = modp; rmod != NULL; rmod = rmod->mod_requisite_loading) {
3216 		/*
3217 		 * Check if there is a module circular dependency.
3218 		 */
3219 		if (rmod->mod_requisite_loading == modp)
3220 			return (1);
3221 	}
3222 	return (0);
3223 }
3224 
3225 static int
3226 mod_getinfo(struct modctl *modp, struct modinfo *modinfop)
3227 {
3228 	int (*func)(struct modinfo *);
3229 	int retval;
3230 
3231 	ASSERT(modp->mod_busy);
3232 
3233 	/* primary modules don't do getinfo */
3234 	if (modp->mod_prim)
3235 		return (0);
3236 
3237 	func = (int (*)(struct modinfo *))kobj_lookup(modp->mod_mp, "_info");
3238 
3239 	if (kobj_addrcheck(modp->mod_mp, (caddr_t)func)) {
3240 		cmn_err(CE_WARN, "_info() not defined properly in %s",
3241 		    modp->mod_filename);
3242 		/*
3243 		 * The semantics of mod_info(9F) are that 0 is failure
3244 		 * and non-zero is success.
3245 		 */
3246 		retval = 0;
3247 	} else
3248 		retval = (*func)(modinfop);	/* call _info() function */
3249 
3250 	if (moddebug & MODDEBUG_USERDEBUG)
3251 		printf("Returned from _info, retval = %x\n", retval);
3252 
3253 	return (retval);
3254 }
3255 
3256 static void
3257 modadd(struct modctl *mp)
3258 {
3259 	ASSERT(MUTEX_HELD(&mod_lock));
3260 
3261 	mp->mod_id = last_module_id++;
3262 	mp->mod_next = &modules;
3263 	mp->mod_prev = modules.mod_prev;
3264 	modules.mod_prev->mod_next = mp;
3265 	modules.mod_prev = mp;
3266 }
3267 
3268 /*ARGSUSED*/
3269 static struct modctl *
3270 allocate_modp(const char *filename, const char *modname)
3271 {
3272 	struct modctl *mp;
3273 
3274 	mp = kobj_zalloc(sizeof (*mp), KM_SLEEP);
3275 	mp->mod_modname = kobj_zalloc(strlen(modname) + 1, KM_SLEEP);
3276 	(void) strcpy(mp->mod_modname, modname);
3277 	return (mp);
3278 }
3279 
3280 /*
3281  * Get the value of a symbol.  This is a wrapper routine that
3282  * calls kobj_getsymvalue().  kobj_getsymvalue() may go away but this
3283  * wrapper will prevent callers from noticing.
3284  */
3285 uintptr_t
3286 modgetsymvalue(char *name, int kernelonly)
3287 {
3288 	return (kobj_getsymvalue(name, kernelonly));
3289 }
3290 
3291 /*
3292  * Get the symbol nearest an address.  This is a wrapper routine that
3293  * calls kobj_getsymname().  kobj_getsymname() may go away but this
3294  * wrapper will prevent callers from noticing.
3295  */
3296 char *
3297 modgetsymname(uintptr_t value, ulong_t *offset)
3298 {
3299 	return (kobj_getsymname(value, offset));
3300 }
3301 
3302 /*
3303  * Lookup a symbol in a specified module.  These are wrapper routines that
3304  * call kobj_lookup().	kobj_lookup() may go away but these wrappers will
3305  * prevent callers from noticing.
3306  */
3307 uintptr_t
3308 modlookup(const char *modname, const char *symname)
3309 {
3310 	struct modctl *modp;
3311 	uintptr_t val;
3312 
3313 	if ((modp = mod_hold_by_name(modname)) == NULL)
3314 		return (0);
3315 	val = kobj_lookup(modp->mod_mp, symname);
3316 	mod_release_mod(modp);
3317 	return (val);
3318 }
3319 
3320 uintptr_t
3321 modlookup_by_modctl(modctl_t *modp, const char *symname)
3322 {
3323 	ASSERT(modp->mod_ref > 0 || modp->mod_busy);
3324 
3325 	return (kobj_lookup(modp->mod_mp, symname));
3326 }
3327 
3328 /*
3329  * Ask the user for the name of the system file and the default path
3330  * for modules.
3331  */
3332 void
3333 mod_askparams()
3334 {
3335 	static char s0[64];
3336 	intptr_t fd;
3337 
3338 	if ((fd = kobj_open(systemfile)) != -1L)
3339 		kobj_close(fd);
3340 	else
3341 		systemfile = NULL;
3342 
3343 	/*CONSTANTCONDITION*/
3344 	while (1) {
3345 		printf("Name of system file [%s]:  ",
3346 		    systemfile ? systemfile : "/dev/null");
3347 
3348 		console_gets(s0, sizeof (s0));
3349 
3350 		if (s0[0] == '\0')
3351 			break;
3352 		else if (strcmp(s0, "/dev/null") == 0) {
3353 			systemfile = NULL;
3354 			break;
3355 		} else {
3356 			if ((fd = kobj_open(s0)) != -1L) {
3357 				kobj_close(fd);
3358 				systemfile = s0;
3359 				break;
3360 			}
3361 		}
3362 		printf("can't find file %s\n", s0);
3363 	}
3364 }
3365 
3366 static char loading_msg[] = "loading '%s' id %d\n";
3367 static char load_msg[] = "load '%s' id %d loaded @ 0x%p/0x%p size %d/%d\n";
3368 
3369 /*
3370  * Common code for loading a module (but not installing it).
3371  * Handoff the task of module loading to a separate thread
3372  * with a large stack if possible, since this code may recurse a few times.
3373  * Return zero if there are no errors or an errno value.
3374  */
3375 static int
3376 mod_load(struct modctl *mp, int usepath)
3377 {
3378 	int		retval;
3379 	struct modinfo	*modinfop = NULL;
3380 	struct loadmt	lt;
3381 
3382 	ASSERT(MUTEX_NOT_HELD(&mod_lock));
3383 	ASSERT(mp->mod_busy);
3384 
3385 	if (mp->mod_loaded)
3386 		return (0);
3387 
3388 	if (mod_sysctl(SYS_CHECK_EXCLUDE, mp->mod_modname) != 0 ||
3389 	    mod_sysctl(SYS_CHECK_EXCLUDE, mp->mod_filename) != 0) {
3390 		if (moddebug & MODDEBUG_LOADMSG) {
3391 			printf(mod_excl_msg, mp->mod_filename,
3392 			    mp->mod_modname);
3393 		}
3394 		return (ENXIO);
3395 	}
3396 	if (moddebug & MODDEBUG_LOADMSG2)
3397 		printf(loading_msg, mp->mod_filename, mp->mod_id);
3398 
3399 	if (curthread != &t0) {
3400 		lt.mp = mp;
3401 		lt.usepath = usepath;
3402 		lt.owner = curthread;
3403 		sema_init(&lt.sema, 0, NULL, SEMA_DEFAULT, NULL);
3404 
3405 		/* create thread to hand of call to */
3406 		(void) thread_create(NULL, DEFAULTSTKSZ * 2,
3407 		    modload_thread, &lt, 0, &p0, TS_RUN, maxclsyspri);
3408 
3409 		/* wait for thread to complete kobj_load_module */
3410 		sema_p(&lt.sema);
3411 
3412 		sema_destroy(&lt.sema);
3413 		retval = lt.retval;
3414 	} else
3415 		retval = kobj_load_module(mp, usepath);
3416 
3417 	if (mp->mod_mp) {
3418 		ASSERT(retval == 0);
3419 		mp->mod_loaded = 1;
3420 		mp->mod_loadcnt++;
3421 		if (moddebug & MODDEBUG_LOADMSG) {
3422 			printf(load_msg, mp->mod_filename, mp->mod_id,
3423 			    (void *)((struct module *)mp->mod_mp)->text,
3424 			    (void *)((struct module *)mp->mod_mp)->data,
3425 			    ((struct module *)mp->mod_mp)->text_size,
3426 			    ((struct module *)mp->mod_mp)->data_size);
3427 		}
3428 
3429 		/*
3430 		 * XXX - There should be a better way to get this.
3431 		 */
3432 		modinfop = kmem_zalloc(sizeof (struct modinfo), KM_SLEEP);
3433 		modinfop->mi_info = MI_INFO_LINKAGE;
3434 		if (mod_getinfo(mp, modinfop) == 0)
3435 			mp->mod_linkage = NULL;
3436 		else {
3437 			mp->mod_linkage = (void *)modinfop->mi_base;
3438 			ASSERT(mp->mod_linkage->ml_rev == MODREV_1);
3439 		}
3440 
3441 		/*
3442 		 * DCS: bootstrapping code. If the driver is loaded
3443 		 * before root mount, it is assumed that the driver
3444 		 * may be used before mounting root. In order to
3445 		 * access mappings of global to local minor no.'s
3446 		 * during installation/open of the driver, we load
3447 		 * them into memory here while the BOP_interfaces
3448 		 * are still up.
3449 		 */
3450 		if ((cluster_bootflags & CLUSTER_BOOTED) && !modrootloaded) {
3451 			retval = clboot_modload(mp);
3452 		}
3453 
3454 		kmem_free(modinfop, sizeof (struct modinfo));
3455 		(void) mod_sysctl(SYS_SET_MVAR, (void *)mp);
3456 		retval = install_stubs_by_name(mp, mp->mod_modname);
3457 
3458 		/*
3459 		 * Now that the module is loaded, we need to give DTrace
3460 		 * a chance to notify its providers.  This is done via
3461 		 * the dtrace_modload function pointer.
3462 		 */
3463 		if (strcmp(mp->mod_modname, "dtrace") != 0) {
3464 			struct modctl *dmp = mod_hold_by_name("dtrace");
3465 
3466 			if (dmp != NULL && dtrace_modload != NULL)
3467 				(*dtrace_modload)(mp);
3468 
3469 			mod_release_mod(dmp);
3470 		}
3471 
3472 	} else {
3473 		/*
3474 		 * If load failed then we need to release any requisites
3475 		 * that we had established.
3476 		 */
3477 		ASSERT(retval);
3478 		mod_release_requisites(mp);
3479 
3480 		if (moddebug & MODDEBUG_ERRMSG)
3481 			printf("error loading '%s', error %d\n",
3482 			    mp->mod_filename, retval);
3483 	}
3484 	return (retval);
3485 }
3486 
3487 static char unload_msg[] = "unloading %s, module id %d, loadcnt %d.\n";
3488 
3489 static void
3490 mod_unload(struct modctl *mp)
3491 {
3492 	ASSERT(MUTEX_NOT_HELD(&mod_lock));
3493 	ASSERT(mp->mod_busy);
3494 	ASSERT((mp->mod_loaded && (mp->mod_installed == 0)) &&
3495 	    ((mp->mod_prim == 0) && (mp->mod_ref >= 0)));
3496 
3497 	if (moddebug & MODDEBUG_LOADMSG)
3498 		printf(unload_msg, mp->mod_modname,
3499 		    mp->mod_id, mp->mod_loadcnt);
3500 
3501 	/*
3502 	 * If mod_ref is not zero, it means some modules might still refer
3503 	 * to this module. Then you can't unload this module right now.
3504 	 * Instead, set 1 to mod_delay_unload to notify the system of
3505 	 * unloading this module later when it's not required any more.
3506 	 */
3507 	if (mp->mod_ref > 0) {
3508 		mp->mod_delay_unload = 1;
3509 		if (moddebug & MODDEBUG_LOADMSG2) {
3510 			printf("module %s not unloaded,"
3511 			    " non-zero reference count (%d)",
3512 			    mp->mod_modname, mp->mod_ref);
3513 		}
3514 		return;
3515 	}
3516 
3517 	if (((mp->mod_loaded == 0) || mp->mod_installed) ||
3518 	    (mp->mod_ref || mp->mod_prim)) {
3519 		/*
3520 		 * A DEBUG kernel would ASSERT panic above, the code is broken
3521 		 * if we get this warning.
3522 		 */
3523 		cmn_err(CE_WARN, "mod_unload: %s in incorrect state: %d %d %d",
3524 		    mp->mod_filename, mp->mod_installed, mp->mod_loaded,
3525 		    mp->mod_ref);
3526 		return;
3527 	}
3528 
3529 	/* reset stub functions to call the binder again */
3530 	reset_stubs(mp);
3531 
3532 	/*
3533 	 * mark module as unloaded before the modctl structure is freed.
3534 	 * This is required not to reuse the modctl structure before
3535 	 * the module is marked as unloaded.
3536 	 */
3537 	mp->mod_loaded = 0;
3538 	mp->mod_linkage = NULL;
3539 
3540 	/* free the memory */
3541 	kobj_unload_module(mp);
3542 
3543 	if (mp->mod_delay_unload) {
3544 		mp->mod_delay_unload = 0;
3545 		if (moddebug & MODDEBUG_LOADMSG2) {
3546 			printf("deferred unload of module %s"
3547 			    " (id %d) successful",
3548 			    mp->mod_modname, mp->mod_id);
3549 		}
3550 	}
3551 
3552 	/* release hold on requisites */
3553 	mod_release_requisites(mp);
3554 
3555 	/*
3556 	 * Now that the module is gone, we need to give DTrace a chance to
3557 	 * remove any probes that it may have had in the module.  This is
3558 	 * done via the dtrace_modunload function pointer.
3559 	 */
3560 	if (strcmp(mp->mod_modname, "dtrace") != 0) {
3561 		struct modctl *dmp = mod_hold_by_name("dtrace");
3562 
3563 		if (dmp != NULL && dtrace_modunload != NULL)
3564 			(*dtrace_modunload)(mp);
3565 
3566 		mod_release_mod(dmp);
3567 	}
3568 }
3569 
3570 static int
3571 modinstall(struct modctl *mp)
3572 {
3573 	int val;
3574 	int (*func)(void);
3575 
3576 	ASSERT(MUTEX_NOT_HELD(&mod_lock));
3577 	ASSERT(mp->mod_busy && mp->mod_loaded);
3578 
3579 	if (mp->mod_installed)
3580 		return (0);
3581 	/*
3582 	 * If mod_delay_unload is on, it means the system chose the deferred
3583 	 * unload for this module. Then you can't install this module until
3584 	 * it's unloaded from the system.
3585 	 */
3586 	if (mp->mod_delay_unload)
3587 		return (ENXIO);
3588 
3589 	if (moddebug & MODDEBUG_LOADMSG)
3590 		printf("installing %s, module id %d.\n",
3591 		    mp->mod_modname, mp->mod_id);
3592 
3593 	ASSERT(mp->mod_mp != NULL);
3594 	if (mod_install_requisites(mp) != 0) {
3595 		/*
3596 		 * Note that we can't call mod_unload(mp) here since
3597 		 * if modinstall() was called by mod_install_requisites(),
3598 		 * we won't be able to hold the dependent modules
3599 		 * (otherwise there would be a deadlock).
3600 		 */
3601 		return (ENXIO);
3602 	}
3603 
3604 	if (moddebug & MODDEBUG_ERRMSG) {
3605 		printf("init '%s' id %d loaded @ 0x%p/0x%p size %lu/%lu\n",
3606 		    mp->mod_filename, mp->mod_id,
3607 		    (void *)((struct module *)mp->mod_mp)->text,
3608 		    (void *)((struct module *)mp->mod_mp)->data,
3609 		    ((struct module *)mp->mod_mp)->text_size,
3610 		    ((struct module *)mp->mod_mp)->data_size);
3611 	}
3612 
3613 	func = (int (*)())kobj_lookup(mp->mod_mp, "_init");
3614 
3615 	if (kobj_addrcheck(mp->mod_mp, (caddr_t)func)) {
3616 		cmn_err(CE_WARN, "_init() not defined properly in %s",
3617 		    mp->mod_filename);
3618 		return (EFAULT);
3619 	}
3620 
3621 	if (moddebug & MODDEBUG_USERDEBUG) {
3622 		printf("breakpoint before calling %s:_init()\n",
3623 		    mp->mod_modname);
3624 		if (DEBUGGER_PRESENT)
3625 			debug_enter("_init");
3626 	}
3627 
3628 	ASSERT(MUTEX_NOT_HELD(&mod_lock));
3629 	ASSERT(mp->mod_busy && mp->mod_loaded);
3630 	val = (*func)();		/* call _init */
3631 
3632 	if (moddebug & MODDEBUG_USERDEBUG)
3633 		printf("Returned from _init, val = %x\n", val);
3634 
3635 	if (val == 0) {
3636 		/*
3637 		 * Set the MODS_INSTALLED flag to enable this module
3638 		 * being called now.
3639 		 */
3640 		install_stubs(mp);
3641 		mp->mod_installed = 1;
3642 	} else if (moddebug & MODDEBUG_ERRMSG)
3643 		printf(mod_init_msg, mp->mod_filename, mp->mod_modname, val);
3644 
3645 	return (val);
3646 }
3647 
3648 int	detach_driver_unconfig = 0;
3649 
3650 static int
3651 detach_driver(char *name)
3652 {
3653 	major_t major;
3654 	int error;
3655 
3656 	/*
3657 	 * If being called from mod_uninstall_all() then the appropriate
3658 	 * driver detaches (leaf only) have already been done.
3659 	 */
3660 	if (mod_in_autounload())
3661 		return (0);
3662 
3663 	major = ddi_name_to_major(name);
3664 	if (major == DDI_MAJOR_T_NONE)
3665 		return (0);
3666 
3667 	error = ndi_devi_unconfig_driver(ddi_root_node(),
3668 	    NDI_DETACH_DRIVER | detach_driver_unconfig, major);
3669 	return (error == NDI_SUCCESS ? 0 : -1);
3670 }
3671 
3672 static char finiret_msg[] = "Returned from _fini for %s, status = %x\n";
3673 
3674 static int
3675 moduninstall(struct modctl *mp)
3676 {
3677 	int status = 0;
3678 	int (*func)(void);
3679 
3680 	ASSERT(MUTEX_NOT_HELD(&mod_lock));
3681 	ASSERT(mp->mod_busy);
3682 
3683 	/*
3684 	 * Verify that we need to do something and can uninstall the module.
3685 	 *
3686 	 * If we should not uninstall the module or if the module is not in
3687 	 * the correct state to start an uninstall we return EBUSY to prevent
3688 	 * us from progressing to mod_unload.  If the module has already been
3689 	 * uninstalled and unloaded we return EALREADY.
3690 	 */
3691 	if (mp->mod_prim || mp->mod_ref || mp->mod_nenabled != 0)
3692 		return (EBUSY);
3693 	if ((mp->mod_installed == 0) || (mp->mod_loaded == 0))
3694 		return (EALREADY);
3695 
3696 	/*
3697 	 * To avoid devinfo / module deadlock we must release this module
3698 	 * prior to initiating the detach_driver, otherwise the detach_driver
3699 	 * might deadlock on a devinfo node held by another thread
3700 	 * coming top down and involving the module we have locked.
3701 	 *
3702 	 * When we regrab the module we must reverify that it is OK
3703 	 * to proceed with the uninstall operation.
3704 	 */
3705 	mod_release_mod(mp);
3706 	status = detach_driver(mp->mod_modname);
3707 	(void) mod_hold_by_modctl(mp, MOD_WAIT_FOREVER | MOD_LOCK_NOT_HELD);
3708 
3709 	/* check detach status and reverify state with lock */
3710 	mutex_enter(&mod_lock);
3711 	if ((status != 0) || mp->mod_prim || mp->mod_ref) {
3712 		mutex_exit(&mod_lock);
3713 		return (EBUSY);
3714 	}
3715 	if ((mp->mod_installed == 0) || (mp->mod_loaded == 0)) {
3716 		mutex_exit(&mod_lock);
3717 		return (EALREADY);
3718 	}
3719 	mutex_exit(&mod_lock);
3720 
3721 	if (moddebug & MODDEBUG_LOADMSG2)
3722 		printf("uninstalling %s\n", mp->mod_modname);
3723 
3724 	/*
3725 	 * lookup _fini, return EBUSY if not defined.
3726 	 *
3727 	 * The MODDEBUG_FINI_EBUSY is usefull in resolving leaks in
3728 	 * detach(9E) - it allows bufctl addresses to be resolved.
3729 	 */
3730 	func = (int (*)())kobj_lookup(mp->mod_mp, "_fini");
3731 	if ((func == NULL) || (mp->mod_loadflags & MOD_NOUNLOAD) ||
3732 	    (moddebug & MODDEBUG_FINI_EBUSY))
3733 		return (EBUSY);
3734 
3735 	/* verify that _fini is in this module */
3736 	if (kobj_addrcheck(mp->mod_mp, (caddr_t)func)) {
3737 		cmn_err(CE_WARN, "_fini() not defined properly in %s",
3738 		    mp->mod_filename);
3739 		return (EFAULT);
3740 	}
3741 
3742 	/* call _fini() */
3743 	ASSERT(MUTEX_NOT_HELD(&mod_lock));
3744 	ASSERT(mp->mod_busy && mp->mod_loaded && mp->mod_installed);
3745 
3746 	status = (*func)();
3747 
3748 	if (status == 0) {
3749 		/* _fini returned success, the module is no longer installed */
3750 		if (moddebug & MODDEBUG_LOADMSG)
3751 			printf("uninstalled %s\n", mp->mod_modname);
3752 
3753 		/*
3754 		 * Even though we only set mod_installed to zero here, a zero
3755 		 * return value means we are committed to a code path were
3756 		 * mod_loaded will also end up as zero - we have no other
3757 		 * way to get the module data and bss back to the pre _init
3758 		 * state except a reload. To ensure this, after return,
3759 		 * mod_busy must stay set until mod_loaded is cleared.
3760 		 */
3761 		mp->mod_installed = 0;
3762 
3763 		/*
3764 		 * Clear the MODS_INSTALLED flag not to call functions
3765 		 * in the module directly from now on.
3766 		 */
3767 		uninstall_stubs(mp);
3768 	} else {
3769 		if (moddebug & MODDEBUG_USERDEBUG)
3770 			printf(finiret_msg, mp->mod_filename, status);
3771 		/*
3772 		 * By definition _fini is only allowed to return EBUSY or the
3773 		 * result of mod_remove (EBUSY or EINVAL).  In the off chance
3774 		 * that a driver returns EALREADY we convert this to EINVAL
3775 		 * since to our caller EALREADY means module was already
3776 		 * removed.
3777 		 */
3778 		if (status == EALREADY)
3779 			status = EINVAL;
3780 	}
3781 
3782 	return (status);
3783 }
3784 
3785 /*
3786  * Uninstall all modules.
3787  */
3788 static void
3789 mod_uninstall_all(void)
3790 {
3791 	struct modctl	*mp;
3792 	modid_t		modid = 0;
3793 
3794 	/* synchronize with any active modunload_disable() */
3795 	modunload_begin();
3796 
3797 	/* mark this thread as doing autounloading */
3798 	(void) tsd_set(mod_autounload_key, (void *)1);
3799 
3800 	(void) devfs_clean(ddi_root_node(), NULL, 0);
3801 	(void) ndi_devi_unconfig(ddi_root_node(), NDI_AUTODETACH);
3802 
3803 	while ((mp = mod_hold_next_by_id(modid)) != NULL) {
3804 		modid = mp->mod_id;
3805 		/*
3806 		 * Skip modules with the MOD_NOAUTOUNLOAD flag set
3807 		 */
3808 		if (mp->mod_loadflags & MOD_NOAUTOUNLOAD) {
3809 			mod_release_mod(mp);
3810 			continue;
3811 		}
3812 
3813 		if (moduninstall(mp) == 0) {
3814 			mod_unload(mp);
3815 			CPU_STATS_ADDQ(CPU, sys, modunload, 1);
3816 		}
3817 		mod_release_mod(mp);
3818 	}
3819 
3820 	(void) tsd_set(mod_autounload_key, NULL);
3821 	modunload_end();
3822 }
3823 
3824 /* wait for unloads that have begun before registering disable */
3825 void
3826 modunload_disable(void)
3827 {
3828 	mutex_enter(&modunload_wait_mutex);
3829 	while (modunload_active_count) {
3830 		modunload_wait++;
3831 		cv_wait(&modunload_wait_cv, &modunload_wait_mutex);
3832 		modunload_wait--;
3833 	}
3834 	modunload_disable_count++;
3835 	mutex_exit(&modunload_wait_mutex);
3836 }
3837 
3838 /* mark end of disable and signal waiters */
3839 void
3840 modunload_enable(void)
3841 {
3842 	mutex_enter(&modunload_wait_mutex);
3843 	modunload_disable_count--;
3844 	if ((modunload_disable_count == 0) && modunload_wait)
3845 		cv_broadcast(&modunload_wait_cv);
3846 	mutex_exit(&modunload_wait_mutex);
3847 }
3848 
3849 /* wait for disables to complete before begining unload */
3850 void
3851 modunload_begin()
3852 {
3853 	mutex_enter(&modunload_wait_mutex);
3854 	while (modunload_disable_count) {
3855 		modunload_wait++;
3856 		cv_wait(&modunload_wait_cv, &modunload_wait_mutex);
3857 		modunload_wait--;
3858 	}
3859 	modunload_active_count++;
3860 	mutex_exit(&modunload_wait_mutex);
3861 }
3862 
3863 /* mark end of unload and signal waiters */
3864 void
3865 modunload_end()
3866 {
3867 	mutex_enter(&modunload_wait_mutex);
3868 	modunload_active_count--;
3869 	if ((modunload_active_count == 0) && modunload_wait)
3870 		cv_broadcast(&modunload_wait_cv);
3871 	mutex_exit(&modunload_wait_mutex);
3872 }
3873 
3874 void
3875 mod_uninstall_daemon(void)
3876 {
3877 	callb_cpr_t	cprinfo;
3878 	clock_t		ticks = 0;
3879 
3880 	mod_aul_thread = curthread;
3881 
3882 	CALLB_CPR_INIT(&cprinfo, &mod_uninstall_lock, callb_generic_cpr, "mud");
3883 	for (;;) {
3884 		mutex_enter(&mod_uninstall_lock);
3885 		CALLB_CPR_SAFE_BEGIN(&cprinfo);
3886 		/*
3887 		 * In DEBUG kernels, unheld drivers are uninstalled periodically
3888 		 * every mod_uninstall_interval seconds.  Periodic uninstall can
3889 		 * be disabled by setting mod_uninstall_interval to 0 which is
3890 		 * the default for a non-DEBUG kernel.
3891 		 */
3892 		if (mod_uninstall_interval) {
3893 			ticks = ddi_get_lbolt() +
3894 			    drv_usectohz(mod_uninstall_interval * 1000000);
3895 			(void) cv_timedwait(&mod_uninstall_cv,
3896 			    &mod_uninstall_lock, ticks);
3897 		} else {
3898 			cv_wait(&mod_uninstall_cv, &mod_uninstall_lock);
3899 		}
3900 		/*
3901 		 * The whole daemon is safe for CPR except we don't want
3902 		 * the daemon to run if FREEZE is issued and this daemon
3903 		 * wakes up from the cv_wait above. In this case, it'll be
3904 		 * blocked in CALLB_CPR_SAFE_END until THAW is issued.
3905 		 *
3906 		 * The reason of calling CALLB_CPR_SAFE_BEGIN twice is that
3907 		 * mod_uninstall_lock is used to protect cprinfo and
3908 		 * CALLB_CPR_SAFE_BEGIN assumes that this lock is held when
3909 		 * called.
3910 		 */
3911 		CALLB_CPR_SAFE_END(&cprinfo, &mod_uninstall_lock);
3912 		CALLB_CPR_SAFE_BEGIN(&cprinfo);
3913 		mutex_exit(&mod_uninstall_lock);
3914 		if ((modunload_disable_count == 0) &&
3915 		    ((moddebug & MODDEBUG_NOAUTOUNLOAD) == 0)) {
3916 			mod_uninstall_all();
3917 		}
3918 	}
3919 }
3920 
3921 /*
3922  * Unload all uninstalled modules.
3923  */
3924 void
3925 modreap(void)
3926 {
3927 	mutex_enter(&mod_uninstall_lock);
3928 	cv_broadcast(&mod_uninstall_cv);
3929 	mutex_exit(&mod_uninstall_lock);
3930 }
3931 
3932 /*
3933  * Hold the specified module. This is the module holding primitive.
3934  *
3935  * If MOD_LOCK_HELD then the caller already holds the mod_lock.
3936  *
3937  * Return values:
3938  *	 0 ==> the module is held
3939  *	 1 ==> the module is not held and the MOD_WAIT_ONCE caller needs
3940  *		to determine how to retry.
3941  */
3942 int
3943 mod_hold_by_modctl(struct modctl *mp, int f)
3944 {
3945 	ASSERT((f & (MOD_WAIT_ONCE | MOD_WAIT_FOREVER)) &&
3946 	    ((f & (MOD_WAIT_ONCE | MOD_WAIT_FOREVER)) !=
3947 	    (MOD_WAIT_ONCE | MOD_WAIT_FOREVER)));
3948 	ASSERT((f & (MOD_LOCK_HELD | MOD_LOCK_NOT_HELD)) &&
3949 	    ((f & (MOD_LOCK_HELD | MOD_LOCK_NOT_HELD)) !=
3950 	    (MOD_LOCK_HELD | MOD_LOCK_NOT_HELD)));
3951 	ASSERT((f & MOD_LOCK_NOT_HELD) || MUTEX_HELD(&mod_lock));
3952 
3953 	if (f & MOD_LOCK_NOT_HELD)
3954 		mutex_enter(&mod_lock);
3955 
3956 	while (mp->mod_busy) {
3957 		mp->mod_want = 1;
3958 		cv_wait(&mod_cv, &mod_lock);
3959 		/*
3960 		 * Module may be unloaded by daemon.
3961 		 * Nevertheless, modctl structure is still in linked list
3962 		 * (i.e., off &modules), not freed!
3963 		 * Caller is not supposed to assume "mp" is valid, but there
3964 		 * is no reasonable way to detect this but using
3965 		 * mp->mod_modinfo->mp == NULL check (follow the back pointer)
3966 		 *   (or similar check depending on calling context)
3967 		 * DON'T free modctl structure, it will be very very
3968 		 * problematic.
3969 		 */
3970 		if (f & MOD_WAIT_ONCE) {
3971 			if (f & MOD_LOCK_NOT_HELD)
3972 				mutex_exit(&mod_lock);
3973 			return (1);	/* caller decides how to retry */
3974 		}
3975 	}
3976 
3977 	mp->mod_busy = 1;
3978 	mp->mod_inprogress_thread =
3979 	    (curthread == NULL ? (kthread_id_t)-1 : curthread);
3980 
3981 	if (f & MOD_LOCK_NOT_HELD)
3982 		mutex_exit(&mod_lock);
3983 	return (0);
3984 }
3985 
3986 static struct modctl *
3987 mod_hold_by_name_common(struct modctl *dep, const char *filename)
3988 {
3989 	const char	*modname;
3990 	struct modctl	*mp;
3991 	char		*curname, *newname;
3992 	int		found = 0;
3993 
3994 	mutex_enter(&mod_lock);
3995 
3996 	if ((modname = strrchr(filename, '/')) == NULL)
3997 		modname = filename;
3998 	else
3999 		modname++;
4000 
4001 	mp = &modules;
4002 	do {
4003 		if (strcmp(modname, mp->mod_modname) == 0) {
4004 			found = 1;
4005 			break;
4006 		}
4007 	} while ((mp = mp->mod_next) != &modules);
4008 
4009 	if (found == 0) {
4010 		mp = allocate_modp(filename, modname);
4011 		modadd(mp);
4012 	}
4013 
4014 	/*
4015 	 * if dep is not NULL, set the mp in mod_requisite_loading for
4016 	 * the module circular dependency check. This field is used in
4017 	 * mod_circdep(), but it's cleard in mod_hold_loaded_mod().
4018 	 */
4019 	if (dep != NULL) {
4020 		ASSERT(dep->mod_busy && dep->mod_requisite_loading == NULL);
4021 		dep->mod_requisite_loading = mp;
4022 	}
4023 
4024 	/*
4025 	 * If the module was held, then it must be us who has it held.
4026 	 */
4027 	if (mod_circdep(mp))
4028 		mp = NULL;
4029 	else {
4030 		(void) mod_hold_by_modctl(mp, MOD_WAIT_FOREVER | MOD_LOCK_HELD);
4031 
4032 		/*
4033 		 * If the name hadn't been set or has changed, allocate
4034 		 * space and set it.  Free space used by previous name.
4035 		 *
4036 		 * Do not change the name of primary modules, for primary
4037 		 * modules the mod_filename was allocated in standalone mode:
4038 		 * it is illegal to kobj_alloc in standalone mode and kobj_free
4039 		 * in non-standalone mode.
4040 		 */
4041 		curname = mp->mod_filename;
4042 		if (curname == NULL ||
4043 		    ((mp->mod_prim == 0) &&
4044 		    (curname != filename) &&
4045 		    (modname != filename) &&
4046 		    (strcmp(curname, filename) != 0))) {
4047 			newname = kobj_zalloc(strlen(filename) + 1, KM_SLEEP);
4048 			(void) strcpy(newname, filename);
4049 			mp->mod_filename = newname;
4050 			if (curname != NULL)
4051 				kobj_free(curname, strlen(curname) + 1);
4052 		}
4053 	}
4054 
4055 	mutex_exit(&mod_lock);
4056 	if (mp && moddebug & MODDEBUG_LOADMSG2)
4057 		printf("Holding %s\n", mp->mod_filename);
4058 	if (mp == NULL && moddebug & MODDEBUG_LOADMSG2)
4059 		printf("circular dependency loading %s\n", filename);
4060 	return (mp);
4061 }
4062 
4063 static struct modctl *
4064 mod_hold_by_name_requisite(struct modctl *dep, char *filename)
4065 {
4066 	return (mod_hold_by_name_common(dep, filename));
4067 }
4068 
4069 struct modctl *
4070 mod_hold_by_name(const char *filename)
4071 {
4072 	return (mod_hold_by_name_common(NULL, filename));
4073 }
4074 
4075 struct modctl *
4076 mod_hold_by_id(modid_t modid)
4077 {
4078 	struct modctl	*mp;
4079 	int		found = 0;
4080 
4081 	mutex_enter(&mod_lock);
4082 	mp = &modules;
4083 	do {
4084 		if (mp->mod_id == modid) {
4085 			found = 1;
4086 			break;
4087 		}
4088 	} while ((mp = mp->mod_next) != &modules);
4089 
4090 	if ((found == 0) || mod_circdep(mp))
4091 		mp = NULL;
4092 	else
4093 		(void) mod_hold_by_modctl(mp, MOD_WAIT_FOREVER | MOD_LOCK_HELD);
4094 
4095 	mutex_exit(&mod_lock);
4096 	return (mp);
4097 }
4098 
4099 static struct modctl *
4100 mod_hold_next_by_id(modid_t modid)
4101 {
4102 	struct modctl	*mp;
4103 	int		found = 0;
4104 
4105 	if (modid < -1)
4106 		return (NULL);
4107 
4108 	mutex_enter(&mod_lock);
4109 
4110 	mp = &modules;
4111 	do {
4112 		if (mp->mod_id > modid) {
4113 			found = 1;
4114 			break;
4115 		}
4116 	} while ((mp = mp->mod_next) != &modules);
4117 
4118 	if ((found == 0) || mod_circdep(mp))
4119 		mp = NULL;
4120 	else
4121 		(void) mod_hold_by_modctl(mp, MOD_WAIT_FOREVER | MOD_LOCK_HELD);
4122 
4123 	mutex_exit(&mod_lock);
4124 	return (mp);
4125 }
4126 
4127 static void
4128 mod_release(struct modctl *mp)
4129 {
4130 	ASSERT(MUTEX_HELD(&mod_lock));
4131 	ASSERT(mp->mod_busy);
4132 
4133 	mp->mod_busy = 0;
4134 	mp->mod_inprogress_thread = NULL;
4135 	if (mp->mod_want) {
4136 		mp->mod_want = 0;
4137 		cv_broadcast(&mod_cv);
4138 	}
4139 }
4140 
4141 void
4142 mod_release_mod(struct modctl *mp)
4143 {
4144 	if (moddebug & MODDEBUG_LOADMSG2)
4145 		printf("Releasing %s\n", mp->mod_filename);
4146 	mutex_enter(&mod_lock);
4147 	mod_release(mp);
4148 	mutex_exit(&mod_lock);
4149 }
4150 
4151 modid_t
4152 mod_name_to_modid(char *filename)
4153 {
4154 	char		*modname;
4155 	struct modctl	*mp;
4156 
4157 	mutex_enter(&mod_lock);
4158 
4159 	if ((modname = strrchr(filename, '/')) == NULL)
4160 		modname = filename;
4161 	else
4162 		modname++;
4163 
4164 	mp = &modules;
4165 	do {
4166 		if (strcmp(modname, mp->mod_modname) == 0) {
4167 			mutex_exit(&mod_lock);
4168 			return (mp->mod_id);
4169 		}
4170 	} while ((mp = mp->mod_next) != &modules);
4171 
4172 	mutex_exit(&mod_lock);
4173 	return (-1);
4174 }
4175 
4176 
4177 int
4178 mod_remove_by_name(char *name)
4179 {
4180 	struct modctl *mp;
4181 	int retval;
4182 
4183 	mp = mod_hold_by_name(name);
4184 
4185 	if (mp == NULL)
4186 		return (EINVAL);
4187 
4188 	if (mp->mod_loadflags & MOD_NOAUTOUNLOAD) {
4189 		/*
4190 		 * Do not unload forceloaded modules
4191 		 */
4192 		mod_release_mod(mp);
4193 		return (0);
4194 	}
4195 
4196 	if ((retval = moduninstall(mp)) == 0) {
4197 		mod_unload(mp);
4198 		CPU_STATS_ADDQ(CPU, sys, modunload, 1);
4199 	} else if (retval == EALREADY)
4200 		retval = 0;		/* already unloaded, not an error */
4201 	mod_release_mod(mp);
4202 	return (retval);
4203 }
4204 
4205 /*
4206  * Record that module "dep" is dependent on module "on_mod."
4207  */
4208 static void
4209 mod_make_requisite(struct modctl *dependent, struct modctl *on_mod)
4210 {
4211 	struct modctl_list **pmlnp;	/* previous next pointer */
4212 	struct modctl_list *mlp;
4213 	struct modctl_list *new;
4214 
4215 	ASSERT(dependent->mod_busy && on_mod->mod_busy);
4216 	mutex_enter(&mod_lock);
4217 
4218 	/*
4219 	 * Search dependent's requisite list to see if on_mod is recorded.
4220 	 * List is ordered by id.
4221 	 */
4222 	for (pmlnp = &dependent->mod_requisites, mlp = *pmlnp;
4223 	    mlp; pmlnp = &mlp->modl_next, mlp = *pmlnp)
4224 		if (mlp->modl_modp->mod_id >= on_mod->mod_id)
4225 			break;
4226 
4227 	/* Create and insert if not already recorded */
4228 	if ((mlp == NULL) || (mlp->modl_modp->mod_id != on_mod->mod_id)) {
4229 		new = kobj_zalloc(sizeof (*new), KM_SLEEP);
4230 		new->modl_modp = on_mod;
4231 		new->modl_next = mlp;
4232 		*pmlnp = new;
4233 
4234 		/*
4235 		 * Increment the mod_ref count in our new requisite module.
4236 		 * This is what keeps a module that has other modules
4237 		 * which are dependent on it from being uninstalled and
4238 		 * unloaded. "on_mod"'s mod_ref count decremented in
4239 		 * mod_release_requisites when the "dependent" module
4240 		 * unload is complete.	"on_mod" must be loaded, but may not
4241 		 * yet be installed.
4242 		 */
4243 		on_mod->mod_ref++;
4244 		ASSERT(on_mod->mod_ref && on_mod->mod_loaded);
4245 	}
4246 
4247 	mutex_exit(&mod_lock);
4248 }
4249 
4250 /*
4251  * release the hold associated with mod_make_requisite mod_ref++
4252  * as part of unload.
4253  */
4254 void
4255 mod_release_requisites(struct modctl *modp)
4256 {
4257 	struct modctl_list *modl;
4258 	struct modctl_list *next;
4259 	struct modctl *req;
4260 	struct modctl_list *start = NULL, *mod_garbage;
4261 
4262 	ASSERT(modp->mod_busy);
4263 	ASSERT(!MUTEX_HELD(&mod_lock));
4264 
4265 	mutex_enter(&mod_lock);		/* needed for manipulation of req */
4266 	for (modl = modp->mod_requisites; modl; modl = next) {
4267 		next = modl->modl_next;
4268 		req = modl->modl_modp;
4269 		ASSERT(req->mod_ref >= 1 && req->mod_loaded);
4270 		req->mod_ref--;
4271 
4272 		/*
4273 		 * Check if the module has to be unloaded or not.
4274 		 */
4275 		if (req->mod_ref == 0 && req->mod_delay_unload) {
4276 			struct modctl_list *new;
4277 			/*
4278 			 * Allocate the modclt_list holding the garbage
4279 			 * module which should be unloaded later.
4280 			 */
4281 			new = kobj_zalloc(sizeof (struct modctl_list),
4282 			    KM_SLEEP);
4283 			new->modl_modp = req;
4284 
4285 			if (start == NULL)
4286 				mod_garbage = start = new;
4287 			else {
4288 				mod_garbage->modl_next = new;
4289 				mod_garbage = new;
4290 			}
4291 		}
4292 
4293 		/* free the list as we go */
4294 		kobj_free(modl, sizeof (*modl));
4295 	}
4296 	modp->mod_requisites = NULL;
4297 	mutex_exit(&mod_lock);
4298 
4299 	/*
4300 	 * Unload the garbage modules.
4301 	 */
4302 	for (mod_garbage = start; mod_garbage != NULL; /* nothing */) {
4303 		struct modctl_list *old = mod_garbage;
4304 		struct modctl *mp = mod_garbage->modl_modp;
4305 		ASSERT(mp != NULL);
4306 
4307 		/*
4308 		 * Hold this module until it's unloaded completely.
4309 		 */
4310 		(void) mod_hold_by_modctl(mp,
4311 		    MOD_WAIT_FOREVER | MOD_LOCK_NOT_HELD);
4312 		/*
4313 		 * Check if the module is not unloaded yet and nobody requires
4314 		 * the module. If it's unloaded already or somebody still
4315 		 * requires the module, don't unload it now.
4316 		 */
4317 		if (mp->mod_loaded && mp->mod_ref == 0)
4318 			mod_unload(mp);
4319 		ASSERT((mp->mod_loaded == 0 && mp->mod_delay_unload == 0) ||
4320 		    (mp->mod_ref > 0));
4321 		mod_release_mod(mp);
4322 
4323 		mod_garbage = mod_garbage->modl_next;
4324 		kobj_free(old, sizeof (struct modctl_list));
4325 	}
4326 }
4327 
4328 /*
4329  * Process dependency of the module represented by "dep" on the
4330  * module named by "on."
4331  *
4332  * Called from kobj_do_dependents() to load a module "on" on which
4333  * "dep" depends.
4334  */
4335 struct modctl *
4336 mod_load_requisite(struct modctl *dep, char *on)
4337 {
4338 	struct modctl *on_mod;
4339 	int retval;
4340 
4341 	if ((on_mod = mod_hold_loaded_mod(dep, on, &retval)) != NULL) {
4342 		mod_make_requisite(dep, on_mod);
4343 	} else if (moddebug & MODDEBUG_ERRMSG) {
4344 		printf("error processing %s on which module %s depends\n",
4345 		    on, dep->mod_modname);
4346 	}
4347 	return (on_mod);
4348 }
4349 
4350 static int
4351 mod_install_requisites(struct modctl *modp)
4352 {
4353 	struct modctl_list *modl;
4354 	struct modctl *req;
4355 	int status = 0;
4356 
4357 	ASSERT(MUTEX_NOT_HELD(&mod_lock));
4358 	ASSERT(modp->mod_busy);
4359 
4360 	for (modl = modp->mod_requisites; modl; modl = modl->modl_next) {
4361 		req = modl->modl_modp;
4362 		(void) mod_hold_by_modctl(req,
4363 		    MOD_WAIT_FOREVER | MOD_LOCK_NOT_HELD);
4364 		status = modinstall(req);
4365 		mod_release_mod(req);
4366 
4367 		if (status != 0)
4368 			break;
4369 	}
4370 	return (status);
4371 }
4372 
4373 /*
4374  * returns 1 if this thread is doing autounload, 0 otherwise.
4375  * see mod_uninstall_all.
4376  */
4377 int
4378 mod_in_autounload()
4379 {
4380 	return ((int)(uintptr_t)tsd_get(mod_autounload_key));
4381 }
4382 
4383 /*
4384  * gmatch adapted from libc, stripping the wchar stuff
4385  */
4386 #define	popchar(p, c)	{ \
4387 		c = *p++; \
4388 		if (c == 0) { \
4389 			return (0); \
4390 		} \
4391 	}
4392 
4393 int
4394 gmatch(const char *s, const char *p)
4395 {
4396 	int c, sc;
4397 	int ok, lc, notflag;
4398 
4399 	sc = *s++;
4400 	c = *p++;
4401 	if (c == 0)
4402 		return (sc == c);	/* nothing matches nothing */
4403 
4404 	switch (c) {
4405 	case '\\':
4406 		/* skip to quoted character */
4407 		popchar(p, c);
4408 		/*FALLTHRU*/
4409 
4410 	default:
4411 		/* straight comparison */
4412 		if (c != sc)
4413 			return (0);
4414 		/*FALLTHRU*/
4415 
4416 	case '?':
4417 		/* first char matches, move to remainder */
4418 		return (sc != '\0' ? gmatch(s, p) : 0);
4419 
4420 
4421 	case '*':
4422 		while (*p == '*')
4423 			p++;
4424 
4425 		/* * matches everything */
4426 		if (*p == 0)
4427 			return (1);
4428 
4429 		/* undo skip at the beginning & iterate over substrings */
4430 		--s;
4431 		while (*s) {
4432 			if (gmatch(s, p))
4433 				return (1);
4434 			s++;
4435 		}
4436 		return (0);
4437 
4438 	case '[':
4439 		/* match any char within [] */
4440 		if (sc == 0)
4441 			return (0);
4442 
4443 		ok = lc = notflag = 0;
4444 
4445 		if (*p == '!') {
4446 			notflag = 1;
4447 			p++;
4448 		}
4449 		popchar(p, c);
4450 
4451 		do {
4452 			if (c == '-' && lc && *p != ']') {
4453 				/* test sc against range [c1-c2] */
4454 				popchar(p, c);
4455 				if (c == '\\') {
4456 					popchar(p, c);
4457 				}
4458 
4459 				if (notflag) {
4460 					/* return 0 on mismatch */
4461 					if (lc <= sc && sc <= c)
4462 						return (0);
4463 					ok++;
4464 				} else if (lc <= sc && sc <= c) {
4465 					ok++;
4466 				}
4467 				/* keep going, may get a match next */
4468 			} else if (c == '\\') {
4469 				/* skip to quoted character */
4470 				popchar(p, c);
4471 			}
4472 			lc = c;
4473 			if (notflag) {
4474 				if (sc == lc)
4475 					return (0);
4476 				ok++;
4477 			} else if (sc == lc) {
4478 				ok++;
4479 			}
4480 			popchar(p, c);
4481 		} while (c != ']');
4482 
4483 		/* recurse on remainder of string */
4484 		return (ok ? gmatch(s, p) : 0);
4485 	}
4486 	/*NOTREACHED*/
4487 }
4488 
4489 
4490 /*
4491  * Get default perm for device from /etc/minor_perm. Return 0 if match found.
4492  *
4493  * Pure wild-carded patterns are handled separately so the ordering of
4494  * these patterns doesn't matter.  We're still dependent on ordering
4495  * however as the first matching entry is the one returned.
4496  * Not ideal but all existing examples and usage do imply this
4497  * ordering implicitly.
4498  *
4499  * Drivers using the clone driver are always good for some entertainment.
4500  * Clone nodes under pseudo have the form clone@0:<driver>.  Some minor
4501  * perm entries have the form clone:<driver>, others use <driver>:*
4502  * Examples are clone:llc1 vs. llc2:*, for example.
4503  *
4504  * Minor perms in the clone:<driver> form are mapped to the drivers's
4505  * mperm list, not the clone driver, as wildcard entries for clone
4506  * reference only.  In other words, a clone wildcard will match
4507  * references for clone@0:<driver> but never <driver>@<minor>.
4508  *
4509  * Additional minor perms in the standard form are also supported,
4510  * for mixed usage, ie a node with an entry clone:<driver> could
4511  * provide further entries <driver>:<minor>.
4512  *
4513  * Finally, some uses of clone use an alias as the minor name rather
4514  * than the driver name, with the alias as the minor perm entry.
4515  * This case is handled by attaching the driver to bring its
4516  * minor list into existence, then discover the alias via DDI_ALIAS.
4517  * The clone device's minor perm list can then be searched for
4518  * that alias.
4519  */
4520 
4521 static int
4522 dev_alias_minorperm(dev_info_t *dip, char *minor_name, mperm_t *rmp)
4523 {
4524 	major_t			major;
4525 	struct devnames		*dnp;
4526 	mperm_t			*mp;
4527 	char			*alias = NULL;
4528 	dev_info_t		*cdevi;
4529 	int			circ;
4530 	struct ddi_minor_data	*dmd;
4531 
4532 	major = ddi_name_to_major(minor_name);
4533 
4534 	ASSERT(dip == clone_dip);
4535 	ASSERT(major != DDI_MAJOR_T_NONE);
4536 
4537 	/*
4538 	 * Attach the driver named by the minor node, then
4539 	 * search its first instance's minor list for an
4540 	 * alias node.
4541 	 */
4542 	if (ddi_hold_installed_driver(major) == NULL)
4543 		return (1);
4544 
4545 	dnp = &devnamesp[major];
4546 	LOCK_DEV_OPS(&dnp->dn_lock);
4547 
4548 	if ((cdevi = dnp->dn_head) != NULL) {
4549 		ndi_devi_enter(cdevi, &circ);
4550 		for (dmd = DEVI(cdevi)->devi_minor; dmd; dmd = dmd->next) {
4551 			if (dmd->type == DDM_ALIAS) {
4552 				alias = i_ddi_strdup(dmd->ddm_name, KM_SLEEP);
4553 				break;
4554 			}
4555 		}
4556 		ndi_devi_exit(cdevi, circ);
4557 	}
4558 
4559 	UNLOCK_DEV_OPS(&dnp->dn_lock);
4560 	ddi_rele_driver(major);
4561 
4562 	if (alias == NULL) {
4563 		if (moddebug & MODDEBUG_MINORPERM)
4564 			cmn_err(CE_CONT, "dev_minorperm: "
4565 			    "no alias for %s\n", minor_name);
4566 		return (1);
4567 	}
4568 
4569 	major = ddi_driver_major(clone_dip);
4570 	dnp = &devnamesp[major];
4571 	LOCK_DEV_OPS(&dnp->dn_lock);
4572 
4573 	/*
4574 	 * Go through the clone driver's mperm list looking
4575 	 * for a match for the specified alias.
4576 	 */
4577 	for (mp = dnp->dn_mperm; mp; mp = mp->mp_next) {
4578 		if (strcmp(alias, mp->mp_minorname) == 0) {
4579 			break;
4580 		}
4581 	}
4582 
4583 	if (mp) {
4584 		if (moddebug & MODDEBUG_MP_MATCH) {
4585 			cmn_err(CE_CONT,
4586 			    "minor perm defaults: %s %s 0%o %d %d (aliased)\n",
4587 			    minor_name, alias, mp->mp_mode,
4588 			    mp->mp_uid, mp->mp_gid);
4589 		}
4590 		rmp->mp_uid = mp->mp_uid;
4591 		rmp->mp_gid = mp->mp_gid;
4592 		rmp->mp_mode = mp->mp_mode;
4593 	}
4594 	UNLOCK_DEV_OPS(&dnp->dn_lock);
4595 
4596 	kmem_free(alias, strlen(alias)+1);
4597 
4598 	return (mp == NULL);
4599 }
4600 
4601 int
4602 dev_minorperm(dev_info_t *dip, char *name, mperm_t *rmp)
4603 {
4604 	major_t major;
4605 	char *minor_name;
4606 	struct devnames *dnp;
4607 	mperm_t *mp;
4608 	int is_clone = 0;
4609 
4610 	if (!minorperm_loaded) {
4611 		if (moddebug & MODDEBUG_MINORPERM)
4612 			cmn_err(CE_CONT,
4613 			    "%s: minor perm not yet loaded\n", name);
4614 		return (1);
4615 	}
4616 
4617 	minor_name = strchr(name, ':');
4618 	if (minor_name == NULL)
4619 		return (1);
4620 	minor_name++;
4621 
4622 	/*
4623 	 * If it's the clone driver, search the driver as named
4624 	 * by the minor.  All clone minor perm entries other than
4625 	 * alias nodes are actually installed on the real driver's list.
4626 	 */
4627 	if (dip == clone_dip) {
4628 		major = ddi_name_to_major(minor_name);
4629 		if (major == DDI_MAJOR_T_NONE) {
4630 			if (moddebug & MODDEBUG_MINORPERM)
4631 				cmn_err(CE_CONT, "dev_minorperm: "
4632 				    "%s: no such driver\n", minor_name);
4633 			return (1);
4634 		}
4635 		is_clone = 1;
4636 	} else {
4637 		major = ddi_driver_major(dip);
4638 		ASSERT(major != DDI_MAJOR_T_NONE);
4639 	}
4640 
4641 	dnp = &devnamesp[major];
4642 	LOCK_DEV_OPS(&dnp->dn_lock);
4643 
4644 	/*
4645 	 * Go through the driver's mperm list looking for
4646 	 * a match for the specified minor.  If there's
4647 	 * no matching pattern, use the wild card.
4648 	 * Defer to the clone wild for clone if specified,
4649 	 * otherwise fall back to the normal form.
4650 	 */
4651 	for (mp = dnp->dn_mperm; mp; mp = mp->mp_next) {
4652 		if (gmatch(minor_name, mp->mp_minorname) != 0) {
4653 			break;
4654 		}
4655 	}
4656 	if (mp == NULL) {
4657 		if (is_clone)
4658 			mp = dnp->dn_mperm_clone;
4659 		if (mp == NULL)
4660 			mp = dnp->dn_mperm_wild;
4661 	}
4662 
4663 	if (mp) {
4664 		if (moddebug & MODDEBUG_MP_MATCH) {
4665 			cmn_err(CE_CONT,
4666 			    "minor perm defaults: %s %s 0%o %d %d\n",
4667 			    name, mp->mp_minorname, mp->mp_mode,
4668 			    mp->mp_uid, mp->mp_gid);
4669 		}
4670 		rmp->mp_uid = mp->mp_uid;
4671 		rmp->mp_gid = mp->mp_gid;
4672 		rmp->mp_mode = mp->mp_mode;
4673 	}
4674 	UNLOCK_DEV_OPS(&dnp->dn_lock);
4675 
4676 	/*
4677 	 * If no match can be found for a clone node,
4678 	 * search for a possible match for an alias.
4679 	 * One such example is /dev/ptmx -> /devices/pseudo/clone@0:ptm,
4680 	 * with minor perm entry clone:ptmx.
4681 	 */
4682 	if (mp == NULL && is_clone) {
4683 		return (dev_alias_minorperm(dip, minor_name, rmp));
4684 	}
4685 
4686 	return (mp == NULL);
4687 }
4688 
4689 /*
4690  * dynamicaly reference load a dl module/library, returning handle
4691  */
4692 /*ARGSUSED*/
4693 ddi_modhandle_t
4694 ddi_modopen(const char *modname, int mode, int *errnop)
4695 {
4696 	char		*subdir;
4697 	char		*mod;
4698 	int		subdirlen;
4699 	struct modctl	*hmodp = NULL;
4700 	int		retval = EINVAL;
4701 
4702 	ASSERT(modname && (mode == KRTLD_MODE_FIRST));
4703 	if ((modname == NULL) || (mode != KRTLD_MODE_FIRST))
4704 		goto out;
4705 
4706 	/* find last '/' in modname */
4707 	mod = strrchr(modname, '/');
4708 
4709 	if (mod) {
4710 		/* for subdir string without modification to argument */
4711 		mod++;
4712 		subdirlen = mod - modname;
4713 		subdir = kmem_alloc(subdirlen, KM_SLEEP);
4714 		(void) strlcpy(subdir, modname, subdirlen);
4715 	} else {
4716 		subdirlen = 0;
4717 		subdir = "misc";
4718 		mod = (char *)modname;
4719 	}
4720 
4721 	/* reference load with errno return value */
4722 	retval = modrload(subdir, mod, &hmodp);
4723 
4724 	if (subdirlen)
4725 		kmem_free(subdir, subdirlen);
4726 
4727 out:	if (errnop)
4728 		*errnop = retval;
4729 
4730 	if (moddebug & MODDEBUG_DDI_MOD)
4731 		printf("ddi_modopen %s mode %x: %s %p %d\n",
4732 		    modname ? modname : "<unknown>", mode,
4733 		    hmodp ? hmodp->mod_filename : "<unknown>",
4734 		    (void *)hmodp, retval);
4735 
4736 	return ((ddi_modhandle_t)hmodp);
4737 }
4738 
4739 /* lookup "name" in open dl module/library */
4740 void *
4741 ddi_modsym(ddi_modhandle_t h, const char *name, int *errnop)
4742 {
4743 	struct modctl	*hmodp = (struct modctl *)h;
4744 	void		*f;
4745 	int		retval;
4746 
4747 	ASSERT(hmodp && name && hmodp->mod_installed && (hmodp->mod_ref >= 1));
4748 	if ((hmodp == NULL) || (name == NULL) ||
4749 	    (hmodp->mod_installed == 0) || (hmodp->mod_ref < 1)) {
4750 		f = NULL;
4751 		retval = EINVAL;
4752 	} else {
4753 		f = (void *)kobj_lookup(hmodp->mod_mp, (char *)name);
4754 		if (f)
4755 			retval = 0;
4756 		else
4757 			retval = ENOTSUP;
4758 	}
4759 
4760 	if (moddebug & MODDEBUG_DDI_MOD)
4761 		printf("ddi_modsym in %s of %s: %d %p\n",
4762 		    hmodp ? hmodp->mod_modname : "<unknown>",
4763 		    name ? name : "<unknown>", retval, f);
4764 
4765 	if (errnop)
4766 		*errnop = retval;
4767 	return (f);
4768 }
4769 
4770 /* dynamic (un)reference unload of an open dl module/library */
4771 int
4772 ddi_modclose(ddi_modhandle_t h)
4773 {
4774 	struct modctl	*hmodp = (struct modctl *)h;
4775 	struct modctl	*modp = NULL;
4776 	int		retval;
4777 
4778 	ASSERT(hmodp && hmodp->mod_installed && (hmodp->mod_ref >= 1));
4779 	if ((hmodp == NULL) ||
4780 	    (hmodp->mod_installed == 0) || (hmodp->mod_ref < 1)) {
4781 		retval = EINVAL;
4782 		goto out;
4783 	}
4784 
4785 	retval = modunrload(hmodp->mod_id, &modp, ddi_modclose_unload);
4786 	if (retval == EBUSY)
4787 		retval = 0;	/* EBUSY is not an error */
4788 
4789 	if (retval == 0) {
4790 		ASSERT(hmodp == modp);
4791 		if (hmodp != modp)
4792 			retval = EINVAL;
4793 	}
4794 
4795 out:	if (moddebug & MODDEBUG_DDI_MOD)
4796 		printf("ddi_modclose %s: %d\n",
4797 		    hmodp ? hmodp->mod_modname : "<unknown>", retval);
4798 
4799 	return (retval);
4800 }
4801