Training courses

Kernel and Embedded Linux

Bootlin training courses

Embedded Linux, kernel,
Yocto Project, Buildroot, real-time,
graphics, boot time, debugging...

Bootlin logo

Elixir Cross Referencer

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
/*	$NetBSD: kern_module.c,v 1.136 2019/06/19 15:01:01 pgoyette Exp $	*/

/*-
 * Copyright (c) 2008 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software developed for The NetBSD Foundation
 * by Andrew Doran.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * Kernel module support.
 */

#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: kern_module.c,v 1.136 2019/06/19 15:01:01 pgoyette Exp $");

#define _MODULE_INTERNAL

#ifdef _KERNEL_OPT
#include "opt_ddb.h"
#include "opt_modular.h"
#endif

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/proc.h>
#include <sys/kauth.h>
#include <sys/kobj.h>
#include <sys/kmem.h>
#include <sys/module.h>
#include <sys/kthread.h>
#include <sys/sysctl.h>
#include <sys/lock.h>

#include <uvm/uvm_extern.h>

struct vm_map *module_map;
const char *module_machine;
char	module_base[MODULE_BASE_SIZE];

struct modlist        module_list = TAILQ_HEAD_INITIALIZER(module_list);
struct modlist        module_builtins = TAILQ_HEAD_INITIALIZER(module_builtins);
static struct modlist module_bootlist = TAILQ_HEAD_INITIALIZER(module_bootlist);

struct module_callbacks {
	TAILQ_ENTRY(module_callbacks) modcb_list;
	void (*modcb_load)(struct module *);
	void (*modcb_unload)(struct module *);
};
TAILQ_HEAD(modcblist, module_callbacks);
static struct modcblist modcblist;

static module_t *module_netbsd;
static const modinfo_t module_netbsd_modinfo = {
	.mi_version = __NetBSD_Version__,
	.mi_class = MODULE_CLASS_MISC,
	.mi_name = "netbsd"
};

static module_t	*module_active;
bool		module_verbose_on;
#ifdef MODULAR_DEFAULT_AUTOLOAD
bool		module_autoload_on = true;
#else
bool		module_autoload_on = false;
#endif
u_int		module_count;
u_int		module_builtinlist;
u_int		module_autotime = 10;
u_int		module_gen = 1;
static kcondvar_t module_thread_cv;
static kmutex_t module_thread_lock;
static int	module_thread_ticks;
int (*module_load_vfs_vec)(const char *, int, bool, module_t *,
			   prop_dictionary_t *) = (void *)eopnotsupp;

static kauth_listener_t	module_listener;

static specificdata_domain_t module_specificdata_domain;

/* Ensure that the kernel's link set isn't empty. */
static modinfo_t module_dummy;
__link_set_add_rodata(modules, module_dummy);

static module_t	*module_newmodule(modsrc_t);
static void	module_free(module_t *);
static void	module_require_force(module_t *);
static int	module_do_load(const char *, bool, int, prop_dictionary_t,
		    module_t **, modclass_t modclass, bool);
static int	module_do_unload(const char *, bool);
static int	module_do_builtin(const module_t *, const char *, module_t **,
    prop_dictionary_t);
static int	module_fetch_info(module_t *);
static void	module_thread(void *);

static module_t	*module_lookup(const char *);
static void	module_enqueue(module_t *);

static bool	module_merge_dicts(prop_dictionary_t, const prop_dictionary_t);

static void	sysctl_module_setup(void);
static int	sysctl_module_autotime(SYSCTLFN_PROTO);

static void	module_callback_load(struct module *);
static void	module_callback_unload(struct module *);

#define MODULE_CLASS_MATCH(mi, modclass) \
	((modclass) == MODULE_CLASS_ANY || (modclass) == (mi)->mi_class)

static void
module_incompat(const modinfo_t *mi, int modclass)
{
	module_error("incompatible module class for `%s' (%d != %d)",
	    mi->mi_name, modclass, mi->mi_class);
}

struct module *
module_kernel(void)
{

	return module_netbsd;
}

/*
 * module_error:
 *
 *	Utility function: log an error.
 */
void
module_error(const char *fmt, ...)
{
	va_list ap;

	va_start(ap, fmt);
	printf("WARNING: module error: ");
	vprintf(fmt, ap);
	printf("\n");
	va_end(ap);
}

/*
 * module_print:
 *
 *	Utility function: log verbose output.
 */
void
module_print(const char *fmt, ...)
{
	va_list ap;

	if (module_verbose_on) {
		va_start(ap, fmt);
		printf("DEBUG: module: ");
		vprintf(fmt, ap);
		printf("\n");
		va_end(ap);
	}
}

/*
 * module_name:
 *
 *	Utility function: return the module's name.
 */
const char *
module_name(struct module *mod)
{

	return mod->mod_info->mi_name;
}

/*
 * module_source:
 *
 *	Utility function: return the module's source.
 */
modsrc_t
module_source(struct module *mod)
{

	return mod->mod_source;
}

static int
module_listener_cb(kauth_cred_t cred, kauth_action_t action, void *cookie,
    void *arg0, void *arg1, void *arg2, void *arg3)
{
	int result;

	result = KAUTH_RESULT_DEFER;

	if (action != KAUTH_SYSTEM_MODULE)
		return result;

	if ((uintptr_t)arg2 != 0)	/* autoload */
		result = KAUTH_RESULT_ALLOW;

	return result;
}

/*
 * Allocate a new module_t
 */
static module_t *
module_newmodule(modsrc_t source)
{
	module_t *mod;

	mod = kmem_zalloc(sizeof(*mod), KM_SLEEP);
	mod->mod_source = source;
	specificdata_init(module_specificdata_domain, &mod->mod_sdref);
	return mod;
}

/*
 * Free a module_t
 */
static void
module_free(module_t *mod)
{

	specificdata_fini(module_specificdata_domain, &mod->mod_sdref);
	if (mod->mod_required)
		kmem_free(mod->mod_required, mod->mod_arequired *
		    sizeof(module_t *));
	kmem_free(mod, sizeof(*mod));
}

/*
 * Require the -f (force) flag to load a module
 */
static void
module_require_force(struct module *mod)
{
	SET(mod->mod_flags, MODFLG_MUST_FORCE);
}

