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