xref: /freebsd/stand/common/module.c (revision 82397d791966b09d344251bc709cd9db2b3a1902)
1 /*-
2  * Copyright (c) 1998 Michael Smith <msmith@freebsd.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 /*
31  * file/module function dispatcher, support, etc.
32  */
33 
34 #include <stand.h>
35 #include <string.h>
36 #include <sys/param.h>
37 #include <sys/linker.h>
38 #include <sys/module.h>
39 #include <sys/queue.h>
40 #include <sys/stdint.h>
41 #include <sys/font.h>
42 #include <gfx_fb.h>
43 
44 #if defined(LOADER_FDT_SUPPORT)
45 #include <fdt_platform.h>
46 #endif
47 
48 #include "bootstrap.h"
49 
50 #define	MDIR_REMOVED	0x0001
51 #define	MDIR_NOHINTS	0x0002
52 
53 struct moduledir {
54 	char	*d_path;	/* path of modules directory */
55 	u_char	*d_hints;	/* content of linker.hints file */
56 	int	d_hintsz;	/* size of hints data */
57 	int	d_flags;
58 	STAILQ_ENTRY(moduledir) d_link;
59 };
60 
61 static int			file_load(char *filename, vm_offset_t dest, struct preloaded_file **result);
62 static int			file_load_dependencies(struct preloaded_file *base_mod);
63 static char *			file_search(const char *name, char **extlist);
64 static struct kernel_module *	file_findmodule(struct preloaded_file *fp, char *modname, struct mod_depend *verinfo);
65 static int			file_havepath(const char *name);
66 static char			*mod_searchmodule(char *name, struct mod_depend *verinfo);
67 static char *			mod_searchmodule_pnpinfo(const char *bus, const char *pnpinfo);
68 static void			file_insert_tail(struct preloaded_file *mp);
69 static void			file_remove(struct preloaded_file *fp);
70 struct file_metadata*		metadata_next(struct file_metadata *base_mp, int type);
71 static void			moduledir_readhints(struct moduledir *mdp);
72 static void			moduledir_rebuild(void);
73 
74 /* load address should be tweaked by first module loaded (kernel) */
75 static vm_offset_t	loadaddr = 0;
76 
77 #if defined(LOADER_FDT_SUPPORT)
78 static const char	*default_searchpath =
79     "/boot/kernel;/boot/modules;/boot/dtb";
80 #else
81 static const char	*default_searchpath = "/boot/kernel;/boot/modules";
82 #endif
83 
84 static STAILQ_HEAD(, moduledir) moduledir_list =
85     STAILQ_HEAD_INITIALIZER(moduledir_list);
86 
87 struct preloaded_file *preloaded_files = NULL;
88 
89 static char *kld_ext_list[] = {
90     ".ko",
91     "",
92     ".debug",
93     NULL
94 };
95 
96 /*
97  * load an object, either a disk file or code module.
98  *
99  * To load a file, the syntax is:
100  *
101  * load -t <type> <path>
102  *
103  * code modules are loaded as:
104  *
105  * load <path> <options>
106  */
107 
108 COMMAND_SET(load, "load", "load a kernel or module", command_load);
109 
110 static int
111 command_load(int argc, char *argv[])
112 {
113 	struct preloaded_file *fp;
114 	char	*typestr;
115 	char	*prefix;
116 	char	*skip;
117 	int		dflag, dofile, dokld, ch, error;
118 
119 	dflag = dokld = dofile = 0;
120 	optind = 1;
121 	optreset = 1;
122 	typestr = NULL;
123 	if (argc == 1) {
124 		command_errmsg = "no filename specified";
125 		return (CMD_CRIT);
126 	}
127 	prefix = skip = NULL;
128 	while ((ch = getopt(argc, argv, "dkp:s:t:")) != -1) {
129 		switch(ch) {
130 		case 'd':
131 			dflag++;
132 			break;
133 		case 'k':
134 			dokld = 1;
135 			break;
136 		case 'p':
137 			prefix = optarg;
138 			break;
139 		case 's':
140 			skip = optarg;
141 			break;
142 		case 't':
143 			typestr = optarg;
144 			dofile = 1;
145 			break;
146 		case '?':
147 		default:
148 			/* getopt has already reported an error */
149 			return (CMD_OK);
150 		}
151 	}
152 	argv += (optind - 1);
153 	argc -= (optind - 1);
154 
155 	/*
156 	 * Request to load a raw file?
157 	 */
158 	if (dofile) {
159 		if ((argc != 2) || (typestr == NULL) || (*typestr == 0)) {
160 			command_errmsg = "invalid load type";
161 			return (CMD_CRIT);
162 		}
163 
164 #ifdef LOADER_VERIEXEC
165 		if (strncmp(typestr, "manifest", 8) == 0) {
166 			if (dflag > 0)
167 				ve_debug_set(dflag);
168 			return (load_manifest(argv[1], prefix, skip, NULL));
169 		}
170 #ifdef LOADER_VERIEXEC_PASS_MANIFEST
171 		if (strncmp(typestr, "pass_manifest", 13) == 0) {
172 			if (dflag > 0)
173 				ve_debug_set(dflag);
174 		    return (pass_manifest(argv[1], prefix));
175 		}
176 #endif
177 #endif
178 
179 		fp = file_findfile(argv[1], typestr);
180 		if (fp) {
181 			snprintf(command_errbuf, sizeof(command_errbuf),
182 			  "warning: file '%s' already loaded", argv[1]);
183 			return (CMD_WARN);
184 		}
185 
186 		if (file_loadraw(argv[1], typestr, 1) != NULL)
187 			return (CMD_OK);
188 
189 		/* Failing to load mfs_root is never going to end well! */
190 		if (strcmp("mfs_root", typestr) == 0)
191 			return (CMD_FATAL);
192 
193 		return (CMD_ERROR);
194 	}
195 	/*
196 	 * Do we have explicit KLD load ?
197 	 */
198 	if (dokld || file_havepath(argv[1])) {
199 		error = mod_loadkld(argv[1], argc - 2, argv + 2);
200 		if (error == EEXIST) {
201 			snprintf(command_errbuf, sizeof(command_errbuf),
202 			  "warning: KLD '%s' already loaded", argv[1]);
203 			return (CMD_WARN);
204 		}
205 
206 		return (error == 0 ? CMD_OK : CMD_CRIT);
207 	}
208 	/*
209 	 * Looks like a request for a module.
210 	 */
211 	error = mod_load(argv[1], NULL, argc - 2, argv + 2);
212 	if (error == EEXIST) {
213 		snprintf(command_errbuf, sizeof(command_errbuf),
214 		  "warning: module '%s' already loaded", argv[1]);
215 		return (CMD_WARN);
216 	}
217 
218 	return (error == 0 ? CMD_OK : CMD_CRIT);
219 }
220 
221 #ifdef LOADER_GELI_SUPPORT
222 COMMAND_SET(load_geli, "load_geli", "load a geli key", command_load_geli);
223 
224 static int
225 command_load_geli(int argc, char *argv[])
226 {
227 	char	typestr[80];
228 	char	*cp;
229 	int		ch, num;
230 
231 	if (argc < 3) {
232 		command_errmsg = "usage is [-n key#] <prov> <file>";
233 		return(CMD_ERROR);
234 	}
235 
236 	num = 0;
237 	optind = 1;
238 	optreset = 1;
239 	while ((ch = getopt(argc, argv, "n:")) != -1) {
240 		switch(ch) {
241 		case 'n':
242 			num = strtol(optarg, &cp, 0);
243 			if (cp == optarg) {
244 				snprintf(command_errbuf, sizeof(command_errbuf),
245 				  "bad key index '%s'", optarg);
246 				return(CMD_ERROR);
247 			}
248 			break;
249 		case '?':
250 		default:
251 			/* getopt has already reported an error */
252 			return(CMD_OK);
253 		}
254 	}
255 	argv += (optind - 1);
256 	argc -= (optind - 1);
257 	sprintf(typestr, "%s:geli_keyfile%d", argv[1], num);
258 	return (file_loadraw(argv[2], typestr, 1) ? CMD_OK : CMD_ERROR);
259 }
260 #endif
261 
262 void
263 unload(void)
264 {
265 	struct preloaded_file *fp;
266 
267 	while (preloaded_files != NULL) {
268 		fp = preloaded_files;
269 		preloaded_files = preloaded_files->f_next;
270 		file_discard(fp);
271 	}
272 	loadaddr = 0;
273 	unsetenv("kernelname");
274 }
275 
276 COMMAND_SET(unload, "unload", "unload all modules", command_unload);
277 
278 static int
279 command_unload(int argc, char *argv[])
280 {
281 	unload();
282 	return(CMD_OK);
283 }
284 
285 COMMAND_SET(lsmod, "lsmod", "list loaded modules", command_lsmod);
286 
287 static int
288 command_lsmod(int argc, char *argv[])
289 {
290 	struct preloaded_file	*fp;
291 	struct kernel_module	*mp;
292 	struct file_metadata	*md;
293 	char			lbuf[80];
294 	int				ch, verbose, ret = 0;
295 
296 	verbose = 0;
297 	optind = 1;
298 	optreset = 1;
299 	while ((ch = getopt(argc, argv, "v")) != -1) {
300 		switch(ch) {
301 		case 'v':
302 			verbose = 1;
303 			break;
304 		case '?':
305 		default:
306 			/* getopt has already reported an error */
307 			return(CMD_OK);
308 		}
309 	}
310 
311 	pager_open();
312 	for (fp = preloaded_files; fp; fp = fp->f_next) {
313 		snprintf(lbuf, sizeof(lbuf), " %p: ", (void *) fp->f_addr);
314 		pager_output(lbuf);
315 		pager_output(fp->f_name);
316 		snprintf(lbuf, sizeof(lbuf), " (%s, 0x%lx)\n", fp->f_type,
317 		  (long)fp->f_size);
318 		if (pager_output(lbuf))
319 			break;
320 		if (fp->f_args != NULL) {
321 			pager_output("    args: ");
322 			pager_output(fp->f_args);
323 			if (pager_output("\n"))
324 				break;
325 		}
326 		if (fp->f_modules) {
327 			pager_output("  modules: ");
328 			for (mp = fp->f_modules; mp; mp = mp->m_next) {
329 				snprintf(lbuf, sizeof(lbuf), "%s.%d ", mp->m_name,
330 				  mp->m_version);
331 				pager_output(lbuf);
332 			}
333 			if (pager_output("\n"))
334 				break;
335 		}
336 		if (verbose) {
337 			/* XXX could add some formatting smarts here to display some better */
338 			for (md = fp->f_metadata; md != NULL; md = md->md_next) {
339 				snprintf(lbuf, sizeof(lbuf), "      0x%04x, 0x%lx\n",
340 				  md->md_type, (long) md->md_size);
341 				if (pager_output(lbuf))
342 					break;
343 			}
344 		}
345 		if (ret)
346 			break;
347 	}
348 	pager_close();
349 	return(CMD_OK);
350 }
351 
352 COMMAND_SET(pnpmatch, "pnpmatch", "list matched modules based on pnpinfo", command_pnpmatch);
353 
354 static int pnp_dump_flag = 0;
355 static int pnp_unbound_flag = 0;
356 static int pnp_verbose_flag = 0;
357 
358 static int
359 command_pnpmatch(int argc, char *argv[])
360 {
361 	char *module;
362 	int ch;
363 
364 	pnp_verbose_flag = 0;
365 	pnp_dump_flag = 0;
366 	optind = 1;
367 	optreset = 1;
368 	while ((ch = getopt(argc, argv, "vd")) != -1) {
369 		switch(ch) {
370 		case 'v':
371 			pnp_verbose_flag = 1;
372 			break;
373 		case 'd':
374 			pnp_dump_flag = 1;
375 			break;
376 		case '?':
377 		default:
378 			/* getopt has already reported an error */
379 			return(CMD_OK);
380 		}
381 	}
382 	argv += (optind - 1);
383 	argc -= (optind - 1);
384 
385 	module = mod_searchmodule_pnpinfo(argv[1], argv[2]);
386 	if (module)
387 		printf("Matched module: %s\n", module);
388 	else if(argv[1])
389 		printf("No module matches %s\n", argv[1]);
390 
391 	return (CMD_OK);
392 }
393 
394 COMMAND_SET(pnpload, "pnpload", "load matched modules based on pnpinfo", command_pnpload);
395 
396 static int
397 command_pnpload(int argc, char *argv[])
398 {
399 	char *module;
400 	int ch, error;
401 
402 	pnp_verbose_flag = 0;
403 	pnp_dump_flag = 0;
404 	optind = 1;
405 	optreset = 1;
406 	while ((ch = getopt(argc, argv, "vd")) != -1) {
407 		switch(ch) {
408 		case 'v':
409 			pnp_verbose_flag = 1;
410 			break;
411 		case 'd':
412 			pnp_dump_flag = 1;
413 			break;
414 		case '?':
415 		default:
416 			/* getopt has already reported an error */
417 			return(CMD_OK);
418 		}
419 	}
420 	argv += (optind - 1);
421 	argc -= (optind - 1);
422 
423 	if (argc != 2)
424 		return (CMD_ERROR);
425 
426 	module = mod_searchmodule_pnpinfo(argv[1], argv[2]);
427 
428 	error = mod_load(module, NULL, 0, NULL);
429 	if (error == EEXIST) {
430 		snprintf(command_errbuf, sizeof(command_errbuf),
431 		  "warning: module '%s' already loaded", argv[1]);
432 		return (CMD_WARN);
433 	}
434 
435 	return (error == 0 ? CMD_OK : CMD_CRIT);
436 }
437 
438 #if defined(LOADER_FDT_SUPPORT)
439 static void
440 pnpautoload_simplebus(void) {
441 	const char *pnpstring;
442 	const char *compatstr;
443 	char *pnpinfo = NULL;
444 	char *module = NULL;
445 	int tag = 0, len, pnplen;
446 	int error;
447 
448 	while (1) {
449 		pnpstring = fdt_devmatch_next(&tag, &len);
450 		if (pnpstring == NULL)
451 			return;
452 
453 		compatstr = pnpstring;
454 		for (pnplen = 0; pnplen != len; compatstr = pnpstring + pnplen) {
455 			pnplen += strlen(compatstr) + 1;
456 			asprintf(&pnpinfo, "compat=%s", compatstr);
457 
458 			module = mod_searchmodule_pnpinfo("simplebus", pnpinfo);
459 			if (module) {
460 				error = mod_loadkld(module, 0, NULL);
461 				if (error)
462 					printf("Cannot load module %s\n", module);
463 				break;
464 			}
465 		}
466 		free(pnpinfo);
467 		free(module);
468 	}
469 }
470 #endif
471 
472 struct pnp_bus {
473 	const char *name;
474 	void (*load)(void);
475 };
476 
477 struct pnp_bus pnp_buses[] = {
478 #if defined(LOADER_FDT_SUPPORT)
479 	{"simplebus", pnpautoload_simplebus},
480 #endif
481 };
482 
483 COMMAND_SET(pnpautoload, "pnpautoload", "auto load modules based on pnpinfo", command_pnpautoload);
484 
485 static int
486 command_pnpautoload(int argc, char *argv[])
487 {
488 	int i;
489 	int verbose;
490 	int ch, match;
491 
492 	pnp_verbose_flag = 0;
493 	pnp_dump_flag = 0;
494 	verbose = 0;
495 	optind = 1;
496 	optreset = 1;
497 	match = 0;
498 	while ((ch = getopt(argc, argv, "v")) != -1) {
499 		switch(ch) {
500 		case 'v':
501 			verbose = 1;
502 			break;
503 		case '?':
504 		default:
505 			/* getopt has already reported an error */
506 			return(CMD_OK);
507 		}
508 	}
509 	argv += (optind - 1);
510 	argc -= (optind - 1);
511 
512 	if (argc > 2)
513 		return (CMD_ERROR);
514 
515 	for (i = 0; i < nitems(pnp_buses); i++) {
516 		if (argc == 2 && strcmp(argv[1], pnp_buses[i].name) != 0) {
517 			if (verbose)
518 				printf("Skipping bus %s\n", pnp_buses[i].name);
519 			continue;
520 		}
521 		if (verbose)
522 			printf("Autoloading modules for simplebus\n");
523 		pnp_buses[i].load();
524 		match = 1;
525 	}
526 	if (match == 0)
527 		printf("Unsupported bus %s\n", argv[1]);
528 
529 	return (CMD_OK);
530 }
531 
532 /*
533  * File level interface, functions file_*
534  */
535 int
536 file_load(char *filename, vm_offset_t dest, struct preloaded_file **result)
537 {
538 	static int last_file_format = 0;
539 	struct preloaded_file *fp;
540 	int error;
541 	int i;
542 
543 	if (archsw.arch_loadaddr != NULL)
544 		dest = archsw.arch_loadaddr(LOAD_RAW, filename, dest);
545 
546 	error = EFTYPE;
547 	for (i = last_file_format, fp = NULL;
548 	     file_formats[i] && fp == NULL; i++) {
549 		error = (file_formats[i]->l_load)(filename, dest, &fp);
550 		if (error == 0) {
551 			fp->f_loader = last_file_format = i; /* remember the loader */
552 			*result = fp;
553 			break;
554 		} else if (last_file_format == i && i != 0) {
555 			/* Restart from the beginning */
556 			i = -1;
557 			last_file_format = 0;
558 			fp = NULL;
559 			continue;
560 		}
561 		if (error == EFTYPE)
562 			continue;		/* Unknown to this handler? */
563 		if (error) {
564 			snprintf(command_errbuf, sizeof(command_errbuf),
565 			  "can't load file '%s': %s", filename, strerror(error));
566 			break;
567 		}
568 	}
569 	return (error);
570 }
571 
572 static int
573 file_load_dependencies(struct preloaded_file *base_file)
574 {
575 	struct file_metadata *md;
576 	struct preloaded_file *fp;
577 	struct mod_depend *verinfo;
578 	struct kernel_module *mp;
579 	char *dmodname;
580 	int error;
581 
582 	md = file_findmetadata(base_file, MODINFOMD_DEPLIST);
583 	if (md == NULL)
584 		return (0);
585 	error = 0;
586 	do {
587 		verinfo = (struct mod_depend*)md->md_data;
588 		dmodname = (char *)(verinfo + 1);
589 		if (file_findmodule(NULL, dmodname, verinfo) == NULL) {
590 			printf("loading required module '%s'\n", dmodname);
591 			error = mod_load(dmodname, verinfo, 0, NULL);
592 			if (error)
593 				break;
594 			/*
595 			 * If module loaded via kld name which isn't listed
596 			 * in the linker.hints file, we should check if it have
597 			 * required version.
598 			 */
599 			mp = file_findmodule(NULL, dmodname, verinfo);
600 			if (mp == NULL) {
601 				snprintf(command_errbuf, sizeof(command_errbuf),
602 				  "module '%s' exists but with wrong version", dmodname);
603 				error = ENOENT;
604 				break;
605 			}
606 		}
607 		md = metadata_next(md, MODINFOMD_DEPLIST);
608 	} while (md);
609 	if (!error)
610 		return (0);
611 	/* Load failed; discard everything */
612 	while (base_file != NULL) {
613 		fp = base_file;
614 		base_file = base_file->f_next;
615 		file_discard(fp);
616 	}
617 	return (error);
618 }
619 
620 vm_offset_t
621 build_font_module(vm_offset_t addr)
622 {
623 	vt_font_bitmap_data_t *bd;
624 	struct vt_font *fd;
625 	struct preloaded_file *fp;
626 	size_t size;
627 	uint32_t checksum;
628 	int i;
629 	struct font_info fi;
630 	struct fontlist *fl;
631 	uint64_t fontp;
632 
633 	if (STAILQ_EMPTY(&fonts))
634 		return (addr);
635 
636 	/* We can't load first */
637 	if ((file_findfile(NULL, NULL)) == NULL) {
638 		printf("Can not load font module: %s\n",
639 		    "the kernel is not loaded");
640 		return (addr);
641 	}
642 
643 	/* helper pointers */
644 	bd = NULL;
645 	STAILQ_FOREACH(fl, &fonts, font_next) {
646 		if (gfx_state.tg_font.vf_width == fl->font_data->vfbd_width &&
647 		    gfx_state.tg_font.vf_height == fl->font_data->vfbd_height) {
648 			/*
649 			 * Kernel does have better built in font.
650 			 */
651 			if (fl->font_flags == FONT_BUILTIN)
652 				return (addr);
653 
654 			bd = fl->font_data;
655 			break;
656 		}
657 	}
658 	if (bd == NULL)
659 		return (addr);
660 	fd = bd->vfbd_font;
661 
662 	fi.fi_width = fd->vf_width;
663 	checksum = fi.fi_width;
664 	fi.fi_height = fd->vf_height;
665 	checksum += fi.fi_height;
666 	fi.fi_bitmap_size = bd->vfbd_uncompressed_size;
667 	checksum += fi.fi_bitmap_size;
668 
669 	size = roundup2(sizeof (struct font_info), 8);
670 	for (i = 0; i < VFNT_MAPS; i++) {
671 		fi.fi_map_count[i] = fd->vf_map_count[i];
672 		checksum += fi.fi_map_count[i];
673 		size += fd->vf_map_count[i] * sizeof (struct vfnt_map);
674 		size += roundup2(size, 8);
675 	}
676 	size += bd->vfbd_uncompressed_size;
677 
678 	fi.fi_checksum = -checksum;
679 
680 	fp = file_findfile(NULL, "elf kernel");
681 	if (fp == NULL)
682 		fp = file_findfile(NULL, "elf64 kernel");
683 	if (fp == NULL)
684 		panic("can't find kernel file");
685 
686 	fontp = addr;
687 	addr += archsw.arch_copyin(&fi, addr, sizeof (struct font_info));
688 	addr = roundup2(addr, 8);
689 
690 	/* Copy maps. */
691 	for (i = 0; i < VFNT_MAPS; i++) {
692 		if (fd->vf_map_count[i] != 0) {
693 			addr += archsw.arch_copyin(fd->vf_map[i], addr,
694 			    fd->vf_map_count[i] * sizeof (struct vfnt_map));
695 			addr = roundup2(addr, 8);
696 		}
697 	}
698 
699 	/* Copy the bitmap. */
700 	addr += archsw.arch_copyin(fd->vf_bytes, addr, fi.fi_bitmap_size);
701 
702 	/* Looks OK so far; populate control structure */
703 	file_addmetadata(fp, MODINFOMD_FONT, sizeof(fontp), &fontp);
704 	return (addr);
705 }
706 
707 #ifdef LOADER_VERIEXEC_VECTX
708 #define VECTX_HANDLE(fd) vctx
709 #else
710 #define VECTX_HANDLE(fd) fd
711 #endif
712 
713 
714 /*
715  * We've been asked to load (fname) as (type), so just suck it in,
716  * no arguments or anything.
717  */
718 struct preloaded_file *
719 file_loadraw(const char *fname, char *type, int insert)
720 {
721 	struct preloaded_file	*fp;
722 	char			*name;
723 	int				fd, got;
724 	vm_offset_t			laddr;
725 #ifdef LOADER_VERIEXEC_VECTX
726 	struct vectx		*vctx;
727 	int			verror;
728 #endif
729 
730 	/* We can't load first */
731 	if ((file_findfile(NULL, NULL)) == NULL) {
732 		command_errmsg = "can't load file before kernel";
733 		return(NULL);
734 	}
735 
736 	/* locate the file on the load path */
737 	name = file_search(fname, NULL);
738 	if (name == NULL) {
739 		snprintf(command_errbuf, sizeof(command_errbuf),
740 		  "can't find '%s'", fname);
741 		return(NULL);
742 	}
743 
744 	if ((fd = open(name, O_RDONLY)) < 0) {
745 		snprintf(command_errbuf, sizeof(command_errbuf),
746 		  "can't open '%s': %s", name, strerror(errno));
747 		free(name);
748 		return(NULL);
749 	}
750 
751 #ifdef LOADER_VERIEXEC_VECTX
752 	vctx = vectx_open(fd, name, 0L, NULL, &verror, __func__);
753 	if (verror) {
754 		sprintf(command_errbuf, "can't verify '%s': %s",
755 		    name, ve_error_get());
756 		free(name);
757 		free(vctx);
758 		close(fd);
759 		return(NULL);
760 	}
761 #else
762 #ifdef LOADER_VERIEXEC
763 	if (verify_file(fd, name, 0, VE_MUST, __func__) < 0) {
764 		sprintf(command_errbuf, "can't verify '%s': %s",
765 		    name, ve_error_get());
766 		free(name);
767 		close(fd);
768 		return(NULL);
769 	}
770 #endif
771 #endif
772 
773 	if (archsw.arch_loadaddr != NULL)
774 		loadaddr = archsw.arch_loadaddr(LOAD_RAW, name, loadaddr);
775 
776 	printf("%s ", name);
777 
778 	laddr = loadaddr;
779 	for (;;) {
780 		/* read in 4k chunks; size is not really important */
781 		got = archsw.arch_readin(VECTX_HANDLE(fd), laddr, 4096);
782 		if (got == 0)				/* end of file */
783 			break;
784 		if (got < 0) {				/* error */
785 			snprintf(command_errbuf, sizeof(command_errbuf),
786 			  "error reading '%s': %s", name, strerror(errno));
787 			free(name);
788 			close(fd);
789 #ifdef LOADER_VERIEXEC_VECTX
790 			free(vctx);
791 #endif
792 			return(NULL);
793 		}
794 		laddr += got;
795 	}
796 
797 	printf("size=%#jx\n", (uintmax_t)(laddr - loadaddr));
798 #ifdef LOADER_VERIEXEC_VECTX
799 	verror = vectx_close(vctx, VE_MUST, __func__);
800 	if (verror) {
801 		free(name);
802 		close(fd);
803 		free(vctx);
804 		return(NULL);
805 	}
806 #endif
807 
808 	/* Looks OK so far; create & populate control structure */
809 	fp = file_alloc();
810 	if (fp == NULL) {
811 		snprintf(command_errbuf, sizeof (command_errbuf),
812 		    "no memory to load %s", name);
813 		free(name);
814 		close(fd);
815 		return (NULL);
816 	}
817 	fp->f_name = name;
818 	fp->f_type = strdup(type);
819 	fp->f_args = NULL;
820 	fp->f_metadata = NULL;
821 	fp->f_loader = -1;
822 	fp->f_addr = loadaddr;
823 	fp->f_size = laddr - loadaddr;
824 
825 	if (fp->f_type == NULL) {
826 		snprintf(command_errbuf, sizeof (command_errbuf),
827 		    "no memory to load %s", name);
828 		free(name);
829 		close(fd);
830 		return (NULL);
831 	}
832 	/* recognise space consumption */
833 	loadaddr = laddr;
834 
835 	/* Add to the list of loaded files */
836 	if (insert != 0)
837 		file_insert_tail(fp);
838 	close(fd);
839 	return(fp);
840 }
841 
842 /*
843  * Load the module (name), pass it (argc),(argv), add container file
844  * to the list of loaded files.
845  * If module is already loaded just assign new argc/argv.
846  */
847 int
848 mod_load(char *modname, struct mod_depend *verinfo, int argc, char *argv[])
849 {
850 	struct kernel_module	*mp;
851 	int				err;
852 	char			*filename;
853 
854 	if (file_havepath(modname)) {
855 		printf("Warning: mod_load() called instead of mod_loadkld() for module '%s'\n", modname);
856 		return (mod_loadkld(modname, argc, argv));
857 	}
858 	/* see if module is already loaded */
859 	mp = file_findmodule(NULL, modname, verinfo);
860 	if (mp) {
861 #ifdef moduleargs
862 		free(mp->m_args);
863 		mp->m_args = unargv(argc, argv);
864 #endif
865 		snprintf(command_errbuf, sizeof(command_errbuf),
866 		  "warning: module '%s' already loaded", mp->m_name);
867 		return (0);
868 	}
869 	/* locate file with the module on the search path */
870 	filename = mod_searchmodule(modname, verinfo);
871 	if (filename == NULL) {
872 		snprintf(command_errbuf, sizeof(command_errbuf),
873 		  "can't find '%s'", modname);
874 		return (ENOENT);
875 	}
876 	err = mod_loadkld(filename, argc, argv);
877 	free(filename);
878 	return (err);
879 }
880 
881 /*
882  * Load specified KLD. If path is omitted, then try to locate it via
883  * search path.
884  */
885 int
886 mod_loadkld(const char *kldname, int argc, char *argv[])
887 {
888 	struct preloaded_file	*fp;
889 	int			err;
890 	char			*filename;
891 	vm_offset_t		loadaddr_saved;
892 
893 	/*
894 	 * Get fully qualified KLD name
895 	 */
896 	filename = file_search(kldname, kld_ext_list);
897 	if (filename == NULL) {
898 		snprintf(command_errbuf, sizeof(command_errbuf),
899 		  "can't find '%s'", kldname);
900 		return (ENOENT);
901 	}
902 	/*
903 	 * Check if KLD already loaded
904 	 */
905 	fp = file_findfile(filename, NULL);
906 	if (fp) {
907 		snprintf(command_errbuf, sizeof(command_errbuf),
908 		  "warning: KLD '%s' already loaded", filename);
909 		free(filename);
910 		return (0);
911 	}
912 
913 	do {
914 		err = file_load(filename, loadaddr, &fp);
915 		if (err)
916 			break;
917 		fp->f_args = unargv(argc, argv);
918 		loadaddr_saved = loadaddr;
919 		loadaddr = fp->f_addr + fp->f_size;
920 		file_insert_tail(fp);	/* Add to the list of loaded files */
921 		if (file_load_dependencies(fp) != 0) {
922 			err = ENOENT;
923 			file_remove(fp);
924 			loadaddr = loadaddr_saved;
925 			fp = NULL;
926 			break;
927 		}
928 	} while(0);
929 	if (err == EFTYPE) {
930 		snprintf(command_errbuf, sizeof(command_errbuf),
931 		  "don't know how to load module '%s'", filename);
932 	}
933 	if (err)
934 		file_discard(fp);
935 	free(filename);
936 	return (err);
937 }
938 
939 /*
940  * Find a file matching (name) and (type).
941  * NULL may be passed as a wildcard to either.
942  */
943 struct preloaded_file *
944 file_findfile(const char *name, const char *type)
945 {
946 	struct preloaded_file *fp;
947 
948 	for (fp = preloaded_files; fp != NULL; fp = fp->f_next) {
949 		if (((name == NULL) || !strcmp(name, fp->f_name)) &&
950 		  ((type == NULL) || !strcmp(type, fp->f_type)))
951 			break;
952 	}
953 	return (fp);
954 }
955 
956 /*
957  * Find a module matching (name) inside of given file.
958  * NULL may be passed as a wildcard.
959  */
960 struct kernel_module *
961 file_findmodule(struct preloaded_file *fp, char *modname,
962 	struct mod_depend *verinfo)
963 {
964 	struct kernel_module *mp, *best;
965 	int bestver, mver;
966 
967 	if (fp == NULL) {
968 		for (fp = preloaded_files; fp; fp = fp->f_next) {
969 			mp = file_findmodule(fp, modname, verinfo);
970 			if (mp)
971 				return (mp);
972 		}
973 		return (NULL);
974 	}
975 	best = NULL;
976 	bestver = 0;
977 	for (mp = fp->f_modules; mp; mp = mp->m_next) {
978 		if (strcmp(modname, mp->m_name) == 0) {
979 			if (verinfo == NULL)
980 				return (mp);
981 			mver = mp->m_version;
982 			if (mver == verinfo->md_ver_preferred)
983 				return (mp);
984 			if (mver >= verinfo->md_ver_minimum &&
985 			  mver <= verinfo->md_ver_maximum &&
986 			  mver > bestver) {
987 				best = mp;
988 				bestver = mver;
989 			}
990 		}
991 	}
992 	return (best);
993 }
994 /*
995  * Make a copy of (size) bytes of data from (p), and associate them as
996  * metadata of (type) to the module (mp).
997  */
998 void
999 file_addmetadata(struct preloaded_file *fp, int type, size_t size, void *p)
1000 {
1001 	struct file_metadata	*md;
1002 
1003 	md = malloc(sizeof(struct file_metadata) - sizeof(md->md_data) + size);
1004 	if (md != NULL) {
1005 		md->md_size = size;
1006 		md->md_type = type;
1007 		bcopy(p, md->md_data, size);
1008 		md->md_next = fp->f_metadata;
1009 	}
1010 	fp->f_metadata = md;
1011 }
1012 
1013 /*
1014  * Find a metadata object of (type) associated with the file (fp)
1015  */
1016 struct file_metadata *
1017 file_findmetadata(struct preloaded_file *fp, int type)
1018 {
1019 	struct file_metadata *md;
1020 
1021 	for (md = fp->f_metadata; md != NULL; md = md->md_next)
1022 		if (md->md_type == type)
1023 			break;
1024 	return(md);
1025 }
1026 
1027 /*
1028  * Remove all metadata from the file.
1029  */
1030 void
1031 file_removemetadata(struct preloaded_file *fp)
1032 {
1033 	struct file_metadata *md, *next;
1034 
1035 	for (md = fp->f_metadata; md != NULL; md = next)
1036 	{
1037 		next = md->md_next;
1038 		free(md);
1039 	}
1040 	fp->f_metadata = NULL;
1041 }
1042 
1043 struct file_metadata *
1044 metadata_next(struct file_metadata *md, int type)
1045 {
1046 
1047 	if (md == NULL)
1048 		return (NULL);
1049 	while((md = md->md_next) != NULL)
1050 		if (md->md_type == type)
1051 			break;
1052 	return (md);
1053 }
1054 
1055 static char *emptyextlist[] = { "", NULL };
1056 
1057 /*
1058  * Check if the given file is in place and return full path to it.
1059  */
1060 static char *
1061 file_lookup(const char *path, const char *name, int namelen, char **extlist)
1062 {
1063 	struct stat	st;
1064 	char	*result, *cp, **cpp;
1065 	int		pathlen, extlen, len;
1066 
1067 	pathlen = strlen(path);
1068 	extlen = 0;
1069 	if (extlist == NULL)
1070 		extlist = emptyextlist;
1071 	for (cpp = extlist; *cpp; cpp++) {
1072 		len = strlen(*cpp);
1073 		if (len > extlen)
1074 			extlen = len;
1075 	}
1076 	result = malloc(pathlen + namelen + extlen + 2);
1077 	if (result == NULL)
1078 		return (NULL);
1079 	bcopy(path, result, pathlen);
1080 	if (pathlen > 0 && result[pathlen - 1] != '/')
1081 		result[pathlen++] = '/';
1082 	cp = result + pathlen;
1083 	bcopy(name, cp, namelen);
1084 	cp += namelen;
1085 	for (cpp = extlist; *cpp; cpp++) {
1086 		strcpy(cp, *cpp);
1087 		if (stat(result, &st) == 0 && S_ISREG(st.st_mode))
1088 			return result;
1089 	}
1090 	free(result);
1091 	return NULL;
1092 }
1093 
1094 /*
1095  * Check if file name have any qualifiers
1096  */
1097 static int
1098 file_havepath(const char *name)
1099 {
1100 	const char		*cp;
1101 
1102 	archsw.arch_getdev(NULL, name, &cp);
1103 	return (cp != name || strchr(name, '/') != NULL);
1104 }
1105 
1106 /*
1107  * Attempt to find the file (name) on the module searchpath.
1108  * If (name) is qualified in any way, we simply check it and
1109  * return it or NULL.  If it is not qualified, then we attempt
1110  * to construct a path using entries in the environment variable
1111  * module_path.
1112  *
1113  * The path we return a pointer to need never be freed, as we manage
1114  * it internally.
1115  */
1116 static char *
1117 file_search(const char *name, char **extlist)
1118 {
1119 	struct moduledir	*mdp;
1120 	struct stat		sb;
1121 	char		*result;
1122 	int			namelen;
1123 
1124 	/* Don't look for nothing */
1125 	if (name == NULL)
1126 		return(NULL);
1127 
1128 	if (*name == 0)
1129 		return(strdup(name));
1130 
1131 	if (file_havepath(name)) {
1132 		/* Qualified, so just see if it exists */
1133 		if (stat(name, &sb) == 0)
1134 			return(strdup(name));
1135 		return(NULL);
1136 	}
1137 	moduledir_rebuild();
1138 	result = NULL;
1139 	namelen = strlen(name);
1140 	STAILQ_FOREACH(mdp, &moduledir_list, d_link) {
1141 		result = file_lookup(mdp->d_path, name, namelen, extlist);
1142 		if (result)
1143 			break;
1144 	}
1145 	return(result);
1146 }
1147 
1148 #define	INT_ALIGN(base, ptr)	ptr = \
1149 	(base) + roundup2((ptr) - (base), sizeof(int))
1150 
1151 static char *
1152 mod_search_hints(struct moduledir *mdp, const char *modname,
1153 	struct mod_depend *verinfo)
1154 {
1155 	u_char	*cp, *recptr, *bufend, *best;
1156 	char	*result;
1157 	int		*intp, bestver, blen, clen, found, ival, modnamelen, reclen;
1158 
1159 	moduledir_readhints(mdp);
1160 	modnamelen = strlen(modname);
1161 	found = 0;
1162 	result = NULL;
1163 	bestver = 0;
1164 	if (mdp->d_hints == NULL)
1165 		goto bad;
1166 	recptr = mdp->d_hints;
1167 	bufend = recptr + mdp->d_hintsz;
1168 	clen = blen = 0;
1169 	best = cp = NULL;
1170 	while (recptr < bufend && !found) {
1171 		intp = (int*)recptr;
1172 		reclen = *intp++;
1173 		ival = *intp++;
1174 		cp = (u_char*)intp;
1175 		switch (ival) {
1176 		case MDT_VERSION:
1177 			clen = *cp++;
1178 			if (clen != modnamelen || bcmp(cp, modname, clen) != 0)
1179 				break;
1180 			cp += clen;
1181 			INT_ALIGN(mdp->d_hints, cp);
1182 			ival = *(int*)cp;
1183 			cp += sizeof(int);
1184 			clen = *cp++;
1185 			if (verinfo == NULL || ival == verinfo->md_ver_preferred) {
1186 				found = 1;
1187 				break;
1188 			}
1189 			if (ival >= verinfo->md_ver_minimum &&
1190 			  ival <= verinfo->md_ver_maximum &&
1191 			  ival > bestver) {
1192 				bestver = ival;
1193 				best = cp;
1194 				blen = clen;
1195 			}
1196 			break;
1197 		default:
1198 			break;
1199 		}
1200 		recptr += reclen + sizeof(int);
1201 	}
1202 	/*
1203 	 * Finally check if KLD is in the place
1204 	 */
1205 	if (found)
1206 		result = file_lookup(mdp->d_path, (const char *)cp, clen, NULL);
1207 	else if (best)
1208 		result = file_lookup(mdp->d_path, (const char *)best, blen, NULL);
1209 bad:
1210 	/*
1211 	 * If nothing found or hints is absent - fallback to the old way
1212 	 * by using "kldname[.ko]" as module name.
1213 	 */
1214 	if (!found && !bestver && result == NULL)
1215 		result = file_lookup(mdp->d_path, modname, modnamelen, kld_ext_list);
1216 	return result;
1217 }
1218 
1219 static int
1220 getint(void **ptr)
1221 {
1222 	int *p = *ptr;
1223 	int rv;
1224 
1225 	p = (int *)roundup2((intptr_t)p, sizeof(int));
1226 	rv = *p++;
1227 	*ptr = p;
1228 	return rv;
1229 }
1230 
1231 static void
1232 getstr(void **ptr, char *val)
1233 {
1234 	int *p = *ptr;
1235 	char *c = (char *)p;
1236 	int len = *(uint8_t *)c;
1237 
1238 	memcpy(val, c + 1, len);
1239 	val[len] = 0;
1240 	c += len + 1;
1241 	*ptr = (void *)c;
1242 }
1243 
1244 static int
1245 pnpval_as_int(const char *val, const char *pnpinfo)
1246 {
1247 	int rv;
1248 	char key[256];
1249 	char *cp;
1250 
1251 	if (pnpinfo == NULL)
1252 		return -1;
1253 
1254 	cp = strchr(val, ';');
1255 	key[0] = ' ';
1256 	if (cp == NULL)
1257 		strlcpy(key + 1, val, sizeof(key) - 1);
1258 	else {
1259 		memcpy(key + 1, val, cp - val);
1260 		key[cp - val + 1] = '\0';
1261 	}
1262 	strlcat(key, "=", sizeof(key));
1263 	if (strncmp(key + 1, pnpinfo, strlen(key + 1)) == 0)
1264 		rv = strtol(pnpinfo + strlen(key + 1), NULL, 0);
1265 	else {
1266 		cp = strstr(pnpinfo, key);
1267 		if (cp == NULL)
1268 			rv = -1;
1269 		else
1270 			rv = strtol(cp + strlen(key), NULL, 0);
1271 	}
1272 	return rv;
1273 }
1274 
1275 static void
1276 quoted_strcpy(char *dst, const char *src)
1277 {
1278 	char q = ' ';
1279 
1280 	if (*src == '\'' || *src == '"')
1281 		q = *src++;
1282 	while (*src && *src != q)
1283 		*dst++ = *src++; // XXX backtick quoting
1284 	*dst++ = '\0';
1285 	// XXX overflow
1286 }
1287 
1288 static char *
1289 pnpval_as_str(const char *val, const char *pnpinfo)
1290 {
1291 	static char retval[256];
1292 	char key[256];
1293 	char *cp;
1294 
1295 	if (pnpinfo == NULL) {
1296 		*retval = '\0';
1297 		return retval;
1298 	}
1299 
1300 	cp = strchr(val, ';');
1301 	key[0] = ' ';
1302 	if (cp == NULL)
1303 		strlcpy(key + 1, val, sizeof(key) - 1);
1304 	else {
1305 		memcpy(key + 1, val, cp - val);
1306 		key[cp - val + 1] = '\0';
1307 	}
1308 	strlcat(key, "=", sizeof(key));
1309 	if (strncmp(key + 1, pnpinfo, strlen(key + 1)) == 0)
1310 		quoted_strcpy(retval, pnpinfo + strlen(key + 1));
1311 	else {
1312 		cp = strstr(pnpinfo, key);
1313 		if (cp == NULL)
1314 			strcpy(retval, "MISSING");
1315 		else
1316 			quoted_strcpy(retval, cp + strlen(key));
1317 	}
1318 	return retval;
1319 }
1320 
1321 static char *
1322 devmatch_search_hints(struct moduledir *mdp, const char *bus, const char *dev, const char *pnpinfo)
1323 {
1324 	char val1[256], val2[256];
1325 	int ival, len, ents, i, notme, mask, bit, v, found;
1326 	void *ptr, *walker, *hints_end;
1327 	char *lastmod = NULL, *cp, *s;
1328 
1329 	moduledir_readhints(mdp);
1330 	found = 0;
1331 	if (mdp->d_hints == NULL)
1332 		goto bad;
1333 	walker = mdp->d_hints;
1334 	hints_end = walker + mdp->d_hintsz;
1335 	while (walker < hints_end && !found) {
1336 		len = getint(&walker);
1337 		ival = getint(&walker);
1338 		ptr = walker;
1339 		switch (ival) {
1340 		case MDT_VERSION:
1341 			getstr(&ptr, val1);
1342 			ival = getint(&ptr);
1343 			getstr(&ptr, val2);
1344 			if (pnp_dump_flag || pnp_verbose_flag)
1345 				printf("Version: if %s.%d kmod %s\n", val1, ival, val2);
1346 			break;
1347 		case MDT_MODULE:
1348 			getstr(&ptr, val1);
1349 			getstr(&ptr, val2);
1350 			if (lastmod)
1351 				free(lastmod);
1352 			lastmod = strdup(val2);
1353 			if (pnp_dump_flag || pnp_verbose_flag)
1354 				printf("module %s in %s\n", val1, val1);
1355 			break;
1356 		case MDT_PNP_INFO:
1357 			if (!pnp_dump_flag && !pnp_unbound_flag && lastmod && strcmp(lastmod, "kernel") == 0)
1358 				break;
1359 			getstr(&ptr, val1);
1360 			getstr(&ptr, val2);
1361 			ents = getint(&ptr);
1362 			if (pnp_dump_flag || pnp_verbose_flag)
1363 				printf("PNP info for bus %s format %s %d entries (%s)\n",
1364 				    val1, val2, ents, lastmod);
1365 			if (strcmp(val1, "usb") == 0) {
1366 				if (pnp_verbose_flag)
1367 					printf("Treating usb as uhub -- bug in source table still?\n");
1368 				strcpy(val1, "uhub");
1369 			}
1370 			if (bus && strcmp(val1, bus) != 0) {
1371 				if (pnp_verbose_flag)
1372 					printf("Skipped because table for bus %s, looking for %s\n",
1373 					    val1, bus);
1374 				break;
1375 			}
1376 			for (i = 0; i < ents; i++) {
1377 				if (pnp_verbose_flag)
1378 					printf("---------- Entry %d ----------\n", i);
1379 				if (pnp_dump_flag)
1380 					printf("   ");
1381 				cp = val2;
1382 				notme = 0;
1383 				mask = -1;
1384 				bit = -1;
1385 				do {
1386 					switch (*cp) {
1387 						/* All integer fields */
1388 					case 'I':
1389 					case 'J':
1390 					case 'G':
1391 					case 'L':
1392 					case 'M':
1393 						ival = getint(&ptr);
1394 						if (pnp_dump_flag) {
1395 							printf("%#x:", ival);
1396 							break;
1397 						}
1398 						if (bit >= 0 && ((1 << bit) & mask) == 0)
1399 							break;
1400 						v = pnpval_as_int(cp + 2, pnpinfo);
1401 						if (pnp_verbose_flag)
1402 							printf("Matching %s (%c) table=%#x tomatch=%#x\n",
1403 							    cp + 2, *cp, v, ival);
1404 						switch (*cp) {
1405 						case 'J':
1406 							if (ival == -1)
1407 								break;
1408 							/*FALLTHROUGH*/
1409 						case 'I':
1410 							if (v != ival)
1411 								notme++;
1412 							break;
1413 						case 'G':
1414 							if (v < ival)
1415 								notme++;
1416 							break;
1417 						case 'L':
1418 							if (v > ival)
1419 								notme++;
1420 							break;
1421 						case 'M':
1422 							mask = ival;
1423 							break;
1424 						}
1425 						break;
1426 						/* String fields */
1427 					case 'D':
1428 					case 'Z':
1429 						getstr(&ptr, val1);
1430 						if (pnp_dump_flag) {
1431 							printf("'%s':", val1);
1432 							break;
1433 						}
1434 						if (*cp == 'D')
1435 							break;
1436 						s = pnpval_as_str(cp + 2, pnpinfo);
1437 						if (strcmp(s, val1) != 0)
1438 							notme++;
1439 						break;
1440 						/* Key override fields, required to be last in the string */
1441 					case 'T':
1442 						/*
1443 						 * This is imperfect and only does one key and will be redone
1444 						 * to be more general for multiple keys. Currently, nothing
1445 						 * does that.
1446 						 */
1447 						if (pnp_dump_flag)				/* No per-row data stored */
1448 							break;
1449 						if (cp[strlen(cp) - 1] == ';')		/* Skip required ; at end */
1450 							cp[strlen(cp) - 1] = '\0';	/* in case it's not there */
1451 						if ((s = strstr(pnpinfo, cp + 2)) == NULL)
1452 							notme++;
1453 						else if (s > pnpinfo && s[-1] != ' ')
1454 							notme++;
1455 						break;
1456 					default:
1457 						printf("Unknown field type %c\n:", *cp);
1458 						break;
1459 					}
1460 					bit++;
1461 					cp = strchr(cp, ';');
1462 					if (cp)
1463 						cp++;
1464 				} while (cp && *cp);
1465 				if (pnp_dump_flag)
1466 					printf("\n");
1467 				else if (!notme) {
1468 					if (!pnp_unbound_flag) {
1469 						if (pnp_verbose_flag)
1470 							printf("Matches --- %s ---\n", lastmod);
1471 					}
1472 					found++;
1473 				}
1474 			}
1475 			break;
1476 		default:
1477 			break;
1478 		}
1479 		walker = (void *)(len - sizeof(int) + (intptr_t)walker);
1480 	}
1481 	if (pnp_unbound_flag && found == 0 && *pnpinfo) {
1482 		if (pnp_verbose_flag)
1483 			printf("------------------------- ");
1484 		printf("%s on %s pnpinfo %s", *dev ? dev : "unattached", bus, pnpinfo);
1485 		if (pnp_verbose_flag)
1486 			printf(" -------------------------");
1487 		printf("\n");
1488 	}
1489 	if (found != 0)
1490 		return (lastmod);
1491 	free(lastmod);
1492 
1493 bad:
1494 	return (NULL);
1495 }
1496 
1497 /*
1498  * Attempt to locate the file containing the module (name)
1499  */
1500 static char *
1501 mod_searchmodule(char *name, struct mod_depend *verinfo)
1502 {
1503 	struct	moduledir *mdp;
1504 	char	*result;
1505 
1506 	moduledir_rebuild();
1507 	/*
1508 	 * Now we ready to lookup module in the given directories
1509 	 */
1510 	result = NULL;
1511 	STAILQ_FOREACH(mdp, &moduledir_list, d_link) {
1512 		result = mod_search_hints(mdp, name, verinfo);
1513 		if (result)
1514 			break;
1515 	}
1516 
1517 	return(result);
1518 }
1519 
1520 static char *
1521 mod_searchmodule_pnpinfo(const char *bus, const char *pnpinfo)
1522 {
1523 	struct	moduledir *mdp;
1524 	char	*result;
1525 
1526 	moduledir_rebuild();
1527 	/*
1528 	 * Now we ready to lookup module in the given directories
1529 	 */
1530 	result = NULL;
1531 	STAILQ_FOREACH(mdp, &moduledir_list, d_link) {
1532 		result = devmatch_search_hints(mdp, bus, NULL, pnpinfo);
1533 		if (result)
1534 			break;
1535 	}
1536 
1537 	return(result);
1538 }
1539 
1540 int
1541 file_addmodule(struct preloaded_file *fp, char *modname, int version,
1542 	struct kernel_module **newmp)
1543 {
1544 	struct kernel_module *mp;
1545 	struct mod_depend mdepend;
1546 
1547 	bzero(&mdepend, sizeof(mdepend));
1548 	mdepend.md_ver_preferred = version;
1549 	mp = file_findmodule(fp, modname, &mdepend);
1550 	if (mp)
1551 		return (EEXIST);
1552 	mp = calloc(1, sizeof(struct kernel_module));
1553 	if (mp == NULL)
1554 		return (ENOMEM);
1555 	mp->m_name = strdup(modname);
1556 	if (mp->m_name == NULL) {
1557 		free(mp);
1558 		return (ENOMEM);
1559 	}
1560 	mp->m_version = version;
1561 	mp->m_fp = fp;
1562 	mp->m_next = fp->f_modules;
1563 	fp->f_modules = mp;
1564 	if (newmp)
1565 		*newmp = mp;
1566 	return (0);
1567 }
1568 
1569 /*
1570  * Throw a file away
1571  */
1572 void
1573 file_discard(struct preloaded_file *fp)
1574 {
1575 	struct file_metadata	*md, *md1;
1576 	struct kernel_module	*mp, *mp1;
1577 	if (fp == NULL)
1578 		return;
1579 	md = fp->f_metadata;
1580 	while (md) {
1581 		md1 = md;
1582 		md = md->md_next;
1583 		free(md1);
1584 	}
1585 	mp = fp->f_modules;
1586 	while (mp) {
1587 		free(mp->m_name);
1588 		mp1 = mp;
1589 		mp = mp->m_next;
1590 		free(mp1);
1591 	}
1592 	free(fp->f_name);
1593 	free(fp->f_type);
1594 	free(fp->f_args);
1595 	free(fp);
1596 }
1597 
1598 /*
1599  * Allocate a new file; must be used instead of malloc()
1600  * to ensure safe initialisation.
1601  */
1602 struct preloaded_file *
1603 file_alloc(void)
1604 {
1605 
1606 	return (calloc(1, sizeof(struct preloaded_file)));
1607 }
1608 
1609 /*
1610  * Add a module to the chain
1611  */
1612 static void
1613 file_insert_tail(struct preloaded_file *fp)
1614 {
1615 	struct preloaded_file	*cm;
1616 
1617 	/* Append to list of loaded file */
1618 	fp->f_next = NULL;
1619 	if (preloaded_files == NULL) {
1620 		preloaded_files = fp;
1621 	} else {
1622 		for (cm = preloaded_files; cm->f_next != NULL; cm = cm->f_next)
1623 			;
1624 		cm->f_next = fp;
1625 	}
1626 }
1627 
1628 /*
1629  * Remove module from the chain
1630  */
1631 static void
1632 file_remove(struct preloaded_file *fp)
1633 {
1634 	struct preloaded_file   *cm;
1635 
1636 	if (preloaded_files == NULL)
1637 		return;
1638 
1639 	if (preloaded_files == fp) {
1640 		preloaded_files = fp->f_next;
1641 		return;
1642         }
1643         for (cm = preloaded_files; cm->f_next != NULL; cm = cm->f_next) {
1644 		if (cm->f_next == fp) {
1645 			cm->f_next = fp->f_next;
1646 			return;
1647 		}
1648 	}
1649 }
1650 
1651 static char *
1652 moduledir_fullpath(struct moduledir *mdp, const char *fname)
1653 {
1654 	char *cp;
1655 
1656 	cp = malloc(strlen(mdp->d_path) + strlen(fname) + 2);
1657 	if (cp == NULL)
1658 		return NULL;
1659 	strcpy(cp, mdp->d_path);
1660 	strcat(cp, "/");
1661 	strcat(cp, fname);
1662 	return (cp);
1663 }
1664 
1665 /*
1666  * Read linker.hints file into memory performing some sanity checks.
1667  */
1668 static void
1669 moduledir_readhints(struct moduledir *mdp)
1670 {
1671 	struct stat	st;
1672 	char	*path;
1673 	int		fd, size, version;
1674 
1675 	if (mdp->d_hints != NULL || (mdp->d_flags & MDIR_NOHINTS))
1676 		return;
1677 	path = moduledir_fullpath(mdp, "linker.hints");
1678 	if (stat(path, &st) != 0 ||
1679 	  st.st_size < (ssize_t)(sizeof(version) + sizeof(int)) ||
1680 	  st.st_size > LINKER_HINTS_MAX || (fd = open(path, O_RDONLY)) < 0) {
1681 		free(path);
1682 		mdp->d_flags |= MDIR_NOHINTS;
1683 		return;
1684 	}
1685 	free(path);
1686 	size = read(fd, &version, sizeof(version));
1687 	if (size != sizeof(version) || version != LINKER_HINTS_VERSION)
1688 		goto bad;
1689 	size = st.st_size - size;
1690 	mdp->d_hints = malloc(size);
1691 	if (mdp->d_hints == NULL)
1692 		goto bad;
1693 	if (read(fd, mdp->d_hints, size) != size)
1694 		goto bad;
1695 	mdp->d_hintsz = size;
1696 	close(fd);
1697 	return;
1698 bad:
1699 	close(fd);
1700 	free(mdp->d_hints);
1701 	mdp->d_hints = NULL;
1702 	mdp->d_flags |= MDIR_NOHINTS;
1703 	return;
1704 }
1705 
1706 /*
1707  * Extract directories from the ';' separated list, remove duplicates.
1708  */
1709 static void
1710 moduledir_rebuild(void)
1711 {
1712 	struct	moduledir *mdp, *mtmp;
1713 	const char	*path, *cp, *ep;
1714 	size_t	cplen;
1715 
1716 	path = getenv("module_path");
1717 	if (path == NULL)
1718 		path = default_searchpath;
1719 	/*
1720 	 * Rebuild list of module directories if it changed
1721 	 */
1722 	STAILQ_FOREACH(mdp, &moduledir_list, d_link)
1723 		mdp->d_flags |= MDIR_REMOVED;
1724 
1725 	for (ep = path; *ep != 0;  ep++) {
1726 		cp = ep;
1727 		for (; *ep != 0 && *ep != ';'; ep++)
1728 			;
1729 		/*
1730 		 * Ignore trailing slashes
1731 		 */
1732 		for (cplen = ep - cp; cplen > 1 && cp[cplen - 1] == '/'; cplen--)
1733 			;
1734 		STAILQ_FOREACH(mdp, &moduledir_list, d_link) {
1735 			if (strlen(mdp->d_path) != cplen ||	bcmp(cp, mdp->d_path, cplen) != 0)
1736 				continue;
1737 			mdp->d_flags &= ~MDIR_REMOVED;
1738 			break;
1739 		}
1740 		if (mdp == NULL) {
1741 			mdp = malloc(sizeof(*mdp) + cplen + 1);
1742 			if (mdp == NULL)
1743 				return;
1744 			mdp->d_path = (char*)(mdp + 1);
1745 			bcopy(cp, mdp->d_path, cplen);
1746 			mdp->d_path[cplen] = 0;
1747 			mdp->d_hints = NULL;
1748 			mdp->d_flags = 0;
1749 			STAILQ_INSERT_TAIL(&moduledir_list, mdp, d_link);
1750 		}
1751 		if (*ep == 0)
1752 			break;
1753 	}
1754 	/*
1755 	 * Delete unused directories if any
1756 	 */
1757 	mdp = STAILQ_FIRST(&moduledir_list);
1758 	while (mdp) {
1759 		if ((mdp->d_flags & MDIR_REMOVED) == 0) {
1760 			mdp = STAILQ_NEXT(mdp, d_link);
1761 		} else {
1762 			free(mdp->d_hints);
1763 			mtmp = mdp;
1764 			mdp = STAILQ_NEXT(mdp, d_link);
1765 			STAILQ_REMOVE(&moduledir_list, mtmp, moduledir, d_link);
1766 			free(mtmp);
1767 		}
1768 	}
1769 	return;
1770 }
1771