/*
 * Add modules to the builtin list.  This can done at boottime or
 * at runtime if the module is linked into the kernel with an
 * external linker.  All or none of the input will be handled.
 * Optionally, the modules can be initialized.  If they are not
 * initialized, module_init_class() or module_load() can be used
 * later, but these are not guaranteed to give atomic results.
 */
int
module_builtin_add(modinfo_t *const *mip, size_t nmodinfo, bool init)
{
	struct module **modp = NULL, *mod_iter;
	int rv = 0, i, mipskip;

	if (init) {
		rv = kauth_authorize_system(kauth_cred_get(),
		    KAUTH_SYSTEM_MODULE, 0, (void *)(uintptr_t)MODCTL_LOAD,
		    (void *)(uintptr_t)1, NULL);
		if (rv) {
			return rv;
		}
	}

	for (i = 0, mipskip = 0; i < nmodinfo; i++) {
		if (mip[i] == &module_dummy) {
			KASSERT(nmodinfo > 0);
			nmodinfo--;
		}
	}
	if (nmodinfo == 0)
		return 0;

	modp = kmem_zalloc(sizeof(*modp) * nmodinfo, KM_SLEEP);
	for (i = 0, mipskip = 0; i < nmodinfo; i++) {
		if (mip[i+mipskip] == &module_dummy) {
			mipskip++;
			continue;
		}
		modp[i] = module_newmodule(MODULE_SOURCE_KERNEL);
		modp[i]->mod_info = mip[i+mipskip];
	}
	kernconfig_lock();

	/* do this in three stages for error recovery and atomicity */

	/* first check for presence */
	for (i = 0; i < nmodinfo; i++) {
		TAILQ_FOREACH(mod_iter, &module_builtins, mod_chain) {
			if (strcmp(mod_iter->mod_info->mi_name,
			    modp[i]->mod_info->mi_name) == 0)
				break;
		}
		if (mod_iter) {
			rv = EEXIST;
			goto out;
		}

		if (module_lookup(modp[i]->mod_info->mi_name) != NULL) {
			rv = EEXIST;
			goto out;
		}
	}

	/* then add to list */
	for (i = 0; i < nmodinfo; i++) {
		TAILQ_INSERT_TAIL(&module_builtins, modp[i], mod_chain);
		module_builtinlist++;
	}

	/* finally, init (if required) */
	if (init) {
		for (i = 0; i < nmodinfo; i++) {
			rv = module_do_builtin(modp[i],
			    modp[i]->mod_info->mi_name, NULL, NULL);
			/* throw in the towel, recovery hard & not worth it */
			if (rv)
				panic("%s: builtin module \"%s\" init failed:"
				    " %d", __func__,
				    modp[i]->mod_info->mi_name, rv);
		}
	}

 out:
	kernconfig_unlock();
	if (rv != 0) {
		for (i = 0; i < nmodinfo; i++) {
			if (modp[i])
				module_free(modp[i]);
		}
	}
	kmem_free(modp, sizeof(*modp) * nmodinfo);
	return rv;
}

/*
 * Optionally fini and remove builtin module from the kernel.
 * Note: the module will now be unreachable except via mi && builtin_add.
 */
int
module_builtin_remove(modinfo_t *mi, bool fini)
{
	struct module *mod;
	int rv = 0;

	if (fini) {
		rv = kauth_authorize_system(kauth_cred_get(),
		    KAUTH_SYSTEM_MODULE, 0, (void *)(uintptr_t)MODCTL_UNLOAD,
		    NULL, NULL);
		if (rv)
			return rv;

		kernconfig_lock();
		rv = module_do_unload(mi->mi_name, true);
		if (rv) {
			goto out;
		}
	} else {
		kernconfig_lock();
	}
	TAILQ_FOREACH(mod, &module_builtins, mod_chain) {
		if (strcmp(mod->mod_info->mi_name, mi->mi_name) == 0)
			break;
	}
	if (mod) {
		TAILQ_REMOVE(&module_builtins, mod, mod_chain);
		module_builtinlist--;
	} else {
		KASSERT(fini == false);
		rv = ENOENT;
	}

 out:
	kernconfig_unlock();
	return rv;
}

/*
 * module_init:
 *
 *	Initialize the module subsystem.
 */
void
module_init(void)
{
	__link_set_decl(modules, modinfo_t);
	extern struct vm_map *module_map;
	modinfo_t *const *mip;
	int rv;

	if (module_map == NULL) {
		module_map = kernel_map;
	}
	cv_init(&module_thread_cv, "mod_unld");
	mutex_init(&module_thread_lock, MUTEX_DEFAULT, IPL_NONE);
	TAILQ_INIT(&modcblist);

#ifdef MODULAR	/* XXX */
	module_init_md();
#endif

	if (!module_machine)
		module_machine = machine;
#if __NetBSD_Version__ / 1000000 % 100 == 99	/* -current */
	snprintf(module_base, sizeof(module_base), "/stand/%s/%s/modules",
	    module_machine, osrelease);
#else						/* release */
	snprintf(module_base, sizeof(module_base), "/stand/%s/%d.%d/modules",
	    module_machine, __NetBSD_Version__ / 100000000,
	    __NetBSD_Version__ / 1000000 % 100);
#endif

	module_listener = kauth_listen_scope(KAUTH_SCOPE_SYSTEM,
	    module_listener_cb, NULL);

	__link_set_foreach(mip, modules) {
		if ((rv = module_builtin_add(mip, 1, false)) != 0)
			module_error("builtin %s failed: %d\n",
			    (*mip)->mi_name, rv);
	}

	sysctl_module_setup();
	module_specificdata_domain = specificdata_domain_create();

	module_netbsd = module_newmodule(MODULE_SOURCE_KERNEL);
	module_netbsd->mod_refcnt = 1;
	module_netbsd->mod_info = &module_netbsd_modinfo;
}

/*
 * module_start_unload_thread:
 *
 *	Start the auto unload kthread.
 */
void
module_start_unload_thread(void)
{
	int error;

	error = kthread_create(PRI_VM, KTHREAD_MPSAFE, NULL, module_thread,
	    NULL, NULL, "modunload");
	if (error != 0)
		panic("%s: %d", __func__, error);
}

/*
 * module_builtin_require_force
 *
 * Require MODCTL_MUST_FORCE to load any built-in modules that have 
 * not yet been initialized
 */
