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