xref: /illumos-gate/usr/src/boot/common/module.c (revision 55fea89d)
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 
29 /*
30  * file/module function dispatcher, support, etc.
31  */
32 
33 #include <stand.h>
34 #include <string.h>
35 #include <sys/param.h>
36 #include <sys/linker.h>
37 #include <sys/module.h>
38 #include <sys/queue.h>
39 #include <sys/stdint.h>
40 #include <sys/tem_impl.h>
41 #include <sys/font.h>
42 #include <sys/sha1.h>
43 #include <libcrypto.h>
44 
45 #include "bootstrap.h"
46 
47 #if defined(EFI)
48 #define	PTOV(pa)	((void *)pa)
49 #else
50 #include "../i386/btx/lib/btxv86.h"
51 #endif
52 
53 #define	MDIR_REMOVED	0x0001
54 #define	MDIR_NOHINTS	0x0002
55 
56 struct moduledir {
57 	char	*d_path;	/* path of modules directory */
58 	uchar_t	*d_hints;	/* content of linker.hints file */
59 	int	d_hintsz;	/* size of hints data */
60 	int	d_flags;
61 	STAILQ_ENTRY(moduledir) d_link;
62 };
63 
64 static int file_load(char *, vm_offset_t, struct preloaded_file **);
65 static int file_load_dependencies(struct preloaded_file *);
66 static char *file_search(const char *, const char **);
67 static struct kernel_module *file_findmodule(struct preloaded_file *, char *,
68     struct mod_depend *);
69 static int file_havepath(const char *);
70 static char *mod_searchmodule(char *, struct mod_depend *);
71 static void file_insert_tail(struct preloaded_file *);
72 static void file_remove(struct preloaded_file *);
73 struct file_metadata *metadata_next(struct file_metadata *, int);
74 static void moduledir_readhints(struct moduledir *);
75 static void moduledir_rebuild(void);
76 
77 /* load address should be tweaked by first module loaded (kernel) */
78 static vm_offset_t loadaddr = 0;
79 
80 #if defined(LOADER_FDT_SUPPORT)
81 static const char *default_searchpath = "/boot/kernel;/boot/modules;/boot/dtb";
82 #else
83 static const char *default_searchpath = "/platform/i86pc";
84 #endif
85 
86 static STAILQ_HEAD(, moduledir) moduledir_list =
87     STAILQ_HEAD_INITIALIZER(moduledir_list);
88 
89 struct preloaded_file *preloaded_files = NULL;
90 
91 static const char *kld_ext_list[] = {
92 	".ko",
93 	"",
94 	".debug",
95 	NULL
96 };
97 
98 
99 /*
100  * load an object, either a disk file or code module.
101  *
102  * To load a file, the syntax is:
103  *
104  * load -t <type> <path>
105  *
106  * code modules are loaded as:
107  *
108  * load <path> <options>
109  */
110 
111 COMMAND_SET(load, "load", "load a kernel or module", command_load);
112 
113 static int
114 command_load(int argc, char *argv[])
115 {
116 	char *typestr;
117 	int dofile, dokld, ch, error;
118 
119 	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 	while ((ch = getopt(argc, argv, "kt:")) != -1) {
128 		switch (ch) {
129 		case 'k':
130 			dokld = 1;
131 			break;
132 		case 't':
133 			typestr = optarg;
134 			dofile = 1;
135 			break;
136 		case '?':
137 		default:
138 			/* getopt has already reported an error */
139 			return (CMD_OK);
140 		}
141 	}
142 	argv += (optind - 1);
143 	argc -= (optind - 1);
144 
145 	printf("Loading %s...\n", argv[1]);
146 	/*
147 	 * Request to load a raw file?
148 	 */
149 	if (dofile) {
150 		struct preloaded_file *fp;
151 
152 		if ((typestr == NULL) || (*typestr == 0)) {
153 			command_errmsg = "invalid load type";
154 			return (CMD_CRIT);
155 		}
156 
157 		if (file_findfile(argv[1], typestr) != NULL) {
158 			(void) snprintf(command_errbuf, sizeof (command_errbuf),
159 			    "warning: file '%s' already loaded", argv[1]);
160 			return (CMD_WARN);
161 		}
162 
163 		fp = file_loadraw(argv[1], typestr, argc - 2, argv + 2, 1);
164 		if (fp != NULL)
165 			return (CMD_OK);
166 
167 		/* Failing to load mfs_root is never going to end well! */
168 		if (strcmp("mfs_root", typestr) == 0)
169 			return (CMD_FATAL);
170 
171 		return (CMD_ERROR);
172 	}
173 	/*
174 	 * Do we have explicit KLD load ?
175 	 */
176 	if (dokld || file_havepath(argv[1])) {
177 		error = mod_loadkld(argv[1], argc - 2, argv + 2);
178 		if (error == EEXIST) {
179 			(void) snprintf(command_errbuf, sizeof (command_errbuf),
180 			    "warning: KLD '%s' already loaded", argv[1]);
181 			return (CMD_WARN);
182 		}
183 
184 		return (error == 0 ? CMD_OK : CMD_CRIT);
185 	}
186 	/*
187 	 * Looks like a request for a module.
188 	 */
189 	error = mod_load(argv[1], NULL, argc - 2, argv + 2);
190 	if (error == EEXIST) {
191 		(void) snprintf(command_errbuf, sizeof (command_errbuf),
192 		    "warning: module '%s' already loaded", argv[1]);
193 		return (CMD_WARN);
194 	}
195 
196 	return (error == 0 ? CMD_OK : CMD_CRIT);
197 }
198 
199 void
200 unload(void)
201 {
202 	struct preloaded_file *fp;
203 
204 	while (preloaded_files != NULL) {
205 		fp = preloaded_files;
206 		preloaded_files = preloaded_files->f_next;
207 		file_discard(fp);
208 	}
209 	loadaddr = 0;
210 	(void) unsetenv("kernelname");
211 }
212 
213 COMMAND_SET(unload, "unload", "unload all modules", command_unload);
214 
215 static int
216 command_unload(int argc __unused, char *argv[] __unused)
217 {
218 	unload();
219 	return (CMD_OK);
220 }
221 
222 COMMAND_SET(lsmod, "lsmod", "list loaded modules", command_lsmod);
223 
224 static int
225 command_lsmod(int argc, char *argv[])
226 {
227 	struct preloaded_file *fp;
228 	struct kernel_module *mp;
229 	struct file_metadata *md;
230 	char lbuf[80];
231 	int ch, verbose, hash, ret = 0;
232 
233 	verbose = 0;
234 	hash = 0;
235 	optind = 1;
236 	optreset = 1;
237 	while ((ch = getopt(argc, argv, "vs")) != -1) {
238 		switch (ch) {
239 		case 'v':
240 			verbose = 1;
241 			break;
242 		case 's':
243 			hash = 1;
244 			break;
245 		case '?':
246 		default:
247 			/* getopt has already reported an error */
248 			return (CMD_OK);
249 		}
250 	}
251 
252 	pager_open();
253 	for (fp = preloaded_files; fp; fp = fp->f_next) {
254 		(void) snprintf(lbuf, sizeof (lbuf), " %p: ",
255 		    (void *) fp->f_addr);
256 		(void) pager_output(lbuf);
257 		(void) pager_output(fp->f_name);
258 		(void) snprintf(lbuf, sizeof (lbuf), " (%s, 0x%lx)\n",
259 		    fp->f_type, (long)fp->f_size);
260 		if (pager_output(lbuf))
261 			break;
262 		if (fp->f_args != NULL) {
263 			(void) pager_output("    args: ");
264 			(void) pager_output(fp->f_args);
265 			if (pager_output("\n"))
266 				break;
267 			if (strcmp(fp->f_type, "hash") == 0) {
268 				size_t dsize;
269 
270 				(void) pager_output("    contents: ");
271 				dsize = fp->f_size + 1;
272 				if (sizeof (lbuf) < dsize)
273 					dsize = sizeof (lbuf);
274 				(void) strlcpy(lbuf, ptov(fp->f_addr), dsize);
275 				if (pager_output(lbuf))
276 					break;
277 			}
278 		}
279 
280 		if (hash == 1) {
281 			void *ptr = PTOV(fp->f_addr);
282 
283 			(void) pager_output("  hash: ");
284 			sha1(ptr, fp->f_size, (uint8_t *)lbuf);
285 			for (int i = 0; i < SHA1_DIGEST_LENGTH; i++)
286 				printf("%02x", (int)(lbuf[i] & 0xff));
287 			if (pager_output("\n"))
288 				break;
289 		}
290 
291 		if (fp->f_modules) {
292 			(void) pager_output("  modules: ");
293 			for (mp = fp->f_modules; mp; mp = mp->m_next) {
294 				(void) snprintf(lbuf, sizeof (lbuf), "%s.%d ",
295 				    mp->m_name, mp->m_version);
296 				(void) pager_output(lbuf);
297 			}
298 			if (pager_output("\n"))
299 				break;
300 		}
301 		if (verbose) {
302 			/*
303 			 * XXX could add some formatting smarts here to
304 			 * display some better
305 			 */
306 			for (md = fp->f_metadata; md != NULL;
307 			    md = md->md_next) {
308 				(void) snprintf(lbuf, sizeof (lbuf),
309 				    "      0x%04x, 0x%lx\n",
310 				    md->md_type, (long)md->md_size);
311 				if ((ret = pager_output(lbuf)))
312 					break;
313 			}
314 		}
315 		if (ret != 0)
316 			break;
317 	}
318 	pager_close();
319 	return (CMD_OK);
320 }
321 
322 /*
323  * File level interface, functions file_*
324  */
325 int
326 file_load(char *filename, vm_offset_t dest, struct preloaded_file **result)
327 {
328 	static int last_file_format = 0;
329 	struct preloaded_file *fp;
330 	int error;
331 	int i;
332 
333 	if (preloaded_files == NULL)
334 		last_file_format = 0;
335 
336 	if (archsw.arch_loadaddr != NULL)
337 		dest = archsw.arch_loadaddr(LOAD_RAW, filename, dest);
338 
339 	error = EFTYPE;
340 	for (i = last_file_format, fp = NULL;
341 	    file_formats[i] && fp == NULL; i++) {
342 		error = (file_formats[i]->l_load)(filename, dest, &fp);
343 		if (error == 0) {
344 			/* remember the loader */
345 			fp->f_loader = last_file_format = i;
346 			*result = fp;
347 			break;
348 		} else if (last_file_format == i && i != 0) {
349 			/* Restart from the beginning */
350 			i = -1;
351 			last_file_format = 0;
352 			fp = NULL;
353 			continue;
354 		}
355 		if (error == EFTYPE)
356 			continue;	/* Unknown to this handler? */
357 		if (error) {
358 			(void) snprintf(command_errbuf, sizeof (command_errbuf),
359 			    "can't load file '%s': %s", filename,
360 			    strerror(error));
361 			break;
362 		}
363 	}
364 	return (error);
365 }
366 
367 static int
368 file_load_dependencies(struct preloaded_file *base_file)
369 {
370 	struct file_metadata *md;
371 	struct preloaded_file *fp;
372 	struct mod_depend *verinfo;
373 	struct kernel_module *mp;
374 	char *dmodname;
375 	int error;
376 
377 	md = file_findmetadata(base_file, MODINFOMD_DEPLIST);
378 	if (md == NULL)
379 		return (0);
380 	error = 0;
381 	do {
382 		verinfo = (struct mod_depend *)md->md_data;
383 		dmodname = (char *)(verinfo + 1);
384 		if (file_findmodule(NULL, dmodname, verinfo) == NULL) {
385 			printf("loading required module '%s'\n", dmodname);
386 			error = mod_load(dmodname, verinfo, 0, NULL);
387 			if (error)
388 				break;
389 			/*
390 			 * If module loaded via kld name which isn't listed
391 			 * in the linker.hints file, we should check if it have
392 			 * required version.
393 			 */
394 			mp = file_findmodule(NULL, dmodname, verinfo);
395 			if (mp == NULL) {
396 				(void) snprintf(command_errbuf,
397 				    sizeof (command_errbuf),
398 				    "module '%s' exists but with wrong version",
399 				    dmodname);
400 				error = ENOENT;
401 				break;
402 			}
403 		}
404 		md = metadata_next(md, MODINFOMD_DEPLIST);
405 	} while (md);
406 	if (!error)
407 		return (0);
408 	/* Load failed; discard everything */
409 	while (base_file != NULL) {
410 		fp = base_file;
411 		base_file = base_file->f_next;
412 		file_discard(fp);
413 	}
414 	return (error);
415 }
416 
417 /*
418  * Calculate the size of the environment module.
419  * The environment is list of name=value C strings, ending with a '\0' byte.
420  */
421 static size_t
422 env_get_size(void)
423 {
424 	size_t size = 0;
425 	struct env_var *ep;
426 
427 	/* Traverse the environment. */
428 	for (ep = environ; ep != NULL; ep = ep->ev_next) {
429 		size += strlen(ep->ev_name);
430 		size++;		/* "=" */
431 		if (ep->ev_value != NULL)
432 			size += strlen(ep->ev_value);
433 		size++;		/* nul byte */
434 	}
435 	size++;			/* nul byte */
436 	return (size);
437 }
438 
439 static void
440 module_hash(struct preloaded_file *fp, void *addr, size_t size)
441 {
442 	uint8_t hash[SHA1_DIGEST_LENGTH];
443 	char ascii[2 * SHA1_DIGEST_LENGTH + 1];
444 	int i;
445 
446 	sha1(addr, size, hash);
447 	for (i = 0; i < SHA1_DIGEST_LENGTH; i++) {
448 		(void) snprintf(ascii + 2 * i, sizeof (ascii) - 2 * i, "%02x",
449 		    hash[i] & 0xff);
450 	}
451 	/* Out of memory here is not fatal issue. */
452 	(void) asprintf(&fp->f_args, "hash=%s", ascii);
453 }
454 
455 /*
456  * Create virtual module for environment variables.
457  * This module should be created as late as possible before executing
458  * the OS kernel, or we may miss some environment variable updates.
459  */
460 void
461 build_environment_module(void)
462 {
463 	struct preloaded_file *fp;
464 	size_t size;
465 	char *name = "environment";
466 	vm_offset_t laddr;
467 
468 	/* We can't load first */
469 	if (file_findfile(NULL, NULL) == NULL) {
470 		printf("Can not load environment module: %s\n",
471 		    "the kernel is not loaded");
472 		return;
473 	}
474 
475 	if (file_findfile(name, name) != NULL) {
476 		printf("warning: '%s' is already loaded\n", name);
477 		return;
478 	}
479 
480 	tem_save_state();	/* Ask tem to save it's state in env. */
481 	size = env_get_size();
482 
483 	fp = file_alloc();
484 	if (fp != NULL) {
485 		fp->f_name = strdup(name);
486 		fp->f_type = strdup(name);
487 	}
488 
489 	if (fp == NULL || fp->f_name == NULL || fp->f_type == NULL) {
490 		printf("Can not load environment module: %s\n",
491 		    "out of memory");
492 		file_discard(fp);
493 		return;
494 	}
495 
496 
497 	if (archsw.arch_loadaddr != NULL)
498 		loadaddr = archsw.arch_loadaddr(LOAD_MEM, &size, loadaddr);
499 
500 	if (loadaddr == 0) {
501 		printf("Can not load environment module: %s\n",
502 		    "out of memory");
503 		file_discard(fp);
504 		return;
505 	}
506 
507 	laddr = bi_copyenv(loadaddr);
508 	/* Looks OK so far; populate control structure */
509 	module_hash(fp, PTOV(loadaddr), laddr - loadaddr);
510 	fp->f_loader = -1;
511 	fp->f_addr = loadaddr;
512 	fp->f_size = laddr - loadaddr;
513 
514 	/* recognise space consumption */
515 	loadaddr = laddr;
516 
517 	file_insert_tail(fp);
518 }
519 
520 void
521 build_font_module(void)
522 {
523 	bitmap_data_t *bd;
524 	struct font *fd;
525 	struct preloaded_file *fp;
526 	size_t size;
527 	uint32_t checksum;
528 	int i;
529 	char *name = "console-font";
530 	vm_offset_t laddr;
531 	struct font_info fi;
532 	struct fontlist *fl;
533 
534 	if (STAILQ_EMPTY(&fonts))
535 		return;
536 
537 	/* We can't load first */
538 	if (file_findfile(NULL, NULL) == NULL) {
539 		printf("Can not load font module: %s\n",
540 		    "the kernel is not loaded");
541 		return;
542 	}
543 
544 	if (file_findfile(name, name) != NULL) {
545 		printf("warning: '%s' is already loaded\n", name);
546 		return;
547 	}
548 
549 	/* helper pointers */
550 	bd = NULL;
551 	STAILQ_FOREACH(fl, &fonts, font_next) {
552 		if (tems.ts_font.vf_width == fl->font_data->width &&
553 		    tems.ts_font.vf_height == fl->font_data->height) {
554 			/*
555 			 * Kernel does have better built in font.
556 			 */
557 			if (fl->font_flags == FONT_BUILTIN)
558 				return;
559 
560 			bd = fl->font_data;
561 			break;
562 		}
563 	}
564 	if (bd == NULL)
565 		return;
566 	fd = bd->font;
567 
568 	fi.fi_width = fd->vf_width;
569 	checksum = fi.fi_width;
570 	fi.fi_height = fd->vf_height;
571 	checksum += fi.fi_height;
572 	fi.fi_bitmap_size = bd->uncompressed_size;
573 	checksum += fi.fi_bitmap_size;
574 
575 	size = roundup2(sizeof (struct font_info), 8);
576 	for (i = 0; i < VFNT_MAPS; i++) {
577 		fi.fi_map_count[i] = fd->vf_map_count[i];
578 		checksum += fi.fi_map_count[i];
579 		size += fd->vf_map_count[i] * sizeof (struct font_map);
580 		size += roundup2(size, 8);
581 	}
582 	size += bd->uncompressed_size;
583 
584 	fi.fi_checksum = -checksum;
585 
586 	fp = file_alloc();
587 	if (fp != NULL) {
588 		fp->f_name = strdup(name);
589 		fp->f_type = strdup(name);
590 	}
591 
592 	if (fp == NULL || fp->f_name == NULL || fp->f_type == NULL) {
593 		printf("Can not load font module: %s\n",
594 		    "out of memory");
595 		file_discard(fp);
596 		return;
597 	}
598 
599 	if (archsw.arch_loadaddr != NULL)
600 		loadaddr = archsw.arch_loadaddr(LOAD_MEM, &size, loadaddr);
601 
602 	if (loadaddr == 0) {
603 		printf("Can not load font module: %s\n",
604 		    "out of memory");
605 		file_discard(fp);
606 		return;
607 	}
608 
609 	laddr = loadaddr;
610 	laddr += archsw.arch_copyin(&fi, laddr, sizeof (struct font_info));
611 	laddr = roundup2(laddr, 8);
612 
613 	/* Copy maps. */
614 	for (i = 0; i < VFNT_MAPS; i++) {
615 		if (fd->vf_map_count[i] != 0) {
616 			laddr += archsw.arch_copyin(fd->vf_map[i], laddr,
617 			    fd->vf_map_count[i] * sizeof (struct font_map));
618 			laddr = roundup2(laddr, 8);
619 		}
620 	}
621 
622 	/* Copy the bitmap. */
623 	laddr += archsw.arch_copyin(fd->vf_bytes, laddr, fi.fi_bitmap_size);
624 
625 	/* Looks OK so far; populate control structure */
626 	module_hash(fp, PTOV(loadaddr), laddr - loadaddr);
627 	fp->f_loader = -1;
628 	fp->f_addr = loadaddr;
629 	fp->f_size = laddr - loadaddr;
630 
631 	/* recognise space consumption */
632 	loadaddr = laddr;
633 
634 	file_insert_tail(fp);
635 }
636 
637 /*
638  * We've been asked to load (fname) as (type), so just suck it in,
639  * no arguments or anything.
640  */
641 struct preloaded_file *
642 file_loadraw(const char *fname, char *type, int argc, char **argv, int insert)
643 {
644 	struct preloaded_file *fp;
645 	char *name;
646 	int fd, got;
647 	vm_offset_t laddr;
648 	struct stat st;
649 
650 	/* We can't load first */
651 	if ((file_findfile(NULL, NULL)) == NULL) {
652 		command_errmsg = "can't load file before kernel";
653 		return (NULL);
654 	}
655 
656 	/* locate the file on the load path */
657 	name = file_search(fname, NULL);
658 	if (name == NULL) {
659 		(void) snprintf(command_errbuf, sizeof (command_errbuf),
660 		    "can't find '%s'", fname);
661 		return (NULL);
662 	}
663 
664 	if ((fd = open(name, O_RDONLY)) < 0) {
665 		(void) snprintf(command_errbuf, sizeof (command_errbuf),
666 		    "can't open '%s': %s", name, strerror(errno));
667 		free(name);
668 		return (NULL);
669 	}
670 	if (fstat(fd, &st) < 0) {
671 		(void) close(fd);
672 		(void) snprintf(command_errbuf, sizeof (command_errbuf),
673 		    "stat error '%s': %s", name, strerror(errno));
674 		free(name);
675 		return (NULL);
676 	}
677 
678 	if (archsw.arch_loadaddr != NULL)
679 		loadaddr = archsw.arch_loadaddr(LOAD_RAW, name, loadaddr);
680 	if (loadaddr == 0) {
681 		(void) close(fd);
682 		(void) snprintf(command_errbuf, sizeof (command_errbuf),
683 		    "no memory to load %s", name);
684 		free(name);
685 		return (NULL);
686 	}
687 
688 	laddr = loadaddr;
689 	for (;;) {
690 		/* read in 4k chunks; size is not really important */
691 		got = archsw.arch_readin(fd, laddr, 4096);
692 		if (got == 0)			/* end of file */
693 			break;
694 		if (got < 0) {			/* error */
695 			(void) snprintf(command_errbuf, sizeof (command_errbuf),
696 			    "error reading '%s': %s", name, strerror(errno));
697 			free(name);
698 			(void) close(fd);
699 			if (archsw.arch_free_loadaddr != NULL &&
700 			    st.st_size != 0) {
701 				archsw.arch_free_loadaddr(loadaddr,
702 				    (uint64_t)
703 				    (roundup2(st.st_size, PAGE_SIZE) >> 12));
704 			}
705 			return (NULL);
706 		}
707 		laddr += got;
708 	}
709 
710 	/* Looks OK so far; create & populate control structure */
711 	fp = file_alloc();
712 	if (fp == NULL) {
713 		if (archsw.arch_free_loadaddr != NULL && st.st_size != 0)
714 			archsw.arch_free_loadaddr(loadaddr,
715 			    (uint64_t)(roundup2(st.st_size, PAGE_SIZE) >> 12));
716 		(void) snprintf(command_errbuf, sizeof (command_errbuf),
717 		    "no memory to load %s", name);
718 		free(name);
719 		(void) close(fd);
720 		return (NULL);
721 	}
722 
723 	fp->f_name = name;
724 	fp->f_args = unargv(argc, argv);
725 	fp->f_type = strdup(type);
726 	fp->f_metadata = NULL;
727 	fp->f_loader = -1;
728 	fp->f_addr = loadaddr;
729 	fp->f_size = laddr - loadaddr;
730 
731 	if (fp->f_type == NULL ||
732 	    (argc != 0 && fp->f_args == NULL)) {
733 		(void) close(fd);
734 		(void) snprintf(command_errbuf, sizeof (command_errbuf),
735 		    "no memory to load %s", name);
736 		file_discard(fp);
737 		return (NULL);
738 	}
739 	/* recognise space consumption */
740 	loadaddr = laddr;
741 
742 	/* Add to the list of loaded files */
743 	if (insert != 0)
744 		file_insert_tail(fp);
745 	(void) close(fd);
746 	return (fp);
747 }
748 
749 /*
750  * Load the module (name), pass it (argc),(argv), add container file
751  * to the list of loaded files.
752  * If module is already loaded just assign new argc/argv.
753  */
754 int
755 mod_load(char *modname, struct mod_depend *verinfo, int argc, char *argv[])
756 {
757 	struct kernel_module *mp;
758 	int err;
759 	char *filename;
760 
761 	if (file_havepath(modname)) {
762 		printf("Warning: mod_load() called instead of mod_loadkld() "
763 		    "for module '%s'\n", modname);
764 		return (mod_loadkld(modname, argc, argv));
765 	}
766 	/* see if module is already loaded */
767 	mp = file_findmodule(NULL, modname, verinfo);
768 	if (mp != NULL) {
769 		free(mp->m_args);
770 		mp->m_args = unargv(argc, argv);
771 		(void) snprintf(command_errbuf, sizeof (command_errbuf),
772 		    "warning: module '%s' already loaded", mp->m_name);
773 		return (0);
774 	}
775 	/* locate file with the module on the search path */
776 	filename = mod_searchmodule(modname, verinfo);
777 	if (filename == NULL) {
778 		(void) snprintf(command_errbuf, sizeof (command_errbuf),
779 		    "can't find '%s'", modname);
780 		return (ENOENT);
781 	}
782 	err = mod_loadkld(filename, argc, argv);
783 	free(filename);
784 	return (err);
785 }
786 
787 /*
788  * Load specified KLD. If path is omitted, then try to locate it via
789  * search path.
790  */
791 int
792 mod_loadkld(const char *kldname, int argc, char *argv[])
793 {
794 	struct preloaded_file *fp;
795 	int err;
796 	char *filename;
797 	vm_offset_t loadaddr_saved;
798 
799 	/*
800 	 * Get fully qualified KLD name
801 	 */
802 	filename = file_search(kldname, kld_ext_list);
803 	if (filename == NULL) {
804 		(void) snprintf(command_errbuf, sizeof (command_errbuf),
805 		    "can't find '%s'", kldname);
806 		return (ENOENT);
807 	}
808 	/*
809 	 * Check if KLD already loaded
810 	 */
811 	fp = file_findfile(filename, NULL);
812 	if (fp != NULL) {
813 		(void) snprintf(command_errbuf, sizeof (command_errbuf),
814 		    "warning: KLD '%s' already loaded", filename);
815 		free(filename);
816 		return (0);
817 	}
818 
819 	do {
820 		err = file_load(filename, loadaddr, &fp);
821 		if (err)
822 			break;
823 		fp->f_args = unargv(argc, argv);
824 		loadaddr_saved = loadaddr;
825 		loadaddr = fp->f_addr + fp->f_size;
826 		file_insert_tail(fp);	/* Add to the list of loaded files */
827 		if (file_load_dependencies(fp) != 0) {
828 			err = ENOENT;
829 			file_remove(fp);
830 			loadaddr = loadaddr_saved;
831 			fp = NULL;
832 			break;
833 		}
834 	} while (0);
835 	if (err == EFTYPE) {
836 		(void) snprintf(command_errbuf, sizeof (command_errbuf),
837 		    "don't know how to load module '%s'", filename);
838 	}
839 	if (err)
840 		file_discard(fp);
841 	free(filename);
842 	return (err);
843 }
844 
845 /*
846  * Find a file matching (name) and (type).
847  * NULL may be passed as a wildcard to either.
848  */
849 struct preloaded_file *
850 file_findfile(const char *name, const char *type)
851 {
852 	struct preloaded_file *fp;
853 
854 	for (fp = preloaded_files; fp != NULL; fp = fp->f_next) {
855 		if (((name == NULL) || strcmp(name, fp->f_name) == 0) &&
856 		    ((type == NULL) || strcmp(type, fp->f_type) == 0))
857 			break;
858 	}
859 	return (fp);
860 }
861 
862 /*
863  * Find a module matching (name) inside of given file.
864  * NULL may be passed as a wildcard.
865  */
866 struct kernel_module *
867 file_findmodule(struct preloaded_file *fp, char *modname,
868     struct mod_depend *verinfo)
869 {
870 	struct kernel_module *mp, *best;
871 	int bestver, mver;
872 
873 	if (fp == NULL) {
874 		for (fp = preloaded_files; fp; fp = fp->f_next) {
875 			mp = file_findmodule(fp, modname, verinfo);
876 			if (mp != NULL)
877 				return (mp);
878 		}
879 		return (NULL);
880 	}
881 	best = NULL;
882 	bestver = 0;
883 	for (mp = fp->f_modules; mp; mp = mp->m_next) {
884 		if (strcmp(modname, mp->m_name) == 0) {
885 			if (verinfo == NULL)
886 				return (mp);
887 			mver = mp->m_version;
888 			if (mver == verinfo->md_ver_preferred)
889 				return (mp);
890 			if (mver >= verinfo->md_ver_minimum &&
891 			    mver <= verinfo->md_ver_maximum &&
892 			    mver > bestver) {
893 				best = mp;
894 				bestver = mver;
895 			}
896 		}
897 	}
898 	return (best);
899 }
900 /*
901  * Make a copy of (size) bytes of data from (p), and associate them as
902  * metadata of (type) to the module (mp).
903  */
904 void
905 file_addmetadata(struct preloaded_file *fp, int type, size_t size, void *p)
906 {
907 	struct file_metadata	*md;
908 
909 	md = malloc(sizeof (struct file_metadata) - sizeof (md->md_data) +
910 	    size);
911 	if (md != NULL) {
912 		md->md_size = size;
913 		md->md_type = type;
914 		bcopy(p, md->md_data, size);
915 		md->md_next = fp->f_metadata;
916 	}
917 	fp->f_metadata = md;
918 }
919 
920 /*
921  * Find a metadata object of (type) associated with the file (fp)
922  */
923 struct file_metadata *
924 file_findmetadata(struct preloaded_file *fp, int type)
925 {
926 	struct file_metadata *md;
927 
928 	for (md = fp->f_metadata; md != NULL; md = md->md_next)
929 		if (md->md_type == type)
930 			break;
931 	return (md);
932 }
933 
934 struct file_metadata *
935 metadata_next(struct file_metadata *md, int type)
936 {
937 
938 	if (md == NULL)
939 		return (NULL);
940 	while ((md = md->md_next) != NULL)
941 		if (md->md_type == type)
942 			break;
943 	return (md);
944 }
945 
946 static const char *emptyextlist[] = { "", NULL };
947 
948 /*
949  * Check if the given file is in place and return full path to it.
950  */
951 static char *
952 file_lookup(const char *path, const char *name, int namelen,
953     const char **extlist)
954 {
955 	struct stat st;
956 	char *result, *cp;
957 	const char **cpp;
958 	int pathlen, extlen, len;
959 
960 	pathlen = strlen(path);
961 	extlen = 0;
962 	if (extlist == NULL)
963 		extlist = emptyextlist;
964 	for (cpp = extlist; *cpp; cpp++) {
965 		len = strlen(*cpp);
966 		if (len > extlen)
967 			extlen = len;
968 	}
969 	result = malloc(pathlen + namelen + extlen + 2);
970 	if (result == NULL)
971 		return (NULL);
972 	bcopy(path, result, pathlen);
973 	if (pathlen > 0 && result[pathlen - 1] != '/')
974 		result[pathlen++] = '/';
975 	cp = result + pathlen;
976 	bcopy(name, cp, namelen);
977 	cp += namelen;
978 	for (cpp = extlist; *cpp; cpp++) {
979 		(void) strcpy(cp, *cpp);
980 		if (stat(result, &st) == 0 && S_ISREG(st.st_mode))
981 			return (result);
982 	}
983 	free(result);
984 	return (NULL);
985 }
986 
987 /*
988  * Check if file name have any qualifiers
989  */
990 static int
991 file_havepath(const char *name)
992 {
993 	const char *cp;
994 
995 	(void) archsw.arch_getdev(NULL, name, &cp);
996 	return (cp != name || strchr(name, '/') != NULL);
997 }
998 
999 /*
1000  * Attempt to find the file (name) on the module searchpath.
1001  * If (name) is qualified in any way, we simply check it and
1002  * return it or NULL.  If it is not qualified, then we attempt
1003  * to construct a path using entries in the environment variable
1004  * module_path.
1005  *
1006  * The path we return a pointer to need never be freed, as we manage
1007  * it internally.
1008  */
1009 static char *
1010 file_search(const char *name, const char **extlist)
1011 {
1012 	struct moduledir *mdp;
1013 	struct stat sb;
1014 	char *result;
1015 	int namelen;
1016 
1017 	/* Don't look for nothing */
1018 	if (name == NULL)
1019 		return (NULL);
1020 
1021 	if (*name == '\0')
1022 		return (strdup(name));
1023 
1024 	if (file_havepath(name)) {
1025 		/* Qualified, so just see if it exists */
1026 		if (stat(name, &sb) == 0)
1027 			return (strdup(name));
1028 		return (NULL);
1029 	}
1030 	moduledir_rebuild();
1031 	result = NULL;
1032 	namelen = strlen(name);
1033 	STAILQ_FOREACH(mdp, &moduledir_list, d_link) {
1034 		result = file_lookup(mdp->d_path, name, namelen, extlist);
1035 		if (result != NULL)
1036 			break;
1037 	}
1038 	return (result);
1039 }
1040 
1041 #define	INT_ALIGN(base, ptr)	ptr = \
1042 	(base) + (((ptr) - (base) + sizeof (int) - 1) & ~(sizeof (int) - 1))
1043 
1044 static char *
1045 mod_search_hints(struct moduledir *mdp, const char *modname,
1046     struct mod_depend *verinfo)
1047 {
1048 	uchar_t *cp, *recptr, *bufend, *best;
1049 	char *result;
1050 	int *intp, bestver, blen, clen, ival, modnamelen, reclen;
1051 	bool found;
1052 
1053 	moduledir_readhints(mdp);
1054 	modnamelen = strlen(modname);
1055 	found = false;
1056 	result = NULL;
1057 	bestver = 0;
1058 	if (mdp->d_hints == NULL)
1059 		goto bad;
1060 	recptr = mdp->d_hints;
1061 	bufend = recptr + mdp->d_hintsz;
1062 	clen = blen = 0;
1063 	best = cp = NULL;
1064 	while (recptr < bufend && !found) {
1065 		intp = (int *)recptr;
1066 		reclen = *intp++;
1067 		ival = *intp++;
1068 		cp = (uchar_t *)intp;
1069 		switch (ival) {
1070 		case MDT_VERSION:
1071 			clen = *cp++;
1072 			if (clen != modnamelen || bcmp(cp, modname, clen) != 0)
1073 				break;
1074 			cp += clen;
1075 			INT_ALIGN(mdp->d_hints, cp);
1076 			ival = *(int *)cp;
1077 			cp += sizeof (int);
1078 			clen = *cp++;
1079 			if (verinfo == NULL ||
1080 			    ival == verinfo->md_ver_preferred) {
1081 				found = true;
1082 				break;
1083 			}
1084 			if (ival >= verinfo->md_ver_minimum &&
1085 			    ival <= verinfo->md_ver_maximum &&
1086 			    ival > bestver) {
1087 				bestver = ival;
1088 				best = cp;
1089 				blen = clen;
1090 			}
1091 			break;
1092 		default:
1093 			break;
1094 		}
1095 		recptr += reclen + sizeof (int);
1096 	}
1097 	/*
1098 	 * Finally check if KLD is in the place
1099 	 */
1100 	if (found)
1101 		result = file_lookup(mdp->d_path, (char *)cp, clen, NULL);
1102 	else if (best)
1103 		result = file_lookup(mdp->d_path, (char *)best, blen, NULL);
1104 bad:
1105 	/*
1106 	 * If nothing found or hints is absent - fallback to the old way
1107 	 * by using "kldname[.ko]" as module name.
1108 	 */
1109 	if (!found && bestver == 0 && result == NULL) {
1110 		result = file_lookup(mdp->d_path, modname, modnamelen,
1111 		    kld_ext_list);
1112 	}
1113 	return (result);
1114 }
1115 
1116 /*
1117  * Attempt to locate the file containing the module (name)
1118  */
1119 static char *
1120 mod_searchmodule(char *name, struct mod_depend *verinfo)
1121 {
1122 	struct moduledir *mdp;
1123 	char *result;
1124 
1125 	moduledir_rebuild();
1126 	/*
1127 	 * Now we ready to lookup module in the given directories
1128 	 */
1129 	result = NULL;
1130 	STAILQ_FOREACH(mdp, &moduledir_list, d_link) {
1131 		result = mod_search_hints(mdp, name, verinfo);
1132 		if (result != NULL)
1133 			break;
1134 	}
1135 
1136 	return (result);
1137 }
1138 
1139 int
1140 file_addmodule(struct preloaded_file *fp, char *modname, int version,
1141     struct kernel_module **newmp)
1142 {
1143 	struct kernel_module *mp;
1144 	struct mod_depend mdepend;
1145 
1146 	bzero(&mdepend, sizeof (mdepend));
1147 	mdepend.md_ver_preferred = version;
1148 	mp = file_findmodule(fp, modname, &mdepend);
1149 	if (mp != NULL)
1150 		return (EEXIST);
1151 	mp = calloc(1, sizeof (struct kernel_module));
1152 	if (mp == NULL)
1153 		return (ENOMEM);
1154 	mp->m_name = strdup(modname);
1155 	if (mp->m_name == NULL) {
1156 		free(mp);
1157 		return (ENOMEM);
1158 	}
1159 	mp->m_version = version;
1160 	mp->m_fp = fp;
1161 	mp->m_next = fp->f_modules;
1162 	fp->f_modules = mp;
1163 	if (newmp)
1164 		*newmp = mp;
1165 	return (0);
1166 }
1167 
1168 /*
1169  * Throw a file away
1170  */
1171 void
1172 file_discard(struct preloaded_file *fp)
1173 {
1174 	struct file_metadata *md, *md1;
1175 	struct kernel_module *mp, *mp1;
1176 
1177 	if (fp == NULL)
1178 		return;
1179 
1180 	if (archsw.arch_free_loadaddr != NULL && fp->f_addr &&
1181 	    fp->f_size != 0) {
1182 		archsw.arch_free_loadaddr(fp->f_addr,
1183 		    (uint64_t)(roundup2(fp->f_size, PAGE_SIZE) >> 12));
1184 	}
1185 
1186 	md = fp->f_metadata;
1187 	while (md != NULL) {
1188 		md1 = md;
1189 		md = md->md_next;
1190 		free(md1);
1191 	}
1192 	mp = fp->f_modules;
1193 	while (mp != NULL) {
1194 		free(mp->m_name);
1195 		mp1 = mp;
1196 		mp = mp->m_next;
1197 		free(mp1);
1198 	}
1199 	free(fp->f_name);
1200 	free(fp->f_type);
1201 	free(fp->f_args);
1202 	free(fp);
1203 }
1204 
1205 /*
1206  * Allocate a new file; must be used instead of malloc()
1207  * to ensure safe initialisation.
1208  */
1209 struct preloaded_file *
1210 file_alloc(void)
1211 {
1212 
1213 	return (calloc(1, sizeof (struct preloaded_file)));
1214 }
1215 
1216 /*
1217  * Add a module to the chain
1218  */
1219 static void
1220 file_insert_tail(struct preloaded_file *fp)
1221 {
1222 	struct preloaded_file *cm;
1223 
1224 	/* Append to list of loaded file */
1225 	fp->f_next = NULL;
1226 	if (preloaded_files == NULL) {
1227 		preloaded_files = fp;
1228 	} else {
1229 		for (cm = preloaded_files; cm->f_next != NULL; cm = cm->f_next)
1230 			;
1231 		cm->f_next = fp;
1232 	}
1233 }
1234 
1235 /*
1236  * Remove module from the chain
1237  */
1238 static void
1239 file_remove(struct preloaded_file *fp)
1240 {
1241 	struct preloaded_file   *cm;
1242 
1243 	if (preloaded_files == NULL)
1244 		return;
1245 
1246 	if (preloaded_files == fp) {
1247 		preloaded_files = fp->f_next;
1248 		return;
1249 	}
1250 	for (cm = preloaded_files; cm->f_next != NULL; cm = cm->f_next) {
1251 		if (cm->f_next == fp) {
1252 			cm->f_next = fp->f_next;
1253 			return;
1254 		}
1255 	}
1256 }
1257 
1258 static char *
1259 moduledir_fullpath(struct moduledir *mdp, const char *fname)
1260 {
1261 	char *cp;
1262 
1263 	cp = malloc(strlen(mdp->d_path) + strlen(fname) + 2);
1264 	if (cp == NULL)
1265 		return (NULL);
1266 	strcpy(cp, mdp->d_path);
1267 	strcat(cp, "/");
1268 	strcat(cp, fname);
1269 	return (cp);
1270 }
1271 
1272 /*
1273  * Read linker.hints file into memory performing some sanity checks.
1274  */
1275 static void
1276 moduledir_readhints(struct moduledir *mdp)
1277 {
1278 	struct stat st;
1279 	char *path;
1280 	int fd, size, version;
1281 
1282 	if (mdp->d_hints != NULL || (mdp->d_flags & MDIR_NOHINTS))
1283 		return;
1284 	path = moduledir_fullpath(mdp, "linker.hints");
1285 	if (stat(path, &st) != 0 ||
1286 	    st.st_size < (ssize_t)(sizeof (version) + sizeof (int)) ||
1287 	    st.st_size > LINKER_HINTS_MAX ||
1288 	    (fd = open(path, O_RDONLY)) < 0) {
1289 		free(path);
1290 		mdp->d_flags |= MDIR_NOHINTS;
1291 		return;
1292 	}
1293 	free(path);
1294 	size = read(fd, &version, sizeof (version));
1295 	if (size != sizeof (version) || version != LINKER_HINTS_VERSION)
1296 		goto bad;
1297 	size = st.st_size - size;
1298 	mdp->d_hints = malloc(size);
1299 	if (mdp->d_hints == NULL)
1300 		goto bad;
1301 	if (read(fd, mdp->d_hints, size) != size)
1302 		goto bad;
1303 	mdp->d_hintsz = size;
1304 	(void) close(fd);
1305 	return;
1306 bad:
1307 	(void) close(fd);
1308 	free(mdp->d_hints);
1309 	mdp->d_hints = NULL;
1310 	mdp->d_flags |= MDIR_NOHINTS;
1311 }
1312 
1313 /*
1314  * Extract directories from the ';' separated list, remove duplicates.
1315  */
1316 static void
1317 moduledir_rebuild(void)
1318 {
1319 	struct moduledir *mdp, *mtmp;
1320 	const char *path, *cp, *ep;
1321 	size_t cplen;
1322 
1323 	path = getenv("module_path");
1324 	if (path == NULL)
1325 		path = default_searchpath;
1326 	/*
1327 	 * Rebuild list of module directories if it changed
1328 	 */
1329 	STAILQ_FOREACH(mdp, &moduledir_list, d_link)
1330 		mdp->d_flags |= MDIR_REMOVED;
1331 
1332 	for (ep = path; *ep != 0; ep++) {
1333 		cp = ep;
1334 		for (; *ep != 0 && *ep != ';'; ep++)
1335 			;
1336 		/*
1337 		 * Ignore trailing slashes
1338 		 */
1339 		for (cplen = ep - cp; cplen > 1 && cp[cplen - 1] == '/';
1340 		    cplen--)
1341 			;
1342 		STAILQ_FOREACH(mdp, &moduledir_list, d_link) {
1343 			if (strlen(mdp->d_path) != cplen ||
1344 			    bcmp(cp, mdp->d_path, cplen) != 0)
1345 				continue;
1346 			mdp->d_flags &= ~MDIR_REMOVED;
1347 			break;
1348 		}
1349 		if (mdp == NULL) {
1350 			mdp = malloc(sizeof (*mdp) + cplen + 1);
1351 			if (mdp == NULL)
1352 				return;
1353 			mdp->d_path = (char *)(mdp + 1);
1354 			bcopy(cp, mdp->d_path, cplen);
1355 			mdp->d_path[cplen] = 0;
1356 			mdp->d_hints = NULL;
1357 			mdp->d_flags = 0;
1358 			STAILQ_INSERT_TAIL(&moduledir_list, mdp, d_link);
1359 		}
1360 		if (*ep == '\0')
1361 			break;
1362 	}
1363 	/*
1364 	 * Delete unused directories if any
1365 	 */
1366 	mdp = STAILQ_FIRST(&moduledir_list);
1367 	while (mdp) {
1368 		if ((mdp->d_flags & MDIR_REMOVED) == 0) {
1369 			mdp = STAILQ_NEXT(mdp, d_link);
1370 		} else {
1371 			free(mdp->d_hints);
1372 			mtmp = mdp;
1373 			mdp = STAILQ_NEXT(mdp, d_link);
1374 			STAILQ_REMOVE(&moduledir_list, mtmp, moduledir, d_link);
1375 			free(mtmp);
1376 		}
1377 	}
1378 }
1379