void
module_builtin_require_force(void)
{
	module_t *mod;

	kernconfig_lock();
	TAILQ_FOREACH(mod, &module_builtins, mod_chain) {
		module_require_force(mod);
	}
	kernconfig_unlock();
}

static struct sysctllog *module_sysctllog;

static int
sysctl_module_autotime(SYSCTLFN_ARGS)
{
	struct sysctlnode node;
	int t, error;

	t = *(int *)rnode->sysctl_data;

	node = *rnode;
	node.sysctl_data = &t;
	error = sysctl_lookup(SYSCTLFN_CALL(&node));
	if (error || newp == NULL)
		return (error);

	if (t < 0)
		return (EINVAL);

	*(int *)rnode->sysctl_data = t;
	return (0);
}

static void
sysctl_module_setup(void)
{
	const struct sysctlnode *node = NULL;

	sysctl_createv(&module_sysctllog, 0, NULL, &node,
		CTLFLAG_PERMANENT,
		CTLTYPE_NODE, "module",
		SYSCTL_DESCR("Module options"),
		NULL, 0, NULL, 0,
		CTL_KERN, CTL_CREATE, CTL_EOL);

	if (node == NULL)
		return;

	sysctl_createv(&module_sysctllog, 0, &node, NULL,
		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
		CTLTYPE_BOOL, "autoload",
		SYSCTL_DESCR("Enable automatic load of modules"),
		NULL, 0, &module_autoload_on, 0,
		CTL_CREATE, CTL_EOL);
	sysctl_createv(&module_sysctllog, 0, &node, NULL,
		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
		CTLTYPE_BOOL, "verbose",
		SYSCTL_DESCR("Enable verbose output"),
		NULL, 0, &module_verbose_on, 0,
		CTL_CREATE, CTL_EOL);
	sysctl_createv(&module_sysctllog, 0, &node, NULL,
		CTLFLAG_PERMANENT | CTLFLAG_READONLY,
		CTLTYPE_STRING, "path",
		SYSCTL_DESCR("Default module load path"),
		NULL, 0, module_base, 0,
		CTL_CREATE, CTL_EOL);
	sysctl_createv(&module_sysctllog, 0, &node, NULL,
		CTLFLAG_PERMANENT | CTLFLAG_READWRITE,
		CTLTYPE_INT, "autotime",
		SYSCTL_DESCR("Auto-unload delay"),
		sysctl_module_autotime, 0, &module_autotime, 0,
		CTL_CREATE, CTL_EOL);
}

/*
 * module_init_class:
 *
 *	Initialize all built-in and pre-loaded modules of the
 *	specified class.
 */
void
module_init_class(modclass_t modclass)
{
	TAILQ_HEAD(, module) bi_fail = TAILQ_HEAD_INITIALIZER(bi_fail);
	module_t *mod;
	modinfo_t *mi;

	kernconfig_lock();
	/*
	 * Builtins first.  These will not depend on pre-loaded modules
	 * (because the kernel would not link).
	 */
	do {
		TAILQ_FOREACH(mod, &module_builtins, mod_chain) {
			mi = mod->mod_info;
			if (!MODULE_CLASS_MATCH(mi, modclass))
				continue;
			/*
			 * If initializing a builtin module fails, don't try
			 * to load it again.  But keep it around and queue it
			 * on the builtins list after we're done with module
			 * init.  Don't set it to MODFLG_MUST_FORCE in case a
			 * future attempt to initialize can be successful.
			 * (If the module has previously been set to
			 * MODFLG_MUST_FORCE, don't try to override that!)
			 */
			if (ISSET(mod->mod_flags, MODFLG_MUST_FORCE) ||
			    module_do_builtin(mod, mi->mi_name, NULL,
			    NULL) != 0) {
				TAILQ_REMOVE(&module_builtins, mod, mod_chain);
				TAILQ_INSERT_TAIL(&bi_fail, mod, mod_chain);
			}
			break;
		}
	} while (mod != NULL);

	/*
	 * Now preloaded modules.  These will be pulled off the
	 * list as we call module_do_load();
	 */
	do {
		TAILQ_FOREACH(mod, &module_bootlist, mod_chain) {
			mi = mod->mod_info;
			if (!MODULE_CLASS_MATCH(mi, modclass))
				continue;
			module_do_load(mi->mi_name, false, 0, NULL, NULL,
			    modclass, false);
			break;
		}
	} while (mod != NULL);

	/* return failed builtin modules to builtin list */
	while ((mod = TAILQ_FIRST(&bi_fail)) != NULL) {
		TAILQ_REMOVE(&bi_fail, mod, mod_chain);
		TAILQ_INSERT_TAIL(&module_builtins, mod, mod_chain);
	}

	kernconfig_unlock();
}

/*
 * module_compatible:
 *
 *	Return true if the two supplied kernel versions are said to
 *	have the same binary interface for kernel code.  The entire
 *	version is signficant for the development tree (-current),
 *	major and minor versions are significant for official
 *	releases of the system.
 */
bool
module_compatible(int v1, int v2)
{

#if __NetBSD_Version__ / 1000000 % 100 == 99	/* -current */
	return v1 == v2;
#else						/* release */
	return abs(v1 - v2) < 10000;
#endif
}

/*
 * module_load:
 *
 *	Load a single module from the file system.
 */
int
module_load(const char *filename, int flags, prop_dictionary_t props,
	    modclass_t modclass)
{
	module_t *mod;
	int error;

	/* Test if we already have the module loaded before
	 * authorizing so we have the opportunity to return EEXIST. */
	kernconfig_lock();
	mod = module_lookup(filename);
	if (mod != NULL) {
		module_print("%s module `%s' already loaded",
		    "requested", filename);
		error = EEXIST;
		goto out;
	}

	/* Authorize. */
	error = kauth_authorize_system(kauth_cred_get(), KAUTH_SYSTEM_MODULE,
	    0, (void *)(uintptr_t)MODCTL_LOAD, NULL, NULL);
	if (error != 0)
		goto out;

	error = module_do_load(filename, false, flags, props, NULL, modclass,
	    false);

out:
	kernconfig_unlock();
	return error;
}

/*
 * module_autoload:
 *
 *	Load a single module from the file system, system initiated.
 */
