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