xref: /illumos-gate/usr/src/uts/common/os/modctl.c (revision c9cc1492d5b27b76cf77300ab3aafd0857f38228)
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 int
2265 modctl_moddevname(int subcmd, uintptr_t a1, uintptr_t a2)
2266 {
2267 	int error = 0;
2268 
2269 	switch (subcmd) {
2270 	case MODDEVNAME_LOOKUPDOOR:
2271 		error = devname_filename_register((char *)a1);
2272 		break;
2273 	case MODDEVNAME_PROFILE:
2274 		error = devname_profile_update((char *)a1, (size_t)a2);
2275 		break;
2276 	case MODDEVNAME_RECONFIG:
2277 		i_ddi_set_reconfig();
2278 		break;
2279 	case MODDEVNAME_SYSAVAIL:
2280 		i_ddi_set_sysavail();
2281 		break;
2282 	default:
2283 		error = EINVAL;
2284 		break;
2285 	}
2286 
2287 	return (error);
2288 }
2289 
2290 /*ARGSUSED5*/
2291 int
2292 modctl(int cmd, uintptr_t a1, uintptr_t a2, uintptr_t a3, uintptr_t a4,
2293     uintptr_t a5)
2294 {
2295 	int	error = EINVAL;
2296 	dev_t	dev;
2297 
2298 	if (secpolicy_modctl(CRED(), cmd) != 0)
2299 		return (set_errno(EPERM));
2300 
2301 	switch (cmd) {
2302 	case MODLOAD:		/* load a module */
2303 		error = modctl_modload((int)a1, (char *)a2, (int *)a3);
2304 		break;
2305 
2306 	case MODUNLOAD:		/* unload a module */
2307 		error = modctl_modunload((modid_t)a1);
2308 		break;
2309 
2310 	case MODINFO:		/* get module status */
2311 		error = modctl_modinfo((modid_t)a1, (struct modinfo *)a2);
2312 		break;
2313 
2314 	case MODRESERVED:	/* get last major number in range */
2315 		error = modctl_modreserve((modid_t)a1, (int *)a2);
2316 		break;
2317 
2318 	case MODSETMINIROOT:	/* we are running in miniroot */
2319 		isminiroot = 1;
2320 		error = 0;
2321 		break;
2322 
2323 	case MODADDMAJBIND:	/* add major / driver alias bindings */
2324 		error = modctl_add_driver_aliases((int *)a2);
2325 		break;
2326 
2327 	case MODGETPATHLEN:	/* get modpath length */
2328 		error = modctl_getmodpathlen((int *)a2);
2329 		break;
2330 
2331 	case MODGETPATH:	/* get modpath */
2332 		error = modctl_getmodpath((char *)a2);
2333 		break;
2334 
2335 	case MODREADSYSBIND:	/* read system call binding file */
2336 		error = modctl_read_sysbinding_file();
2337 		break;
2338 
2339 	case MODGETMAJBIND:	/* get major number for named device */
2340 		error = modctl_getmaj((char *)a1, (uint_t)a2, (int *)a3);
2341 		break;
2342 
2343 	case MODGETNAME:	/* get name of device given major number */
2344 		error = modctl_getname((char *)a1, (uint_t)a2, (int *)a3);
2345 		break;
2346 
2347 	case MODDEVT2INSTANCE:
2348 		if (get_udatamodel() == DATAMODEL_NATIVE) {
2349 			dev = (dev_t)a1;
2350 		}
2351 #ifdef _SYSCALL32_IMPL
2352 		else {
2353 			dev = expldev(a1);
2354 		}
2355 #endif
2356 		error = modctl_devt2instance(dev, (int *)a2);
2357 		break;
2358 
2359 	case MODSIZEOF_DEVID:	/* sizeof device id of device given dev_t */
2360 		if (get_udatamodel() == DATAMODEL_NATIVE) {
2361 			dev = (dev_t)a1;
2362 		}
2363 #ifdef _SYSCALL32_IMPL
2364 		else {
2365 			dev = expldev(a1);
2366 		}
2367 #endif
2368 		error = modctl_sizeof_devid(dev, (uint_t *)a2);
2369 		break;
2370 
2371 	case MODGETDEVID:	/* get device id of device given dev_t */
2372 		if (get_udatamodel() == DATAMODEL_NATIVE) {
2373 			dev = (dev_t)a1;
2374 		}
2375 #ifdef _SYSCALL32_IMPL
2376 		else {
2377 			dev = expldev(a1);
2378 		}
2379 #endif
2380 		error = modctl_get_devid(dev, (uint_t)a2, (ddi_devid_t)a3);
2381 		break;
2382 
2383 	case MODSIZEOF_MINORNAME:	/* sizeof minor nm (dev_t,spectype) */
2384 		if (get_udatamodel() == DATAMODEL_NATIVE) {
2385 			error = modctl_sizeof_minorname((dev_t)a1, (int)a2,
2386 			    (uint_t *)a3);
2387 		}
2388 #ifdef _SYSCALL32_IMPL
2389 		else {
2390 			error = modctl_sizeof_minorname(expldev(a1), (int)a2,
2391 			    (uint_t *)a3);
2392 		}
2393 
2394 #endif
2395 		break;
2396 
2397 	case MODGETMINORNAME:		/* get minor name of (dev_t,spectype) */
2398 		if (get_udatamodel() == DATAMODEL_NATIVE) {
2399 			error = modctl_get_minorname((dev_t)a1, (int)a2,
2400 			    (uint_t)a3, (char *)a4);
2401 		}
2402 #ifdef _SYSCALL32_IMPL
2403 		else {
2404 			error = modctl_get_minorname(expldev(a1), (int)a2,
2405 			    (uint_t)a3, (char *)a4);
2406 		}
2407 #endif
2408 		break;
2409 
2410 	case MODGETDEVFSPATH_LEN:	/* sizeof path nm of (dev_t,spectype) */
2411 		if (get_udatamodel() == DATAMODEL_NATIVE) {
2412 			error = modctl_devfspath_len((dev_t)a1, (int)a2,
2413 			    (uint_t *)a3);
2414 		}
2415 #ifdef _SYSCALL32_IMPL
2416 		else {
2417 			error = modctl_devfspath_len(expldev(a1), (int)a2,
2418 			    (uint_t *)a3);
2419 		}
2420 
2421 #endif
2422 		break;
2423 
2424 	case MODGETDEVFSPATH:   	/* get path name of (dev_t,spec) type */
2425 		if (get_udatamodel() == DATAMODEL_NATIVE) {
2426 			error = modctl_devfspath((dev_t)a1, (int)a2,
2427 			    (uint_t)a3, (char *)a4);
2428 		}
2429 #ifdef _SYSCALL32_IMPL
2430 		else {
2431 			error = modctl_devfspath(expldev(a1), (int)a2,
2432 			    (uint_t)a3, (char *)a4);
2433 		}
2434 #endif
2435 		break;
2436 
2437 	case MODGETDEVFSPATH_MI_LEN:	/* sizeof path nm of (major,instance) */
2438 		error = modctl_devfspath_mi_len((major_t)a1, (int)a2,
2439 		    (uint_t *)a3);
2440 		break;
2441 
2442 	case MODGETDEVFSPATH_MI:   	/* get path name of (major,instance) */
2443 		error = modctl_devfspath_mi((major_t)a1, (int)a2,
2444 		    (uint_t)a3, (char *)a4);
2445 		break;
2446 
2447 
2448 	case MODEVENTS:
2449 		error = modctl_modevents((int)a1, a2, a3, a4, (uint_t)a5);
2450 		break;
2451 
2452 	case MODGETFBNAME:	/* get the framebuffer name */
2453 		error = modctl_get_fbname((char *)a1);
2454 		break;
2455 
2456 	case MODREREADDACF:	/* reread dacf rule database from given file */
2457 		error = modctl_reread_dacf((char *)a1);
2458 		break;
2459 
2460 	case MODLOADDRVCONF:	/* load driver.conf file for major */
2461 		error = modctl_load_drvconf((major_t)a1, (int)a2);
2462 		break;
2463 
2464 	case MODUNLOADDRVCONF:	/* unload driver.conf file for major */
2465 		error = modctl_unload_drvconf((major_t)a1);
2466 		break;
2467 
2468 	case MODREMMAJBIND:	/* remove a major binding */
2469 		error = modctl_rem_major((major_t)a1);
2470 		break;
2471 
2472 	case MODREMDRVALIAS:	/* remove a major/alias binding */
2473 		error = modctl_remove_driver_aliases((int *)a2);
2474 		break;
2475 
2476 	case MODDEVID2PATHS:	/* get paths given devid */
2477 		error = modctl_devid2paths((ddi_devid_t)a1, (char *)a2,
2478 		    (uint_t)a3, (size_t *)a4, (char *)a5);
2479 		break;
2480 
2481 	case MODSETDEVPOLICY:	/* establish device policy */
2482 		error = devpolicy_load((int)a1, (size_t)a2, (devplcysys_t *)a3);
2483 		break;
2484 
2485 	case MODGETDEVPOLICY:	/* get device policy */
2486 		error = devpolicy_get((int *)a1, (size_t)a2,
2487 		    (devplcysys_t *)a3);
2488 		break;
2489 
2490 	case MODALLOCPRIV:
2491 		error = modctl_allocpriv((const char *)a1);
2492 		break;
2493 
2494 	case MODGETDEVPOLICYBYNAME:
2495 		error = devpolicy_getbyname((size_t)a1,
2496 		    (devplcysys_t *)a2, (char *)a3);
2497 		break;
2498 
2499 	case MODLOADMINORPERM:
2500 	case MODADDMINORPERM:
2501 	case MODREMMINORPERM:
2502 		error = modctl_minorperm(cmd, (char *)a1, (size_t)a2);
2503 		break;
2504 
2505 	case MODREMDRVCLEANUP:
2506 		error = modctl_remdrv_cleanup((const char *)a1);
2507 		break;
2508 
2509 	case MODDEVEXISTS:	/* non-reconfiguring /dev lookup */
2510 		error = modctl_devexists((const char *)a1, (size_t)a2);
2511 		break;
2512 
2513 	case MODDEVREADDIR:	/* non-reconfiguring /dev readdir */
2514 		error = modctl_devreaddir((const char *)a1, (size_t)a2,
2515 		    (char *)a3, (int64_t *)a4);
2516 		break;
2517 
2518 	case MODDEVEMPTYDIR:	/* non-reconfiguring /dev emptydir */
2519 		error = modctl_devemptydir((const char *)a1, (size_t)a2,
2520 		    (int *)a3);
2521 		break;
2522 
2523 	case MODDEVNAME:
2524 		error = modctl_moddevname((int)a1, a2, a3);
2525 		break;
2526 
2527 	case MODRETIRE:	/* retire device named by physpath a1 */
2528 		error = modctl_retire((char *)a1, (char *)a2, (size_t)a3);
2529 		break;
2530 
2531 	case MODISRETIRED:  /* check if a device is retired. */
2532 		error = modctl_is_retired((char *)a1, (int *)a2);
2533 		break;
2534 
2535 	case MODUNRETIRE:	/* unretire device named by physpath a1 */
2536 		error = modctl_unretire((char *)a1);
2537 		break;
2538 
2539 	default:
2540 		error = EINVAL;
2541 		break;
2542 	}
2543 
2544 	return (error ? set_errno(error) : 0);
2545 }
2546 
2547 /*
2548  * Calls to kobj_load_module()() are handled off to this routine in a
2549  * separate thread.
2550  */
2551 static void
2552 modload_thread(struct loadmt *ltp)
2553 {
2554 	/* load the module and signal the creator of this thread */
2555 	kmutex_t	cpr_lk;
2556 	callb_cpr_t	cpr_i;
2557 
2558 	mutex_init(&cpr_lk, NULL, MUTEX_DEFAULT, NULL);
2559 	CALLB_CPR_INIT(&cpr_i, &cpr_lk, callb_generic_cpr, "modload");
2560 	/* borrow the devi lock from thread which invoked us */
2561 	pm_borrow_lock(ltp->owner);
2562 	ltp->retval = kobj_load_module(ltp->mp, ltp->usepath);
2563 	pm_return_lock();
2564 	sema_v(&ltp->sema);
2565 	mutex_enter(&cpr_lk);
2566 	CALLB_CPR_EXIT(&cpr_i);
2567 	mutex_destroy(&cpr_lk);
2568 	thread_exit();
2569 }
2570 
2571 /*
2572  * load a module, adding a reference if caller specifies rmodp.  If rmodp
2573  * is specified then an errno is returned, otherwise a module index is
2574  * returned (-1 on error).
2575  */
2576 static int
2577 modrload(const char *subdir, const char *filename, struct modctl **rmodp)
2578 {
2579 	struct modctl *modp;
2580 	size_t size;
2581 	char *fullname;
2582 	int retval = EINVAL;
2583 	int id = -1;
2584 
2585 	if (rmodp)
2586 		*rmodp = NULL;			/* avoid garbage */
2587 
2588 	if (subdir != NULL) {
2589 		/*
2590 		 * refuse / in filename to prevent "../" escapes.
2591 		 */
2592 		if (strchr(filename, '/') != NULL)
2593 			return (rmodp ? retval : id);
2594 
2595 		/*
2596 		 * allocate enough space for <subdir>/<filename><NULL>
2597 		 */
2598 		size = strlen(subdir) + strlen(filename) + 2;
2599 		fullname = kmem_zalloc(size, KM_SLEEP);
2600 		(void) sprintf(fullname, "%s/%s", subdir, filename);
2601 	} else {
2602 		fullname = (char *)filename;
2603 	}
2604 
2605 	modp = mod_hold_installed_mod(fullname, 1, 0, &retval);
2606 	if (modp != NULL) {
2607 		id = modp->mod_id;
2608 		if (rmodp) {
2609 			/* add mod_ref and return *rmodp */
2610 			mutex_enter(&mod_lock);
2611 			modp->mod_ref++;
2612 			mutex_exit(&mod_lock);
2613 			*rmodp = modp;
2614 		}
2615 		mod_release_mod(modp);
2616 		CPU_STATS_ADDQ(CPU, sys, modload, 1);
2617 	}
2618 
2619 done:	if (subdir != NULL)
2620 		kmem_free(fullname, size);
2621 	return (rmodp ? retval : id);
2622 }
2623 
2624 /*
2625  * This is the primary kernel interface to load a module. It loads and
2626  * installs the named module.  It does not hold mod_ref of the module, so
2627  * a module unload attempt can occur at any time - it is up to the
2628  * _fini/mod_remove implementation to determine if unload will succeed.
2629  */
2630 int
2631 modload(const char *subdir, const char *filename)
2632 {
2633 	return (modrload(subdir, filename, NULL));
2634 }
2635 
2636 /*
2637  * Load a module using a series of qualified names from most specific to least
2638  * specific, e.g. for subdir "foo", p1 "bar", p2 "baz", we might try:
2639  *			Value returned in *chosen
2640  * foo/bar.baz.1.2.3	3
2641  * foo/bar.baz.1.2	2
2642  * foo/bar.baz.1	1
2643  * foo/bar.baz		0
2644  *
2645  * Return the module ID on success; -1 if no module was loaded.  On success
2646  * and if 'chosen' is not NULL we also return the number of suffices that
2647  * were in the module we chose to load.
2648  */
2649 int
2650 modload_qualified(const char *subdir, const char *p1,
2651     const char *p2, const char *delim, uint_t suffv[], int suffc, int *chosen)
2652 {
2653 	char path[MOD_MAXPATH];
2654 	size_t n, resid = sizeof (path);
2655 	char *p = path;
2656 
2657 	char **dotv;
2658 	int i, rc, id;
2659 	modctl_t *mp;
2660 
2661 	if (p2 != NULL)
2662 		n = snprintf(p, resid, "%s/%s%s%s", subdir, p1, delim, p2);
2663 	else
2664 		n = snprintf(p, resid, "%s/%s", subdir, p1);
2665 
2666 	if (n >= resid)
2667 		return (-1);
2668 
2669 	p += n;
2670 	resid -= n;
2671 	dotv = kmem_alloc(sizeof (char *) * (suffc + 1), KM_SLEEP);
2672 
2673 	for (i = 0; i < suffc; i++) {
2674 		dotv[i] = p;
2675 		n = snprintf(p, resid, "%s%u", delim, suffv[i]);
2676 
2677 		if (n >= resid) {
2678 			kmem_free(dotv, sizeof (char *) * (suffc + 1));
2679 			return (-1);
2680 		}
2681 
2682 		p += n;
2683 		resid -= n;
2684 	}
2685 
2686 	dotv[suffc] = p;
2687 
2688 	for (i = suffc; i >= 0; i--) {
2689 		dotv[i][0] = '\0';
2690 		mp = mod_hold_installed_mod(path, 1, 1, &rc);
2691 
2692 		if (mp != NULL) {
2693 			kmem_free(dotv, sizeof (char *) * (suffc + 1));
2694 			id = mp->mod_id;
2695 			mod_release_mod(mp);
2696 			if (chosen != NULL)
2697 				*chosen = i;
2698 			return (id);
2699 		}
2700 	}
2701 
2702 	kmem_free(dotv, sizeof (char *) * (suffc + 1));
2703 	return (-1);
2704 }
2705 
2706 /*
2707  * Load a module.
2708  */
2709 int
2710 modloadonly(const char *subdir, const char *filename)
2711 {
2712 	struct modctl *modp;
2713 	char *fullname;
2714 	size_t size;
2715 	int id, retval;
2716 
2717 	if (subdir != NULL) {
2718 		/*
2719 		 * allocate enough space for <subdir>/<filename><NULL>
2720 		 */
2721 		size = strlen(subdir) + strlen(filename) + 2;
2722 		fullname = kmem_zalloc(size, KM_SLEEP);
2723 		(void) sprintf(fullname, "%s/%s", subdir, filename);
2724 	} else {
2725 		fullname = (char *)filename;
2726 	}
2727 
2728 	modp = mod_hold_loaded_mod(NULL, fullname, &retval);
2729 	if (modp) {
2730 		id = modp->mod_id;
2731 		mod_release_mod(modp);
2732 	}
2733 
2734 	if (subdir != NULL)
2735 		kmem_free(fullname, size);
2736 
2737 	if (retval == 0)
2738 		return (id);
2739 	return (-1);
2740 }
2741 
2742 /*
2743  * Try to uninstall and unload a module, removing a reference if caller
2744  * specifies rmodp.
2745  */
2746 static int
2747 modunrload(modid_t id, struct modctl **rmodp, int unload)
2748 {
2749 	struct modctl	*modp;
2750 	int		retval;
2751 
2752 	if (rmodp)
2753 		*rmodp = NULL;			/* avoid garbage */
2754 
2755 	if ((modp = mod_hold_by_id((modid_t)id)) == NULL)
2756 		return (EINVAL);
2757 
2758 	if (rmodp) {
2759 		mutex_enter(&mod_lock);
2760 		modp->mod_ref--;
2761 		mutex_exit(&mod_lock);
2762 		*rmodp = modp;
2763 	}
2764 
2765 	if (unload) {
2766 		retval = moduninstall(modp);
2767 		if (retval == 0) {
2768 			mod_unload(modp);
2769 			CPU_STATS_ADDQ(CPU, sys, modunload, 1);
2770 		} else if (retval == EALREADY)
2771 			retval = 0;	/* already unloaded, not an error */
2772 	} else
2773 		retval = 0;
2774 
2775 	mod_release_mod(modp);
2776 	return (retval);
2777 }
2778 
2779 /*
2780  * Uninstall and unload a module.
2781  */
2782 int
2783 modunload(modid_t id)
2784 {
2785 	int		retval;
2786 
2787 	/* synchronize with any active modunload_disable() */
2788 	modunload_begin();
2789 	if (ddi_root_node())
2790 		(void) devfs_clean(ddi_root_node(), NULL, 0);
2791 	retval = modunrload(id, NULL, 1);
2792 	modunload_end();
2793 	return (retval);
2794 }
2795 
2796 /*
2797  * Return status of a loaded module.
2798  */
2799 static int
2800 modinfo(modid_t id, struct modinfo *modinfop)
2801 {
2802 	struct modctl	*modp;
2803 	modid_t		mid;
2804 	int		i;
2805 
2806 	mid = modinfop->mi_id;
2807 	if (modinfop->mi_info & MI_INFO_ALL) {
2808 		while ((modp = mod_hold_next_by_id(mid++)) != NULL) {
2809 			if ((modinfop->mi_info & MI_INFO_CNT) ||
2810 			    modp->mod_installed)
2811 				break;
2812 			mod_release_mod(modp);
2813 		}
2814 		if (modp == NULL)
2815 			return (EINVAL);
2816 	} else {
2817 		modp = mod_hold_by_id(id);
2818 		if (modp == NULL)
2819 			return (EINVAL);
2820 		if (!(modinfop->mi_info & MI_INFO_CNT) &&
2821 		    (modp->mod_installed == 0)) {
2822 			mod_release_mod(modp);
2823 			return (EINVAL);
2824 		}
2825 	}
2826 
2827 	modinfop->mi_rev = 0;
2828 	modinfop->mi_state = 0;
2829 	for (i = 0; i < MODMAXLINK; i++) {
2830 		modinfop->mi_msinfo[i].msi_p0 = -1;
2831 		modinfop->mi_msinfo[i].msi_linkinfo[0] = 0;
2832 	}
2833 	if (modp->mod_loaded) {
2834 		modinfop->mi_state = MI_LOADED;
2835 		kobj_getmodinfo(modp->mod_mp, modinfop);
2836 	}
2837 	if (modp->mod_installed) {
2838 		modinfop->mi_state |= MI_INSTALLED;
2839 
2840 		(void) mod_getinfo(modp, modinfop);
2841 	}
2842 
2843 	modinfop->mi_id = modp->mod_id;
2844 	modinfop->mi_loadcnt = modp->mod_loadcnt;
2845 	(void) strcpy(modinfop->mi_name, modp->mod_modname);
2846 
2847 	mod_release_mod(modp);
2848 	return (0);
2849 }
2850 
2851 static char mod_stub_err[] = "mod_hold_stub: Couldn't load stub module %s";
2852 static char no_err[] = "No error function for weak stub %s";
2853 
2854 /*
2855  * used by the stubs themselves to load and hold a module.
2856  * Returns  0 if the module is successfully held;
2857  *	    the stub needs to call mod_release_stub().
2858  *	    -1 if the stub should just call the err_fcn.
2859  * Note that this code is stretched out so that we avoid subroutine calls
2860  * and optimize for the most likely case.  That is, the case where the
2861  * module is loaded and installed and not held.  In that case we just inc
2862  * the mod_ref count and continue.
2863  */
2864 int
2865 mod_hold_stub(struct mod_stub_info *stub)
2866 {
2867 	struct modctl *mp;
2868 	struct mod_modinfo *mip;
2869 
2870 	mip = stub->mods_modinfo;
2871 
2872 	mutex_enter(&mod_lock);
2873 
2874 	/* we do mod_hold_by_modctl inline for speed */
2875 
2876 mod_check_again:
2877 	if ((mp = mip->mp) != NULL) {
2878 		if (mp->mod_busy == 0) {
2879 			if (mp->mod_installed) {
2880 				/* increment the reference count */
2881 				mp->mod_ref++;
2882 				ASSERT(mp->mod_ref && mp->mod_installed);
2883 				mutex_exit(&mod_lock);
2884 				return (0);
2885 			} else {
2886 				mp->mod_busy = 1;
2887 				mp->mod_inprogress_thread =
2888 				    (curthread == NULL ?
2889 				    (kthread_id_t)-1 : curthread);
2890 			}
2891 		} else {
2892 			/*
2893 			 * wait one time and then go see if someone
2894 			 * else has resolved the stub (set mip->mp).
2895 			 */
2896 			if (mod_hold_by_modctl(mp,
2897 			    MOD_WAIT_ONCE | MOD_LOCK_HELD))
2898 				goto mod_check_again;
2899 
2900 			/*
2901 			 * what we have now may have been unloaded!, in
2902 			 * that case, mip->mp will be NULL, we'll hit this
2903 			 * module and load again..
2904 			 */
2905 			cmn_err(CE_PANIC, "mod_hold_stub should have blocked");
2906 		}
2907 		mutex_exit(&mod_lock);
2908 	} else {
2909 		/* first time we've hit this module */
2910 		mutex_exit(&mod_lock);
2911 		mp = mod_hold_by_name(mip->modm_module_name);
2912 		mip->mp = mp;
2913 	}
2914 
2915 	/*
2916 	 * If we are here, it means that the following conditions
2917 	 * are satisfied.
2918 	 *
2919 	 * mip->mp != NULL
2920 	 * this thread has set the mp->mod_busy = 1
2921 	 * mp->mod_installed = 0
2922 	 *
2923 	 */
2924 	ASSERT(mp != NULL);
2925 	ASSERT(mp->mod_busy == 1);
2926 
2927 	if (mp->mod_installed == 0) {
2928 		/* Module not loaded, if weak stub don't load it */
2929 		if (stub->mods_flag & MODS_WEAK) {
2930 			if (stub->mods_errfcn == NULL) {
2931 				mod_release_mod(mp);
2932 				cmn_err(CE_PANIC, no_err,
2933 				    mip->modm_module_name);
2934 			}
2935 		} else {
2936 			/* Not a weak stub so load the module */
2937 
2938 			if (mod_load(mp, 1) != 0 || modinstall(mp) != 0) {
2939 				/*
2940 				 * If mod_load() was successful
2941 				 * and modinstall() failed, then
2942 				 * unload the module.
2943 				 */
2944 				if (mp->mod_loaded)
2945 					mod_unload(mp);
2946 
2947 				mod_release_mod(mp);
2948 				if (stub->mods_errfcn == NULL) {
2949 					cmn_err(CE_PANIC, mod_stub_err,
2950 					    mip->modm_module_name);
2951 				} else {
2952 					return (-1);
2953 				}
2954 			}
2955 		}
2956 	}
2957 
2958 	/*
2959 	 * At this point module is held and loaded. Release
2960 	 * the mod_busy and mod_inprogress_thread before
2961 	 * returning. We actually call mod_release() here so
2962 	 * that if another stub wants to access this module,
2963 	 * it can do so. mod_ref is incremented before mod_release()
2964 	 * is called to prevent someone else from snatching the
2965 	 * module from this thread.
2966 	 */
2967 	mutex_enter(&mod_lock);
2968 	mp->mod_ref++;
2969 	ASSERT(mp->mod_ref &&
2970 	    (mp->mod_loaded || (stub->mods_flag & MODS_WEAK)));
2971 	mod_release(mp);
2972 	mutex_exit(&mod_lock);
2973 	return (0);
2974 }
2975 
2976 void
2977 mod_release_stub(struct mod_stub_info *stub)
2978 {
2979 	struct modctl *mp = stub->mods_modinfo->mp;
2980 
2981 	/* inline mod_release_mod */
2982 	mutex_enter(&mod_lock);
2983 	ASSERT(mp->mod_ref &&
2984 	    (mp->mod_loaded || (stub->mods_flag & MODS_WEAK)));
2985 	mp->mod_ref--;
2986 	if (mp->mod_want) {
2987 		mp->mod_want = 0;
2988 		cv_broadcast(&mod_cv);
2989 	}
2990 	mutex_exit(&mod_lock);
2991 }
2992 
2993 static struct modctl *
2994 mod_hold_loaded_mod(struct modctl *dep, char *filename, int *status)
2995 {
2996 	struct modctl *modp;
2997 	int retval;
2998 
2999 	/*
3000 	 * Hold the module.
3001 	 */
3002 	modp = mod_hold_by_name_requisite(dep, filename);
3003 	if (modp) {
3004 		retval = mod_load(modp, 1);
3005 		if (retval != 0) {
3006 			mod_release_mod(modp);
3007 			modp = NULL;
3008 		}
3009 		*status = retval;
3010 	} else {
3011 		*status = ENOSPC;
3012 	}
3013 
3014 	/*
3015 	 * if dep is not NULL, clear the module dependency information.
3016 	 * This information is set in mod_hold_by_name_common().
3017 	 */
3018 	if (dep != NULL && dep->mod_requisite_loading != NULL) {
3019 		ASSERT(dep->mod_busy);
3020 		dep->mod_requisite_loading = NULL;
3021 	}
3022 
3023 	return (modp);
3024 }
3025 
3026 /*
3027  * hold, load, and install the named module
3028  */
3029 static struct modctl *
3030 mod_hold_installed_mod(char *name, int usepath, int forcecheck, int *r)
3031 {
3032 	struct modctl *modp;
3033 	int retval;
3034 
3035 	/*
3036 	 * Verify that that module in question actually exists on disk
3037 	 * before allocation of module structure by mod_hold_by_name.
3038 	 */
3039 	if (modrootloaded && swaploaded || forcecheck) {
3040 		if (!kobj_path_exists(name, usepath)) {
3041 			*r = ENOENT;
3042 			return (NULL);
3043 		}
3044 	}
3045 
3046 	/*
3047 	 * Hold the module.
3048 	 */
3049 	modp = mod_hold_by_name(name);
3050 	if (modp) {
3051 		retval = mod_load(modp, usepath);
3052 		if (retval != 0) {
3053 			mod_release_mod(modp);
3054 			modp = NULL;
3055 			*r = retval;
3056 		} else {
3057 			if ((*r = modinstall(modp)) != 0) {
3058 				/*
3059 				 * We loaded it, but failed to _init() it.
3060 				 * Be kind to developers -- force it
3061 				 * out of memory now so that the next
3062 				 * attempt to use the module will cause
3063 				 * a reload.  See 1093793.
3064 				 */
3065 				mod_unload(modp);
3066 				mod_release_mod(modp);
3067 				modp = NULL;
3068 			}
3069 		}
3070 	} else {
3071 		*r = ENOSPC;
3072 	}
3073 	return (modp);
3074 }
3075 
3076 static char mod_excl_msg[] =
3077 	"module %s(%s) is EXCLUDED and will not be loaded\n";
3078 static char mod_init_msg[] = "loadmodule:%s(%s): _init() error %d\n";
3079 
3080 /*
3081  * This routine is needed for dependencies.  Users specify dependencies
3082  * by declaring a character array initialized to filenames of dependents.
3083  * So the code that handles dependents deals with filenames (and not
3084  * module names) because that's all it has.  We load by filename and once
3085  * we've loaded a file we can get the module name.
3086  * Unfortunately there isn't a single unified filename/modulename namespace.
3087  * C'est la vie.
3088  *
3089  * We allow the name being looked up to be prepended by an optional
3090  * subdirectory e.g. we can lookup (NULL, "fs/ufs") or ("fs", "ufs")
3091  */
3092 struct modctl *
3093 mod_find_by_filename(char *subdir, char *filename)
3094 {
3095 	struct modctl	*mp;
3096 	size_t		sublen;
3097 
3098 	ASSERT(!MUTEX_HELD(&mod_lock));
3099 	if (subdir != NULL)
3100 		sublen = strlen(subdir);
3101 	else
3102 		sublen = 0;
3103 
3104 	mutex_enter(&mod_lock);
3105 	mp = &modules;
3106 	do {
3107 		if (sublen) {
3108 			char *mod_filename = mp->mod_filename;
3109 
3110 			if (strncmp(subdir, mod_filename, sublen) == 0 &&
3111 			    mod_filename[sublen] == '/' &&
3112 			    strcmp(filename, &mod_filename[sublen + 1]) == 0) {
3113 				mutex_exit(&mod_lock);
3114 				return (mp);
3115 			}
3116 		} else if (strcmp(filename, mp->mod_filename) == 0) {
3117 			mutex_exit(&mod_lock);
3118 			return (mp);
3119 		}
3120 	} while ((mp = mp->mod_next) != &modules);
3121 	mutex_exit(&mod_lock);
3122 	return (NULL);
3123 }
3124 
3125 /*
3126  * Check for circular dependencies.  This is called from do_dependents()
3127  * in kobj.c.  If we are the thread already loading this module, then
3128  * we're trying to load a dependent that we're already loading which
3129  * means the user specified circular dependencies.
3130  */
3131 static int
3132 mod_circdep(struct modctl *modp)
3133 {
3134 	struct modctl	*rmod;
3135 
3136 	ASSERT(MUTEX_HELD(&mod_lock));
3137 
3138 	/*
3139 	 * Check the mod_inprogress_thread first.
3140 	 * mod_inprogress_thread is used in mod_hold_stub()
3141 	 * directly to improve performance.
3142 	 */
3143 	if (modp->mod_inprogress_thread == curthread)
3144 		return (1);
3145 
3146 	/*
3147 	 * Check the module circular dependencies.
3148 	 */
3149 	for (rmod = modp; rmod != NULL; rmod = rmod->mod_requisite_loading) {
3150 		/*
3151 		 * Check if there is a module circular dependency.
3152 		 */
3153 		if (rmod->mod_requisite_loading == modp)
3154 			return (1);
3155 	}
3156 	return (0);
3157 }
3158 
3159 static int
3160 mod_getinfo(struct modctl *modp, struct modinfo *modinfop)
3161 {
3162 	int (*func)(struct modinfo *);
3163 	int retval;
3164 
3165 	ASSERT(modp->mod_busy);
3166 
3167 	/* primary modules don't do getinfo */
3168 	if (modp->mod_prim)
3169 		return (0);
3170 
3171 	func = (int (*)(struct modinfo *))kobj_lookup(modp->mod_mp, "_info");
3172 
3173 	if (kobj_addrcheck(modp->mod_mp, (caddr_t)func)) {
3174 		cmn_err(CE_WARN, "_info() not defined properly in %s",
3175 		    modp->mod_filename);
3176 		/*
3177 		 * The semantics of mod_info(9F) are that 0 is failure
3178 		 * and non-zero is success.
3179 		 */
3180 		retval = 0;
3181 	} else
3182 		retval = (*func)(modinfop);	/* call _info() function */
3183 
3184 	if (moddebug & MODDEBUG_USERDEBUG)
3185 		printf("Returned from _info, retval = %x\n", retval);
3186 
3187 	return (retval);
3188 }
3189 
3190 static void
3191 modadd(struct modctl *mp)
3192 {
3193 	ASSERT(MUTEX_HELD(&mod_lock));
3194 
3195 	mp->mod_id = last_module_id++;
3196 	mp->mod_next = &modules;
3197 	mp->mod_prev = modules.mod_prev;
3198 	modules.mod_prev->mod_next = mp;
3199 	modules.mod_prev = mp;
3200 }
3201 
3202 /*ARGSUSED*/
3203 static struct modctl *
3204 allocate_modp(const char *filename, const char *modname)
3205 {
3206 	struct modctl *mp;
3207 
3208 	mp = kobj_zalloc(sizeof (*mp), KM_SLEEP);
3209 	mp->mod_modname = kobj_zalloc(strlen(modname) + 1, KM_SLEEP);
3210 	(void) strcpy(mp->mod_modname, modname);
3211 	return (mp);
3212 }
3213 
3214 /*
3215  * Get the value of a symbol.  This is a wrapper routine that
3216  * calls kobj_getsymvalue().  kobj_getsymvalue() may go away but this
3217  * wrapper will prevent callers from noticing.
3218  */
3219 uintptr_t
3220 modgetsymvalue(char *name, int kernelonly)
3221 {
3222 	return (kobj_getsymvalue(name, kernelonly));
3223 }
3224 
3225 /*
3226  * Get the symbol nearest an address.  This is a wrapper routine that
3227  * calls kobj_getsymname().  kobj_getsymname() may go away but this
3228  * wrapper will prevent callers from noticing.
3229  */
3230 char *
3231 modgetsymname(uintptr_t value, ulong_t *offset)
3232 {
3233 	return (kobj_getsymname(value, offset));
3234 }
3235 
3236 /*
3237  * Lookup a symbol in a specified module.  These are wrapper routines that
3238  * call kobj_lookup().  kobj_lookup() may go away but these wrappers will
3239  * prevent callers from noticing.
3240  */
3241 uintptr_t
3242 modlookup(const char *modname, const char *symname)
3243 {
3244 	struct modctl *modp;
3245 	uintptr_t val;
3246 
3247 	if ((modp = mod_hold_by_name(modname)) == NULL)
3248 		return (0);
3249 	val = kobj_lookup(modp->mod_mp, symname);
3250 	mod_release_mod(modp);
3251 	return (val);
3252 }
3253 
3254 uintptr_t
3255 modlookup_by_modctl(modctl_t *modp, const char *symname)
3256 {
3257 	ASSERT(modp->mod_ref > 0 || modp->mod_busy);
3258 
3259 	return (kobj_lookup(modp->mod_mp, symname));
3260 }
3261 
3262 /*
3263  * Ask the user for the name of the system file and the default path
3264  * for modules.
3265  */
3266 void
3267 mod_askparams()
3268 {
3269 	static char s0[64];
3270 	intptr_t fd;
3271 
3272 	if ((fd = kobj_open(systemfile)) != -1L)
3273 		kobj_close(fd);
3274 	else
3275 		systemfile = NULL;
3276 
3277 	/*CONSTANTCONDITION*/
3278 	while (1) {
3279 		printf("Name of system file [%s]:  ",
3280 		    systemfile ? systemfile : "/dev/null");
3281 
3282 		console_gets(s0, sizeof (s0));
3283 
3284 		if (s0[0] == '\0')
3285 			break;
3286 		else if (strcmp(s0, "/dev/null") == 0) {
3287 			systemfile = NULL;
3288 			break;
3289 		} else {
3290 			if ((fd = kobj_open(s0)) != -1L) {
3291 				kobj_close(fd);
3292 				systemfile = s0;
3293 				break;
3294 			}
3295 		}
3296 		printf("can't find file %s\n", s0);
3297 	}
3298 }
3299 
3300 static char loading_msg[] = "loading '%s' id %d\n";
3301 static char load_msg[] = "load '%s' id %d loaded @ 0x%p/0x%p size %d/%d\n";
3302 
3303 /*
3304  * Common code for loading a module (but not installing it).
3305  * Handoff the task of module loading to a separate thread
3306  * with a large stack if possible, since this code may recurse a few times.
3307  * Return zero if there are no errors or an errno value.
3308  */
3309 static int
3310 mod_load(struct modctl *mp, int usepath)
3311 {
3312 	int		retval;
3313 	struct modinfo	*modinfop = NULL;
3314 	struct loadmt	lt;
3315 
3316 	ASSERT(MUTEX_NOT_HELD(&mod_lock));
3317 	ASSERT(mp->mod_busy);
3318 
3319 	if (mp->mod_loaded)
3320 		return (0);
3321 
3322 	if (mod_sysctl(SYS_CHECK_EXCLUDE, mp->mod_modname) != 0 ||
3323 	    mod_sysctl(SYS_CHECK_EXCLUDE, mp->mod_filename) != 0) {
3324 		if (moddebug & MODDEBUG_LOADMSG) {
3325 			printf(mod_excl_msg, mp->mod_filename,
3326 			    mp->mod_modname);
3327 		}
3328 		return (ENXIO);
3329 	}
3330 	if (moddebug & MODDEBUG_LOADMSG2)
3331 		printf(loading_msg, mp->mod_filename, mp->mod_id);
3332 
3333 	if (curthread != &t0) {
3334 		lt.mp = mp;
3335 		lt.usepath = usepath;
3336 		lt.owner = curthread;
3337 		sema_init(&lt.sema, 0, NULL, SEMA_DEFAULT, NULL);
3338 
3339 		/* create thread to hand of call to */
3340 		(void) thread_create(NULL, DEFAULTSTKSZ * 2,
3341 		    modload_thread, &lt, 0, &p0, TS_RUN, maxclsyspri);
3342 
3343 		/* wait for thread to complete kobj_load_module */
3344 		sema_p(&lt.sema);
3345 
3346 		sema_destroy(&lt.sema);
3347 		retval = lt.retval;
3348 	} else
3349 		retval = kobj_load_module(mp, usepath);
3350 
3351 	if (mp->mod_mp) {
3352 		ASSERT(retval == 0);
3353 		mp->mod_loaded = 1;
3354 		mp->mod_loadcnt++;
3355 		if (moddebug & MODDEBUG_LOADMSG) {
3356 			printf(load_msg, mp->mod_filename, mp->mod_id,
3357 			    (void *)((struct module *)mp->mod_mp)->text,
3358 			    (void *)((struct module *)mp->mod_mp)->data,
3359 			    ((struct module *)mp->mod_mp)->text_size,
3360 			    ((struct module *)mp->mod_mp)->data_size);
3361 		}
3362 
3363 		/*
3364 		 * XXX - There should be a better way to get this.
3365 		 */
3366 		modinfop = kmem_zalloc(sizeof (struct modinfo), KM_SLEEP);
3367 		modinfop->mi_info = MI_INFO_LINKAGE;
3368 		if (mod_getinfo(mp, modinfop) == 0)
3369 			mp->mod_linkage = NULL;
3370 		else {
3371 			mp->mod_linkage = (void *)modinfop->mi_base;
3372 			ASSERT(mp->mod_linkage->ml_rev == MODREV_1);
3373 		}
3374 
3375 		/*
3376 		 * DCS: bootstrapping code. If the driver is loaded
3377 		 * before root mount, it is assumed that the driver
3378 		 * may be used before mounting root. In order to
3379 		 * access mappings of global to local minor no.'s
3380 		 * during installation/open of the driver, we load
3381 		 * them into memory here while the BOP_interfaces
3382 		 * are still up.
3383 		 */
3384 		if ((cluster_bootflags & CLUSTER_BOOTED) && !modrootloaded) {
3385 			retval = clboot_modload(mp);
3386 		}
3387 
3388 		kmem_free(modinfop, sizeof (struct modinfo));
3389 		(void) mod_sysctl(SYS_SET_MVAR, (void *)mp);
3390 		retval = install_stubs_by_name(mp, mp->mod_modname);
3391 
3392 		/*
3393 		 * Now that the module is loaded, we need to give DTrace
3394 		 * a chance to notify its providers.  This is done via
3395 		 * the dtrace_modload function pointer.
3396 		 */
3397 		if (strcmp(mp->mod_modname, "dtrace") != 0) {
3398 			struct modctl *dmp = mod_hold_by_name("dtrace");
3399 
3400 			if (dmp != NULL && dtrace_modload != NULL)
3401 				(*dtrace_modload)(mp);
3402 
3403 			mod_release_mod(dmp);
3404 		}
3405 
3406 	} else {
3407 		/*
3408 		 * If load failed then we need to release any requisites
3409 		 * that we had established.
3410 		 */
3411 		ASSERT(retval);
3412 		mod_release_requisites(mp);
3413 
3414 		if (moddebug & MODDEBUG_ERRMSG)
3415 			printf("error loading '%s', error %d\n",
3416 			    mp->mod_filename, retval);
3417 	}
3418 	return (retval);
3419 }
3420 
3421 static char unload_msg[] = "unloading %s, module id %d, loadcnt %d.\n";
3422 
3423 static void
3424 mod_unload(struct modctl *mp)
3425 {
3426 	ASSERT(MUTEX_NOT_HELD(&mod_lock));
3427 	ASSERT(mp->mod_busy);
3428 	ASSERT((mp->mod_loaded && (mp->mod_installed == 0)) &&
3429 	    ((mp->mod_prim == 0) && (mp->mod_ref >= 0)));
3430 
3431 	if (moddebug & MODDEBUG_LOADMSG)
3432 		printf(unload_msg, mp->mod_modname,
3433 		    mp->mod_id, mp->mod_loadcnt);
3434 
3435 	/*
3436 	 * If mod_ref is not zero, it means some modules might still refer
3437 	 * to this module. Then you can't unload this module right now.
3438 	 * Instead, set 1 to mod_delay_unload to notify the system of
3439 	 * unloading this module later when it's not required any more.
3440 	 */
3441 	if (mp->mod_ref > 0) {
3442 		mp->mod_delay_unload = 1;
3443 		if (moddebug & MODDEBUG_LOADMSG2) {
3444 			printf("module %s not unloaded,"
3445 			    " non-zero reference count (%d)",
3446 			    mp->mod_modname, mp->mod_ref);
3447 		}
3448 		return;
3449 	}
3450 
3451 	if (((mp->mod_loaded == 0) || mp->mod_installed) ||
3452 	    (mp->mod_ref || mp->mod_prim)) {
3453 		/*
3454 		 * A DEBUG kernel would ASSERT panic above, the code is broken
3455 		 * if we get this warning.
3456 		 */
3457 		cmn_err(CE_WARN, "mod_unload: %s in incorrect state: %d %d %d",
3458 		    mp->mod_filename, mp->mod_installed, mp->mod_loaded,
3459 		    mp->mod_ref);
3460 		return;
3461 	}
3462 
3463 	/* reset stub functions to call the binder again */
3464 	reset_stubs(mp);
3465 
3466 	/*
3467 	 * mark module as unloaded before the modctl structure is freed.
3468 	 * This is required not to reuse the modctl structure before
3469 	 * the module is marked as unloaded.
3470 	 */
3471 	mp->mod_loaded = 0;
3472 	mp->mod_linkage = NULL;
3473 
3474 	/* free the memory */
3475 	kobj_unload_module(mp);
3476 
3477 	if (mp->mod_delay_unload) {
3478 		mp->mod_delay_unload = 0;
3479 		if (moddebug & MODDEBUG_LOADMSG2) {
3480 			printf("deferred unload of module %s"
3481 			    " (id %d) successful",
3482 			    mp->mod_modname, mp->mod_id);
3483 		}
3484 	}
3485 
3486 	/* release hold on requisites */
3487 	mod_release_requisites(mp);
3488 
3489 	/*
3490 	 * Now that the module is gone, we need to give DTrace a chance to
3491 	 * remove any probes that it may have had in the module.  This is
3492 	 * done via the dtrace_modunload function pointer.
3493 	 */
3494 	if (strcmp(mp->mod_modname, "dtrace") != 0) {
3495 		struct modctl *dmp = mod_hold_by_name("dtrace");
3496 
3497 		if (dmp != NULL && dtrace_modunload != NULL)
3498 			(*dtrace_modunload)(mp);
3499 
3500 		mod_release_mod(dmp);
3501 	}
3502 }
3503 
3504 static int
3505 modinstall(struct modctl *mp)
3506 {
3507 	int val;
3508 	int (*func)(void);
3509 
3510 	ASSERT(MUTEX_NOT_HELD(&mod_lock));
3511 	ASSERT(mp->mod_busy && mp->mod_loaded);
3512 
3513 	if (mp->mod_installed)
3514 		return (0);
3515 	/*
3516 	 * If mod_delay_unload is on, it means the system chose the deferred
3517 	 * unload for this module. Then you can't install this module until
3518 	 * it's unloaded from the system.
3519 	 */
3520 	if (mp->mod_delay_unload)
3521 		return (ENXIO);
3522 
3523 	if (moddebug & MODDEBUG_LOADMSG)
3524 		printf("installing %s, module id %d.\n",
3525 		    mp->mod_modname, mp->mod_id);
3526 
3527 	ASSERT(mp->mod_mp != NULL);
3528 	if (mod_install_requisites(mp) != 0) {
3529 		/*
3530 		 * Note that we can't call mod_unload(mp) here since
3531 		 * if modinstall() was called by mod_install_requisites(),
3532 		 * we won't be able to hold the dependent modules
3533 		 * (otherwise there would be a deadlock).
3534 		 */
3535 		return (ENXIO);
3536 	}
3537 
3538 	if (moddebug & MODDEBUG_ERRMSG) {
3539 		printf("init '%s' id %d loaded @ 0x%p/0x%p size %lu/%lu\n",
3540 		    mp->mod_filename, mp->mod_id,
3541 		    (void *)((struct module *)mp->mod_mp)->text,
3542 		    (void *)((struct module *)mp->mod_mp)->data,
3543 		    ((struct module *)mp->mod_mp)->text_size,
3544 		    ((struct module *)mp->mod_mp)->data_size);
3545 	}
3546 
3547 	func = (int (*)())kobj_lookup(mp->mod_mp, "_init");
3548 
3549 	if (kobj_addrcheck(mp->mod_mp, (caddr_t)func)) {
3550 		cmn_err(CE_WARN, "_init() not defined properly in %s",
3551 		    mp->mod_filename);
3552 		return (EFAULT);
3553 	}
3554 
3555 	if (moddebug & MODDEBUG_USERDEBUG) {
3556 		printf("breakpoint before calling %s:_init()\n",
3557 		    mp->mod_modname);
3558 		if (DEBUGGER_PRESENT)
3559 			debug_enter("_init");
3560 	}
3561 
3562 	ASSERT(MUTEX_NOT_HELD(&mod_lock));
3563 	ASSERT(mp->mod_busy && mp->mod_loaded);
3564 	val = (*func)();		/* call _init */
3565 
3566 	if (moddebug & MODDEBUG_USERDEBUG)
3567 		printf("Returned from _init, val = %x\n", val);
3568 
3569 	if (val == 0) {
3570 		/*
3571 		 * Set the MODS_INSTALLED flag to enable this module
3572 		 * being called now.
3573 		 */
3574 		install_stubs(mp);
3575 		mp->mod_installed = 1;
3576 	} else if (moddebug & MODDEBUG_ERRMSG)
3577 		printf(mod_init_msg, mp->mod_filename, mp->mod_modname, val);
3578 
3579 	return (val);
3580 }
3581 
3582 int	detach_driver_unconfig = 0;
3583 
3584 static int
3585 detach_driver(char *name)
3586 {
3587 	major_t major;
3588 	int error;
3589 
3590 	/*
3591 	 * If being called from mod_uninstall_all() then the appropriate
3592 	 * driver detaches (leaf only) have already been done.
3593 	 */
3594 	if (mod_in_autounload())
3595 		return (0);
3596 
3597 	major = ddi_name_to_major(name);
3598 	if (major == DDI_MAJOR_T_NONE)
3599 		return (0);
3600 
3601 	error = ndi_devi_unconfig_driver(ddi_root_node(),
3602 	    NDI_DETACH_DRIVER | detach_driver_unconfig, major);
3603 	return (error == NDI_SUCCESS ? 0 : -1);
3604 }
3605 
3606 static char finiret_msg[] = "Returned from _fini for %s, status = %x\n";
3607 
3608 static int
3609 moduninstall(struct modctl *mp)
3610 {
3611 	int status = 0;
3612 	int (*func)(void);
3613 
3614 	ASSERT(MUTEX_NOT_HELD(&mod_lock));
3615 	ASSERT(mp->mod_busy);
3616 
3617 	/*
3618 	 * Verify that we need to do something and can uninstall the module.
3619 	 *
3620 	 * If we should not uninstall the module or if the module is not in
3621 	 * the correct state to start an uninstall we return EBUSY to prevent
3622 	 * us from progressing to mod_unload.  If the module has already been
3623 	 * uninstalled and unloaded we return EALREADY.
3624 	 */
3625 	if (mp->mod_prim || mp->mod_ref || mp->mod_nenabled != 0)
3626 		return (EBUSY);
3627 	if ((mp->mod_installed == 0) || (mp->mod_loaded == 0))
3628 		return (EALREADY);
3629 
3630 	/*
3631 	 * To avoid devinfo / module deadlock we must release this module
3632 	 * prior to initiating the detach_driver, otherwise the detach_driver
3633 	 * might deadlock on a devinfo node held by another thread
3634 	 * coming top down and involving the module we have locked.
3635 	 *
3636 	 * When we regrab the module we must reverify that it is OK
3637 	 * to proceed with the uninstall operation.
3638 	 */
3639 	mod_release_mod(mp);
3640 	status = detach_driver(mp->mod_modname);
3641 	(void) mod_hold_by_modctl(mp, MOD_WAIT_FOREVER | MOD_LOCK_NOT_HELD);
3642 
3643 	/* check detach status and reverify state with lock */
3644 	mutex_enter(&mod_lock);
3645 	if ((status != 0) || mp->mod_prim || mp->mod_ref) {
3646 		mutex_exit(&mod_lock);
3647 		return (EBUSY);
3648 	}
3649 	if ((mp->mod_installed == 0) || (mp->mod_loaded == 0)) {
3650 		mutex_exit(&mod_lock);
3651 		return (EALREADY);
3652 	}
3653 	mutex_exit(&mod_lock);
3654 
3655 	if (moddebug & MODDEBUG_LOADMSG2)
3656 		printf("uninstalling %s\n", mp->mod_modname);
3657 
3658 	/*
3659 	 * lookup _fini, return EBUSY if not defined.
3660 	 *
3661 	 * The MODDEBUG_FINI_EBUSY is usefull in resolving leaks in
3662 	 * detach(9E) - it allows bufctl addresses to be resolved.
3663 	 */
3664 	func = (int (*)())kobj_lookup(mp->mod_mp, "_fini");
3665 	if ((func == NULL) || (mp->mod_loadflags & MOD_NOUNLOAD) ||
3666 	    (moddebug & MODDEBUG_FINI_EBUSY))
3667 		return (EBUSY);
3668 
3669 	/* verify that _fini is in this module */
3670 	if (kobj_addrcheck(mp->mod_mp, (caddr_t)func)) {
3671 		cmn_err(CE_WARN, "_fini() not defined properly in %s",
3672 		    mp->mod_filename);
3673 		return (EFAULT);
3674 	}
3675 
3676 	/* call _fini() */
3677 	ASSERT(MUTEX_NOT_HELD(&mod_lock));
3678 	ASSERT(mp->mod_busy && mp->mod_loaded && mp->mod_installed);
3679 
3680 	status = (*func)();
3681 
3682 	if (status == 0) {
3683 		/* _fini returned success, the module is no longer installed */
3684 		if (moddebug & MODDEBUG_LOADMSG)
3685 			printf("uninstalled %s\n", mp->mod_modname);
3686 
3687 		/*
3688 		 * Even though we only set mod_installed to zero here, a zero
3689 		 * return value means we are committed to a code path were
3690 		 * mod_loaded will also end up as zero - we have no other
3691 		 * way to get the module data and bss back to the pre _init
3692 		 * state except a reload. To ensure this, after return,
3693 		 * mod_busy must stay set until mod_loaded is cleared.
3694 		 */
3695 		mp->mod_installed = 0;
3696 
3697 		/*
3698 		 * Clear the MODS_INSTALLED flag not to call functions
3699 		 * in the module directly from now on.
3700 		 */
3701 		uninstall_stubs(mp);
3702 	} else {
3703 		if (moddebug & MODDEBUG_USERDEBUG)
3704 			printf(finiret_msg, mp->mod_filename, status);
3705 		/*
3706 		 * By definition _fini is only allowed to return EBUSY or the
3707 		 * result of mod_remove (EBUSY or EINVAL).  In the off chance
3708 		 * that a driver returns EALREADY we convert this to EINVAL
3709 		 * since to our caller EALREADY means module was already
3710 		 * removed.
3711 		 */
3712 		if (status == EALREADY)
3713 			status = EINVAL;
3714 	}
3715 
3716 	return (status);
3717 }
3718 
3719 /*
3720  * Uninstall all modules.
3721  */
3722 static void
3723 mod_uninstall_all(void)
3724 {
3725 	struct modctl	*mp;
3726 	modid_t		modid = 0;
3727 
3728 	/* synchronize with any active modunload_disable() */
3729 	modunload_begin();
3730 
3731 	/* mark this thread as doing autounloading */
3732 	(void) tsd_set(mod_autounload_key, (void *)1);
3733 
3734 	(void) devfs_clean(ddi_root_node(), NULL, 0);
3735 	(void) ndi_devi_unconfig(ddi_root_node(), NDI_AUTODETACH);
3736 
3737 	while ((mp = mod_hold_next_by_id(modid)) != NULL) {
3738 		modid = mp->mod_id;
3739 		/*
3740 		 * Skip modules with the MOD_NOAUTOUNLOAD flag set
3741 		 */
3742 		if (mp->mod_loadflags & MOD_NOAUTOUNLOAD) {
3743 			mod_release_mod(mp);
3744 			continue;
3745 		}
3746 
3747 		if (moduninstall(mp) == 0) {
3748 			mod_unload(mp);
3749 			CPU_STATS_ADDQ(CPU, sys, modunload, 1);
3750 		}
3751 		mod_release_mod(mp);
3752 	}
3753 
3754 	(void) tsd_set(mod_autounload_key, NULL);
3755 	modunload_end();
3756 }
3757 
3758 /* wait for unloads that have begun before registering disable */
3759 void
3760 modunload_disable(void)
3761 {
3762 	mutex_enter(&modunload_wait_mutex);
3763 	while (modunload_active_count) {
3764 		modunload_wait++;
3765 		cv_wait(&modunload_wait_cv, &modunload_wait_mutex);
3766 		modunload_wait--;
3767 	}
3768 	modunload_disable_count++;
3769 	mutex_exit(&modunload_wait_mutex);
3770 }
3771 
3772 /* mark end of disable and signal waiters */
3773 void
3774 modunload_enable(void)
3775 {
3776 	mutex_enter(&modunload_wait_mutex);
3777 	modunload_disable_count--;
3778 	if ((modunload_disable_count == 0) && modunload_wait)
3779 		cv_broadcast(&modunload_wait_cv);
3780 	mutex_exit(&modunload_wait_mutex);
3781 }
3782 
3783 /* wait for disables to complete before begining unload */
3784 void
3785 modunload_begin()
3786 {
3787 	mutex_enter(&modunload_wait_mutex);
3788 	while (modunload_disable_count) {
3789 		modunload_wait++;
3790 		cv_wait(&modunload_wait_cv, &modunload_wait_mutex);
3791 		modunload_wait--;
3792 	}
3793 	modunload_active_count++;
3794 	mutex_exit(&modunload_wait_mutex);
3795 }
3796 
3797 /* mark end of unload and signal waiters */
3798 void
3799 modunload_end()
3800 {
3801 	mutex_enter(&modunload_wait_mutex);
3802 	modunload_active_count--;
3803 	if ((modunload_active_count == 0) && modunload_wait)
3804 		cv_broadcast(&modunload_wait_cv);
3805 	mutex_exit(&modunload_wait_mutex);
3806 }
3807 
3808 void
3809 mod_uninstall_daemon(void)
3810 {
3811 	callb_cpr_t	cprinfo;
3812 	clock_t		ticks = 0;
3813 
3814 	mod_aul_thread = curthread;
3815 
3816 	CALLB_CPR_INIT(&cprinfo, &mod_uninstall_lock, callb_generic_cpr, "mud");
3817 	for (;;) {
3818 		mutex_enter(&mod_uninstall_lock);
3819 		CALLB_CPR_SAFE_BEGIN(&cprinfo);
3820 		/*
3821 		 * In DEBUG kernels, unheld drivers are uninstalled periodically
3822 		 * every mod_uninstall_interval seconds.  Periodic uninstall can
3823 		 * be disabled by setting mod_uninstall_interval to 0 which is
3824 		 * the default for a non-DEBUG kernel.
3825 		 */
3826 		if (mod_uninstall_interval) {
3827 			ticks = ddi_get_lbolt() +
3828 			    drv_usectohz(mod_uninstall_interval * 1000000);
3829 			(void) cv_timedwait(&mod_uninstall_cv,
3830 			    &mod_uninstall_lock, ticks);
3831 		} else {
3832 			cv_wait(&mod_uninstall_cv, &mod_uninstall_lock);
3833 		}
3834 		/*
3835 		 * The whole daemon is safe for CPR except we don't want
3836 		 * the daemon to run if FREEZE is issued and this daemon
3837 		 * wakes up from the cv_wait above. In this case, it'll be
3838 		 * blocked in CALLB_CPR_SAFE_END until THAW is issued.
3839 		 *
3840 		 * The reason of calling CALLB_CPR_SAFE_BEGIN twice is that
3841 		 * mod_uninstall_lock is used to protect cprinfo and
3842 		 * CALLB_CPR_SAFE_BEGIN assumes that this lock is held when
3843 		 * called.
3844 		 */
3845 		CALLB_CPR_SAFE_END(&cprinfo, &mod_uninstall_lock);
3846 		CALLB_CPR_SAFE_BEGIN(&cprinfo);
3847 		mutex_exit(&mod_uninstall_lock);
3848 		if ((modunload_disable_count == 0) &&
3849 		    ((moddebug & MODDEBUG_NOAUTOUNLOAD) == 0)) {
3850 			mod_uninstall_all();
3851 		}
3852 	}
3853 }
3854 
3855 /*
3856  * Unload all uninstalled modules.
3857  */
3858 void
3859 modreap(void)
3860 {
3861 	mutex_enter(&mod_uninstall_lock);
3862 	cv_broadcast(&mod_uninstall_cv);
3863 	mutex_exit(&mod_uninstall_lock);
3864 }
3865 
3866 /*
3867  * Hold the specified module. This is the module holding primitive.
3868  *
3869  * If MOD_LOCK_HELD then the caller already holds the mod_lock.
3870  *
3871  * Return values:
3872  *	 0 ==> the module is held
3873  *	 1 ==> the module is not held and the MOD_WAIT_ONCE caller needs
3874  *		to determine how to retry.
3875  */
3876 int
3877 mod_hold_by_modctl(struct modctl *mp, int f)
3878 {
3879 	ASSERT((f & (MOD_WAIT_ONCE | MOD_WAIT_FOREVER)) &&
3880 	    ((f & (MOD_WAIT_ONCE | MOD_WAIT_FOREVER)) !=
3881 	    (MOD_WAIT_ONCE | MOD_WAIT_FOREVER)));
3882 	ASSERT((f & (MOD_LOCK_HELD | MOD_LOCK_NOT_HELD)) &&
3883 	    ((f & (MOD_LOCK_HELD | MOD_LOCK_NOT_HELD)) !=
3884 	    (MOD_LOCK_HELD | MOD_LOCK_NOT_HELD)));
3885 	ASSERT((f & MOD_LOCK_NOT_HELD) || MUTEX_HELD(&mod_lock));
3886 
3887 	if (f & MOD_LOCK_NOT_HELD)
3888 		mutex_enter(&mod_lock);
3889 
3890 	while (mp->mod_busy) {
3891 		mp->mod_want = 1;
3892 		cv_wait(&mod_cv, &mod_lock);
3893 		/*
3894 		 * Module may be unloaded by daemon.
3895 		 * Nevertheless, modctl structure is still in linked list
3896 		 * (i.e., off &modules), not freed!
3897 		 * Caller is not supposed to assume "mp" is valid, but there
3898 		 * is no reasonable way to detect this but using
3899 		 * mp->mod_modinfo->mp == NULL check (follow the back pointer)
3900 		 *   (or similar check depending on calling context)
3901 		 * DON'T free modctl structure, it will be very very
3902 		 * problematic.
3903 		 */
3904 		if (f & MOD_WAIT_ONCE) {
3905 			if (f & MOD_LOCK_NOT_HELD)
3906 				mutex_exit(&mod_lock);
3907 			return (1);	/* caller decides how to retry */
3908 		}
3909 	}
3910 
3911 	mp->mod_busy = 1;
3912 	mp->mod_inprogress_thread =
3913 	    (curthread == NULL ? (kthread_id_t)-1 : curthread);
3914 
3915 	if (f & MOD_LOCK_NOT_HELD)
3916 		mutex_exit(&mod_lock);
3917 	return (0);
3918 }
3919 
3920 static struct modctl *
3921 mod_hold_by_name_common(struct modctl *dep, const char *filename)
3922 {
3923 	const char	*modname;
3924 	struct modctl	*mp;
3925 	char		*curname, *newname;
3926 	int		found = 0;
3927 
3928 	mutex_enter(&mod_lock);
3929 
3930 	if ((modname = strrchr(filename, '/')) == NULL)
3931 		modname = filename;
3932 	else
3933 		modname++;
3934 
3935 	mp = &modules;
3936 	do {
3937 		if (strcmp(modname, mp->mod_modname) == 0) {
3938 			found = 1;
3939 			break;
3940 		}
3941 	} while ((mp = mp->mod_next) != &modules);
3942 
3943 	if (found == 0) {
3944 		mp = allocate_modp(filename, modname);
3945 		modadd(mp);
3946 	}
3947 
3948 	/*
3949 	 * if dep is not NULL, set the mp in mod_requisite_loading for
3950 	 * the module circular dependency check. This field is used in
3951 	 * mod_circdep(), but it's cleard in mod_hold_loaded_mod().
3952 	 */
3953 	if (dep != NULL) {
3954 		ASSERT(dep->mod_busy && dep->mod_requisite_loading == NULL);
3955 		dep->mod_requisite_loading = mp;
3956 	}
3957 
3958 	/*
3959 	 * If the module was held, then it must be us who has it held.
3960 	 */
3961 	if (mod_circdep(mp))
3962 		mp = NULL;
3963 	else {
3964 		(void) mod_hold_by_modctl(mp, MOD_WAIT_FOREVER | MOD_LOCK_HELD);
3965 
3966 		/*
3967 		 * If the name hadn't been set or has changed, allocate
3968 		 * space and set it.  Free space used by previous name.
3969 		 *
3970 		 * Do not change the name of primary modules, for primary
3971 		 * modules the mod_filename was allocated in standalone mode:
3972 		 * it is illegal to kobj_alloc in standalone mode and kobj_free
3973 		 * in non-standalone mode.
3974 		 */
3975 		curname = mp->mod_filename;
3976 		if (curname == NULL ||
3977 		    ((mp->mod_prim == 0) &&
3978 		    (curname != filename) &&
3979 		    (modname != filename) &&
3980 		    (strcmp(curname, filename) != 0))) {
3981 			newname = kobj_zalloc(strlen(filename) + 1, KM_SLEEP);
3982 			(void) strcpy(newname, filename);
3983 			mp->mod_filename = newname;
3984 			if (curname != NULL)
3985 				kobj_free(curname, strlen(curname) + 1);
3986 		}
3987 	}
3988 
3989 	mutex_exit(&mod_lock);
3990 	if (mp && moddebug & MODDEBUG_LOADMSG2)
3991 		printf("Holding %s\n", mp->mod_filename);
3992 	if (mp == NULL && moddebug & MODDEBUG_LOADMSG2)
3993 		printf("circular dependency loading %s\n", filename);
3994 	return (mp);
3995 }
3996 
3997 static struct modctl *
3998 mod_hold_by_name_requisite(struct modctl *dep, char *filename)
3999 {
4000 	return (mod_hold_by_name_common(dep, filename));
4001 }
4002 
4003 struct modctl *
4004 mod_hold_by_name(const char *filename)
4005 {
4006 	return (mod_hold_by_name_common(NULL, filename));
4007 }
4008 
4009 struct modctl *
4010 mod_hold_by_id(modid_t modid)
4011 {
4012 	struct modctl	*mp;
4013 	int		found = 0;
4014 
4015 	mutex_enter(&mod_lock);
4016 	mp = &modules;
4017 	do {
4018 		if (mp->mod_id == modid) {
4019 			found = 1;
4020 			break;
4021 		}
4022 	} while ((mp = mp->mod_next) != &modules);
4023 
4024 	if ((found == 0) || mod_circdep(mp))
4025 		mp = NULL;
4026 	else
4027 		(void) mod_hold_by_modctl(mp, MOD_WAIT_FOREVER | MOD_LOCK_HELD);
4028 
4029 	mutex_exit(&mod_lock);
4030 	return (mp);
4031 }
4032 
4033 static struct modctl *
4034 mod_hold_next_by_id(modid_t modid)
4035 {
4036 	struct modctl	*mp;
4037 	int		found = 0;
4038 
4039 	if (modid < -1)
4040 		return (NULL);
4041 
4042 	mutex_enter(&mod_lock);
4043 
4044 	mp = &modules;
4045 	do {
4046 		if (mp->mod_id > modid) {
4047 			found = 1;
4048 			break;
4049 		}
4050 	} while ((mp = mp->mod_next) != &modules);
4051 
4052 	if ((found == 0) || mod_circdep(mp))
4053 		mp = NULL;
4054 	else
4055 		(void) mod_hold_by_modctl(mp, MOD_WAIT_FOREVER | MOD_LOCK_HELD);
4056 
4057 	mutex_exit(&mod_lock);
4058 	return (mp);
4059 }
4060 
4061 static void
4062 mod_release(struct modctl *mp)
4063 {
4064 	ASSERT(MUTEX_HELD(&mod_lock));
4065 	ASSERT(mp->mod_busy);
4066 
4067 	mp->mod_busy = 0;
4068 	mp->mod_inprogress_thread = NULL;
4069 	if (mp->mod_want) {
4070 		mp->mod_want = 0;
4071 		cv_broadcast(&mod_cv);
4072 	}
4073 }
4074 
4075 void
4076 mod_release_mod(struct modctl *mp)
4077 {
4078 	if (moddebug & MODDEBUG_LOADMSG2)
4079 		printf("Releasing %s\n", mp->mod_filename);
4080 	mutex_enter(&mod_lock);
4081 	mod_release(mp);
4082 	mutex_exit(&mod_lock);
4083 }
4084 
4085 modid_t
4086 mod_name_to_modid(char *filename)
4087 {
4088 	char		*modname;
4089 	struct modctl	*mp;
4090 
4091 	mutex_enter(&mod_lock);
4092 
4093 	if ((modname = strrchr(filename, '/')) == NULL)
4094 		modname = filename;
4095 	else
4096 		modname++;
4097 
4098 	mp = &modules;
4099 	do {
4100 		if (strcmp(modname, mp->mod_modname) == 0) {
4101 			mutex_exit(&mod_lock);
4102 			return (mp->mod_id);
4103 		}
4104 	} while ((mp = mp->mod_next) != &modules);
4105 
4106 	mutex_exit(&mod_lock);
4107 	return (-1);
4108 }
4109 
4110 
4111 int
4112 mod_remove_by_name(char *name)
4113 {
4114 	struct modctl *mp;
4115 	int retval;
4116 
4117 	mp = mod_hold_by_name(name);
4118 
4119 	if (mp == NULL)
4120 		return (EINVAL);
4121 
4122 	if (mp->mod_loadflags & MOD_NOAUTOUNLOAD) {
4123 		/*
4124 		 * Do not unload forceloaded modules
4125 		 */
4126 		mod_release_mod(mp);
4127 		return (0);
4128 	}
4129 
4130 	if ((retval = moduninstall(mp)) == 0) {
4131 		mod_unload(mp);
4132 		CPU_STATS_ADDQ(CPU, sys, modunload, 1);
4133 	} else if (retval == EALREADY)
4134 		retval = 0;		/* already unloaded, not an error */
4135 	mod_release_mod(mp);
4136 	return (retval);
4137 }
4138 
4139 /*
4140  * Record that module "dep" is dependent on module "on_mod."
4141  */
4142 static void
4143 mod_make_requisite(struct modctl *dependent, struct modctl *on_mod)
4144 {
4145 	struct modctl_list **pmlnp;	/* previous next pointer */
4146 	struct modctl_list *mlp;
4147 	struct modctl_list *new;
4148 
4149 	ASSERT(dependent->mod_busy && on_mod->mod_busy);
4150 	mutex_enter(&mod_lock);
4151 
4152 	/*
4153 	 * Search dependent's requisite list to see if on_mod is recorded.
4154 	 * List is ordered by id.
4155 	 */
4156 	for (pmlnp = &dependent->mod_requisites, mlp = *pmlnp;
4157 	    mlp; pmlnp = &mlp->modl_next, mlp = *pmlnp)
4158 		if (mlp->modl_modp->mod_id >= on_mod->mod_id)
4159 			break;
4160 
4161 	/* Create and insert if not already recorded */
4162 	if ((mlp == NULL) || (mlp->modl_modp->mod_id != on_mod->mod_id)) {
4163 		new = kobj_zalloc(sizeof (*new), KM_SLEEP);
4164 		new->modl_modp = on_mod;
4165 		new->modl_next = mlp;
4166 		*pmlnp = new;
4167 
4168 		/*
4169 		 * Increment the mod_ref count in our new requisite module.
4170 		 * This is what keeps a module that has other modules
4171 		 * which are dependent on it from being uninstalled and
4172 		 * unloaded. "on_mod"'s mod_ref count decremented in
4173 		 * mod_release_requisites when the "dependent" module
4174 		 * unload is complete.  "on_mod" must be loaded, but may not
4175 		 * yet be installed.
4176 		 */
4177 		on_mod->mod_ref++;
4178 		ASSERT(on_mod->mod_ref && on_mod->mod_loaded);
4179 	}
4180 
4181 	mutex_exit(&mod_lock);
4182 }
4183 
4184 /*
4185  * release the hold associated with mod_make_requisite mod_ref++
4186  * as part of unload.
4187  */
4188 void
4189 mod_release_requisites(struct modctl *modp)
4190 {
4191 	struct modctl_list *modl;
4192 	struct modctl_list *next;
4193 	struct modctl *req;
4194 	struct modctl_list *start = NULL, *mod_garbage;
4195 
4196 	ASSERT(modp->mod_busy);
4197 	ASSERT(!MUTEX_HELD(&mod_lock));
4198 
4199 	mutex_enter(&mod_lock);		/* needed for manipulation of req */
4200 	for (modl = modp->mod_requisites; modl; modl = next) {
4201 		next = modl->modl_next;
4202 		req = modl->modl_modp;
4203 		ASSERT(req->mod_ref >= 1 && req->mod_loaded);
4204 		req->mod_ref--;
4205 
4206 		/*
4207 		 * Check if the module has to be unloaded or not.
4208 		 */
4209 		if (req->mod_ref == 0 && req->mod_delay_unload) {
4210 			struct modctl_list *new;
4211 			/*
4212 			 * Allocate the modclt_list holding the garbage
4213 			 * module which should be unloaded later.
4214 			 */
4215 			new = kobj_zalloc(sizeof (struct modctl_list),
4216 			    KM_SLEEP);
4217 			new->modl_modp = req;
4218 
4219 			if (start == NULL)
4220 				mod_garbage = start = new;
4221 			else {
4222 				mod_garbage->modl_next = new;
4223 				mod_garbage = new;
4224 			}
4225 		}
4226 
4227 		/* free the list as we go */
4228 		kobj_free(modl, sizeof (*modl));
4229 	}
4230 	modp->mod_requisites = NULL;
4231 	mutex_exit(&mod_lock);
4232 
4233 	/*
4234 	 * Unload the garbage modules.
4235 	 */
4236 	for (mod_garbage = start; mod_garbage != NULL; /* nothing */) {
4237 		struct modctl_list *old = mod_garbage;
4238 		struct modctl *mp = mod_garbage->modl_modp;
4239 		ASSERT(mp != NULL);
4240 
4241 		/*
4242 		 * Hold this module until it's unloaded completely.
4243 		 */
4244 		(void) mod_hold_by_modctl(mp,
4245 		    MOD_WAIT_FOREVER | MOD_LOCK_NOT_HELD);
4246 		/*
4247 		 * Check if the module is not unloaded yet and nobody requires
4248 		 * the module. If it's unloaded already or somebody still
4249 		 * requires the module, don't unload it now.
4250 		 */
4251 		if (mp->mod_loaded && mp->mod_ref == 0)
4252 			mod_unload(mp);
4253 		ASSERT((mp->mod_loaded == 0 && mp->mod_delay_unload == 0) ||
4254 		    (mp->mod_ref > 0));
4255 		mod_release_mod(mp);
4256 
4257 		mod_garbage = mod_garbage->modl_next;
4258 		kobj_free(old, sizeof (struct modctl_list));
4259 	}
4260 }
4261 
4262 /*
4263  * Process dependency of the module represented by "dep" on the
4264  * module named by "on."
4265  *
4266  * Called from kobj_do_dependents() to load a module "on" on which
4267  * "dep" depends.
4268  */
4269 struct modctl *
4270 mod_load_requisite(struct modctl *dep, char *on)
4271 {
4272 	struct modctl *on_mod;
4273 	int retval;
4274 
4275 	if ((on_mod = mod_hold_loaded_mod(dep, on, &retval)) != NULL) {
4276 		mod_make_requisite(dep, on_mod);
4277 	} else if (moddebug & MODDEBUG_ERRMSG) {
4278 		printf("error processing %s on which module %s depends\n",
4279 		    on, dep->mod_modname);
4280 	}
4281 	return (on_mod);
4282 }
4283 
4284 static int
4285 mod_install_requisites(struct modctl *modp)
4286 {
4287 	struct modctl_list *modl;
4288 	struct modctl *req;
4289 	int status = 0;
4290 
4291 	ASSERT(MUTEX_NOT_HELD(&mod_lock));
4292 	ASSERT(modp->mod_busy);
4293 
4294 	for (modl = modp->mod_requisites; modl; modl = modl->modl_next) {
4295 		req = modl->modl_modp;
4296 		(void) mod_hold_by_modctl(req,
4297 		    MOD_WAIT_FOREVER | MOD_LOCK_NOT_HELD);
4298 		status = modinstall(req);
4299 		mod_release_mod(req);
4300 
4301 		if (status != 0)
4302 			break;
4303 	}
4304 	return (status);
4305 }
4306 
4307 /*
4308  * returns 1 if this thread is doing autounload, 0 otherwise.
4309  * see mod_uninstall_all.
4310  */
4311 int
4312 mod_in_autounload()
4313 {
4314 	return ((int)(uintptr_t)tsd_get(mod_autounload_key));
4315 }
4316 
4317 /*
4318  * gmatch adapted from libc, stripping the wchar stuff
4319  */
4320 #define	popchar(p, c)	{ \
4321 		c = *p++; \
4322 		if (c == 0) { \
4323 			return (0); \
4324 		} \
4325 	}
4326 
4327 int
4328 gmatch(const char *s, const char *p)
4329 {
4330 	int c, sc;
4331 	int ok, lc, notflag;
4332 
4333 	sc = *s++;
4334 	c = *p++;
4335 	if (c == 0)
4336 		return (sc == c);	/* nothing matches nothing */
4337 
4338 	switch (c) {
4339 	case '\\':
4340 		/* skip to quoted character */
4341 		popchar(p, c);
4342 		/*FALLTHRU*/
4343 
4344 	default:
4345 		/* straight comparison */
4346 		if (c != sc)
4347 			return (0);
4348 		/*FALLTHRU*/
4349 
4350 	case '?':
4351 		/* first char matches, move to remainder */
4352 		return (sc != '\0' ? gmatch(s, p) : 0);
4353 
4354 
4355 	case '*':
4356 		while (*p == '*')
4357 			p++;
4358 
4359 		/* * matches everything */
4360 		if (*p == 0)
4361 			return (1);
4362 
4363 		/* undo skip at the beginning & iterate over substrings */
4364 		--s;
4365 		while (*s) {
4366 			if (gmatch(s, p))
4367 				return (1);
4368 			s++;
4369 		}
4370 		return (0);
4371 
4372 	case '[':
4373 		/* match any char within [] */
4374 		if (sc == 0)
4375 			return (0);
4376 
4377 		ok = lc = notflag = 0;
4378 
4379 		if (*p == '!') {
4380 			notflag = 1;
4381 			p++;
4382 		}
4383 		popchar(p, c);
4384 
4385 		do {
4386 			if (c == '-' && lc && *p != ']') {
4387 				/* test sc against range [c1-c2] */
4388 				popchar(p, c);
4389 				if (c == '\\') {
4390 					popchar(p, c);
4391 				}
4392 
4393 				if (notflag) {
4394 					/* return 0 on mismatch */
4395 					if (lc <= sc && sc <= c)
4396 						return (0);
4397 					ok++;
4398 				} else if (lc <= sc && sc <= c) {
4399 					ok++;
4400 				}
4401 				/* keep going, may get a match next */
4402 			} else if (c == '\\') {
4403 				/* skip to quoted character */
4404 				popchar(p, c);
4405 			}
4406 			lc = c;
4407 			if (notflag) {
4408 				if (sc == lc)
4409 					return (0);
4410 				ok++;
4411 			} else if (sc == lc) {
4412 				ok++;
4413 			}
4414 			popchar(p, c);
4415 		} while (c != ']');
4416 
4417 		/* recurse on remainder of string */
4418 		return (ok ? gmatch(s, p) : 0);
4419 	}
4420 	/*NOTREACHED*/
4421 }
4422 
4423 
4424 /*
4425  * Get default perm for device from /etc/minor_perm. Return 0 if match found.
4426  *
4427  * Pure wild-carded patterns are handled separately so the ordering of
4428  * these patterns doesn't matter.  We're still dependent on ordering
4429  * however as the first matching entry is the one returned.
4430  * Not ideal but all existing examples and usage do imply this
4431  * ordering implicitly.
4432  *
4433  * Drivers using the clone driver are always good for some entertainment.
4434  * Clone nodes under pseudo have the form clone@0:<driver>.  Some minor
4435  * perm entries have the form clone:<driver>, others use <driver>:*
4436  * Examples are clone:llc1 vs. llc2:*, for example.
4437  *
4438  * Minor perms in the clone:<driver> form are mapped to the drivers's
4439  * mperm list, not the clone driver, as wildcard entries for clone
4440  * reference only.  In other words, a clone wildcard will match
4441  * references for clone@0:<driver> but never <driver>@<minor>.
4442  *
4443  * Additional minor perms in the standard form are also supported,
4444  * for mixed usage, ie a node with an entry clone:<driver> could
4445  * provide further entries <driver>:<minor>.
4446  *
4447  * Finally, some uses of clone use an alias as the minor name rather
4448  * than the driver name, with the alias as the minor perm entry.
4449  * This case is handled by attaching the driver to bring its
4450  * minor list into existence, then discover the alias via DDI_ALIAS.
4451  * The clone device's minor perm list can then be searched for
4452  * that alias.
4453  */
4454 
4455 static int
4456 dev_alias_minorperm(dev_info_t *dip, char *minor_name, mperm_t *rmp)
4457 {
4458 	major_t			major;
4459 	struct devnames		*dnp;
4460 	mperm_t			*mp;
4461 	char			*alias = NULL;
4462 	dev_info_t		*cdevi;
4463 	int			circ;
4464 	struct ddi_minor_data	*dmd;
4465 
4466 	major = ddi_name_to_major(minor_name);
4467 
4468 	ASSERT(dip == clone_dip);
4469 	ASSERT(major != DDI_MAJOR_T_NONE);
4470 
4471 	/*
4472 	 * Attach the driver named by the minor node, then
4473 	 * search its first instance's minor list for an
4474 	 * alias node.
4475 	 */
4476 	if (ddi_hold_installed_driver(major) == NULL)
4477 		return (1);
4478 
4479 	dnp = &devnamesp[major];
4480 	LOCK_DEV_OPS(&dnp->dn_lock);
4481 
4482 	if ((cdevi = dnp->dn_head) != NULL) {
4483 		ndi_devi_enter(cdevi, &circ);
4484 		for (dmd = DEVI(cdevi)->devi_minor; dmd; dmd = dmd->next) {
4485 			if (dmd->type == DDM_ALIAS) {
4486 				alias = i_ddi_strdup(dmd->ddm_name, KM_SLEEP);
4487 				break;
4488 			}
4489 		}
4490 		ndi_devi_exit(cdevi, circ);
4491 	}
4492 
4493 	UNLOCK_DEV_OPS(&dnp->dn_lock);
4494 	ddi_rele_driver(major);
4495 
4496 	if (alias == NULL) {
4497 		if (moddebug & MODDEBUG_MINORPERM)
4498 			cmn_err(CE_CONT, "dev_minorperm: "
4499 			    "no alias for %s\n", minor_name);
4500 		return (1);
4501 	}
4502 
4503 	major = ddi_driver_major(clone_dip);
4504 	dnp = &devnamesp[major];
4505 	LOCK_DEV_OPS(&dnp->dn_lock);
4506 
4507 	/*
4508 	 * Go through the clone driver's mperm list looking
4509 	 * for a match for the specified alias.
4510 	 */
4511 	for (mp = dnp->dn_mperm; mp; mp = mp->mp_next) {
4512 		if (strcmp(alias, mp->mp_minorname) == 0) {
4513 			break;
4514 		}
4515 	}
4516 
4517 	if (mp) {
4518 		if (moddebug & MODDEBUG_MP_MATCH) {
4519 			cmn_err(CE_CONT,
4520 			    "minor perm defaults: %s %s 0%o %d %d (aliased)\n",
4521 			    minor_name, alias, mp->mp_mode,
4522 			    mp->mp_uid, mp->mp_gid);
4523 		}
4524 		rmp->mp_uid = mp->mp_uid;
4525 		rmp->mp_gid = mp->mp_gid;
4526 		rmp->mp_mode = mp->mp_mode;
4527 	}
4528 	UNLOCK_DEV_OPS(&dnp->dn_lock);
4529 
4530 	kmem_free(alias, strlen(alias)+1);
4531 
4532 	return (mp == NULL);
4533 }
4534 
4535 int
4536 dev_minorperm(dev_info_t *dip, char *name, mperm_t *rmp)
4537 {
4538 	major_t major;
4539 	char *minor_name;
4540 	struct devnames *dnp;
4541 	mperm_t *mp;
4542 	int is_clone = 0;
4543 
4544 	if (!minorperm_loaded) {
4545 		if (moddebug & MODDEBUG_MINORPERM)
4546 			cmn_err(CE_CONT,
4547 			    "%s: minor perm not yet loaded\n", name);
4548 		return (1);
4549 	}
4550 
4551 	minor_name = strchr(name, ':');
4552 	if (minor_name == NULL)
4553 		return (1);
4554 	minor_name++;
4555 
4556 	/*
4557 	 * If it's the clone driver, search the driver as named
4558 	 * by the minor.  All clone minor perm entries other than
4559 	 * alias nodes are actually installed on the real driver's list.
4560 	 */
4561 	if (dip == clone_dip) {
4562 		major = ddi_name_to_major(minor_name);
4563 		if (major == DDI_MAJOR_T_NONE) {
4564 			if (moddebug & MODDEBUG_MINORPERM)
4565 				cmn_err(CE_CONT, "dev_minorperm: "
4566 				    "%s: no such driver\n", minor_name);
4567 			return (1);
4568 		}
4569 		is_clone = 1;
4570 	} else {
4571 		major = ddi_driver_major(dip);
4572 		ASSERT(major != DDI_MAJOR_T_NONE);
4573 	}
4574 
4575 	dnp = &devnamesp[major];
4576 	LOCK_DEV_OPS(&dnp->dn_lock);
4577 
4578 	/*
4579 	 * Go through the driver's mperm list looking for
4580 	 * a match for the specified minor.  If there's
4581 	 * no matching pattern, use the wild card.
4582 	 * Defer to the clone wild for clone if specified,
4583 	 * otherwise fall back to the normal form.
4584 	 */
4585 	for (mp = dnp->dn_mperm; mp; mp = mp->mp_next) {
4586 		if (gmatch(minor_name, mp->mp_minorname) != 0) {
4587 			break;
4588 		}
4589 	}
4590 	if (mp == NULL) {
4591 		if (is_clone)
4592 			mp = dnp->dn_mperm_clone;
4593 		if (mp == NULL)
4594 			mp = dnp->dn_mperm_wild;
4595 	}
4596 
4597 	if (mp) {
4598 		if (moddebug & MODDEBUG_MP_MATCH) {
4599 			cmn_err(CE_CONT,
4600 			    "minor perm defaults: %s %s 0%o %d %d\n",
4601 			    name, mp->mp_minorname, mp->mp_mode,
4602 			    mp->mp_uid, mp->mp_gid);
4603 		}
4604 		rmp->mp_uid = mp->mp_uid;
4605 		rmp->mp_gid = mp->mp_gid;
4606 		rmp->mp_mode = mp->mp_mode;
4607 	}
4608 	UNLOCK_DEV_OPS(&dnp->dn_lock);
4609 
4610 	/*
4611 	 * If no match can be found for a clone node,
4612 	 * search for a possible match for an alias.
4613 	 * One such example is /dev/ptmx -> /devices/pseudo/clone@0:ptm,
4614 	 * with minor perm entry clone:ptmx.
4615 	 */
4616 	if (mp == NULL && is_clone) {
4617 		return (dev_alias_minorperm(dip, minor_name, rmp));
4618 	}
4619 
4620 	return (mp == NULL);
4621 }
4622 
4623 /*
4624  * dynamicaly reference load a dl module/library, returning handle
4625  */
4626 /*ARGSUSED*/
4627 ddi_modhandle_t
4628 ddi_modopen(const char *modname, int mode, int *errnop)
4629 {
4630 	char		*subdir;
4631 	char		*mod;
4632 	int		subdirlen;
4633 	struct modctl	*hmodp = NULL;
4634 	int		retval = EINVAL;
4635 
4636 	ASSERT(modname && (mode == KRTLD_MODE_FIRST));
4637 	if ((modname == NULL) || (mode != KRTLD_MODE_FIRST))
4638 		goto out;
4639 
4640 	/* find last '/' in modname */
4641 	mod = strrchr(modname, '/');
4642 
4643 	if (mod) {
4644 		/* for subdir string without modification to argument */
4645 		mod++;
4646 		subdirlen = mod - modname;
4647 		subdir = kmem_alloc(subdirlen, KM_SLEEP);
4648 		(void) strlcpy(subdir, modname, subdirlen);
4649 	} else {
4650 		subdirlen = 0;
4651 		subdir = "misc";
4652 		mod = (char *)modname;
4653 	}
4654 
4655 	/* reference load with errno return value */
4656 	retval = modrload(subdir, mod, &hmodp);
4657 
4658 	if (subdirlen)
4659 		kmem_free(subdir, subdirlen);
4660 
4661 out:	if (errnop)
4662 		*errnop = retval;
4663 
4664 	if (moddebug & MODDEBUG_DDI_MOD)
4665 		printf("ddi_modopen %s mode %x: %s %p %d\n",
4666 		    modname ? modname : "<unknown>", mode,
4667 		    hmodp ? hmodp->mod_filename : "<unknown>",
4668 		    (void *)hmodp, retval);
4669 
4670 	return ((ddi_modhandle_t)hmodp);
4671 }
4672 
4673 /* lookup "name" in open dl module/library */
4674 void *
4675 ddi_modsym(ddi_modhandle_t h, const char *name, int *errnop)
4676 {
4677 	struct modctl	*hmodp = (struct modctl *)h;
4678 	void		*f;
4679 	int		retval;
4680 
4681 	ASSERT(hmodp && name && hmodp->mod_installed && (hmodp->mod_ref >= 1));
4682 	if ((hmodp == NULL) || (name == NULL) ||
4683 	    (hmodp->mod_installed == 0) || (hmodp->mod_ref < 1)) {
4684 		f = NULL;
4685 		retval = EINVAL;
4686 	} else {
4687 		f = (void *)kobj_lookup(hmodp->mod_mp, (char *)name);
4688 		if (f)
4689 			retval = 0;
4690 		else
4691 			retval = ENOTSUP;
4692 	}
4693 
4694 	if (moddebug & MODDEBUG_DDI_MOD)
4695 		printf("ddi_modsym in %s of %s: %d %p\n",
4696 		    hmodp ? hmodp->mod_modname : "<unknown>",
4697 		    name ? name : "<unknown>", retval, f);
4698 
4699 	if (errnop)
4700 		*errnop = retval;
4701 	return (f);
4702 }
4703 
4704 /* dynamic (un)reference unload of an open dl module/library */
4705 int
4706 ddi_modclose(ddi_modhandle_t h)
4707 {
4708 	struct modctl	*hmodp = (struct modctl *)h;
4709 	struct modctl	*modp = NULL;
4710 	int		retval;
4711 
4712 	ASSERT(hmodp && hmodp->mod_installed && (hmodp->mod_ref >= 1));
4713 	if ((hmodp == NULL) ||
4714 	    (hmodp->mod_installed == 0) || (hmodp->mod_ref < 1)) {
4715 		retval = EINVAL;
4716 		goto out;
4717 	}
4718 
4719 	retval = modunrload(hmodp->mod_id, &modp, ddi_modclose_unload);
4720 	if (retval == EBUSY)
4721 		retval = 0;	/* EBUSY is not an error */
4722 
4723 	if (retval == 0) {
4724 		ASSERT(hmodp == modp);
4725 		if (hmodp != modp)
4726 			retval = EINVAL;
4727 	}
4728 
4729 out:	if (moddebug & MODDEBUG_DDI_MOD)
4730 		printf("ddi_modclose %s: %d\n",
4731 		    hmodp ? hmodp->mod_modname : "<unknown>", retval);
4732 
4733 	return (retval);
4734 }
4735