int
module_autoload(const char *filename, modclass_t modclass)
{
	int error;

	kernconfig_lock();

	/* Nothing if the user has disabled it. */
	if (!module_autoload_on) {
		kernconfig_unlock();
		return EPERM;
	}

        /* Disallow path separators and magic symlinks. */
        if (strchr(filename, '/') != NULL || strchr(filename, '@') != NULL ||
            strchr(filename, '.') != NULL) {
		kernconfig_unlock();
        	return EPERM;
	}

	/* Authorize. */
	error = kauth_authorize_system(kauth_cred_get(), KAUTH_SYSTEM_MODULE,
	    0, (void *)(uintptr_t)MODCTL_LOAD, (void *)(uintptr_t)1, NULL);

	if (error == 0)
		error = module_do_load(filename, false, 0, NULL, NULL, modclass,
		    true);

	kernconfig_unlock();
	return error;
}

/*
 * module_unload:
 *
 *	Find and unload a module by name.
 */
int
module_unload(const char *name)
{
	int error;

	/* Authorize. */
	error = kauth_authorize_system(kauth_cred_get(), KAUTH_SYSTEM_MODULE,
	    0, (void *)(uintptr_t)MODCTL_UNLOAD, NULL, NULL);
	if (error != 0) {
		return error;
	}

	kernconfig_lock();
	error = module_do_unload(name, true);
	kernconfig_unlock();

	return error;
}

/*
 * module_lookup:
 *
 *	Look up a module by name.
 */
module_t *
module_lookup(const char *name)
{
	module_t *mod;

	KASSERT(kernconfig_is_held());

	TAILQ_FOREACH(mod, &module_list, mod_chain) {
		if (strcmp(mod->mod_info->mi_name, name) == 0)
			break;
	}

	return mod;
}

/*
 * module_hold:
 *
 *	Add a single reference to a module.  It's the caller's
 *	responsibility to ensure that the reference is dropped
 *	later.
 */
void
module_hold(module_t *mod)
{

	kernconfig_lock();
	mod->mod_refcnt++;
	kernconfig_unlock();
}

/*
 * module_rele:
 *
 *	Release a reference acquired with module_hold().
 */
void
module_rele(module_t *mod)
{

	kernconfig_lock();
	KASSERT(mod->mod_refcnt > 0);
	mod->mod_refcnt--;
	kernconfig_unlock();
}

/*
 * module_enqueue:
 *
 *	Put a module onto the global list and update counters.
 */
void
module_enqueue(module_t *mod)
{
	int i;

	KASSERT(kernconfig_is_held());

	/*
	 * Put new entry at the head of the queue so autounload can unload
	 * requisite modules with only one pass through the queue.
	 */
	TAILQ_INSERT_HEAD(&module_list, mod, mod_chain);
	if (mod->mod_nrequired) {

		/* Add references to the requisite modules. */
		for (i = 0; i < mod->mod_nrequired; i++) {
			KASSERT((*mod->mod_required)[i] != NULL);
			(*mod->mod_required)[i]->mod_refcnt++;
		}
	}
	module_count++;
	module_gen++;
}

/*
 * Our array of required module pointers starts with zero entries.  If we
 * need to add a new entry, and the list is already full, we reallocate a
 * larger array, adding MAXMODDEPS entries.
 */
static void
alloc_required(module_t *mod)
{
	module_t *(*new)[], *(*old)[];
	int areq;
	int i;

	if (mod->mod_nrequired >= mod->mod_arequired) {
		areq = mod->mod_arequired + MAXMODDEPS;
		old = mod->mod_required;
		new = kmem_zalloc(areq * sizeof(module_t *), KM_SLEEP);
		for (i = 0; i < mod->mod_arequired; i++)
			(*new)[i] = (*old)[i];
		mod->mod_required = new;
		if (old)
			kmem_free(old, mod->mod_arequired * sizeof(module_t *));
		mod->mod_arequired = areq;
	}
}

/*
 * module_do_builtin:
 *
 *	Initialize a module from the list of modules that are
 *	already linked into the kernel.
 */
static int
module_do_builtin(const module_t *pmod, const char *name, module_t **modp,
    prop_dictionary_t props)
{
	const char *p, *s;
	char buf[MAXMODNAME];
	modinfo_t *mi = NULL;
	module_t *mod, *mod2, *mod_loaded, *prev_active;
	size_t len;
	int error;

	KASSERT(kernconfig_is_held());

	/*
	 * Search the list to see if we have a module by this name.
	 */
	TAILQ_FOREACH(mod, &module_builtins, mod_chain) {
		if (strcmp(mod->mod_info->mi_name, name) == 0) {
			mi = mod->mod_info;
			break;
		}
	}

	/*
	 * Check to see if already loaded.  This might happen if we
	 * were already loaded as a dependency.
	 */
	if ((mod_loaded = module_lookup(name)) != NULL) {
		KASSERT(mod == NULL);
		if (modp)
			*modp = mod_loaded;
		return 0;
	}

	/* Note! This is from TAILQ, not immediate above */
	if (mi == NULL) {
		/*
		 * XXX: We'd like to panic here, but currently in some
		 * cases (such as nfsserver + nfs), the dependee can be
		 * succesfully linked without the dependencies.
		 */
		module_error("built-in module %s can't find builtin "
		    "dependency `%s'", pmod->mod_info->mi_name, name);
		return ENOENT;
	}

	/*
	 * Initialize pre-requisites.
	 */
	KASSERT(mod->mod_required == NULL);
	KASSERT(mod->mod_arequired == 0);
	KASSERT(mod->mod_nrequired == 0);
	if (mi->mi_required != NULL) {
		for (s = mi->mi_required; *s != '\0'; s = p) {
			if (*s == ',')
				s++;
			p = s;
			while (*p != '\0' && *p != ',')
				p++;
			len = uimin(p - s + 1, sizeof(buf));
			strlcpy(buf, s, len);
			if (buf[0] == '\0')
				break;
			alloc_required(mod);
			error = module_do_builtin(mod, buf, &mod2, NULL);
			if (error != 0) {
				module_error("built-in module %s prerequisite "
				    "%s failed, error %d", name, buf, error);
				goto fail;
			}
			(*mod->mod_required)[mod->mod_nrequired++] = mod2;
		}
	}

	/*
	 * Try to initialize the module.
	 */
	prev_active = module_active;
	module_active = mod;
	error = (*mi->mi_modcmd)(MODULE_CMD_INIT, props);
	module_active = prev_active;
	if (error != 0) {
		module_error("built-in module %s failed its MODULE_CMD_INIT, "
		    "error %d", mi->mi_name, error);
		goto fail;
	}

	/* load always succeeds after this point */

	TAILQ_REMOVE(&module_builtins, mod, mod_chain);
	module_builtinlist--;
	if (modp != NULL) {
		*modp = mod;
	}
	module_enqueue(mod);
	return 0;

 fail:
	if (mod->mod_required)
		kmem_free(mod->mod_required, mod->mod_arequired *
		    sizeof(module_t *));
	mod->mod_arequired = 0;
	mod->mod_nrequired = 0;
	mod->mod_required = NULL;
	return error;
}

/*
 * module_do_load:
 *
 *	Helper routine: load a module from the file system, or one
 *	pushed by the boot loader.
 */
static int
module_do_load(const char *name, bool isdep, int flags,
	       prop_dictionary_t props, module_t **modp, modclass_t modclass,
	       bool autoload)
{
	/* The pending list for this level of recursion */
	TAILQ_HEAD(pending_t, module);
	struct pending_t *pending;
	struct pending_t new_pending = TAILQ_HEAD_INITIALIZER(new_pending);

	/* The stack of pending lists */
	static SLIST_HEAD(pend_head, pend_entry) pend_stack =
		SLIST_HEAD_INITIALIZER(pend_stack);
	struct pend_entry {
		SLIST_ENTRY(pend_entry) pe_entry;
		struct pending_t *pe_pending;
	} my_pend_entry;

	modinfo_t *mi;
	module_t *mod, *mod2, *prev_active;
	prop_dictionary_t filedict;
	char buf[MAXMODNAME];
	const char *s, *p;
	int error;
	size_t len;

	KASSERT(kernconfig_is_held());

	filedict = NULL;
	error = 0;

	/*
	 * Set up the pending list for this entry.  If this is an
	 * internal entry (for a dependency), then use the same list
	 * as for the outer call;  otherwise, it's an external entry
	 * (possibly recursive, ie a module's xxx_modcmd(init, ...)
	 * routine called us), so use the locally allocated list.  In
	 * either case, add it to our stack.
	 */
	if (isdep) {
		KASSERT(SLIST_FIRST(&pend_stack) != NULL);
		pending = SLIST_FIRST(&pend_stack)->pe_pending;
	} else
		pending = &new_pending;
	my_pend_entry.pe_pending = pending;
	SLIST_INSERT_HEAD(&pend_stack, &my_pend_entry, pe_entry);

	/*
	 * Search the list of disabled builtins first.
	 */
	TAILQ_FOREACH(mod, &module_builtins, mod_chain) {
		if (strcmp(mod->mod_info->mi_name, name) == 0) {
			break;
		}
	}
	if (mod) {
		if (ISSET(mod->mod_flags, MODFLG_MUST_FORCE) &&
		    !ISSET(flags, MODCTL_LOAD_FORCE)) {
			if (!autoload) {
				module_error("use -f to reinstate "
				    "builtin module `%s'", name);
			}
			SLIST_REMOVE_HEAD(&pend_stack, pe_entry);
			return EPERM;
		} else {
			SLIST_REMOVE_HEAD(&pend_stack, pe_entry);
			error = module_do_builtin(mod, name, modp, props);
			return error;
		}
	}

	/*
	 * Load the module and link.  Before going to the file system,
	 * scan the list of modules loaded by the boot loader.
	 */
	TAILQ_FOREACH(mod, &module_bootlist, mod_chain) {
		if (strcmp(mod->mod_info->mi_name, name) == 0) {
			TAILQ_REMOVE(&module_bootlist, mod, mod_chain);
			break;
		}
	}
	if (mod != NULL) {
		TAILQ_INSERT_TAIL(pending, mod, mod_chain);
	} else {
		/*
		 * Check to see if module is already present.
		 */
		mod = module_lookup(name);
		if (mod != NULL) {
			if (modp != NULL) {
				*modp = mod;
			}
			module_print("%s module `%s' already loaded",
			    isdep ? "dependent" : "requested", name);
			SLIST_REMOVE_HEAD(&pend_stack, pe_entry);
			return EEXIST;
		}

		mod = module_newmodule(MODULE_SOURCE_FILESYS);
		if (mod == NULL) {
			module_error("out of memory for `%s'", name);
			SLIST_REMOVE_HEAD(&pend_stack, pe_entry);
			return ENOMEM;
		}

		error = module_load_vfs_vec(name, flags, autoload, mod,
					    &filedict);
		if (error != 0) {
#ifdef DEBUG
			/*
			 * The exec class of modules contains a list of
			 * modules that is the union of all the modules
			 * available for each architecture, so we don't
			 * print an error if they are missing.
			 */
			if ((modclass != MODULE_CLASS_EXEC || error != ENOENT)
			    && root_device != NULL)
				module_error("vfs load failed for `%s', "
				    "error %d", name, error);
#endif
			SLIST_REMOVE_HEAD(&pend_stack, pe_entry);
			module_free(mod);
			return error;
		}
		TAILQ_INSERT_TAIL(pending, mod, mod_chain);

		error = module_fetch_info(mod);
		if (error != 0) {
			module_error("cannot fetch info for `%s', error %d",
			    name, error);
			goto fail;
		}
	}

	/*
	 * Check compatibility.
	 */
	mi = mod->mod_info;
	if (strnlen(mi->mi_name, MAXMODNAME) >= MAXMODNAME) {
		error = EINVAL;
		module_error("module name `%s' longer than %d", mi->mi_name,
		    MAXMODNAME);
		goto fail;
	}
	if (mi->mi_class <= MODULE_CLASS_ANY ||
	    mi->mi_class >= MODULE_CLASS_MAX) {
		error = EINVAL;
		module_error("module `%s' has invalid class %d",
		    mi->mi_name, mi->mi_class);
		    goto fail;
	}
	if (!module_compatible(mi->mi_version, __NetBSD_Version__)) {
		module_error("module `%s' built for `%d', system `%d'",
		    mi->mi_name, mi->mi_version, __NetBSD_Version__);
		if (ISSET(flags, MODCTL_LOAD_FORCE)) {
			module_error("forced load, system may be unstable");
		} else {
			error = EPROGMISMATCH;
			goto fail;
		}
	}

	/*
	 * If a specific kind of module was requested, ensure that we have
	 * a match.
	 */
	if (!MODULE_CLASS_MATCH(mi, modclass)) {
		module_incompat(mi, modclass);
		error = ENOENT;
		goto fail;
	}

	/*
	 * If loading a dependency, `name' is a plain module name.
	 * The name must match.
	 */
	if (isdep && strcmp(mi->mi_name, name) != 0) {
		module_error("dependency name mismatch (`%s' != `%s')",
		    name, mi->mi_name);
		error = ENOENT;
		goto fail;
	}

	/*
	 * If we loaded a module from the filesystem, check the actual
	 * module name (from the modinfo_t) to ensure another module
	 * with the same name doesn't already exist.  (There's no
	 * guarantee the filename will match the module name, and the
	 * dup-symbols check may not be sufficient.)
	 */
	if (mod->mod_source == MODULE_SOURCE_FILESYS) {
		mod2 = module_lookup(mod->mod_info->mi_name);
		if ( mod2 && mod2 != mod) {
			module_error("module with name `%s' already loaded",
			    mod2->mod_info->mi_name);
			error = EEXIST;
			if (modp != NULL)
				*modp = mod2;
			goto fail;
		}
	}

	/*
	 * Block circular dependencies.
	 */
	TAILQ_FOREACH(mod2, pending, mod_chain) {
		if (mod == mod2) {
			continue;
		}
		if (strcmp(mod2->mod_info->mi_name, mi->mi_name) == 0) {
			error = EDEADLK;
			module_error("circular dependency detected for `%s'",
			    mi->mi_name);
			goto fail;
		}
	}

	/*
	 * Now try to load any requisite modules.
	 */
	if (mi->mi_required != NULL) {
		mod->mod_arequired = 0;
		for (s = mi->mi_required; *s != '\0'; s = p) {
			if (*s == ',')
				s++;
			p = s;
			while (*p != '\0' && *p != ',')
				p++;
			len = p - s + 1;
			if (len >= MAXMODNAME) {
				error = EINVAL;
				module_error("required module name `%s' "
				    "longer than %d", mi->mi_required,
				    MAXMODNAME);
				goto fail;
			}
			strlcpy(buf, s, len);
			if (buf[0] == '\0')
				break;
			alloc_required(mod);
			if (strcmp(buf, mi->mi_name) == 0) {
				error = EDEADLK;
				module_error("self-dependency detected for "
				   "`%s'", mi->mi_name);
				goto fail;
			}
			error = module_do_load(buf, true, flags, NULL,
			    &mod2, MODULE_CLASS_ANY, true);
			if (error != 0 && error != EEXIST) {
				module_error("recursive load failed for `%s' "
				    "(`%s' required), error %d", mi->mi_name,
				    buf, error);
				goto fail;
			}
			(*mod->mod_required)[mod->mod_nrequired++] = mod2;
		}
	}

	/*
	 * We loaded all needed modules successfully: perform global
	 * relocations and initialize.
	 */
	{
		char xname[MAXMODNAME];

		/*
		 * In case of error the entire module is gone, so we
		 * need to save its name for possible error report.
		 */

		strlcpy(xname, mi->mi_name, MAXMODNAME);
		error = kobj_affix(mod->mod_kobj, mi->mi_name);
		if (error != 0) {
			module_error("unable to affix module `%s', error %d",
			    xname, error);
			goto fail2;
		}
	}

	if (filedict) {
		if (!module_merge_dicts(filedict, props)) {
			module_error("module properties failed for %s", name);
			error = EINVAL;
			goto fail;
		}
	}

	prev_active = module_active;
	module_active = mod;
	error = (*mi->mi_modcmd)(MODULE_CMD_INIT, filedict ? filedict : props);
	module_active = prev_active;
	if (filedict) {
		prop_object_release(filedict);
		filedict = NULL;
	}
	if (error != 0) {
		module_error("modcmd(CMD_INIT) failed for `%s', error %d",
		    mi->mi_name, error);
		goto fail;
	}

	/*
	 * If a recursive load already added a module with the same
	 * name, abort.
	 */
	mod2 = module_lookup(mi->mi_name);
	if (mod2 && mod2 != mod) {
		module_error("recursive load causes duplicate module `%s'",
		    mi->mi_name);
		error = EEXIST;
		goto fail1;
	}

	/*
	 * Good, the module loaded successfully.  Put it onto the
	 * list and add references to its requisite modules.
	 */
	TAILQ_REMOVE(pending, mod, mod_chain);
	module_enqueue(mod);
	if (modp != NULL) {
		*modp = mod;
	}
	if (autoload && module_autotime > 0) {
		/*
		 * Arrange to try unloading the module after
		 * a short delay unless auto-unload is disabled.
		 */
		mod->mod_autotime = time_second + module_autotime;
		SET(mod->mod_flags, MODFLG_AUTO_LOADED);
		module_thread_kick();
	}
	SLIST_REMOVE_HEAD(&pend_stack, pe_entry);
	module_print("module `%s' loaded successfully", mi->mi_name);
	module_callback_load(mod);
	return 0;

 fail1:
	(*mi->mi_modcmd)(MODULE_CMD_FINI, NULL);
 fail:
	kobj_unload(mod->mod_kobj);
 fail2:
	if (filedict != NULL) {
		prop_object_release(filedict);
		filedict = NULL;
	}
	TAILQ_REMOVE(pending, mod, mod_chain);
	SLIST_REMOVE_HEAD(&pend_stack, pe_entry);
	module_free(mod);
	return error;
}

/*
 * module_do_unload:
 *
 *	Helper routine: do the dirty work of unloading a module.
 */
static int
module_do_unload(const char *name, bool load_requires_force)
{
	module_t *mod, *prev_active;
	int error;
	u_int i;

	KASSERT(kernconfig_is_held());
	KASSERT(name != NULL);

	module_print("unload requested for '%s' (%s)", name,
	    load_requires_force ? "TRUE" : "FALSE");
	mod = module_lookup(name);
	if (mod == NULL) {
		module_error("module `%s' not found", name);
		return ENOENT;
	}
	if (mod->mod_refcnt != 0) {
		module_print("module `%s' busy (%d refs)", name,
		    mod->mod_refcnt);
		return EBUSY;
	}

	/*
	 * Builtin secmodels are there to stay.
	 */
	if (mod->mod_source == MODULE_SOURCE_KERNEL &&
	    mod->mod_info->mi_class == MODULE_CLASS_SECMODEL) {
		module_print("cannot unload built-in secmodel module `%s'",
		    name);
		return EPERM;
	}

	prev_active = module_active;
	module_active = mod;
	module_callback_unload(mod);
	error = (*mod->mod_info->mi_modcmd)(MODULE_CMD_FINI, NULL);
	module_active = prev_active;
	if (error != 0) {
		module_print("cannot unload module `%s' error=%d", name,
		    error);
		return error;
	}
	module_count--;
	TAILQ_REMOVE(&module_list, mod, mod_chain);
	for (i = 0; i < mod->mod_nrequired; i++) {
		(*mod->mod_required)[i]->mod_refcnt--;
	}
	module_print("unloaded module `%s'", name);
	if (mod->mod_kobj != NULL) {
		kobj_unload(mod->mod_kobj);
	}
	if (mod->mod_source == MODULE_SOURCE_KERNEL) {
		if (mod->mod_required != NULL) {
			/*
			 * release "required" resources - will be re-parsed
			 * if the module is re-enabled
			 */
			kmem_free(mod->mod_required,
			    mod->mod_arequired * sizeof(module_t *));
			mod->mod_nrequired = 0;
			mod->mod_arequired = 0;
			mod->mod_required = NULL;
		}
		if (load_requires_force)
			module_require_force(mod);
		TAILQ_INSERT_TAIL(&module_builtins, mod, mod_chain);
		module_builtinlist++;
	} else {
		module_free(mod);
	}
	module_gen++;

	return 0;
}

/*
 * module_prime:
 *
 *	Push a module loaded by the bootloader onto our internal
 *	list.
 */
int
module_prime(const char *name, void *base, size_t size)
{
	__link_set_decl(modules, modinfo_t);
	modinfo_t *const *mip;
	module_t *mod;
	int error;

	/* Check for module name same as a built-in module */

	__link_set_foreach(mip, modules) {
		if (*mip == &module_dummy)
			continue;
		if (strcmp((*mip)->mi_name, name) == 0) {
			module_error("module `%s' pushed by boot loader "
			    "already exists", name);
			return EEXIST;
		}
	}

	/* Also eliminate duplicate boolist entries */

	TAILQ_FOREACH(mod, &module_bootlist, mod_chain) {
		if (strcmp(mod->mod_info->mi_name, name) == 0) {
			module_error("duplicate bootlist entry for module "
			    "`%s'", name);
			return EEXIST;
		}
	}

	mod = module_newmodule(MODULE_SOURCE_BOOT);
	if (mod == NULL) {
		return ENOMEM;
	}

	error = kobj_load_mem(&mod->mod_kobj, name, base, size);
	if (error != 0) {
		module_free(mod);
		module_error("unable to load `%s' pushed by boot loader, "
		    "error %d", name, error);
		return error;
	}
	error = module_fetch_info(mod);
	if (error != 0) {
		kobj_unload(mod->mod_kobj);
		module_free(mod);
		module_error("unable to fetch_info for `%s' pushed by boot "
		    "loader, error %d", name, error);
		return error;
	}

	TAILQ_INSERT_TAIL(&module_bootlist, mod, mod_chain);

	return 0;
}

/*
 * module_fetch_into:
 *
 *	Fetch modinfo record from a loaded module.
 */
static int
module_fetch_info(module_t *mod)
{
	int error;
	void *addr;
	size_t size;

	/*
	 * Find module info record and check compatibility.
	 */
	error = kobj_find_section(mod->mod_kobj, "link_set_modules",
	    &addr, &size);
	if (error != 0) {
		module_error("`link_set_modules' section not present, "
		    "error %d", error);
		return error;
	}
	if (size != sizeof(modinfo_t **)) {
		module_error("`link_set_modules' section wrong size "
		    "(got %zu, wanted %zu)", size, sizeof(modinfo_t **));
		return ENOEXEC;
	}
	mod->mod_info = *(modinfo_t **)addr;

	return 0;
}

/*
 * module_find_section:
 *
 *	Allows a module that is being initialized to look up a section
 *	within its ELF object.
 */
int
module_find_section(const char *name, void **addr, size_t *size)
{

	KASSERT(kernconfig_is_held());
	KASSERT(module_active != NULL);

	return kobj_find_section(module_active->mod_kobj, name, addr, size);
}

/*
 * module_thread:
 *
 *	Automatically unload modules.  We try once to unload autoloaded
 *	modules after module_autotime seconds.  If the system is under
 *	severe memory pressure, we'll try unloading all modules, else if
 *	module_autotime is zero, we don't try to unload, even if the
 *	module was previously scheduled for unload.
 */
static void
module_thread(void *cookie)
{
	module_t *mod, *next;
	modinfo_t *mi;
	int error;

	for (;;) {
		kernconfig_lock();
		for (mod = TAILQ_FIRST(&module_list); mod != NULL; mod = next) {
			next = TAILQ_NEXT(mod, mod_chain);

			/* skip built-in modules */
			if (mod->mod_source == MODULE_SOURCE_KERNEL)
				continue;
			/* skip modules that weren't auto-loaded */
			if (!ISSET(mod->mod_flags, MODFLG_AUTO_LOADED))
				continue;

			if (uvmexp.free < uvmexp.freemin) {
				module_thread_ticks = hz;
			} else if (module_autotime == 0 ||
				   mod->mod_autotime == 0) {
				continue;
			} else if (time_second < mod->mod_autotime) {
				module_thread_ticks = hz;
			    	continue;
			} else {
				mod->mod_autotime = 0;
			}

			/*
			 * If this module wants to avoid autounload then
			 * skip it.  Some modules can ping-pong in and out
			 * because their use is transient but often. 
			 * Example: exec_script.
			 */
			mi = mod->mod_info;
			error = (*mi->mi_modcmd)(MODULE_CMD_AUTOUNLOAD, NULL);
			if (error == 0 || error == ENOTTY) {
				(void)module_do_unload(mi->mi_name, false);
			} else
				module_print("module `%s' declined to be "
				    "auto-unloaded error=%d", mi->mi_name,
				    error);
		}
		kernconfig_unlock();

		mutex_enter(&module_thread_lock);
		(void)cv_timedwait(&module_thread_cv, &module_thread_lock,
		    module_thread_ticks);
		module_thread_ticks = 0;
		mutex_exit(&module_thread_lock);
	}
}

/*
 * module_thread:
 *
 *	Kick the module thread into action, perhaps because the
 *	system is low on memory.
 */
void
module_thread_kick(void)
{

	mutex_enter(&module_thread_lock);
	module_thread_ticks = hz;
	cv_broadcast(&module_thread_cv);
	mutex_exit(&module_thread_lock);
}

#ifdef DDB
/*
 * module_whatis:
 *
 *	Helper routine for DDB.
 */
void
module_whatis(uintptr_t addr, void (*pr)(const char *, ...))
{
	module_t *mod;
	size_t msize;
	vaddr_t maddr;

	TAILQ_FOREACH(mod, &module_list, mod_chain) {
		if (mod->mod_kobj == NULL) {
			continue;
		}
		if (kobj_stat(mod->mod_kobj, &maddr, &msize) != 0)
			continue;
		if (addr < maddr || addr >= maddr + msize) {
			continue;
		}
		(*pr)("%p is %p+%zu, in kernel module `%s'\n",
		    (void *)addr, (void *)maddr,
		    (size_t)(addr - maddr), mod->mod_info->mi_name);
	}
}

/*
 * module_print_list:
 *
 *	Helper routine for DDB.
 */
void
module_print_list(void (*pr)(const char *, ...))
{
	const char *src;
	module_t *mod;
	size_t msize;
	vaddr_t maddr;

	(*pr)("%16s %16s %8s %8s\n", "NAME", "TEXT/DATA", "SIZE", "SOURCE");

	TAILQ_FOREACH(mod, &module_list, mod_chain) {
		switch (mod->mod_source) {
		case MODULE_SOURCE_KERNEL:
			src = "builtin";
			break;
		case MODULE_SOURCE_FILESYS:
			src = "filesys";
			break;
		case MODULE_SOURCE_BOOT:
			src = "boot";
			break;
		default:
			src = "unknown";
			break;
		}
		if (mod->mod_kobj == NULL) {
			maddr = 0;
			msize = 0;
		} else if (kobj_stat(mod->mod_kobj, &maddr, &msize) != 0)
			continue;
		(*pr)("%16s %16lx %8ld %8s\n", mod->mod_info->mi_name,
		    (long)maddr, (long)msize, src);
	}
}
#endif	/* DDB */

static bool
module_merge_dicts(prop_dictionary_t existing_dict,
		   const prop_dictionary_t new_dict)
{
	prop_dictionary_keysym_t props_keysym;
	prop_object_iterator_t props_iter;
	prop_object_t props_obj;
	const char *props_key;
	bool error;

	if (new_dict == NULL) {			/* nothing to merge */
		return true;
	}

	error = false;
	props_iter = prop_dictionary_iterator(new_dict);
	if (props_iter == NULL) {
		return false;
	}

	while ((props_obj = prop_object_iterator_next(props_iter)) != NULL) {
		props_keysym = (prop_dictionary_keysym_t)props_obj;
		props_key = prop_dictionary_keysym_cstring_nocopy(props_keysym);
		props_obj = prop_dictionary_get_keysym(new_dict, props_keysym);
		if ((props_obj == NULL) || !prop_dictionary_set(existing_dict,
		    props_key, props_obj)) {
			error = true;
			goto out;
		}
	}
	error = false;

out:
	prop_object_iterator_release(props_iter);

	return !error;
}

/*
 * module_specific_key_create:
 *
 *	Create a key for subsystem module-specific data.
 */
specificdata_key_t
module_specific_key_create(specificdata_key_t *keyp, specificdata_dtor_t dtor)
{

	return specificdata_key_create(module_specificdata_domain, keyp, dtor);
}

/*
 * module_specific_key_delete:
 *
 *	Delete a key for subsystem module-specific data.
 */
void
module_specific_key_delete(specificdata_key_t key)
{

	return specificdata_key_delete(module_specificdata_domain, key);
}

/*
 * module_getspecific:
 *
 *	Return module-specific data corresponding to the specified key.
 */
void *
module_getspecific(module_t *mod, specificdata_key_t key)
{

	return specificdata_getspecific(module_specificdata_domain,
	    &mod->mod_sdref, key);
}

/*
 * module_setspecific:
 *
 *	Set module-specific data corresponding to the specified key.
 */
void
module_setspecific(module_t *mod, specificdata_key_t key, void *data)
{

	specificdata_setspecific(module_specificdata_domain,
	    &mod->mod_sdref, key, data);
}

/*
 * module_register_callbacks:
 *
 *	Register a new set of callbacks to be called on module load/unload.
 *	Call the load callback on each existing module.
 *	Return an opaque handle for unregistering these later.
 */
void *
module_register_callbacks(void (*load)(struct module *),
    void (*unload)(struct module *))
{
	struct module_callbacks *modcb;
	struct module *mod;

	modcb = kmem_alloc(sizeof(*modcb), KM_SLEEP);
	modcb->modcb_load = load;
	modcb->modcb_unload = unload;

	kernconfig_lock();
	TAILQ_INSERT_TAIL(&modcblist, modcb, modcb_list);
	TAILQ_FOREACH(mod, &module_list, mod_chain)
		load(mod);
	kernconfig_unlock();

	return modcb;
}

/*
 * module_unregister_callbacks:
 *
 *	Unregister a previously-registered set of module load/unload callbacks.
 *	Call the unload callback on each existing module.
 */
void
module_unregister_callbacks(void *opaque)
{
	struct module_callbacks *modcb;
	struct module *mod;

	modcb = opaque;
	kernconfig_lock();
	TAILQ_FOREACH(mod, &module_list, mod_chain)
		modcb->modcb_unload(mod);
	TAILQ_REMOVE(&modcblist, modcb, modcb_list);
	kernconfig_unlock();
	kmem_free(modcb, sizeof(*modcb));
}

/*
 * module_callback_load:
 *
 *	Helper routine: call all load callbacks on a module being loaded.
 */
static void
module_callback_load(struct module *mod)
{
	struct module_callbacks *modcb;

	TAILQ_FOREACH(modcb, &modcblist, modcb_list) {
		modcb->modcb_load(mod);
	}
}

/*
 * module_callback_unload:
 *
 *	Helper routine: call all unload callbacks on a module being unloaded.
 */
static void
module_callback_unload(struct module *mod)
{
	struct module_callbacks *modcb;

	TAILQ_FOREACH(modcb, &modcblist, modcb_list) {
		modcb->modcb_unload(mod);
	}
}