|
root / base / usr / src / uts / common / io / overlay
overlay Plain Text 5144 lines 146.4 KB
   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
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
/*
 * This file and its contents are supplied under the terms of the
 * Common Development and Distribution License ("CDDL"), version 1.0.
 * You may only use this file in accordance with the terms of version
 * 1.0 of the CDDL.
 *
 * A full copy of the text of the CDDL should have accompanied this
 * source.  A copy of the CDDL is also available via the Internet at
 * http://www.illumos.org/license/CDDL.
 */

/*
 * Copyright 2016 Joyent, Inc.
 * Copyright 2022 MNX Cloud, Inc.
 */

/*
 * Overlay Devices
 *
 * Overlay devices provide a means for creating overlay networks, a means of
 * multiplexing multiple logical, isolated, and discrete layer two and layer
 * three networks on top of one physical network.
 *
 * In general, these overlay devices encapsulate the logic to answer two
 * different questions:
 *
 *   1) How should I transform a packet to put it on the wire?
 *   2) Where should I send a transformed packet?
 *
 * Each overlay device is presented to the user as a GLDv3 device. While the
 * link itself cannot have an IP interface created on top of it, it allows for
 * additional GLDv3 devices, such as a VNIC, to be created on top of it which
 * can be plumbed up with IP interfaces.
 *
 *
 * --------------------
 * General Architecture
 * --------------------
 *
 * The logical overlay device that a user sees in dladm(8) is a combination of
 * two different components that work together. The first component is this
 * kernel module, which is responsible for answering question one -- how should
 * I transform a packet to put it on the wire.
 *
 * The second component is what we call the virtual ARP daemon, or varpd. It is
 * a userland component that is responsible for answering the second question --
 * Where should I send a transformed packet. Instances of the kernel overlay
 * GLDv3 device ask varpd the question of where should a packet go.
 *
 * The split was done for a few reasons. Importantly, we wanted to keep the act
 * of generating encapsulated packets in the kernel so as to ensure that the
 * general data path was fast and also kept simple. On the flip side, while the
 * question of where should something go may be simple, it may often be
 * complicated and need to interface with several different external or
 * distributed systems. In those cases, it's simpler to allow for the full
 * flexibility of userland to be brought to bear to solve that problem and in
 * general, the path isn't very common.
 *
 * The following is what makes up the logical overlay device that a user would
 * create with dladm(8).
 *
 *       Kernel                                     Userland
 *   . . . . . . . . . . . . . . . . . . . . .   . . . . . . . . . . . . .
 *   . +--------+   +--------+  +--------+   .   .                       .
 *   . | VNIC 0 |   | VNIC 1 |  | VNIC 2 |   .   .                       .
 *   . +--------+   +--------+  +--------+   .   .                       .
 *   .     |            |           |        .   .                       .
 *   .     |            |           |        .   .                       .
 *   .     +------------+-----------+        .   .                       .
 *   .                  |              . . /dev/overlay                  .
 *   .           +--------------+      .     .   .       +------------+  .
 *   .           |              |      .     .   .       |            |  .
 *   .           |    Overlay   |======*=================|   Virtual  |  .
 *   .           | GLDv3 Device |========================| ARP Daemon |  .
 *   .           |              |            .   .       |            |  .
 *   .           +--------------+            .   .       +------------+  .
 *   .                  |                    .   .              |        .
 *   .                  |                    .   .              |        .
 *   .           +----------------+          .   .         +--------+    .
 *   .           |  Overlay       |          .   .         | varpd  |    .
 *   .           |  Encapsulation |          .   .         | Lookup |    .
 *   .           |  Plugin        |          .   .         | Plugin |    .
 *   .           +----------------+          .   .         +--------+    .
 *   . . . . . . . . . . . . . . . . . . . . .   . . . . . . . . . . . . .
 *
 *
 * This image shows the two different components and where they live.
 * Importantly, it also shows that both the kernel overlay device and the
 * userland varpd both support plugins. The plugins actually implement the
 * things that users care about and the APIs have been designed to try to
 * minimize the amount of things that a module writer needs to worry about it.
 *
 * IDENTIFIERS
 *
 * Every overlay device is defined by a unique identifier which is the overlay
 * identifier. Its purpose is similar to that of a VLAN identifier, it's a
 * unique number that is used to differentiate between different entries on the
 * wire.
 *
 * ENCAPSULATION
 *
 * An overlay encapsulation plugin is a kernel miscellaneous module whose
 * purpose is to contain knowledge about how to transform packets to put them
 * onto the wire and to take them off. An example of an encapsulation plugin is
 * vxlan. It's also how support for things like nvgre or geneve would be brought
 * into the system.
 *
 * Each encapsulation plugins defines a series of operation vectors and
 * properties. For the full details on everything they should provide, please
 * read uts/common/sys/overlay_plugin.h. The encapsulation plugin is responsible
 * for telling the system what information is required to send a packet. For
 * example, vxlan is defined to send everything over a UDP packet and therefore
 * requires a port and an IP address, while nvgre on the other hand is its own
 * IP type and therefore just requires an IP address. In addition, it also
 * provides information about the kind of socket that should be created. This is
 * used by the kernel multiplexor, more of that in the Kernel Components
 * section.
 *
 * LOOKUPS
 *
 * The kernel communicates requests for lookups over the character device
 * /dev/overlay. varpd is responsible for listening for requests on that device
 * and answering them. The character device is specific to the target path and
 * varpd.
 *
 * Much as the kernel overlay module handles the bulk of the scaffolding but
 * leaves the important work to the encapsulation plugin, varpd provides a
 * similar role and leaves the full brunt of lookups to a userland dynamic
 * shared object which implements the logic of lookups.
 *
 * Each lookup plugin defines a series of operation vectors and properties. For
 * the full details on everything that they should provide, please read
 * lib/varpd/libvarpd/libvarpd_provider.h. Essentially, they are given a MAC
 * address and asked to give an address on the physical network that it should
 * be sent to. In addition, they handle questions related to how to handle
 * things like broadcast and multicast traffic, etc.
 *
 * ----------
 * Properties
 * ----------
 *
 * A device from a dladm perspective has a unique set of properties that are
 * combined from three different sources:
 *
 *   1) Generic properties that every overlay device has
 *   2) Properties that are specific to the encapsulation plugin
 *   3) Properties that are specific to the lookup plugin
 *
 * All of these are exposed in a single set of properties in dladm. Note that
 * these are not necessarily traditional link properties. However, if something
 * is both a traditional GLDv3 link property, say the MTU of a device, and a
 * specific property here, than the driver ensures that all existing GLDv3
 * specific means of manipulating it are used and wraps up its private property
 * interfaces to ensure that works.
 *
 * Properties in the second and third category are prefixed with the name of
 * their module. For example, the vxlan encapsulation module has a property
 * called the 'listen_ip'. This property would show up in dladm as
 * 'vxlan/listen_ip'. This allows different plugins to both use similar names
 * for similar properties and to also have independent name spaces so that
 * overlapping names do not conflict with anything else.
 *
 * While the kernel combines both sets one and two into a single coherent view,
 * it does not do anything with respect to the properties that are owned by the
 * lookup plugin -- those are owned wholly by varpd. Instead, libdladm is in
 * charge of bridging these two worlds into one magical experience for the user.
 * It carries the burden of knowing about both overlay specific and varpd
 * specific properties. Importantly, we want to maintain this distinction. We
 * don't want to treat the kernel as an arbitrary key/value store for varpd and
 * we want the kernel to own its own data and not have to ask userland for
 * information that it owns.
 *
 * Every property in the system has the following attributes:
 *
 *   o A name
 *   o A type
 *   o A size
 *   o Permissions
 *   o Default value
 *   o Valid value ranges
 *   o A value
 *
 * Everything except for the value is obtained by callers through the propinfo
 * callbacks and a property has a maximum size of OVERLAY_PROP_SIZEMAX,
 * currently 256 bytes.
 *
 * The following are the supported types of properties:
 *
 *	OVERLAY_PROP_T_INT
 *
 *		A signed integer, its length is 8 bytes, corresponding to a
 *		int64_t.
 *
 *	OVERLAY_PROP_T_UINT
 *
 *		An unsigned integer, its length is 8 bytes, corresponding to a
 *		uint64_t.
 *
 *	OVERLAY_PROP_T_IP
 *
 *		A struct in6_addr, it has a fixed size.
 *
 *	OVERLAY_PROP_T_STRING
 *
 *		A null-terminated character string encoded in either ASCII or
 *		UTF-8. Note that the size of the string includes the null
 *		terminator.
 *
 * The next thing that we apply to a property is its permission. The permissions
 * are put together by the bitwise or of the following flags and values.
 *
 *	OVERLAY_PROP_PERM_REQ
 *
 *		This indicates a required property. A property that is required
 *		must be set by a consumer before the device can be created. If a
 *		required property has a default property, this constraint is
 *		loosened because the default property defines the value.
 *
 *	OVERLAY_PORP_PERM_READ
 *
 *		This indicates that a property can be read. All properties will
 *		have this value set.
 *
 *	OVERLAY_PROP_PERM_WRITE
 *
 *		This indicates that a property can be written to and thus
 *		updated by userland. Properties that are only intended to
 *		display information, will not have OVERLAY_PROP_PERM_WRITE set.
 *
 * In addition, a few additional values are defined as a convenience to
 * consumers. The first, OVERLAY_PROP_PERM_RW, is a combination of
 * OVERLAY_PROP_PERM_READ and OVERLAY_PERM_PROP_WRITE. The second,
 * OVERLAY_PROP_PERM_RRW, is a combination of OVERLAY_PROP_PERM_REQ,
 * OVERLAY_PROP_PERM_READ, and OVERLAY_PROP_PERM_WRITE. The protection mode of a
 * property should generally be a constant across its lifetime.
 *
 * A property may optionally have a default value. If it does have a default
 * value, and that property is not set to be a different value, then the default
 * value is inherited automatically. It also means that if the default value is
 * acceptable, there is no need to set the value for a required property. For
 * example, the vxlan module has the vxlan/listen_port property which is
 * required, but has a default value of 4789 (the IANA assigned port). Because
 * of that default value, there is no need for it to be set.
 *
 * Finally, a property may declare a list of valid values. These valid values
 * are used for display purposes, they are not enforced by the broader system,
 * but merely allow a means for the information to be communicated to the user
 * through dladm(8). Like a default value, this is optional.
 *
 * The general scaffolding does not do very much with respect to the getting and
 * setting of properties. That is really owned by the individual plugins
 * themselves.
 *
 * -----------------------------
 * Destinations and Plugin Types
 * -----------------------------
 *
 * Both encapsulation and lookup plugins define the kinds of destinations that
 * they know how to support. There are three different pieces of information
 * that can be used to address to a destination currently, all of which is
 * summarized in the type overlay_point_t. Any combination of these is
 * supported.
 *
 *	OVERLAY_PLUGIN_D_ETHERNET
 *
 *		An Ethernet MAC address is required.
 *
 *	OVERLAY_PLUGIN_D_IP
 *
 *		An IP address is required. All IP addresses used by the overlay
 *		system are transmitted as IPv6 addresses. IPv4 addresses can be
 *		represented by using IPv4-mapped IPv6 addresses.
 *
 *	OVERLAY_PLUGIN_D_PORT
 *
 *		A TCP/UDP port is required.
 *
 * A kernel encapsulation plugin declares which of these that it requires, it's
 * a static set. On the other hand, a userland lookup plugin can be built to
 * support all of these or any combination thereof. It gets passed the required
 * destination type, based on the kernel encapsulation method, and then it makes
 * the determination as to whether or not it supports it. For example, the
 * direct plugin can support either an IP or both an IP and a port, it simply
 * doesn't display the direct/dest_port property in the cases where a port is
 * not required to support this.
 *
 * The user lookup plugins have two different modes of operation which
 * determines how they interact with the broader system and how look ups are
 * performed. These types are:
 *
 *	OVERLAY_TARGET_POINT
 *
 *		A point to point plugin has a single static definition for where
 *		to send all traffic. Every packet in the system always gets sent
 *		to the exact same destination which is programmed into the
 *		kernel when the general device is activated.
 *
 *	OVERLAY_TARGET_DYNAMIC
 *
 *		A dynamic plugin does not have a single static definition.
 *		Instead, for each destination, the kernel makes an asynchronous
 *		request to varpd to determine where the packet should be routed,
 *		and if a specific destination is found, then that destination is
 *		cached in the overlay device's target cache.
 *
 * This distinction, while important for the general overlay device's operation,
 * is not important to the encapsulation plugins. They don't need to know about
 * any of these pieces. It's just a concern for varpd, the userland plugin, and
 * the general overlay scaffolding.
 *
 * When an overlay device is set to OVERLAY_TARGET_POINT, then it does not
 * maintain a target cache, and instead just keeps track of the destination and
 * always sends encapsulated packets to that address. When the target type is of
 * OVERLAY_TARGET_DYNAMIC, then the kernel maintains a cache of all such
 * destinations. These destinations are kept around in an instance of a
 * reference hash that is specific to the given overlay device. Entries in the
 * cache can be invalidated and replaced by varpd and its lookup plugins.
 *
 * ----------------------------------
 * Kernel Components and Architecture
 * ----------------------------------
 *
 * There are multiple pieces inside the kernel that work together, there is the
 * general overlay_dev_t structure, which is the logical GLDv3 device, but it
 * itself has references to things like an instance of an encapsulation plugin,
 * a pointer to a mux and a target cache. It can roughly be summarized in the
 * following image:
 *
 *     +------------------+
 *     | global           |
 *     | overlay list     |
 *     | overlay_dev_list |
 *     +------------------+
 *        |
 *        |  +-----------------------+            +---------------+
 *        +->| GLDv3 Device          |----------->| GLDv3 Device  | -> ...
 *           | overlay_dev_t         |            | overlay_dev_t |
 *           |                       |            +---------------+
 *           |                       |
 *           | mac_handle_t     -----+---> GLDv3 handle to MAC
 *           | datalink_id_t    -----+---> Datalink ID used by DLS
 *           | overlay_dev_flag_t ---+---> Device state
 *           | uint_t           -----+---> Current device MTU
 *           | uint_t           -----+---> In-progress RX operations
 *           | uint_t           -----+---> In-progress TX operations
 *           | char[]           -----+---> FMA degraded message
 *           | void *           -----+---> plugin private data
 *           | overlay_target_t * ---+---------------------+
 *           | overlay_plugin_t * ---+---------+           |
 *           +-----------------------+         |           |
 *                           ^                 |           |
 *   +--------------------+  |                 |           |
 *   | Kernel Socket      |  |                 |           |
 *   | Multiplexor        |  |                 |           |
 *   | overlay_mux_t      |  |                 |           |
 *   |                    |  |                 |           |
 *   | avl_tree_t        -+--+                 |           |
 *   | uint_t            -+--> socket family   |           |
 *   | uint_t            -+--> socket type     |           |
 *   | uint_t            -+--> socket protocol |           |
 *   | ksocket_t         -+--> I/O socket      |           |
 *   | struct sockaddr * -+--> ksocket address |           |
 *   | overlay_plugin_t --+--------+           |           |
 *   +--------------------+        |           |           |
 *                                 |           |           |
 *   +-------------------------+   |           |           |
 *   | Encap Plugin            |<--+-----------+           |
 *   | overlay_plugin_t        |                           |
 *   |                         |                           |
 *   | char *               ---+--> plugin name            |
 *   | overlay_plugin_ops_t * -+--> plugin downcalls       |
 *   | char ** (props)      ---+--> property list          |
 *   | uint_t               ---+--> id length              |
 *   | overlay_plugin_flags_t -+--> plugin flags           |
 *   | overlay_plugin_dest_t --+--> destination type       v
 *   +-------------------------+                    +-------------------------+
 *                                                  |   Target Cache          |
 *                                                  |   overlay_target_t      |
 *                                                  |                         |
 *                                    cache mode <--+- overlay_target_mode_t  |
 *                                     dest type <--+- overlay_plugin_dest_t  |
 *                                   cache flags <--+- overlay_target_flag_t  |
 *                                     varpd id  <--+- uint64_t               |
 *                       outstanding varpd reqs. <--+- uint_t                 |
 *                   OVERLAY_TARGET_POINT state  <--+- overlay_target_point_t |
 *               OVERLAY_TARGET_DYNAMIC state <-+---+- overlay_target_dyn_t   |
 *                                              |   +-------------------------+
 *                      +-----------------------+
 *                      |
 *                      v
 *   +-------------------------------+   +------------------------+
 *   | Target Entry                  |-->| Target Entry           |--> ...
 *   | overlay_target_entry_t        |   | overlay_target_entry_t |
 *   |                               |   +------------------------+
 *   |                               |
 *   | overlay_target_entry_flags_t -+--> Entry flags
 *   | uint8_t[ETHERADDRL]        ---+--> Target MAC address
 *   | overlay_target_point_t     ---+--> Target underlay address
 *   | mblk_t *                   ---+--> outstanding mblk head
 *   | mblk_t *                   ---+--> outstanding mblk tail
 *   | size_t                     ---+--> outstanding mblk size
 *   +-------------------------------+
 *
 * The primary entries that we care about are the overlay_dev_t, which
 * correspond to each overlay device that is created with dladm(8). Globally,
 * these devices are maintained in a simple list_t which is protected with a
 * lock.  Hence, these include important information such as the mac_handle_t
 * and a datalink_id_t which is used to interact with the broader MAC and DLS
 * ecosystem. We also maintain additional information such as the current state,
 * outstanding operations, the mtu, and importantly, the plugin's private data.
 * This is the instance of an encapsulation plugin that gets created as part of
 * creating an overlay device. Another aspect of this is that the overlay_dev_t
 * also includes information with respect to FMA. For more information, see the
 * FMA section.
 *
 * Each overlay_dev_t has a pointer to a plugin, a mux, and a target. The plugin
 * is the encapsulation plugin. This allows the device to make downcalls into it
 * based on doing things like getting and setting properties. Otherwise, the
 * plugin itself is a fairly straightforward entity. They are maintained in an
 * (not pictured above) list. The plugins themselves mostly maintain things like
 * the static list of properties, what kind of destination they require, and the
 * operations vector. A given module may contain more if necessary.
 *
 * The next piece of the puzzle is the mux, or a multiplexor. The mux itself
 * maintains a ksocket and it is through the mux that we send and receive
 * message blocks. The mux represents a socket type and address, as well as a
 * plugin. Multiple overlay_dev_t devices may then share the same mux. For
 * example, consider the case where you have different instances of vxlan all on
 * the same underlay network. These would all logically share the same IP
 * address and port that packets are sent and received on; however, what differs
 * is the decapuslation ID.
 *
 * Each mux maintains a ksocket_t which is similar to a socket(3SOCKET). Unlike
 * a socket, we enable a direct callback on the ksocket. This means that
 * whenever a message block chain is received, rather than sitting there and
 * getting a callback in a context and kicking that back out to a taskq. Instead
 * data comes into the callback function overlay_mux_recv().
 *
 * The mux is given encapsulated packets (via overlay_m_tx, the GLDv3 tx
 * function) to transmit. It receives encapsulated packets, decapsulates them to
 * determine the overlay identifier, looks up the given device that matches that
 * identifier, and then causes the broader MAC world to receive the packet with
 * a call to mac_rx().
 *
 * Today, we don't do too much that's special with the ksocket; however, as
 * hardware is gaining understanding for these encapsulation protocols, we'll
 * probably want to think of better ways to get those capabilities passed down
 * and potentially better ways to program receive filters so they get directly
 * to us. Though, that's all fantasy future land.
 *
 * The next part of the puzzle is the target cache. The purpose of the target
 * cache is to cache where we should send a packet on the underlay network,
 * given its mac address. The target cache operates in two modes depending on
 * whether the lookup module was declared to OVERLAY_TARGET_POINT or
 * OVERLAY_TARGET_DYANMIC.
 *
 * In the case where the target cache has been programmed to be
 * OVERLAY_TARGET_POINT, then we only maintain a single overlay_target_point_t
 * which has the destination that we send everything, no matter the destination
 * mac address.
 *
 * On the other hand, when we have an instance of OVERLAY_TARGET_DYNAMIC, things
 * are much more interesting and as a result, more complicated. We primarily
 * store lists of overlay_target_entry_t's which are stored in both an avl tree
 * and a refhash_t. The primary look up path uses the refhash_t and the avl tree
 * is only used for a few of the target ioctls used to dump data such that we
 * can get a consistent iteration order for things like dladm show-overlay -t.
 * The key that we use for the reference hashtable is based on the mac address
 * in the cache and currently we just do a simple CRC32 to transform it into a
 * hash.
 *
 * Each entry maintains a set of flags to indicate the current status of the
 * request. The flags may indicate one of three states: that current cache entry
 * is valid, that the current cache entry has been directed to drop all output,
 * and that the current cache entry is invalid and may be being looked up. In
 * the case where it's valid, we just take the destination address and run with
 * it.
 *
 * If it's invalid and a lookup has not been made, then we start the process
 * that prepares a query that will make its way up to varpd. The cache entry
 * entry maintains a message block chain of outstanding message blocks and a
 * size. These lists are populated only when we don't know the answer as to
 * where should these be sent. The size entry is used to cap the amount of
 * outstanding data that we don't know the answer to. If we exceed a cap on the
 * amount of outstanding data (currently 1 Mb), then we'll drop any additional
 * packets. Once we get an answer indicating a valid destination, we transmit
 * any outstanding data to that place. For the full story on how we look that up
 * will be discussed in the section on the Target Cache Lifecycle.
 *
 * ------------------------
 * FMA and Degraded Devices
 * ------------------------
 *
 * Every kernel overlay device keeps track of its FMA state. Today in FMA we
 * cannot represent partitions between resources nor can we represent that a
 * given minor node of a pseudo device has failed -- if we degrade the overlay
 * device, then the entire dev_info_t is degraded. However, we still want to be
 * able to indicate to administrators that things may go wrong.
 *
 * To this end, we've added a notion of a degraded state to every overlay
 * device. This state is primarily dictated by userland and it can happen for
 * various reasons. Generally, because a userland lookup plugin has been
 * partitioned, or something has gone wrong such that there is no longer any
 * userland lookup module for a device, then we'll mark it degraded.
 *
 * As long as any of our minor instances is degraded, then we'll fire off the
 * FMA event to note that. Once the last degraded instance is no longer
 * degraded, then we'll end up telling FMA that we're all clean.
 *
 * To help administrators get a better sense of which of the various minor
 * devices is wrong, we store the odd_fmamsg[] character array. This character
 * array can be fetched with doing a dladm show-overlay -f.
 *
 * Note, that it's important that we do not update the link status of the
 * devices. We want to remain up as much as possible. By changing the link in a
 * degraded state, this may end up making things worse. We may still actually
 * have information in the target cache and if we mark the link down, that'll
 * result in not being able to use it. The reason being that this'll mark all
 * the downstream VNICs down which will go to IP and from there we end up
 * dealing with sadness.
 *
 * -----------------------
 * Target Cache Life Cycle
 * -----------------------
 *
 * This section only applies when we have a lookup plugin of
 * OVERLAY_TARGET_DYNAMIC. None of this applies to those of type
 * OVERLAY_TARGET_POINT.
 *
 * While we got into the target cache in the general architecture section, it's
 * worth going into more details as to how this actually works and showing some
 * examples and state machines. Recall that a target cache entry basically has
 * the following state transition diagram:
 *
 * Initial state
 *    . . .           . . . first access       . . . varpd lookup enqueued
 *        .           .                        .
 *        .           .                        .
 *     +-------+      .     +----------+       .
 *     |  No   |------*---->| Invalid  |-------*----+
 *     | Entry |            |  Entry   |            |
 *     +-------+            +----------+            |
 *                 varpd      ^      ^   varpd      |
 *                 invalidate |      |   drop       |
 *                      . . . *      * . .          v
 *          +-------+         |      |         +---------+
 *          | Entry |--->-----+      +----<----| Entry   |
 *          | Valid |<----------*---------<----| Pending |->-+     varpd
 *          +-------+           .              +---------+   * . . drop, but
 *                              . varpd                ^     |     other queued
 *                              . success              |     |     entries
 *                                                     +-----+
 *
 * When the table is first created, it is empty. As we attempt to lookup entries
 * and we find there is no entry at all, we'll create a new table entry for it.
 * At that point the entry is technically in an invalid state, that means that
 * we have no valid data from varpd. In that case, we'll go ahead and queue the
 * packet into the entry's pending chain, and queue a varpd lookup, setting the
 * OVERLAY_ENTRY_F_PENDING flag in the progress.
 *
 * If additional mblk_t's come in for this entry, we end up appending them to
 * the tail of the chain, if and only if, we don't exceed the threshold for the
 * amount of space they can take up. An entry remains pending until we get a
 * varpd reply. If varpd replies with a valid results, we move to the valid
 * entry state, and remove the OVERLAY_ENTRY_F_PENDING flag and set it with one
 * of OVERLAY_ENTRY_F_VALID or OVERLAY_ENTRY_F_DROP as appropriate.
 *
 * Once an entry is valid, it stays valid until user land tells us to invalidate
 * it with an ioctl or replace it, OVERLAY_TARG_CACHE_REMOE and
 * OVERLAY_TARG_CACHE_SET respectively.
 *
 * If the lookup fails with a call to drop the packet, then the next state is
 * determined by the state of the queue. If the set of outstanding entries is
 * empty, then we just transition back to the invalid state. If instead, the
 * set of outstanding entries is not empty, then we'll queue another entry and
 * stay in the same state, repeating this until the number of requests is
 * drained.
 *
 * The following images describes the flow of a given lookup and where the
 * overlay_target_entry_t is at any given time.
 *
 *     +-------------------+
 *     | Invalid Entry     |		An entry starts off as an invalid entry
 *     | de:ad:be:ef:00:00 |		and only exists in the target cache.
 *     +-------------------+
 *
 *	~~~~
 *
 *     +---------------------+
 *     | Global list_t       |		A mblk_t comes in for an entry. We
 *     | overlay_target_list |		append it to the overlay_target_list.
 *     +---------------------+
 *                   |
 *                   v
 *             +-------------------+      +-------------------+
 *             | Pending Entry     |----->| Pending Entry     |--->...
 *             | 42:5e:1a:10:d6:2d |      | de:ad:be:ef:00:00 |
 *             +-------------------+      +-------------------+
 *
 *	~~~~
 *
 *     +--------------------------+
 *     | /dev/overlay minor state |	User land said that it would look up an
 *     | overlay_target_hdl_t     |	entry for us. We remove it from the
 *     +--------------------------+	global list and add it to the handle's
 *                  |			outstanding list.
 *                  |
 *                  v
 *            +-------------------+      +-------------------+
 *            | Pending Entry     |----->| Pending Entry     |
 *            | 90:b8:d0:79:02:dd |      | de:ad:be:ef:00:00 |
 *            +-------------------+      +-------------------+
 *
 *	~~~~
 *
 *     +-------------------+
 *     | Valid Entry       |		varpd returned an answer with
 *     | de:ad:be:ef:00:00 |		OVERLAY_IOC_RESPOND and the target cache
 *     | 10.169.23.42:4789 |		entry is now populated with a
 *     +-------------------+		destination and marked as valid
 *
 *
 * The lookup mechanism is performed via a series of operations on the character
 * pseudo-device /dev/overlay. The only thing that uses this device is the
 * userland daemon varpd. /dev/overlay is a cloneable device, each open of it
 * granting a new minor number which maintains its own state. We maintain this
 * state so that way if an outstanding lookup was queued to something that
 * crashed or closed its handle without responding, we can know about this and
 * thus handle it appropriately.
 *
 * When a lookup is first created it's added to our global list of outstanding
 * lookups. To service requests, userland is required to perform an ioctl to ask
 * for a request. We will block it in the kernel a set amount of time waiting
 * for a request. When we give a request to a given minor instance of the
 * device, we remove it from the global list and append the request to the
 * device's list of outstanding entries, for the reasons we discussed above.
 * When a lookup comes in, we give user land a smaller amount of information
 * specific to that packet, the overlay_targ_lookup_t. It includes a request id
 * to identify this, and then the overlay id, the varpd id, the header and
 * packet size, the source and destination mac address, the SAP, and any
 * potential VLAN header.
 *
 * At that point, it stays in that outstanding list until one of two ioctls are
 * returned: OVERLAY_TARG_RESPOND or OVERLAY_TARG_DROP. During this time,
 * userland may also perform other operations. For example, it may use
 * OVERLAY_TARG_PKT to get a copy of this packet so it can perform more in-depth
 * analysis of what to do beyond what we gave it initially. This is useful for
 * providing proxy arp and the like. Finally, there are two other ioctls that
 * varpd can then do. The first is OVERLAY_TARG_INJECT which injects the
 * non-jumbo frame packet up into that mac device and OVERLAY_TARG_RESEND which
 * causes us to encapsulate and send out the packet they've given us.
 *
 *
 * Finally, through the target cache, several ioctls are provided to allow for
 * interrogation and management of the cache. They allow for individual entries
 * to be retrieved, set, or have the entire table flushed. For the full set of
 * ioctls here and what they do, take a look at uts/common/sys/overlay_target.h.
 *
 * ------------------
 * Sample Packet Flow
 * ------------------
 *
 * There's a lot of pieces here, hopefully an example of how this all fits
 * together will help clarify and elucidate what's going on. We're going to
 * first track an outgoing packet, eg. one that is sent from an IP interface on
 * a VNIC on top of an overlay device, and then we'll look at what it means to
 * respond to that.
 *
 *
 *    +----------------+        +--------------+            +------------------+
 *    | IP/DLS send    |------->| MAC sends it |----------->| mblk_t reaches   |
 *    | packet to MAC  |        | to the GLDv3 |            | overlay GLDv3 tx |
 *    +----------------+        | VNIC device  |            | overlay_m_tx()   |
 *                              +--------------+            +------------------+
 *                                                                   |
 *                             . lookup              . cache         |
 *                             . drop                . miss          v
 *            +---------+      .       +--------+    .      +------------------+
 *            | freemsg |<-----*-------| varpd  |<---*------| Lookup each mblk |
 *            | mblk_t  |              | lookup |           | in the target    |
 *            +---------+              | queued |           | cache            |
 *                ^                    +--------+           +------------------+
 *      on send   |                        |                         |     cache
 *      error . . *                        *. . lookup               * . . hit
 *                |                        |    success              v
 *                |                        |                +------------------+
 *    +-----------------+                  +--------------->| call plugin      |
 *    | Send out        |                                   | ovpo_encap() to  |
 *    | overlay_mux_t's |<----------------------------------| get encap mblk_t |
 *    | ksocket         |                                   +------------------+
 *    +-----------------+
 *
 * The receive end point looks a little different and looks more like:
 *
 *  +------------------+     +----------------+    +-----------+
 *  | mblk_t comes off |---->| enter netstack |--->| delivered |---+
 *  | the physical     |     | IP stack       |    |     to    |   * . . direct
 *  | device           |     +----------------+    |  ksocket  |   |   callback
 *  +------------------+                           +-----------+   |
 *                       . overlay id                              |
 *                       . not found                               v
 *       +-----------+   .      +-----------------+       +--------------------+
 *       | freemsg   |<--*------| call plugin     |<------| overlay_mux_recv() |
 *       | mblk_t    |          | ovpo_decap() to |       +--------------------+
 *       +-----------+          | decap mblk_t    |
 *                              +-----------------+
 *                                     |
 *                                     * . . overlay id
 *                                     v     found
 *                                 +--------+      +----------------+
 *                                 | adjust |----->| call mac_rx    |
 *                                 | mblk_t |      | on original    |
 *                                 +--------+      | decaped packet |
 *                                                 +----------------+
 *
 * ------------------
 * Netstack Awareness
 * ------------------
 *
 * In the above image we note that this enters a netstack. Today the only
 * netstack that can be is the global zone as the overlay driver itself is not
 * exactly netstack aware. What this really means is that varpd cannot run in a
 * non-global zone and an overlay device cannot belong to a non-global zone.
 * Non-global zones can still have a VNIC assigned to them that's been created
 * over the overlay device the same way they would if it had been created over
 * an etherstub or a physical device.
 *
 * The majority of the work to make it netstack aware is straightforward and the
 * biggest thing is to create a netstack module that allows us to hook into
 * netstack (and thus zone) creation and destruction.  From there, we need to
 * amend the target cache lookup routines that we discussed earlier to not have
 * a global outstanding list and a global list of handles, but rather, one per
 * netstack.
 *
 * For the mux, we'll need to open the ksocket in the context of the zone, we
 * can likely do this with a properly composed credential, but we'll need to do
 * some more work on that path. Finally, we'll want to make sure the dld ioctls
 * are aware of the zoneid of the caller and we use that appropriately and store
 * it in the overlay_dev_t.
 *
 * -----------
 * GLDv3 Notes
 * -----------
 *
 * The overlay driver implements a GLDv3 device. Parts of GLDv3 are more
 * relevant and other parts are much less relevant for us. For example, the
 * GLDv3 is used to toggle the device being put into and out of promiscuous
 * mode, to program MAC addresses for unicast and multicast hardware filters.
 * Today, an overlay device doesn't have a notion of promiscuous mode nor does
 * it have a notion of unicast and multicast addresses programmed into the
 * device. Instead, for the purposes of the hardware filter, we don't do
 * anything and just always accept new addresses being added and removed.
 *
 * If the GLDv3 start function has not been called, then we will not use this
 * device for I/O purposes. Any calls to transmit or receive should be dropped,
 * though the GLDv3 guarantees us that transmit will not be called without
 * calling start. Similarly, once stop is called, then no packets can be dealt
 * with.
 *
 * Today we don't support the stat interfaces, though there's no good reason
 * that we shouldn't assemble some of the stats based on what we have in the
 * future.
 *
 * When it comes to link properties, many of the traditional link properties do
 * not apply and many others MAC handles for us. For example, we don't need to
 * implement anything for overlay_m_getprop() to deal with returning the MTU, as
 * MAC never calls into us for that. As such, there isn't much of anything to
 * support in terms of properties.
 *
 * Today, we don't support any notion of hardware capabilities. However, if
 * future NIC hardware or other changes to the system cause it to make sense for
 * us to emulate logical groups, then we should do that. However, we still do
 * implement a capab function so that we can identify ourselves as an overlay
 * device to the broader MAC framework. This is done mostly so that a device
 * created on top of us can have fanout rings as we don't try to lie about a
 * speed for our device.
 *
 * The other question is what should be done for a device's MTU and margin. We
 * set our minimum supported MTU to be the minimum value that an IP network may
 * be set to 576 -- which mimics what an etherstub does. On the flip side, we
 * have our upper bound set to 8900. This value comes from the fact that a lot
 * of jumbo networks use their maximum as 9000. As such, we want to reserve 100
 * bytes, which isn't exactly the most accurate number, but it'll be good enough
 * for now. Because of that, our default MTU off of these devices is 1400, as
 * the default MTU for everything is usually 1500 or whatever the underlying
 * device is at; however, this is a bit simpler than asking the netstack what
 * are all the IP interfaces at. It also calls into question how PMTU and PMTU
 * discovery should work here. The challenge, especially for
 * OVERLAY_TARG_DYNAMIC is that the MTU to any of the places will vary and it's
 * not clear that if you have a single bad entry that the overall MTU should be
 * lowered. Instead, we should figure out a better way of determining these
 * kinds of PMTU errors and appropriately alerting the administrator via FMA.
 *
 * Regarding margin, we allow a margin of up to VLAN_TAGSZ depending on whether
 * or not the underlying encapsulation device supports VLAN tags. If it does,
 * then we'll set the margin to allow for it, otherwise, we will not.
 */

#include <sys/conf.h>
#include <sys/errno.h>
#include <sys/stat.h>
#include <sys/ddi.h>
#include <sys/sunddi.h>
#include <sys/modctl.h>
#include <sys/policy.h>
#include <sys/stream.h>
#include <sys/strsubr.h>
#include <sys/strsun.h>
#include <sys/types.h>
#include <sys/kmem.h>
#include <sys/param.h>
#include <sys/sysmacros.h>
#include <sys/ddifm.h>

#include <sys/dls.h>
#include <sys/dld_ioc.h>
#include <sys/mac_provider.h>
#include <sys/mac_client_priv.h>
#include <sys/mac_ether.h>
#include <sys/vlan.h>

#include <sys/overlay_impl.h>

dev_info_t *overlay_dip;
static kmutex_t overlay_dev_lock;
static list_t overlay_dev_list;
static uint8_t overlay_macaddr[ETHERADDRL] =
	{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };

typedef enum overlay_dev_prop {
	OVERLAY_DEV_P_MTU = 0,
	OVERLAY_DEV_P_VNETID,
	OVERLAY_DEV_P_ENCAP,
	OVERLAY_DEV_P_VARPDID
} overlay_dev_prop_t;

#define	OVERLAY_DEV_NPROPS	4
static const char *overlay_dev_props[] = {
	"mtu",
	"vnetid",
	"encap",
	"varpd/id"
};

#define	OVERLAY_MTU_MIN	576
#define	OVERLAY_MTU_DEF	1400
#define	OVERLAY_MTU_MAX	8900

overlay_dev_t *
overlay_hold_by_dlid(datalink_id_t id)
{
	overlay_dev_t *o;

	mutex_enter(&overlay_dev_lock);
	for (o = list_head(&overlay_dev_list); o != NULL;
	    o = list_next(&overlay_dev_list, o)) {
		if (id == o->odd_linkid) {
			mutex_enter(&o->odd_lock);
			o->odd_ref++;
			mutex_exit(&o->odd_lock);
			mutex_exit(&overlay_dev_lock);
			return (o);
		}
	}

	mutex_exit(&overlay_dev_lock);
	return (NULL);
}

void
overlay_hold_rele(overlay_dev_t *odd)
{
	mutex_enter(&odd->odd_lock);
	ASSERT(odd->odd_ref > 0);
	odd->odd_ref--;
	mutex_exit(&odd->odd_lock);
}

void
overlay_io_start(overlay_dev_t *odd, overlay_dev_flag_t flag)
{
	ASSERT(flag == OVERLAY_F_IN_RX || flag == OVERLAY_F_IN_TX);
	ASSERT(MUTEX_HELD(&odd->odd_lock));

	if (flag & OVERLAY_F_IN_RX)
		odd->odd_rxcount++;
	if (flag & OVERLAY_F_IN_TX)
		odd->odd_txcount++;
	odd->odd_flags |= flag;
}

void
overlay_io_done(overlay_dev_t *odd, overlay_dev_flag_t flag)
{
	boolean_t signal = B_FALSE;

	ASSERT(flag == OVERLAY_F_IN_RX || flag == OVERLAY_F_IN_TX);
	ASSERT(MUTEX_HELD(&odd->odd_lock));

	if (flag & OVERLAY_F_IN_RX) {
		ASSERT(odd->odd_rxcount > 0);
		odd->odd_rxcount--;
		if (odd->odd_rxcount == 0) {
			signal = B_TRUE;
			odd->odd_flags &= ~OVERLAY_F_IN_RX;
		}
	}
	if (flag & OVERLAY_F_IN_TX) {
		ASSERT(odd->odd_txcount > 0);
		odd->odd_txcount--;
		if (odd->odd_txcount == 0) {
			signal = B_TRUE;
			odd->odd_flags &= ~OVERLAY_F_IN_TX;
		}
	}

	if (signal == B_TRUE)
		cv_broadcast(&odd->odd_iowait);
}

static void
overlay_io_wait(overlay_dev_t *odd, overlay_dev_flag_t flag)
{
	ASSERT((flag & ~OVERLAY_F_IOMASK) == 0);
	ASSERT(MUTEX_HELD(&odd->odd_lock));

	while (odd->odd_flags & flag) {
		cv_wait(&odd->odd_iowait, &odd->odd_lock);
	}
}

void
overlay_dev_iter(overlay_dev_iter_f func, void *arg)
{
	overlay_dev_t *odd;

	mutex_enter(&overlay_dev_lock);
	for (odd = list_head(&overlay_dev_list); odd != NULL;
	    odd = list_next(&overlay_dev_list, odd)) {
		if (func(odd, arg) != 0) {
			mutex_exit(&overlay_dev_lock);
			return;
		}
	}
	mutex_exit(&overlay_dev_lock);
}

/* ARGSUSED */
static int
overlay_m_stat(void *arg, uint_t stat, uint64_t *val)
{
	return (ENOTSUP);
}

static int
overlay_m_start(void *arg)
{
	overlay_dev_t *odd = arg;
	overlay_mux_t *mux;
	int ret, domain, family, prot;
	struct sockaddr_storage storage;
	socklen_t slen;

	mutex_enter(&odd->odd_lock);
	if ((odd->odd_flags & OVERLAY_F_ACTIVATED) == 0) {
		mutex_exit(&odd->odd_lock);
		return (EAGAIN);
	}
	mutex_exit(&odd->odd_lock);

	ret = odd->odd_plugin->ovp_ops->ovpo_socket(odd->odd_pvoid, &domain,
	    &family, &prot, (struct sockaddr *)&storage, &slen);
	if (ret != 0)
		return (ret);

	mux = overlay_mux_open(odd->odd_plugin, domain, family, prot,
	    (struct sockaddr *)&storage, slen, &ret);
	if (mux == NULL)
		return (ret);

	overlay_mux_add_dev(mux, odd);
	odd->odd_mux = mux;
	mutex_enter(&odd->odd_lock);
	ASSERT(!(odd->odd_flags & OVERLAY_F_IN_MUX));
	odd->odd_flags |= OVERLAY_F_IN_MUX;
	mutex_exit(&odd->odd_lock);

	return (0);
}

static void
overlay_m_stop(void *arg)
{
	overlay_dev_t *odd = arg;

	/*
	 * The MAC Perimeter is held here, so we don't have to worry about
	 * synchronizing this with respect to metadata operations.
	 */
	mutex_enter(&odd->odd_lock);
	VERIFY(odd->odd_flags & OVERLAY_F_IN_MUX);
	VERIFY(!(odd->odd_flags & OVERLAY_F_MDDROP));
	odd->odd_flags |= OVERLAY_F_MDDROP;
	overlay_io_wait(odd, OVERLAY_F_IOMASK);
	mutex_exit(&odd->odd_lock);

	overlay_mux_remove_dev(odd->odd_mux, odd);
	overlay_mux_close(odd->odd_mux);
	odd->odd_mux = NULL;

	mutex_enter(&odd->odd_lock);
	odd->odd_flags &= ~OVERLAY_F_IN_MUX;
	odd->odd_flags &= ~OVERLAY_F_MDDROP;
	VERIFY((odd->odd_flags & OVERLAY_F_STOPMASK) == 0);
	mutex_exit(&odd->odd_lock);
}

/*
 * For more info on this, see the big theory statement.
 */
/* ARGSUSED */
static int
overlay_m_promisc(void *arg, boolean_t on)
{
	return (0);
}

/*
 * For more info on this, see the big theory statement.
 */
/* ARGSUSED */
static int
overlay_m_multicast(void *arg, boolean_t add, const uint8_t *addrp)
{
	return (0);
}

/*
 * For more info on this, see the big theory statement.
 */
/* ARGSUSED */
static int
overlay_m_unicast(void *arg, const uint8_t *macaddr)
{
	return (0);
}

mblk_t *
overlay_m_tx(void *arg, mblk_t *mp_chain)
{
	overlay_dev_t *odd = arg;
	mblk_t *mp, *ep;
	int ret;
	ovep_encap_info_t einfo;
	struct msghdr hdr;

	mutex_enter(&odd->odd_lock);
	if ((odd->odd_flags & OVERLAY_F_MDDROP) ||
	    !(odd->odd_flags & OVERLAY_F_IN_MUX)) {
		mutex_exit(&odd->odd_lock);
		freemsgchain(mp_chain);
		return (NULL);
	}
	overlay_io_start(odd, OVERLAY_F_IN_TX);
	mutex_exit(&odd->odd_lock);

	bzero(&hdr, sizeof (struct msghdr));

	bzero(&einfo, sizeof (ovep_encap_info_t));
	einfo.ovdi_id = odd->odd_vid;
	mp = mp_chain;
	while (mp != NULL) {
		socklen_t slen;
		struct sockaddr_storage storage;

		mp_chain = mp->b_next;
		mp->b_next = NULL;
		ep = NULL;

		ret = overlay_target_lookup(odd, mp,
		    (struct sockaddr *)&storage, &slen);
		if (ret != OVERLAY_TARGET_OK) {
			if (ret == OVERLAY_TARGET_DROP)
				freemsg(mp);
			mp = mp_chain;
			continue;
		}

		hdr.msg_name = &storage;
		hdr.msg_namelen = slen;

		ret = odd->odd_plugin->ovp_ops->ovpo_encap(odd->odd_mh, mp,
		    &einfo, &ep);
		if (ret != 0 || ep == NULL) {
			freemsg(mp);
			goto out;
		}

		ASSERT(ep->b_cont == mp || ep == mp);
		ret = overlay_mux_tx(odd->odd_mux, &hdr, ep);
		if (ret != 0)
			goto out;

		mp = mp_chain;
	}

out:
	mutex_enter(&odd->odd_lock);
	overlay_io_done(odd, OVERLAY_F_IN_TX);
	mutex_exit(&odd->odd_lock);
	return (mp_chain);
}

/* ARGSUSED */
static void
overlay_m_ioctl(void *arg, queue_t *q, mblk_t *mp)
{
	miocnak(q, mp, 0, ENOTSUP);
}

/* ARGSUSED */
static boolean_t
overlay_m_getcapab(void *arg, mac_capab_t cap, void *cap_data)
{
	/*
	 * Tell MAC we're an overlay.
	 */
	if (cap == MAC_CAPAB_OVERLAY)
		return (B_TRUE);
	return (B_FALSE);
}

/* ARGSUSED */
static int
overlay_m_setprop(void *arg, const char *pr_name, mac_prop_id_t pr_num,
    uint_t pr_valsize, const void *pr_val)
{
	uint32_t mtu, old;
	int err;
	overlay_dev_t *odd = arg;

	if (pr_num != MAC_PROP_MTU)
		return (ENOTSUP);

	bcopy(pr_val, &mtu, sizeof (mtu));
	if (mtu < OVERLAY_MTU_MIN || mtu > OVERLAY_MTU_MAX)
		return (EINVAL);

	mutex_enter(&odd->odd_lock);
	old = odd->odd_mtu;
	odd->odd_mtu = mtu;
	err = mac_maxsdu_update(odd->odd_mh, mtu);
	if (err != 0)
		odd->odd_mtu = old;
	mutex_exit(&odd->odd_lock);

	return (err);
}

/* ARGSUSED */
static int
overlay_m_getprop(void *arg, const char *pr_name, mac_prop_id_t pr_num,
    uint_t pr_valsize, void *pr_val)
{
	return (ENOTSUP);
}

/* ARGSUSED */
static void
overlay_m_propinfo(void *arg, const char *pr_name, mac_prop_id_t pr_num,
    mac_prop_info_handle_t prh)
{
	if (pr_num != MAC_PROP_MTU)
		return;

	mac_prop_info_set_default_uint32(prh, OVERLAY_MTU_DEF);
	mac_prop_info_set_range_uint32(prh, OVERLAY_MTU_MIN, OVERLAY_MTU_MAX);
}

static mac_callbacks_t overlay_m_callbacks = {
	.mc_callbacks = (MC_IOCTL | MC_GETCAPAB | MC_SETPROP | MC_GETPROP |
	    MC_PROPINFO),
	.mc_getstat = overlay_m_stat,
	.mc_start = overlay_m_start,
	.mc_stop = overlay_m_stop,
	.mc_setpromisc = overlay_m_promisc,
	.mc_multicst = overlay_m_multicast,
	.mc_unicst = overlay_m_unicast,
	.mc_tx = overlay_m_tx,
	.mc_ioctl = overlay_m_ioctl,
	.mc_getcapab = overlay_m_getcapab,
	.mc_getprop = overlay_m_getprop,
	.mc_setprop = overlay_m_setprop,
	.mc_propinfo = overlay_m_propinfo
};

static boolean_t
overlay_valid_name(const char *name, size_t buflen)
{
	size_t actlen;
	int err, i;

	for (i = 0; i < buflen; i++) {
		if (name[i] == '\0')
			break;
	}

	if (i == 0 || i == buflen)
		return (B_FALSE);
	actlen = i;
	if (strchr(name, '/') != NULL)
		return (B_FALSE);
	if (u8_validate((char *)name, actlen, NULL,
	    U8_VALIDATE_ENTIRE, &err) < 0)
		return (B_FALSE);
	return (B_TRUE);
}

/* ARGSUSED */
static int
overlay_i_create(void *karg, intptr_t arg, int mode, cred_t *cred, int *rvalp)
{
	int err;
	uint64_t maxid;
	overlay_dev_t *odd, *o;
	mac_register_t *mac;
	overlay_ioc_create_t *oicp = karg;

	if (overlay_valid_name(oicp->oic_encap, MAXLINKNAMELEN) == B_FALSE)
		return (EINVAL);

	odd = kmem_zalloc(sizeof (overlay_dev_t), KM_SLEEP);
	odd->odd_linkid = oicp->oic_linkid;
	odd->odd_plugin = overlay_plugin_lookup(oicp->oic_encap);
	if (odd->odd_plugin == NULL) {
		kmem_free(odd, sizeof (overlay_dev_t));
		return (ENOENT);
	}
	err = odd->odd_plugin->ovp_ops->ovpo_init((overlay_handle_t)odd,
	    &odd->odd_pvoid);
	if (err != 0) {
		odd->odd_plugin->ovp_ops->ovpo_fini(odd->odd_pvoid);
		overlay_plugin_rele(odd->odd_plugin);
		kmem_free(odd, sizeof (overlay_dev_t));
		return (EINVAL);
	}

	/*
	 * Make sure that our virtual network id is valid for the given plugin
	 * that we're working with.
	 */
	ASSERT(odd->odd_plugin->ovp_id_size <= 8);
	maxid = UINT64_MAX;
	if (odd->odd_plugin->ovp_id_size != 8)
		maxid = (1ULL << (odd->odd_plugin->ovp_id_size * 8)) - 1ULL;
	if (oicp->oic_vnetid > maxid) {
		odd->odd_plugin->ovp_ops->ovpo_fini(odd->odd_pvoid);
		overlay_plugin_rele(odd->odd_plugin);
		kmem_free(odd, sizeof (overlay_dev_t));
		return (EINVAL);
	}
	odd->odd_vid = oicp->oic_vnetid;

	mac = mac_alloc(MAC_VERSION);
	if (mac == NULL) {
		mutex_exit(&overlay_dev_lock);
		odd->odd_plugin->ovp_ops->ovpo_fini(odd->odd_pvoid);
		overlay_plugin_rele(odd->odd_plugin);
		kmem_free(odd, sizeof (overlay_dev_t));
		return (EINVAL);
	}

	mac->m_type_ident = MAC_PLUGIN_IDENT_ETHER;
	mac->m_driver = odd;
	mac->m_dip = overlay_dip;
	mac->m_dst_addr = NULL;
	mac->m_callbacks = &overlay_m_callbacks;
	mac->m_pdata = NULL;
	mac->m_pdata_size = 0;

	mac->m_priv_props = NULL;

	/* Let mac handle this itself. */
	mac->m_instance = (uint_t)-1;

	/*
	 * There is no real source address that should be used here, but saying
	 * that we're not ethernet is going to cause its own problems. At the
	 * end of the say, this is fine.
	 */
	mac->m_src_addr = overlay_macaddr;

	/*
	 * Start with the default MTU as the max SDU. If the MTU is changed, the
	 * SDU will be changed to reflect that.
	 */
	mac->m_min_sdu = 1;
	mac->m_max_sdu = OVERLAY_MTU_DEF;
	mac->m_multicast_sdu = 0;

	/*
	 * The underlying device doesn't matter, instead this comes from the
	 * encapsulation protocol and whether or not they allow VLAN tags.
	 */
	if (odd->odd_plugin->ovp_flags & OVEP_F_VLAN_TAG) {
		mac->m_margin = VLAN_TAGSZ;
	} else {
		mac->m_margin = 0;
	}

	/*
	 * Today, we have no MAC virtualization, it may make sense in the future
	 * to go ahead and emulate some subset of this, but it doesn't today.
	 */
	mac->m_v12n = MAC_VIRT_NONE;

	mutex_enter(&overlay_dev_lock);
	for (o = list_head(&overlay_dev_list); o != NULL;
	    o = list_next(&overlay_dev_list, o)) {
		if (o->odd_linkid == oicp->oic_linkid) {
			mutex_exit(&overlay_dev_lock);
			odd->odd_plugin->ovp_ops->ovpo_fini(odd->odd_pvoid);
			overlay_plugin_rele(odd->odd_plugin);
			kmem_free(odd, sizeof (overlay_dev_t));
			return (EEXIST);
		}

		if (o->odd_vid == oicp->oic_vnetid &&
		    o->odd_plugin == odd->odd_plugin) {
			mutex_exit(&overlay_dev_lock);
			odd->odd_plugin->ovp_ops->ovpo_fini(odd->odd_pvoid);
			overlay_plugin_rele(odd->odd_plugin);
			kmem_free(odd, sizeof (overlay_dev_t));
			return (EEXIST);
		}
	}

	err = mac_register(mac, &odd->odd_mh);
	mac_free(mac);
	if (err != 0) {
		mutex_exit(&overlay_dev_lock);
		odd->odd_plugin->ovp_ops->ovpo_fini(odd->odd_pvoid);
		overlay_plugin_rele(odd->odd_plugin);
		kmem_free(odd, sizeof (overlay_dev_t));
		return (err);
	}

	err = dls_devnet_create(odd->odd_mh, odd->odd_linkid,
	    crgetzoneid(cred));
	if (err != 0) {
		mutex_exit(&overlay_dev_lock);
		(void) mac_unregister(odd->odd_mh);
		odd->odd_plugin->ovp_ops->ovpo_fini(odd->odd_pvoid);
		overlay_plugin_rele(odd->odd_plugin);
		kmem_free(odd, sizeof (overlay_dev_t));
		return (err);
	}

	mutex_init(&odd->odd_lock, NULL, MUTEX_DRIVER, NULL);
	cv_init(&odd->odd_iowait, NULL, CV_DRIVER, NULL);
	odd->odd_ref = 0;
	odd->odd_flags = 0;
	list_insert_tail(&overlay_dev_list, odd);
	mutex_exit(&overlay_dev_lock);

	return (0);
}

/* ARGSUSED */
static int
overlay_i_activate(void *karg, intptr_t arg, int mode, cred_t *cred, int *rvalp)
{
	int i, ret;
	overlay_dev_t *odd;
	mac_perim_handle_t mph;
	overlay_ioc_activate_t *oiap = karg;
	overlay_ioc_propinfo_t *infop;
	overlay_ioc_prop_t *oip;
	overlay_prop_handle_t phdl;

	odd = overlay_hold_by_dlid(oiap->oia_linkid);
	if (odd == NULL)
		return (ENOENT);

	infop = kmem_alloc(sizeof (overlay_ioc_propinfo_t), KM_SLEEP);
	oip = kmem_alloc(sizeof (overlay_ioc_prop_t), KM_SLEEP);
	phdl = (overlay_prop_handle_t)infop;

	mac_perim_enter_by_mh(odd->odd_mh, &mph);
	mutex_enter(&odd->odd_lock);
	if (odd->odd_flags & OVERLAY_F_ACTIVATED) {
		mutex_exit(&odd->odd_lock);
		mac_perim_exit(mph);
		overlay_hold_rele(odd);
		kmem_free(infop, sizeof (overlay_ioc_propinfo_t));
		kmem_free(oip, sizeof (overlay_ioc_prop_t));
		return (EEXIST);
	}
	mutex_exit(&odd->odd_lock);

	for (i = 0; i < odd->odd_plugin->ovp_nprops; i++) {
		const char *pname = odd->odd_plugin->ovp_props[i];
		bzero(infop, sizeof (overlay_ioc_propinfo_t));
		overlay_prop_init(phdl);
		ret = odd->odd_plugin->ovp_ops->ovpo_propinfo(pname, phdl);
		if (ret != 0) {
			mac_perim_exit(mph);
			overlay_hold_rele(odd);
			kmem_free(infop, sizeof (overlay_ioc_propinfo_t));
			kmem_free(oip, sizeof (overlay_ioc_prop_t));
			return (ret);
		}

		if ((infop->oipi_prot & OVERLAY_PROP_PERM_REQ) == 0)
			continue;
		bzero(oip, sizeof (overlay_ioc_prop_t));
		oip->oip_size = sizeof (oip->oip_value);
		ret = odd->odd_plugin->ovp_ops->ovpo_getprop(odd->odd_pvoid,
		    pname, oip->oip_value, &oip->oip_size);
		if (ret != 0) {
			mac_perim_exit(mph);
			overlay_hold_rele(odd);
			kmem_free(infop, sizeof (overlay_ioc_propinfo_t));
			kmem_free(oip, sizeof (overlay_ioc_prop_t));
			return (ret);
		}
		if (oip->oip_size == 0) {
			mac_perim_exit(mph);
			overlay_hold_rele(odd);
			kmem_free(infop, sizeof (overlay_ioc_propinfo_t));
			kmem_free(oip, sizeof (overlay_ioc_prop_t));
			return (EINVAL);
		}
	}

	mutex_enter(&odd->odd_lock);
	if ((odd->odd_flags & OVERLAY_F_VARPD) == 0) {
		mutex_exit(&odd->odd_lock);
		mac_perim_exit(mph);
		overlay_hold_rele(odd);
		kmem_free(infop, sizeof (overlay_ioc_propinfo_t));
		kmem_free(oip, sizeof (overlay_ioc_prop_t));
		return (ENXIO);
	}

	ASSERT((odd->odd_flags & OVERLAY_F_ACTIVATED) == 0);
	odd->odd_flags |= OVERLAY_F_ACTIVATED;

	/*
	 * Now that we've activated ourselves, we should indicate to the world
	 * that we're up. Note that we may not be able to perform lookups at
	 * this time, but our notion of being 'up' isn't dependent on that
	 * ability.
	 */
	mac_link_update(odd->odd_mh, LINK_STATE_UP);
	mutex_exit(&odd->odd_lock);

	mac_perim_exit(mph);
	overlay_hold_rele(odd);
	kmem_free(infop, sizeof (overlay_ioc_propinfo_t));
	kmem_free(oip, sizeof (overlay_ioc_prop_t));

	return (0);
}

/* ARGSUSED */
static int
overlay_i_delete(void *karg, intptr_t arg, int mode, cred_t *cred, int *rvalp)
{
	overlay_ioc_delete_t *oidp = karg;
	overlay_dev_t *odd;
	datalink_id_t tid;
	int ret;

	odd = overlay_hold_by_dlid(oidp->oid_linkid);
	if (odd == NULL) {
		return (ENOENT);
	}

	mutex_enter(&odd->odd_lock);
	/* If we're not the only hold, we're busy */
	if (odd->odd_ref != 1) {
		mutex_exit(&odd->odd_lock);
		overlay_hold_rele(odd);
		return (EBUSY);
	}

	if (odd->odd_flags & OVERLAY_F_IN_MUX) {
		mutex_exit(&odd->odd_lock);
		overlay_hold_rele(odd);
		return (EBUSY);
	}

	/*
	 * To remove this, we need to first remove it from dls and then remove
	 * it from mac. The act of removing it from mac will check if there are
	 * devices on top of this, eg. vnics. If there are, then that will fail
	 * and we'll have to go through and recreate the dls entry. Only after
	 * mac_unregister has succeeded, then we'll go through and actually free
	 * everything and drop the dev lock.
	 */
	ret = dls_devnet_destroy(odd->odd_mh, &tid, B_TRUE);
	if (ret != 0) {
		overlay_hold_rele(odd);
		return (ret);
	}

	ASSERT(oidp->oid_linkid == tid);
	ret = mac_disable(odd->odd_mh);
	if (ret != 0) {
		(void) dls_devnet_create(odd->odd_mh, odd->odd_linkid,
		    crgetzoneid(cred));
		overlay_hold_rele(odd);
		return (ret);
	}

	overlay_target_quiesce(odd->odd_target);

	mutex_enter(&overlay_dev_lock);
	list_remove(&overlay_dev_list, odd);
	mutex_exit(&overlay_dev_lock);

	cv_destroy(&odd->odd_iowait);
	mutex_destroy(&odd->odd_lock);
	overlay_target_free(odd);
	odd->odd_plugin->ovp_ops->ovpo_fini(odd->odd_pvoid);
	overlay_plugin_rele(odd->odd_plugin);
	kmem_free(odd, sizeof (overlay_dev_t));

	return (0);
}

/* ARGSUSED */
static int
overlay_i_nprops(void *karg, intptr_t arg, int mode, cred_t *cred,
    int *rvalp)
{
	overlay_dev_t *odd;
	overlay_ioc_nprops_t *on = karg;

	odd = overlay_hold_by_dlid(on->oipn_linkid);
	if (odd == NULL)
		return (ENOENT);
	on->oipn_nprops = odd->odd_plugin->ovp_nprops + OVERLAY_DEV_NPROPS;
	overlay_hold_rele(odd);

	return (0);
}

static int
overlay_propinfo_plugin_cb(overlay_plugin_t *opp, void *arg)
{
	overlay_prop_handle_t phdl = arg;
	overlay_prop_set_range_str(phdl, opp->ovp_name);
	return (0);
}

static int
overlay_i_name_to_propid(overlay_dev_t *odd, const char *name, uint_t *id)
{
	int i;

	for (i = 0; i < OVERLAY_DEV_NPROPS; i++) {
		if (strcmp(overlay_dev_props[i], name) == 0) {
			*id = i;
			return (0);
		}
	}

	for (i = 0; i < odd->odd_plugin->ovp_nprops; i++) {
		if (strcmp(odd->odd_plugin->ovp_props[i], name) == 0) {
			*id = i + OVERLAY_DEV_NPROPS;
			return (0);
		}
	}

	return (ENOENT);
}

static void
overlay_i_propinfo_mtu(overlay_dev_t *odd, overlay_prop_handle_t phdl)
{
	uint32_t def;
	mac_propval_range_t range;
	uint_t perm;

	ASSERT(MAC_PERIM_HELD(odd->odd_mh));

	bzero(&range, sizeof (mac_propval_range_t));
	range.mpr_count = 1;
	if (mac_prop_info(odd->odd_mh, MAC_PROP_MTU, "mtu", &def,
	    sizeof (def), &range, &perm) != 0)
		return;

	if (perm == MAC_PROP_PERM_READ)
		overlay_prop_set_prot(phdl, OVERLAY_PROP_PERM_READ);
	else if (perm == MAC_PROP_PERM_WRITE)
		overlay_prop_set_prot(phdl, OVERLAY_PROP_PERM_WRITE);
	else if (perm == MAC_PROP_PERM_RW)
		overlay_prop_set_prot(phdl, OVERLAY_PROP_PERM_RW);

	overlay_prop_set_type(phdl, OVERLAY_PROP_T_UINT);
	overlay_prop_set_default(phdl, &def, sizeof (def));
	overlay_prop_set_range_uint32(phdl, range.mpr_range_uint32[0].mpur_min,
	    range.mpr_range_uint32[0].mpur_max);
}

/* ARGSUSED */
static int
overlay_i_propinfo(void *karg, intptr_t arg, int mode, cred_t *cred,
    int *rvalp)
{
	overlay_dev_t *odd;
	int ret;
	mac_perim_handle_t mph;
	uint_t propid = UINT_MAX;
	overlay_ioc_propinfo_t *oip = karg;
	overlay_prop_handle_t phdl = (overlay_prop_handle_t)oip;

	odd = overlay_hold_by_dlid(oip->oipi_linkid);
	if (odd == NULL)
		return (ENOENT);

	overlay_prop_init(phdl);
	mac_perim_enter_by_mh(odd->odd_mh, &mph);

	/*
	 * If the id is -1, then the property that we're looking for is named in
	 * oipi_name and we should fill in its id. Otherwise, we've been given
	 * an id and we need to turn that into a name for our plugin's sake. The
	 * id is our own fabrication for property discovery.
	 */
	if (oip->oipi_id == -1) {
		/*
		 * Determine if it's a known generic property or it belongs to a
		 * module by checking against the list of known names.
		 */
		oip->oipi_name[OVERLAY_PROP_NAMELEN-1] = '\0';
		if ((ret = overlay_i_name_to_propid(odd, oip->oipi_name,
		    &propid)) != 0) {
			overlay_hold_rele(odd);
			mac_perim_exit(mph);
			return (ret);
		}
		oip->oipi_id = propid;
		if (propid >= OVERLAY_DEV_NPROPS) {
			ret = odd->odd_plugin->ovp_ops->ovpo_propinfo(
			    oip->oipi_name, phdl);
			overlay_hold_rele(odd);
			mac_perim_exit(mph);
			return (ret);

		}
	} else if (oip->oipi_id >= OVERLAY_DEV_NPROPS) {
		uint_t id = oip->oipi_id - OVERLAY_DEV_NPROPS;

		if (id >= odd->odd_plugin->ovp_nprops) {
			overlay_hold_rele(odd);
			mac_perim_exit(mph);
			return (EINVAL);
		}
		ret = odd->odd_plugin->ovp_ops->ovpo_propinfo(
		    odd->odd_plugin->ovp_props[id], phdl);
		overlay_hold_rele(odd);
		mac_perim_exit(mph);
		return (ret);
	} else if (oip->oipi_id < -1) {
		overlay_hold_rele(odd);
		mac_perim_exit(mph);
		return (EINVAL);
	} else {
		ASSERT(oip->oipi_id < OVERLAY_DEV_NPROPS);
		ASSERT(oip->oipi_id >= 0);
		propid = oip->oipi_id;
		(void) strlcpy(oip->oipi_name, overlay_dev_props[propid],
		    sizeof (oip->oipi_name));
	}

	switch (propid) {
	case OVERLAY_DEV_P_MTU:
		overlay_i_propinfo_mtu(odd, phdl);
		break;
	case OVERLAY_DEV_P_VNETID:
		overlay_prop_set_prot(phdl, OVERLAY_PROP_PERM_RW);
		overlay_prop_set_type(phdl, OVERLAY_PROP_T_UINT);
		overlay_prop_set_nodefault(phdl);
		break;
	case OVERLAY_DEV_P_ENCAP:
		overlay_prop_set_prot(phdl, OVERLAY_PROP_PERM_READ);
		overlay_prop_set_type(phdl, OVERLAY_PROP_T_STRING);
		overlay_prop_set_nodefault(phdl);
		overlay_plugin_walk(overlay_propinfo_plugin_cb, phdl);
		break;
	case OVERLAY_DEV_P_VARPDID:
		overlay_prop_set_prot(phdl, OVERLAY_PROP_PERM_READ);
		overlay_prop_set_type(phdl, OVERLAY_PROP_T_UINT);
		overlay_prop_set_nodefault(phdl);
		break;
	default:
		overlay_hold_rele(odd);
		mac_perim_exit(mph);
		return (ENOENT);
	}

	overlay_hold_rele(odd);
	mac_perim_exit(mph);
	return (0);
}

/* ARGSUSED */
static int
overlay_i_getprop(void *karg, intptr_t arg, int mode, cred_t *cred,
    int *rvalp)
{
	int ret;
	overlay_dev_t *odd;
	mac_perim_handle_t mph;
	overlay_ioc_prop_t *oip = karg;
	uint_t propid, mtu;

	odd = overlay_hold_by_dlid(oip->oip_linkid);
	if (odd == NULL)
		return (ENOENT);

	mac_perim_enter_by_mh(odd->odd_mh, &mph);
	oip->oip_size = OVERLAY_PROP_SIZEMAX;
	oip->oip_name[OVERLAY_PROP_NAMELEN-1] = '\0';
	if (oip->oip_id == -1) {
		int i;

		for (i = 0; i < OVERLAY_DEV_NPROPS; i++) {
			if (strcmp(overlay_dev_props[i], oip->oip_name) == 0)
				break;
			if (i == OVERLAY_DEV_NPROPS) {
				ret = odd->odd_plugin->ovp_ops->ovpo_getprop(
				    odd->odd_pvoid, oip->oip_name,
				    oip->oip_value, &oip->oip_size);
				overlay_hold_rele(odd);
				mac_perim_exit(mph);
				return (ret);
			}
		}

		propid = i;
	} else if (oip->oip_id >= OVERLAY_DEV_NPROPS) {
		uint_t id = oip->oip_id - OVERLAY_DEV_NPROPS;

		if (id > odd->odd_plugin->ovp_nprops) {
			overlay_hold_rele(odd);
			mac_perim_exit(mph);
			return (EINVAL);
		}
		ret = odd->odd_plugin->ovp_ops->ovpo_getprop(odd->odd_pvoid,
		    odd->odd_plugin->ovp_props[id], oip->oip_value,
		    &oip->oip_size);
		overlay_hold_rele(odd);
		mac_perim_exit(mph);
		return (ret);
	} else if (oip->oip_id < -1) {
		overlay_hold_rele(odd);
		mac_perim_exit(mph);
		return (EINVAL);
	} else {
		ASSERT(oip->oip_id < OVERLAY_DEV_NPROPS);
		ASSERT(oip->oip_id >= 0);
		propid = oip->oip_id;
	}

	ret = 0;
	switch (propid) {
	case OVERLAY_DEV_P_MTU:
		/*
		 * The MTU is always set and retrieved through MAC, to allow for
		 * MAC to do whatever it wants, as really that property belongs
		 * to MAC. This is important for things where vnics have hold on
		 * the MTU.
		 */
		mac_sdu_get(odd->odd_mh, NULL, &mtu);
		bcopy(&mtu, oip->oip_value, sizeof (uint_t));
		oip->oip_size = sizeof (uint_t);
		break;
	case OVERLAY_DEV_P_VNETID:
		/*
		 * While it's read-only while inside of a mux, we're not in a
		 * context that can guarantee that. Therefore we always grab the
		 * overlay_dev_t's odd_lock.
		 */
		mutex_enter(&odd->odd_lock);
		bcopy(&odd->odd_vid, oip->oip_value, sizeof (uint64_t));
		mutex_exit(&odd->odd_lock);
		oip->oip_size = sizeof (uint64_t);
		break;
	case OVERLAY_DEV_P_ENCAP:
		oip->oip_size = strlcpy((char *)oip->oip_value,
		    odd->odd_plugin->ovp_name, oip->oip_size);
		break;
	case OVERLAY_DEV_P_VARPDID:
		mutex_enter(&odd->odd_lock);
		if (odd->odd_flags & OVERLAY_F_VARPD) {
			const uint64_t val = odd->odd_target->ott_id;
			bcopy(&val, oip->oip_value, sizeof (uint64_t));
			oip->oip_size = sizeof (uint64_t);
		} else {
			oip->oip_size = 0;
		}
		mutex_exit(&odd->odd_lock);
		break;
	default:
		ret = ENOENT;
	}

	overlay_hold_rele(odd);
	mac_perim_exit(mph);
	return (ret);
}

static void
overlay_setprop_vnetid(overlay_dev_t *odd, uint64_t vnetid)
{
	mutex_enter(&odd->odd_lock);

	/* Simple case, not active */
	if (!(odd->odd_flags & OVERLAY_F_IN_MUX)) {
		odd->odd_vid = vnetid;
		mutex_exit(&odd->odd_lock);
		return;
	}

	/*
	 * In the hard case, we need to set the drop flag, quiesce I/O and then
	 * we can go ahead and do everything.
	 */
	odd->odd_flags |= OVERLAY_F_MDDROP;
	overlay_io_wait(odd, OVERLAY_F_IOMASK);
	mutex_exit(&odd->odd_lock);

	overlay_mux_remove_dev(odd->odd_mux, odd);

	mutex_enter(&odd->odd_lock);
	odd->odd_vid = vnetid;
	mutex_exit(&odd->odd_lock);

	overlay_mux_add_dev(odd->odd_mux, odd);

	mutex_enter(&odd->odd_lock);
	ASSERT(odd->odd_flags & OVERLAY_F_IN_MUX);
	odd->odd_flags &= ~OVERLAY_F_MDDROP;
	mutex_exit(&odd->odd_lock);
}

/* ARGSUSED */
static int
overlay_i_setprop(void *karg, intptr_t arg, int mode, cred_t *cred,
    int *rvalp)
{
	int ret;
	overlay_dev_t *odd;
	overlay_ioc_prop_t *oip = karg;
	uint_t propid = UINT_MAX;
	mac_perim_handle_t mph;
	uint64_t maxid, *vidp;

	if (oip->oip_size > OVERLAY_PROP_SIZEMAX)
		return (EINVAL);

	odd = overlay_hold_by_dlid(oip->oip_linkid);
	if (odd == NULL)
		return (ENOENT);

	oip->oip_name[OVERLAY_PROP_NAMELEN-1] = '\0';
	mac_perim_enter_by_mh(odd->odd_mh, &mph);
	mutex_enter(&odd->odd_lock);
	if (odd->odd_flags & OVERLAY_F_ACTIVATED) {
		mac_perim_exit(mph);
		mutex_exit(&odd->odd_lock);
		return (ENOTSUP);
	}
	mutex_exit(&odd->odd_lock);
	if (oip->oip_id == -1) {
		int i;

		for (i = 0; i < OVERLAY_DEV_NPROPS; i++) {
			if (strcmp(overlay_dev_props[i], oip->oip_name) == 0)
				break;
			if (i == OVERLAY_DEV_NPROPS) {
				ret = odd->odd_plugin->ovp_ops->ovpo_setprop(
				    odd->odd_pvoid, oip->oip_name,
				    oip->oip_value, oip->oip_size);
				overlay_hold_rele(odd);
				mac_perim_exit(mph);
				return (ret);
			}
		}

		propid = i;
	} else if (oip->oip_id >= OVERLAY_DEV_NPROPS) {
		uint_t id = oip->oip_id - OVERLAY_DEV_NPROPS;

		if (id > odd->odd_plugin->ovp_nprops) {
			mac_perim_exit(mph);
			overlay_hold_rele(odd);
			return (EINVAL);
		}
		ret = odd->odd_plugin->ovp_ops->ovpo_setprop(odd->odd_pvoid,
		    odd->odd_plugin->ovp_props[id], oip->oip_value,
		    oip->oip_size);
		mac_perim_exit(mph);
		overlay_hold_rele(odd);
		return (ret);
	} else if (oip->oip_id < -1) {
		mac_perim_exit(mph);
		overlay_hold_rele(odd);
		return (EINVAL);
	} else {
		ASSERT(oip->oip_id < OVERLAY_DEV_NPROPS);
		ASSERT(oip->oip_id >= 0);
		propid = oip->oip_id;
	}

	ret = 0;
	switch (propid) {
	case OVERLAY_DEV_P_MTU:
		ret = mac_set_prop(odd->odd_mh, MAC_PROP_MTU, "mtu",
		    oip->oip_value, oip->oip_size);
		break;
	case OVERLAY_DEV_P_VNETID:
		if (oip->oip_size != sizeof (uint64_t)) {
			ret = EINVAL;
			break;
		}
		vidp = (uint64_t *)oip->oip_value;
		ASSERT(odd->odd_plugin->ovp_id_size <= 8);
		maxid = UINT64_MAX;
		if (odd->odd_plugin->ovp_id_size != 8)
			maxid = (1ULL << (odd->odd_plugin->ovp_id_size * 8)) -
			    1ULL;
		if (*vidp >= maxid) {
			ret = EINVAL;
			break;
		}
		overlay_setprop_vnetid(odd, *vidp);
		break;
	case OVERLAY_DEV_P_ENCAP:
	case OVERLAY_DEV_P_VARPDID:
		ret = EPERM;
		break;
	default:
		ret = ENOENT;
	}

	mac_perim_exit(mph);
	overlay_hold_rele(odd);
	return (ret);
}

/* ARGSUSED */
static int
overlay_i_status(void *karg, intptr_t arg, int mode, cred_t *cred,
    int *rvalp)
{
	overlay_dev_t *odd;
	overlay_ioc_status_t *os = karg;

	odd = overlay_hold_by_dlid(os->ois_linkid);
	if (odd == NULL)
		return (ENOENT);

	mutex_enter(&odd->odd_lock);
	if ((odd->odd_flags & OVERLAY_F_DEGRADED) != 0) {
		os->ois_status = OVERLAY_I_DEGRADED;
		(void) strlcpy(os->ois_message, odd->odd_fmamsg,
		    OVERLAY_STATUS_BUFLEN);
	} else {
		os->ois_status = OVERLAY_I_OK;
		os->ois_message[0] = '\0';
	}
	mutex_exit(&odd->odd_lock);
	overlay_hold_rele(odd);

	return (0);
}

static dld_ioc_info_t overlay_ioc_list[] = {
	{ OVERLAY_IOC_CREATE, DLDCOPYIN, sizeof (overlay_ioc_create_t),
		overlay_i_create, secpolicy_dl_config },
	{ OVERLAY_IOC_ACTIVATE, DLDCOPYIN, sizeof (overlay_ioc_activate_t),
		overlay_i_activate, secpolicy_dl_config },
	{ OVERLAY_IOC_DELETE, DLDCOPYIN, sizeof (overlay_ioc_delete_t),
		overlay_i_delete, secpolicy_dl_config },
	{ OVERLAY_IOC_PROPINFO, DLDCOPYIN | DLDCOPYOUT,
		sizeof (overlay_ioc_propinfo_t), overlay_i_propinfo,
		secpolicy_dl_config },
	{ OVERLAY_IOC_GETPROP, DLDCOPYIN | DLDCOPYOUT,
		sizeof (overlay_ioc_prop_t), overlay_i_getprop,
		secpolicy_dl_config },
	{ OVERLAY_IOC_SETPROP, DLDCOPYIN,
		sizeof (overlay_ioc_prop_t), overlay_i_setprop,
		secpolicy_dl_config },
	{ OVERLAY_IOC_NPROPS, DLDCOPYIN | DLDCOPYOUT,
		sizeof (overlay_ioc_nprops_t), overlay_i_nprops,
		secpolicy_dl_config },
	{ OVERLAY_IOC_STATUS, DLDCOPYIN | DLDCOPYOUT,
		sizeof (overlay_ioc_status_t), overlay_i_status,
		NULL }
};

static int
overlay_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
{
	int fmcap = DDI_FM_EREPORT_CAPABLE;
	if (cmd != DDI_ATTACH)
		return (DDI_FAILURE);

	if (overlay_dip != NULL || ddi_get_instance(dip) != 0)
		return (DDI_FAILURE);

	ddi_fm_init(dip, &fmcap, NULL);

	if (ddi_create_minor_node(dip, OVERLAY_CTL, S_IFCHR,
	    ddi_get_instance(dip), DDI_PSEUDO, 0) == DDI_FAILURE)
		return (DDI_FAILURE);

	if (dld_ioc_register(OVERLAY_IOC, overlay_ioc_list,
	    DLDIOCCNT(overlay_ioc_list)) != 0) {
		ddi_remove_minor_node(dip, OVERLAY_CTL);
		return (DDI_FAILURE);
	}

	overlay_dip = dip;
	return (DDI_SUCCESS);
}

/* ARGSUSED */
static int
overlay_getinfo(dev_info_t *dip, ddi_info_cmd_t cmd, void *arg, void **resp)
{
	int error;

	switch (cmd) {
	case DDI_INFO_DEVT2DEVINFO:
		*resp = (void *)overlay_dip;
		error = DDI_SUCCESS;
		break;
	case DDI_INFO_DEVT2INSTANCE:
		*resp = (void *)0;
		error = DDI_SUCCESS;
		break;
	default:
		error = DDI_FAILURE;
		break;
	}

	return (error);
}

static int
overlay_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
{
	if (cmd != DDI_DETACH)
		return (DDI_FAILURE);

	mutex_enter(&overlay_dev_lock);
	if (!list_is_empty(&overlay_dev_list) || overlay_target_busy()) {
		mutex_exit(&overlay_dev_lock);
		return (EBUSY);
	}
	mutex_exit(&overlay_dev_lock);


	dld_ioc_unregister(OVERLAY_IOC);
	ddi_remove_minor_node(dip, OVERLAY_CTL);
	ddi_fm_fini(dip);
	overlay_dip = NULL;
	return (DDI_SUCCESS);
}

static struct cb_ops overlay_cbops = {
	overlay_target_open,	/* cb_open */
	overlay_target_close,	/* cb_close */
	nodev,			/* cb_strategy */
	nodev,			/* cb_print */
	nodev,			/* cb_dump */
	nodev,			/* cb_read */
	nodev,			/* cb_write */
	overlay_target_ioctl,	/* cb_ioctl */
	nodev,			/* cb_devmap */
	nodev,			/* cb_mmap */
	nodev,			/* cb_segmap */
	nochpoll,		/* cb_chpoll */
	ddi_prop_op,		/* cb_prop_op */
	NULL,			/* cb_stream */
	D_MP,			/* cb_flag */
	CB_REV,			/* cb_rev */
	nodev,			/* cb_aread */
	nodev,			/* cb_awrite */
};

static struct dev_ops overlay_dev_ops = {
	DEVO_REV,		/* devo_rev */
	0,			/* devo_refcnt */
	overlay_getinfo,	/* devo_getinfo */
	nulldev,		/* devo_identify */
	nulldev,		/* devo_probe */
	overlay_attach,		/* devo_attach */
	overlay_detach,		/* devo_detach */
	nulldev,		/* devo_reset */
	&overlay_cbops,		/* devo_cb_ops */
	NULL,			/* devo_bus_ops */
	NULL,			/* devo_power */
	ddi_quiesce_not_supported	/* devo_quiesce */
};

static struct modldrv overlay_modldrv = {
	&mod_driverops,
	"Overlay Network Driver",
	&overlay_dev_ops
};

static struct modlinkage overlay_linkage = {
	MODREV_1,
	&overlay_modldrv
};

static int
overlay_init(void)
{
	mutex_init(&overlay_dev_lock, NULL, MUTEX_DRIVER, NULL);
	list_create(&overlay_dev_list, sizeof (overlay_dev_t),
	    offsetof(overlay_dev_t, odd_link));
	overlay_mux_init();
	overlay_plugin_init();
	overlay_target_init();

	return (DDI_SUCCESS);
}

static void
overlay_fini(void)
{
	overlay_target_fini();
	overlay_plugin_fini();
	overlay_mux_fini();
	mutex_destroy(&overlay_dev_lock);
	list_destroy(&overlay_dev_list);
}

int
_init(void)
{
	int err;

	if ((err = overlay_init()) != DDI_SUCCESS)
		return (err);

	mac_init_ops(NULL, "overlay");
	err = mod_install(&overlay_linkage);
	if (err != DDI_SUCCESS) {
		overlay_fini();
		return (err);
	}

	return (0);
}

int
_info(struct modinfo *modinfop)
{
	return (mod_info(&overlay_linkage, modinfop));
}

int
_fini(void)
{
	int err;

	err = mod_remove(&overlay_linkage);
	if (err != 0)
		return (err);

	overlay_fini();
	return (0);
}
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright 2015, Joyent, Inc.
#

name="overlay" parent="pseudo" instance=0;
#
# This file and its contents are supplied under the terms of the
# Common Development and Distribution License ("CDDL"), version 1.0.
# You may only use this file in accordance with the terms of version
# 1.0 of the CDDL.
#
# A full copy of the text of the CDDL should have accompanied this
# source.  A copy of the CDDL is also available via the Internet at
# http://www.illumos.org/license/CDDL.
#

#
# Copyright 2015 Joyent, Inc.
#

#
# MAPFILE HEADER START
#
# WARNING:  STOP NOW.  DO NOT MODIFY THIS FILE.
# Object versioning must comply with the rules detailed in
#
#	usr/src/lib/README.mapfiles
#
# You should not be making modifications here until you've read the most current
# copy of that file. If you need help, contact a gatekeeper for guidance.
#
# MAPFILE HEADER END
#

$mapfile_version 2

SYMBOL_VERSION ILLUMOSprivate {
    global:
	# DDI Interfaces
	_fini;
	_init;
	_info;

	# Encapsualation Plugin interfaces
	overlay_plugin_alloc;
	overlay_plugin_free;
	overlay_plugin_register;
	overlay_plugin_unregister;
    local:
	*;
};
/*
 * This file and its contents are supplied under the terms of the
 * Common Development and Distribution License ("CDDL"), version 1.0.
 * You may only use this file in accordance with the terms of version
 * 1.0 of the CDDL.
 *
 * A full copy of the text of the CDDL should have accompanied this
 * source.  A copy of the CDDL is also available via the Internet at
 * http://www.illumos.org/license/CDDL.
 */

/*
 * Copyright 2016 Joyent, Inc.
 */

/*
 * Overlay device FMA operations.
 *
 * For more information, see the big theory statement in
 * uts/common/io/overlay/overlay.c
 */

#include <sys/ddifm.h>
#include <sys/overlay_impl.h>

kmutex_t overlay_fm_lock;
uint_t overlay_fm_count;

void
overlay_fm_init(void)
{
	overlay_fm_count = 0;
	mutex_init(&overlay_fm_lock, NULL, MUTEX_DRIVER, NULL);
}

void
overlay_fm_fini(void)
{
	VERIFY(overlay_fm_count == 0);
	mutex_destroy(&overlay_fm_lock);
}

void
overlay_fm_degrade(overlay_dev_t *odd, const char *msg)
{
	mutex_enter(&overlay_fm_lock);
	mutex_enter(&odd->odd_lock);

	if (msg != NULL)
		(void) strlcpy(odd->odd_fmamsg, msg, OVERLAY_STATUS_BUFLEN);

	if (odd->odd_flags & OVERLAY_F_DEGRADED)
		goto out;

	odd->odd_flags |= OVERLAY_F_DEGRADED;
	overlay_fm_count++;
	if (overlay_fm_count == 1) {
		ddi_fm_service_impact(overlay_dip, DDI_SERVICE_DEGRADED);
	}
out:
	mutex_exit(&odd->odd_lock);
	mutex_exit(&overlay_fm_lock);
}

void
overlay_fm_restore(overlay_dev_t *odd)
{
	mutex_enter(&overlay_fm_lock);
	mutex_enter(&odd->odd_lock);
	if (!(odd->odd_flags & OVERLAY_F_DEGRADED))
		goto out;

	odd->odd_fmamsg[0] = '\0';
	odd->odd_flags &= ~OVERLAY_F_DEGRADED;
	overlay_fm_count--;
	if (overlay_fm_count == 0) {
		ddi_fm_service_impact(overlay_dip, DDI_SERVICE_RESTORED);
	}
out:
	mutex_exit(&odd->odd_lock);
	mutex_exit(&overlay_fm_lock);
}
/*
 * This file and its contents are supplied under the terms of the
 * Common Development and Distribution License ("CDDL"), version 1.0.
 * You may only use this file in accordance with the terms of version
 * 1.0 of the CDDL.
 *
 * A full copy of the text of the CDDL should have accompanied this
 * source.  A copy of the CDDL is also available via the Internet at
 * http://www.illumos.org/license/CDDL.
 */

/*
 * Copyright 2019 Joyent, Inc.
 */

/*
 * Overlay device ksocket multiplexer.
 *
 * For more information, see the big theory statement in
 * uts/common/io/overlay/overlay.c
 */

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ksynch.h>
#include <sys/ksocket.h>
#include <sys/avl.h>
#include <sys/list.h>
#include <sys/pattr.h>
#include <sys/sysmacros.h>
#include <sys/strsubr.h>
#include <sys/strsun.h>
#include <sys/tihdr.h>

#include <sys/overlay_impl.h>

#include <sys/sdt.h>

static list_t overlay_mux_list;
static kmutex_t overlay_mux_lock;

void
overlay_mux_init(void)
{
	list_create(&overlay_mux_list, sizeof (overlay_mux_t),
	    offsetof(overlay_mux_t, omux_lnode));
	mutex_init(&overlay_mux_lock, NULL, MUTEX_DRIVER, NULL);
}

void
overlay_mux_fini(void)
{
	mutex_destroy(&overlay_mux_lock);
	list_destroy(&overlay_mux_list);
}

static int
overlay_mux_comparator(const void *a, const void *b)
{
	const overlay_dev_t *odl, *odr;
	odl = a;
	odr = b;
	if (odl->odd_vid > odr->odd_vid)
		return (1);
	else if (odl->odd_vid < odr->odd_vid)
		return (-1);
	else
		return (0);
}

/*
 * This is the central receive data path. We need to decode the packet, if we
 * can, and then deliver it to the appropriate overlay.
 */
/* ARGSUSED */
static boolean_t
overlay_mux_recv(ksocket_t ks, mblk_t *mpchain, size_t msgsize, int oob,
    void *arg)
{
	mblk_t *mp, *nmp, *fmp;
	overlay_mux_t *mux = arg;

	/*
	 * We may have a received a chain of messages. Each message in the
	 * chain will likely have a T_unitdata_ind attached to it as an M_PROTO.
	 * If we aren't getting that, we should probably drop that for the
	 * moment.
	 */
	for (mp = mpchain; mp != NULL; mp = nmp) {
		struct T_unitdata_ind *tudi;
		ovep_encap_info_t infop;
		overlay_dev_t od, *odd;
		int ret;

		nmp = mp->b_next;
		mp->b_next = NULL;

		if (DB_TYPE(mp) != M_PROTO) {
			OVERLAY_FREEMSG(mp, "first one isn't M_PROTO");
			freemsg(mp);
			continue;
		}

		if (mp->b_cont == NULL) {
			OVERLAY_FREEMSG(mp, "missing a b_cont");
			freemsg(mp);
			continue;
		}

		tudi = (struct T_unitdata_ind *)mp->b_rptr;
		if (tudi->PRIM_type != T_UNITDATA_IND) {
			OVERLAY_FREEMSG(mp, "Not a T_unitdata_ind *");
			freemsg(mp);
			continue;
		}

		/*
		 * In the future, we'll care about the source information
		 * for purposes of telling varpd for oob invalidation. But for
		 * now, just drop that block.
		 */
		fmp = mp;
		mp = fmp->b_cont;
		freeb(fmp);

		/*
		 * Until we have VXLAN-or-other-decap HW acceleration support
		 * (e.g.  we support NICs that reach into VXLAN-encapsulated
		 * packets and check the inside-VXLAN IP packets' checksums,
		 * or do LSO with VXLAN), we should clear any HW-accelerated-
		 * performed bits.
		 */
		DB_CKSUMFLAGS(mp) = 0;

		/*
		 * Decap and deliver.
		 */
		bzero(&infop, sizeof (ovep_encap_info_t));
		ret = mux->omux_plugin->ovp_ops->ovpo_decap(NULL, mp, &infop);
		if (ret != 0) {
			OVERLAY_FREEMSG(mp, "decap failed");
			freemsg(mp);
			continue;
		}
		if (MBLKL(mp) > infop.ovdi_hdr_size) {
			mp->b_rptr += infop.ovdi_hdr_size;
		} else {
			while (infop.ovdi_hdr_size != 0) {
				size_t rem, blkl;

				if (mp == NULL)
					break;

				blkl = MBLKL(mp);
				rem = MIN(infop.ovdi_hdr_size, blkl);
				infop.ovdi_hdr_size -= rem;
				mp->b_rptr += rem;
				if (rem == blkl) {
					fmp = mp;
					mp = fmp->b_cont;
					fmp->b_cont = NULL;
					OVERLAY_FREEMSG(mp,
					    "freed a fmp block");
					freemsg(fmp);
				}
			}
			if (mp == NULL) {
				OVERLAY_FREEMSG(mp, "freed it all...");
				continue;
			}
		}


		od.odd_vid = infop.ovdi_id;
		mutex_enter(&mux->omux_lock);
		odd = avl_find(&mux->omux_devices, &od, NULL);
		if (odd == NULL) {
			mutex_exit(&mux->omux_lock);
			OVERLAY_FREEMSG(mp, "no matching vid");
			freemsg(mp);
			continue;
		}
		mutex_enter(&odd->odd_lock);
		if ((odd->odd_flags & OVERLAY_F_MDDROP) ||
		    !(odd->odd_flags & OVERLAY_F_IN_MUX)) {
			mutex_exit(&odd->odd_lock);
			mutex_exit(&mux->omux_lock);
			OVERLAY_FREEMSG(mp, "dev dropped");
			freemsg(mp);
			continue;
		}
		overlay_io_start(odd, OVERLAY_F_IN_RX);
		mutex_exit(&odd->odd_lock);
		mutex_exit(&mux->omux_lock);

		mac_rx(odd->odd_mh, NULL, mp);

		mutex_enter(&odd->odd_lock);
		overlay_io_done(odd, OVERLAY_F_IN_RX);
		mutex_exit(&odd->odd_lock);
	}

	return (B_TRUE);
}

/*
 * Register a given device with a socket backend. If no such device socket
 * exists, create a new one.
 */
overlay_mux_t *
overlay_mux_open(overlay_plugin_t *opp, int domain, int family, int protocol,
    struct sockaddr *addr, socklen_t len, int *errp)
{
	int err;
	overlay_mux_t *mux;
	ksocket_t ksock;

	if (errp == NULL)
		errp = &err;

	mutex_enter(&overlay_mux_lock);
	for (mux = list_head(&overlay_mux_list); mux != NULL;
	    mux = list_next(&overlay_mux_list, mux)) {
		if (domain == mux->omux_domain &&
		    family == mux->omux_family &&
		    protocol == mux->omux_protocol &&
		    len == mux->omux_alen &&
		    bcmp(addr, mux->omux_addr, len) == 0) {

			if (opp != mux->omux_plugin) {
				*errp = EEXIST;
				return (NULL);
			}

			mutex_enter(&mux->omux_lock);
			mux->omux_count++;
			mutex_exit(&mux->omux_lock);
			mutex_exit(&overlay_mux_lock);
			*errp = 0;
			return (mux);
		}
	}

	/*
	 * Today we aren't zone-aware and only exist in the global zone. When we
	 * allow for things to exist in the non-global zone, we'll want to use a
	 * credential that's actually specific to the zone.
	 */
	*errp = ksocket_socket(&ksock, domain, family, protocol, KSOCKET_SLEEP,
	    kcred);
	if (*errp != 0) {
		mutex_exit(&overlay_mux_lock);
		return (NULL);
	}

	*errp = ksocket_bind(ksock, addr, len, kcred);
	if (*errp != 0) {
		mutex_exit(&overlay_mux_lock);
		ksocket_close(ksock, kcred);
		return (NULL);
	}

	/*
	 * Ask our lower layer to optionally toggle anything they need on this
	 * socket. Because a socket is owned by a single type of plugin, we can
	 * then ask it to perform any additional socket set up it'd like to do.
	 */
	if (opp->ovp_ops->ovpo_sockopt != NULL &&
	    (*errp = opp->ovp_ops->ovpo_sockopt(ksock)) != 0) {
		mutex_exit(&overlay_mux_lock);
		ksocket_close(ksock, kcred);
		return (NULL);
	}

	mux = kmem_alloc(sizeof (overlay_mux_t), KM_SLEEP);
	list_link_init(&mux->omux_lnode);
	mux->omux_ksock = ksock;
	mux->omux_plugin = opp;
	mux->omux_domain = domain;
	mux->omux_family = family;
	mux->omux_protocol = protocol;
	mux->omux_addr = kmem_alloc(len, KM_SLEEP);
	bcopy(addr, mux->omux_addr, len);
	mux->omux_alen = len;
	mux->omux_count = 1;
	avl_create(&mux->omux_devices, overlay_mux_comparator,
	    sizeof (overlay_dev_t), offsetof(overlay_dev_t, odd_muxnode));
	mutex_init(&mux->omux_lock, NULL, MUTEX_DRIVER, NULL);


	/* Once this is called, we need to expect to rx data */
	*errp = ksocket_krecv_set(ksock, overlay_mux_recv, mux);
	if (*errp != 0) {
		ksocket_close(ksock, kcred);
		mutex_destroy(&mux->omux_lock);
		avl_destroy(&mux->omux_devices);
		kmem_free(mux->omux_addr, len);
		kmem_free(mux, sizeof (overlay_mux_t));
		return (NULL);
	}

	list_insert_tail(&overlay_mux_list, mux);
	mutex_exit(&overlay_mux_lock);

	*errp = 0;
	return (mux);
}

void
overlay_mux_close(overlay_mux_t *mux)
{
	mutex_enter(&overlay_mux_lock);
	mutex_enter(&mux->omux_lock);
	mux->omux_count--;
	if (mux->omux_count != 0) {
		mutex_exit(&mux->omux_lock);
		mutex_exit(&overlay_mux_lock);
		return;
	}
	list_remove(&overlay_mux_list, mux);
	mutex_exit(&mux->omux_lock);
	mutex_exit(&overlay_mux_lock);

	ksocket_close(mux->omux_ksock, kcred);
	avl_destroy(&mux->omux_devices);
	kmem_free(mux->omux_addr, mux->omux_alen);
	kmem_free(mux, sizeof (overlay_mux_t));
}

void
overlay_mux_add_dev(overlay_mux_t *mux, overlay_dev_t *odd)
{
	mutex_enter(&mux->omux_lock);
	avl_add(&mux->omux_devices, odd);
	mutex_exit(&mux->omux_lock);
}

void
overlay_mux_remove_dev(overlay_mux_t *mux, overlay_dev_t *odd)
{
	mutex_enter(&mux->omux_lock);
	avl_remove(&mux->omux_devices, odd);
	mutex_exit(&mux->omux_lock);
}

int
overlay_mux_tx(overlay_mux_t *mux, struct msghdr *hdr, mblk_t *mp)
{
	int ret;

	/*
	 * It'd be nice to be able to use MSG_MBLK_QUICKRELE, unfortunately,
	 * that isn't actually supported by UDP at this time.
	 */
	ret = ksocket_sendmblk(mux->omux_ksock, hdr, 0, &mp, kcred);
	if (ret != 0)
		freemsg(mp);

	return (ret);
}
/*
 * This file and its contents are supplied under the terms of the
 * Common Development and Distribution License ("CDDL"), version 1.0.
 * You may only use this file in accordance with the terms of version
 * 1.0 of the CDDL.
 *
 * A full copy of the text of the CDDL should have accompanied this
 * source.  A copy of the CDDL is also available via the Internet at
 * http://www.illumos.org/license/CDDL.
 */

/*
 * Copyright 2015 Joyent, Inc.
 */

/*
 * Overlay device encapsulation plugin management
 *
 * For more information, see the big theory statement in
 * uts/common/io/overlay/overlay.c
 */

#include <sys/types.h>
#include <sys/kmem.h>
#include <sys/ddi.h>
#include <sys/sunddi.h>
#include <sys/errno.h>
#include <sys/sysmacros.h>
#include <sys/modctl.h>

#include <sys/overlay_impl.h>

static kmem_cache_t *overlay_plugin_cache;
static kmutex_t overlay_plugin_lock;
static list_t overlay_plugin_list;

#define	OVERLAY_MODDIR	"overlay"

/* ARGSUSED */
static int
overlay_plugin_cache_constructor(void *buf, void *arg, int kmflags)
{
	overlay_plugin_t *opp = buf;

	mutex_init(&opp->ovp_mutex, NULL, MUTEX_DRIVER, NULL);
	list_link_init(&opp->ovp_link);

	return (0);
}

/* ARGSUSED */
static void
overlay_plugin_cache_destructor(void *buf, void *arg)
{
	overlay_plugin_t *opp = buf;
	ASSERT(list_link_active(&opp->ovp_link) == 0);
	mutex_destroy(&opp->ovp_mutex);
}

void
overlay_plugin_init(void)
{
	mutex_init(&overlay_plugin_lock, NULL, MUTEX_DRIVER, 0);

	/*
	 * In the future we may want to have a reaper to unload unused modules
	 * to help the kernel be able to reclaim memory.
	 */
	overlay_plugin_cache = kmem_cache_create("overlay_plugin_cache",
	    sizeof (overlay_plugin_t), 0, overlay_plugin_cache_constructor,
	    overlay_plugin_cache_destructor, NULL, NULL, NULL, 0);
	list_create(&overlay_plugin_list, sizeof (overlay_plugin_t),
	    offsetof(overlay_plugin_t, ovp_link));
}

void
overlay_plugin_fini(void)
{
	mutex_enter(&overlay_plugin_lock);
	VERIFY(list_is_empty(&overlay_plugin_list));
	mutex_exit(&overlay_plugin_lock);

	list_destroy(&overlay_plugin_list);
	kmem_cache_destroy(overlay_plugin_cache);
	mutex_destroy(&overlay_plugin_lock);
}

overlay_plugin_register_t *
overlay_plugin_alloc(uint_t version)
{
	overlay_plugin_register_t *ovrp;
	/* Version 1 is the only one that exists */
	if (version != OVEP_VERSION_ONE)
		return (NULL);

	ovrp = kmem_zalloc(sizeof (overlay_plugin_register_t), KM_SLEEP);
	ovrp->ovep_version = version;
	return (ovrp);
}

void
overlay_plugin_free(overlay_plugin_register_t *ovrp)
{
	kmem_free(ovrp, sizeof (overlay_plugin_register_t));
}

int
overlay_plugin_register(overlay_plugin_register_t *ovrp)
{
	overlay_plugin_t *opp, *ipp;

	/* Sanity check parameters of the registration */
	if (ovrp->ovep_version != OVEP_VERSION_ONE)
		return (EINVAL);

	if (ovrp->ovep_name == NULL || ovrp->ovep_ops == NULL)
		return (EINVAL);

	if ((ovrp->ovep_flags & ~(OVEP_F_VLAN_TAG)) != 0)
		return (EINVAL);

	if (ovrp->ovep_id_size < 1)
		return (EINVAL);

	/* Don't support anything that has an id size larger than 8 bytes */
	if (ovrp->ovep_id_size > 8)
		return (ENOTSUP);

	if (ovrp->ovep_dest == OVERLAY_PLUGIN_D_INVALID)
		return (EINVAL);

	if ((ovrp->ovep_dest & ~OVERLAY_PLUGIN_D_MASK) != 0)
		return (EINVAL);

	if (ovrp->ovep_ops->ovpo_callbacks != 0)
		return (EINVAL);
	if (ovrp->ovep_ops->ovpo_init == NULL)
		return (EINVAL);
	if (ovrp->ovep_ops->ovpo_fini == NULL)
		return (EINVAL);
	if (ovrp->ovep_ops->ovpo_encap == NULL)
		return (EINVAL);
	if (ovrp->ovep_ops->ovpo_decap == NULL)
		return (EINVAL);
	if (ovrp->ovep_ops->ovpo_socket == NULL)
		return (EINVAL);
	if (ovrp->ovep_ops->ovpo_getprop == NULL)
		return (EINVAL);
	if (ovrp->ovep_ops->ovpo_setprop == NULL)
		return (EINVAL);
	if (ovrp->ovep_ops->ovpo_propinfo == NULL)
		return (EINVAL);


	opp = kmem_cache_alloc(overlay_plugin_cache, KM_SLEEP);
	opp->ovp_active = 0;
	opp->ovp_name = ovrp->ovep_name;
	opp->ovp_ops = ovrp->ovep_ops;
	opp->ovp_props = ovrp->ovep_props;
	opp->ovp_id_size = ovrp->ovep_id_size;
	opp->ovp_flags = ovrp->ovep_flags;
	opp->ovp_dest = ovrp->ovep_dest;

	opp->ovp_nprops = 0;
	if (ovrp->ovep_props != NULL) {
		while (ovrp->ovep_props[opp->ovp_nprops] != NULL) {
			if (strlen(ovrp->ovep_props[opp->ovp_nprops]) >=
			    OVERLAY_PROP_NAMELEN) {
				mutex_exit(&overlay_plugin_lock);
				kmem_cache_free(overlay_plugin_cache, opp);
				return (EINVAL);
			}
			opp->ovp_nprops++;
		}
	}

	mutex_enter(&overlay_plugin_lock);
	for (ipp = list_head(&overlay_plugin_list); ipp != NULL;
	    ipp = list_next(&overlay_plugin_list, ipp)) {
		if (strcmp(ipp->ovp_name, opp->ovp_name) == 0) {
			mutex_exit(&overlay_plugin_lock);
			kmem_cache_free(overlay_plugin_cache, opp);
			return (EEXIST);
		}
	}
	list_insert_tail(&overlay_plugin_list, opp);
	mutex_exit(&overlay_plugin_lock);

	return (0);
}

int
overlay_plugin_unregister(const char *name)
{
	overlay_plugin_t *opp;

	mutex_enter(&overlay_plugin_lock);
	for (opp = list_head(&overlay_plugin_list); opp != NULL;
	    opp = list_next(&overlay_plugin_list, opp)) {
		if (strcmp(opp->ovp_name, name) == 0)
			break;
	}

	if (opp == NULL) {
		mutex_exit(&overlay_plugin_lock);
		return (ENOENT);
	}

	mutex_enter(&opp->ovp_mutex);
	if (opp->ovp_active > 0) {
		mutex_exit(&opp->ovp_mutex);
		mutex_exit(&overlay_plugin_lock);
		return (EBUSY);
	}
	mutex_exit(&opp->ovp_mutex);

	list_remove(&overlay_plugin_list, opp);
	mutex_exit(&overlay_plugin_lock);

	kmem_cache_free(overlay_plugin_cache, opp);
	return (0);
}

overlay_plugin_t *
overlay_plugin_lookup(const char *name)
{
	overlay_plugin_t *opp;
	boolean_t trymodload = B_FALSE;

	for (;;) {
		mutex_enter(&overlay_plugin_lock);
		for (opp = list_head(&overlay_plugin_list); opp != NULL;
		    opp = list_next(&overlay_plugin_list, opp)) {
			if (strcmp(name, opp->ovp_name) == 0) {
				mutex_enter(&opp->ovp_mutex);
				opp->ovp_active++;
				mutex_exit(&opp->ovp_mutex);
				mutex_exit(&overlay_plugin_lock);
				return (opp);
			}
		}
		mutex_exit(&overlay_plugin_lock);

		if (trymodload == B_TRUE)
			return (NULL);

		/*
		 * If we didn't find it, it may still exist, but just not have
		 * been a loaded module. In that case, we'll do one attempt to
		 * load it.
		 */
		if (modload(OVERLAY_MODDIR, (char *)name) == -1)
			return (NULL);
		trymodload = B_TRUE;
	}

}

void
overlay_plugin_rele(overlay_plugin_t *opp)
{
	mutex_enter(&opp->ovp_mutex);
	ASSERT(opp->ovp_active > 0);
	opp->ovp_active--;
	mutex_exit(&opp->ovp_mutex);
}

void
overlay_plugin_walk(overlay_plugin_walk_f func, void *arg)
{
	overlay_plugin_t *opp;
	mutex_enter(&overlay_plugin_lock);
	for (opp = list_head(&overlay_plugin_list); opp != NULL;
	    opp = list_next(&overlay_plugin_list, opp)) {
		if (func(opp, arg) != 0) {
			mutex_exit(&overlay_plugin_lock);
			return;
		}
	}
	mutex_exit(&overlay_plugin_lock);
}
/*
 * This file and its contents are supplied under the terms of the
 * Common Development and Distribution License ("CDDL"), version 1.0.
 * You may only use this file in accordance with the terms of version
 * 1.0 of the CDDL.
 *
 * A full copy of the text of the CDDL should have accompanied this
 * source.  A copy of the CDDL is also available via the Internet at
 * http://www.illumos.org/license/CDDL.
 */

/*
 * Copyright 2015, Joyent, Inc.
 */

/*
 * Routines for manipulating property information structures.
 *
 * For more information, see the big theory statement in
 * uts/common/io/overlay/overlay.c
 */

#include <sys/overlay_impl.h>

void
overlay_prop_init(overlay_prop_handle_t phdl)
{
	overlay_ioc_propinfo_t *infop = (overlay_ioc_propinfo_t *)phdl;
	mac_propval_range_t *rangep = (mac_propval_range_t *)infop->oipi_poss;

	infop->oipi_posssize = sizeof (mac_propval_range_t);
	bzero(rangep, sizeof (mac_propval_range_t));
}

void
overlay_prop_set_name(overlay_prop_handle_t phdl, const char *name)
{
	overlay_ioc_propinfo_t *infop = (overlay_ioc_propinfo_t *)phdl;
	(void) strlcpy(infop->oipi_name, name, OVERLAY_PROP_NAMELEN);
}

void
overlay_prop_set_prot(overlay_prop_handle_t phdl, overlay_prop_prot_t prot)
{
	overlay_ioc_propinfo_t *infop = (overlay_ioc_propinfo_t *)phdl;
	infop->oipi_prot = prot;
}

void
overlay_prop_set_type(overlay_prop_handle_t phdl, overlay_prop_type_t type)
{
	overlay_ioc_propinfo_t *infop = (overlay_ioc_propinfo_t *)phdl;
	infop->oipi_type = type;
}

int
overlay_prop_set_default(overlay_prop_handle_t phdl, void *def, ssize_t len)
{
	overlay_ioc_propinfo_t *infop = (overlay_ioc_propinfo_t *)phdl;

	if (len > OVERLAY_PROP_SIZEMAX)
		return (E2BIG);

	if (len < 0)
		return (EOVERFLOW);

	bcopy(def, infop->oipi_default, len);
	infop->oipi_defsize = (uint32_t)len;

	return (0);
}

void
overlay_prop_set_nodefault(overlay_prop_handle_t phdl)
{
	overlay_ioc_propinfo_t *infop = (overlay_ioc_propinfo_t *)phdl;
	infop->oipi_default[0] = '\0';
	infop->oipi_defsize = 0;
}

void
overlay_prop_set_range_uint32(overlay_prop_handle_t phdl, uint32_t min,
    uint32_t max)
{
	overlay_ioc_propinfo_t *infop = (overlay_ioc_propinfo_t *)phdl;
	mac_propval_range_t *rangep = (mac_propval_range_t *)infop->oipi_poss;

	if (rangep->mpr_count != 0 && rangep->mpr_type != MAC_PROPVAL_UINT32)
		return;

	if (infop->oipi_posssize + sizeof (mac_propval_uint32_range_t) >
	    sizeof (infop->oipi_poss))
		return;

	infop->oipi_posssize += sizeof (mac_propval_uint32_range_t);
	rangep->mpr_count++;
	rangep->mpr_type = MAC_PROPVAL_UINT32;
	rangep->u.mpr_uint32[rangep->mpr_count-1].mpur_min = min;
	rangep->u.mpr_uint32[rangep->mpr_count-1].mpur_max = max;
}

void
overlay_prop_set_range_str(overlay_prop_handle_t phdl, const char *str)
{
	size_t len = strlen(str) + 1; /* Account for a null terminator */
	overlay_ioc_propinfo_t *infop = (overlay_ioc_propinfo_t *)phdl;
	mac_propval_range_t *rangep = (mac_propval_range_t *)infop->oipi_poss;
	mac_propval_str_range_t *pstr = &rangep->u.mpr_str;

	if (rangep->mpr_count != 0 && rangep->mpr_type != MAC_PROPVAL_STR)
		return;

	if (infop->oipi_posssize + len > sizeof (infop->oipi_poss))
		return;

	rangep->mpr_count++;
	rangep->mpr_type = MAC_PROPVAL_STR;
	strlcpy((char *)&pstr->mpur_data[pstr->mpur_nextbyte], str,
	    sizeof (infop->oipi_poss) - infop->oipi_posssize);
	pstr->mpur_nextbyte += len;
	infop->oipi_posssize += len;
}
/*
 * This file and its contents are supplied under the terms of the
 * Common Development and Distribution License ("CDDL"), version 1.0.
 * You may only use this file in accordance with the terms of version
 * 1.0 of the CDDL.
 *
 * A full copy of the text of the CDDL should have accompanied this
 * source.  A copy of the CDDL is also available via the Internet at
 * http://www.illumos.org/license/CDDL.
 */

/*
 * Copyright 2016 Joyent, Inc.
 * Copyright 2022 MNX Cloud, Inc.
 */

/*
 * Overlay device target cache management
 *
 * For more information, see the big theory statement in
 * uts/common/io/overlay/overlay.c
 */

#include <sys/types.h>
#include <sys/ethernet.h>
#include <sys/kmem.h>
#include <sys/policy.h>
#include <sys/sysmacros.h>
#include <sys/stream.h>
#include <sys/strsun.h>
#include <sys/strsubr.h>
#include <sys/mac_provider.h>
#include <sys/mac_client.h>
#include <sys/mac_client_priv.h>
#include <sys/vlan.h>
#include <sys/crc32.h>
#include <sys/cred.h>
#include <sys/file.h>
#include <sys/errno.h>
#include <sys/ddi.h>
#include <sys/sunddi.h>

#include <sys/overlay_impl.h>
#include <sys/sdt.h>

/*
 * This is total straw man, but at least it's a prime number. Here we're
 * going to have to go through and do a lot of evaluation and understanding as
 * to how these target caches should grow and shrink, as well as, memory
 * pressure and evictions. This just gives us a starting point that'll be 'good
 * enough', until it's not.
 */
#define	OVERLAY_HSIZE	823

/*
 * We use this data structure to keep track of what requests have been actively
 * allocated to a given instance so we know what to put back on the pending
 * list.
 */
typedef struct overlay_target_hdl {
	minor_t oth_minor;		/* RO */
	zoneid_t oth_zoneid;		/* RO */
	int oth_oflags;			/* RO */
	list_node_t oth_link;		/* overlay_target_lock */
	kmutex_t oth_lock;
	list_t	oth_outstanding;	/* oth_lock */
} overlay_target_hdl_t;

typedef int (*overlay_target_copyin_f)(const void *, void **, size_t *, int);
typedef int (*overlay_target_ioctl_f)(overlay_target_hdl_t *, void *);
typedef int (*overlay_target_copyout_f)(void *, void *, size_t, int);

typedef struct overlay_target_ioctl {
	int		oti_cmd;	/* ioctl id */
	boolean_t	oti_write;	/* ioctl requires FWRITE */
	boolean_t	oti_ncopyout;	/* copyout data? */
	overlay_target_copyin_f oti_copyin;	/* copyin func */
	overlay_target_ioctl_f oti_func; /* function to call */
	overlay_target_copyout_f oti_copyout;	/* copyin func */
	size_t		oti_size;	/* size of user level structure */
} overlay_target_ioctl_t;

static kmem_cache_t *overlay_target_cache;
static kmem_cache_t *overlay_entry_cache;
static id_space_t *overlay_thdl_idspace;
static void *overlay_thdl_state;

/*
 * When we support overlay devices in the NGZ, then all of these need to become
 * zone aware, by plugging into the netstack engine and becoming per-netstack
 * data.
 */
static list_t overlay_thdl_list;
static kmutex_t overlay_target_lock;
static kcondvar_t overlay_target_condvar;
static list_t overlay_target_list;
static boolean_t overlay_target_excl;

/*
 * Outstanding data per hash table entry.
 */
static int overlay_ent_size = 128 * 1024;

/* ARGSUSED */
static int
overlay_target_cache_constructor(void *buf, void *arg, int kmflgs)
{
	overlay_target_t *ott = buf;

	mutex_init(&ott->ott_lock, NULL, MUTEX_DRIVER, NULL);
	cv_init(&ott->ott_cond, NULL, CV_DRIVER, NULL);
	return (0);
}

/* ARGSUSED */
static void
overlay_target_cache_destructor(void *buf, void *arg)
{
	overlay_target_t *ott = buf;

	cv_destroy(&ott->ott_cond);
	mutex_destroy(&ott->ott_lock);
}

/* ARGSUSED */
static int
overlay_entry_cache_constructor(void *buf, void *arg, int kmflgs)
{
	overlay_target_entry_t *ote = buf;

	bzero(ote, sizeof (overlay_target_entry_t));
	mutex_init(&ote->ote_lock, NULL, MUTEX_DRIVER, NULL);
	return (0);
}

/* ARGSUSED */
static void
overlay_entry_cache_destructor(void *buf, void *arg)
{
	overlay_target_entry_t *ote = buf;

	mutex_destroy(&ote->ote_lock);
}

static uint64_t
overlay_mac_hash(const void *v)
{
	uint32_t crc;
	CRC32(crc, v, ETHERADDRL, -1U, crc32_table);
	return (crc);
}

static int
overlay_mac_cmp(const void *a, const void *b)
{
	return (bcmp(a, b, ETHERADDRL));
}

/* ARGSUSED */
static void
overlay_target_entry_dtor(void *arg)
{
	overlay_target_entry_t *ote = arg;

	ote->ote_flags = 0;
	bzero(ote->ote_addr, ETHERADDRL);
	ote->ote_ott = NULL;
	ote->ote_odd = NULL;
	freemsgchain(ote->ote_chead);
	ote->ote_chead = ote->ote_ctail = NULL;
	ote->ote_mbsize = 0;
	ote->ote_vtime = 0;
	kmem_cache_free(overlay_entry_cache, ote);
}

static int
overlay_mac_avl(const void *a, const void *b)
{
	int i;
	const overlay_target_entry_t *l, *r;
	l = a;
	r = b;

	for (i = 0; i < ETHERADDRL; i++) {
		if (l->ote_addr[i] > r->ote_addr[i])
			return (1);
		else if (l->ote_addr[i] < r->ote_addr[i])
			return (-1);
	}

	return (0);
}

void
overlay_target_init(void)
{
	int ret;
	ret = ddi_soft_state_init(&overlay_thdl_state,
	    sizeof (overlay_target_hdl_t), 1);
	VERIFY(ret == 0);
	overlay_target_cache = kmem_cache_create("overlay_target",
	    sizeof (overlay_target_t), 0, overlay_target_cache_constructor,
	    overlay_target_cache_destructor, NULL, NULL, NULL, 0);
	overlay_entry_cache = kmem_cache_create("overlay_entry",
	    sizeof (overlay_target_entry_t), 0, overlay_entry_cache_constructor,
	    overlay_entry_cache_destructor, NULL, NULL, NULL, 0);
	mutex_init(&overlay_target_lock, NULL, MUTEX_DRIVER, NULL);
	cv_init(&overlay_target_condvar, NULL, CV_DRIVER, NULL);
	list_create(&overlay_target_list, sizeof (overlay_target_entry_t),
	    offsetof(overlay_target_entry_t, ote_qlink));
	list_create(&overlay_thdl_list, sizeof (overlay_target_hdl_t),
	    offsetof(overlay_target_hdl_t, oth_link));
	overlay_thdl_idspace = id_space_create("overlay_target_minors",
	    1, INT32_MAX);
}

void
overlay_target_fini(void)
{
	id_space_destroy(overlay_thdl_idspace);
	list_destroy(&overlay_thdl_list);
	list_destroy(&overlay_target_list);
	cv_destroy(&overlay_target_condvar);
	mutex_destroy(&overlay_target_lock);
	kmem_cache_destroy(overlay_entry_cache);
	kmem_cache_destroy(overlay_target_cache);
	ddi_soft_state_fini(&overlay_thdl_state);
}

void
overlay_target_free(overlay_dev_t *odd)
{
	if (odd->odd_target == NULL)
		return;

	if (odd->odd_target->ott_mode == OVERLAY_TARGET_DYNAMIC) {
		refhash_t *rp = odd->odd_target->ott_u.ott_dyn.ott_dhash;
		avl_tree_t *ap = &odd->odd_target->ott_u.ott_dyn.ott_tree;
		overlay_target_entry_t *ote;

		/*
		 * Our AVL tree and hashtable contain the same elements,
		 * therefore we should just remove it from the tree, but then
		 * delete the entries when we remove them from the hash table
		 * (which happens through the refhash dtor).
		 */
		while ((ote = avl_first(ap)) != NULL)
			avl_remove(ap, ote);

		avl_destroy(ap);
		for (ote = refhash_first(rp); ote != NULL;
		    ote = refhash_next(rp, ote)) {
			refhash_remove(rp, ote);
		}
		refhash_destroy(rp);
	}

	ASSERT(odd->odd_target->ott_ocount == 0);
	kmem_cache_free(overlay_target_cache, odd->odd_target);
}

int
overlay_target_busy()
{
	int ret;

	mutex_enter(&overlay_target_lock);
	ret = !list_is_empty(&overlay_thdl_list);
	mutex_exit(&overlay_target_lock);

	return (ret);
}

static void
overlay_target_queue(overlay_target_entry_t *entry)
{
	mutex_enter(&overlay_target_lock);
	mutex_enter(&entry->ote_ott->ott_lock);
	if (entry->ote_ott->ott_flags & OVERLAY_T_TEARDOWN) {
		mutex_exit(&entry->ote_ott->ott_lock);
		mutex_exit(&overlay_target_lock);
		return;
	}
	entry->ote_ott->ott_ocount++;
	mutex_exit(&entry->ote_ott->ott_lock);
	list_insert_tail(&overlay_target_list, entry);
	cv_signal(&overlay_target_condvar);
	mutex_exit(&overlay_target_lock);
}

void
overlay_target_quiesce(overlay_target_t *ott)
{
	if (ott == NULL)
		return;
	mutex_enter(&ott->ott_lock);
	ott->ott_flags |= OVERLAY_T_TEARDOWN;
	while (ott->ott_ocount != 0)
		cv_wait(&ott->ott_cond, &ott->ott_lock);
	mutex_exit(&ott->ott_lock);
}

/*
 * This functions assumes that the destination mode is OVERLAY_PLUGIN_D_IP |
 * OVERLAY_PLUGIN_D_PORT. As we don't have an implementation of anything else at
 * this time, say for NVGRE, we drop all packets that mcuh this.
 */
int
overlay_target_lookup(overlay_dev_t *odd, mblk_t *mp, struct sockaddr *sock,
    socklen_t *slenp)
{
	int ret;
	struct sockaddr_in6 *v6;
	overlay_target_t *ott;
	mac_header_info_t mhi;
	overlay_target_entry_t *entry;

	ASSERT(odd->odd_target != NULL);

	/*
	 * At this point, the overlay device is in a mux which means that it's
	 * been activated. At this point, parts of the target, such as the mode
	 * and the destination are now read-only and we don't have to worry
	 * about synchronization for them.
	 */
	ott = odd->odd_target;
	if (ott->ott_dest != (OVERLAY_PLUGIN_D_IP | OVERLAY_PLUGIN_D_PORT))
		return (OVERLAY_TARGET_DROP);

	v6 = (struct sockaddr_in6 *)sock;
	bzero(v6, sizeof (struct sockaddr_in6));
	v6->sin6_family = AF_INET6;

	if (ott->ott_mode == OVERLAY_TARGET_POINT) {
		mutex_enter(&ott->ott_lock);
		bcopy(&ott->ott_u.ott_point.otp_ip, &v6->sin6_addr,
		    sizeof (struct in6_addr));
		v6->sin6_port = htons(ott->ott_u.ott_point.otp_port);
		mutex_exit(&ott->ott_lock);
		*slenp = sizeof (struct sockaddr_in6);

		return (OVERLAY_TARGET_OK);
	}

	ASSERT(ott->ott_mode == OVERLAY_TARGET_DYNAMIC);

	/*
	 * Note we only want the MAC address here, therefore we won't bother
	 * using mac_vlan_header_info(). If any caller needs the vlan info at
	 * this point, this should change to a call to mac_vlan_header_info().
	 */
	if (mac_header_info(odd->odd_mh, mp, &mhi) != 0)
		return (OVERLAY_TARGET_DROP);
	mutex_enter(&ott->ott_lock);
	entry = refhash_lookup(ott->ott_u.ott_dyn.ott_dhash,
	    mhi.mhi_daddr);
	if (entry == NULL) {
		entry = kmem_cache_alloc(overlay_entry_cache, KM_NOSLEEP_LAZY);
		if (entry == NULL) {
			mutex_exit(&ott->ott_lock);
			return (OVERLAY_TARGET_DROP);
		}
		bcopy(mhi.mhi_daddr, entry->ote_addr, ETHERADDRL);
		entry->ote_chead = entry->ote_ctail = mp;
		entry->ote_mbsize = msgsize(mp);
		entry->ote_flags |= OVERLAY_ENTRY_F_PENDING;
		entry->ote_ott = ott;
		entry->ote_odd = odd;
		refhash_insert(ott->ott_u.ott_dyn.ott_dhash, entry);
		avl_add(&ott->ott_u.ott_dyn.ott_tree, entry);
		mutex_exit(&ott->ott_lock);
		overlay_target_queue(entry);
		return (OVERLAY_TARGET_ASYNC);
	}
	refhash_hold(ott->ott_u.ott_dyn.ott_dhash, entry);
	mutex_exit(&ott->ott_lock);

	mutex_enter(&entry->ote_lock);
	if (entry->ote_flags & OVERLAY_ENTRY_F_DROP) {
		ret = OVERLAY_TARGET_DROP;
	} else if (entry->ote_flags & OVERLAY_ENTRY_F_VALID) {
		bcopy(&entry->ote_dest.otp_ip, &v6->sin6_addr,
		    sizeof (struct in6_addr));
		v6->sin6_port = htons(entry->ote_dest.otp_port);
		*slenp = sizeof (struct sockaddr_in6);
		ret = OVERLAY_TARGET_OK;
	} else {
		size_t mlen = msgsize(mp);

		if (mlen + entry->ote_mbsize > overlay_ent_size) {
			ret = OVERLAY_TARGET_DROP;
		} else {
			if (entry->ote_ctail != NULL) {
				ASSERT(entry->ote_ctail->b_next ==
				    NULL);
				entry->ote_ctail->b_next = mp;
				entry->ote_ctail = mp;
			} else {
				entry->ote_chead = mp;
				entry->ote_ctail = mp;
			}
			entry->ote_mbsize += mlen;
			if ((entry->ote_flags &
			    OVERLAY_ENTRY_F_PENDING) == 0) {
				entry->ote_flags |=
				    OVERLAY_ENTRY_F_PENDING;
				overlay_target_queue(entry);
			}
			ret = OVERLAY_TARGET_ASYNC;
		}
	}
	mutex_exit(&entry->ote_lock);

	mutex_enter(&ott->ott_lock);
	refhash_rele(ott->ott_u.ott_dyn.ott_dhash, entry);
	mutex_exit(&ott->ott_lock);

	return (ret);
}

/* ARGSUSED */
static int
overlay_target_info(overlay_target_hdl_t *thdl, void *arg)
{
	overlay_dev_t *odd;
	overlay_targ_info_t *oti = arg;

	odd = overlay_hold_by_dlid(oti->oti_linkid);
	if (odd == NULL)
		return (ENOENT);

	mutex_enter(&odd->odd_lock);
	oti->oti_flags = 0;
	oti->oti_needs = odd->odd_plugin->ovp_dest;
	if (odd->odd_flags & OVERLAY_F_DEGRADED)
		oti->oti_flags |= OVERLAY_TARG_INFO_F_DEGRADED;
	if (odd->odd_flags & OVERLAY_F_ACTIVATED)
		oti->oti_flags |= OVERLAY_TARG_INFO_F_ACTIVE;
	oti->oti_vnetid = odd->odd_vid;
	mutex_exit(&odd->odd_lock);
	overlay_hold_rele(odd);
	return (0);
}

/* ARGSUSED */
static int
overlay_target_associate(overlay_target_hdl_t *thdl, void *arg)
{
	overlay_dev_t *odd;
	overlay_target_t *ott;
	overlay_targ_associate_t *ota = arg;

	odd = overlay_hold_by_dlid(ota->ota_linkid);
	if (odd == NULL)
		return (ENOENT);

	if (ota->ota_id == 0) {
		overlay_hold_rele(odd);
		return (EINVAL);
	}

	if (ota->ota_mode != OVERLAY_TARGET_POINT &&
	    ota->ota_mode != OVERLAY_TARGET_DYNAMIC) {
		overlay_hold_rele(odd);
		return (EINVAL);
	}

	if (ota->ota_provides != odd->odd_plugin->ovp_dest) {
		overlay_hold_rele(odd);
		return (EINVAL);
	}

	if (ota->ota_mode == OVERLAY_TARGET_POINT) {
		if (ota->ota_provides & OVERLAY_PLUGIN_D_IP) {
			if (IN6_IS_ADDR_UNSPECIFIED(&ota->ota_point.otp_ip) ||
			    IN6_IS_ADDR_V4COMPAT(&ota->ota_point.otp_ip) ||
			    IN6_IS_ADDR_V4MAPPED_ANY(&ota->ota_point.otp_ip)) {
				overlay_hold_rele(odd);
				return (EINVAL);
			}
		}

		if (ota->ota_provides & OVERLAY_PLUGIN_D_PORT) {
			if (ota->ota_point.otp_port == 0) {
				overlay_hold_rele(odd);
				return (EINVAL);
			}
		}
	}

	ott = kmem_cache_alloc(overlay_target_cache, KM_SLEEP);
	ott->ott_flags = 0;
	ott->ott_ocount = 0;
	ott->ott_mode = ota->ota_mode;
	ott->ott_dest = ota->ota_provides;
	ott->ott_id = ota->ota_id;

	if (ott->ott_mode == OVERLAY_TARGET_POINT) {
		bcopy(&ota->ota_point, &ott->ott_u.ott_point,
		    sizeof (overlay_target_point_t));
	} else {
		ott->ott_u.ott_dyn.ott_dhash = refhash_create(OVERLAY_HSIZE,
		    overlay_mac_hash, overlay_mac_cmp,
		    overlay_target_entry_dtor, sizeof (overlay_target_entry_t),
		    offsetof(overlay_target_entry_t, ote_reflink),
		    offsetof(overlay_target_entry_t, ote_addr), KM_SLEEP);
		avl_create(&ott->ott_u.ott_dyn.ott_tree, overlay_mac_avl,
		    sizeof (overlay_target_entry_t),
		    offsetof(overlay_target_entry_t, ote_avllink));
	}
	mutex_enter(&odd->odd_lock);
	if (odd->odd_flags & OVERLAY_F_VARPD) {
		mutex_exit(&odd->odd_lock);
		kmem_cache_free(overlay_target_cache, ott);
		overlay_hold_rele(odd);
		return (EEXIST);
	}

	odd->odd_flags |= OVERLAY_F_VARPD;
	odd->odd_target = ott;
	mutex_exit(&odd->odd_lock);

	overlay_hold_rele(odd);


	return (0);
}


/* ARGSUSED */
static int
overlay_target_degrade(overlay_target_hdl_t *thdl, void *arg)
{
	overlay_dev_t *odd;
	overlay_targ_degrade_t *otd = arg;

	odd = overlay_hold_by_dlid(otd->otd_linkid);
	if (odd == NULL)
		return (ENOENT);

	overlay_fm_degrade(odd, otd->otd_buf);
	overlay_hold_rele(odd);
	return (0);
}

/* ARGSUSED */
static int
overlay_target_restore(overlay_target_hdl_t *thdl, void *arg)
{
	overlay_dev_t *odd;
	overlay_targ_id_t *otid = arg;

	odd = overlay_hold_by_dlid(otid->otid_linkid);
	if (odd == NULL)
		return (ENOENT);

	overlay_fm_restore(odd);
	overlay_hold_rele(odd);
	return (0);
}

/* ARGSUSED */
static int
overlay_target_disassociate(overlay_target_hdl_t *thdl, void *arg)
{
	overlay_dev_t *odd;
	overlay_targ_id_t *otid = arg;

	odd = overlay_hold_by_dlid(otid->otid_linkid);
	if (odd == NULL)
		return (ENOENT);

	mutex_enter(&odd->odd_lock);
	odd->odd_flags &= ~OVERLAY_F_VARPD;
	mutex_exit(&odd->odd_lock);

	overlay_hold_rele(odd);
	return (0);

}

static int
overlay_target_lookup_request(overlay_target_hdl_t *thdl, void *arg)
{
	overlay_targ_lookup_t *otl = arg;
	overlay_target_entry_t *entry;
	clock_t ret, timeout;
	mac_header_info_t mhi;

	timeout = ddi_get_lbolt() + drv_usectohz(MICROSEC);
again:
	mutex_enter(&overlay_target_lock);
	while (list_is_empty(&overlay_target_list)) {
		ret = cv_timedwait(&overlay_target_condvar,
		    &overlay_target_lock, timeout);
		if (ret == -1) {
			mutex_exit(&overlay_target_lock);
			return (ETIME);
		}
	}
	entry = list_remove_head(&overlay_target_list);
	mutex_exit(&overlay_target_lock);
	mutex_enter(&entry->ote_lock);
	if (entry->ote_flags & OVERLAY_ENTRY_F_VALID) {
		ASSERT(entry->ote_chead == NULL);
		mutex_exit(&entry->ote_lock);
		goto again;
	}
	ASSERT(entry->ote_chead != NULL);

	/*
	 * If we have a bogon that doesn't have a valid mac header, drop it and
	 * try again.
	 */
	if (mac_vlan_header_info(entry->ote_odd->odd_mh, entry->ote_chead,
	    &mhi) != 0) {
		boolean_t queue = B_FALSE;
		mblk_t *mp = entry->ote_chead;
		entry->ote_chead = mp->b_next;
		mp->b_next = NULL;
		if (entry->ote_ctail == mp)
			entry->ote_ctail = entry->ote_chead;
		entry->ote_mbsize -= msgsize(mp);
		if (entry->ote_chead != NULL)
			queue = B_TRUE;
		mutex_exit(&entry->ote_lock);
		if (queue == B_TRUE)
			overlay_target_queue(entry);
		freemsg(mp);
		goto again;
	}

	otl->otl_dlid = entry->ote_odd->odd_linkid;
	otl->otl_reqid = (uintptr_t)entry;
	otl->otl_varpdid = entry->ote_ott->ott_id;
	otl->otl_vnetid = entry->ote_odd->odd_vid;

	otl->otl_hdrsize = mhi.mhi_hdrsize;
	otl->otl_pktsize = msgsize(entry->ote_chead) - otl->otl_hdrsize;
	bcopy(mhi.mhi_daddr, otl->otl_dstaddr, ETHERADDRL);
	bcopy(mhi.mhi_saddr, otl->otl_srcaddr, ETHERADDRL);
	otl->otl_dsttype = mhi.mhi_dsttype;
	otl->otl_sap = mhi.mhi_bindsap;
	otl->otl_vlan = VLAN_ID(mhi.mhi_tci);
	mutex_exit(&entry->ote_lock);

	mutex_enter(&thdl->oth_lock);
	list_insert_tail(&thdl->oth_outstanding, entry);
	mutex_exit(&thdl->oth_lock);

	return (0);
}

static int
overlay_target_lookup_respond(overlay_target_hdl_t *thdl, void *arg)
{
	const overlay_targ_resp_t *otr = arg;
	overlay_target_entry_t *entry;
	mblk_t *mp;

	mutex_enter(&thdl->oth_lock);
	for (entry = list_head(&thdl->oth_outstanding); entry != NULL;
	    entry = list_next(&thdl->oth_outstanding, entry)) {
		if ((uintptr_t)entry == otr->otr_reqid)
			break;
	}

	if (entry == NULL) {
		mutex_exit(&thdl->oth_lock);
		return (EINVAL);
	}
	list_remove(&thdl->oth_outstanding, entry);
	mutex_exit(&thdl->oth_lock);

	mutex_enter(&entry->ote_lock);
	bcopy(&otr->otr_answer, &entry->ote_dest,
	    sizeof (overlay_target_point_t));
	entry->ote_flags &= ~OVERLAY_ENTRY_F_PENDING;
	entry->ote_flags |= OVERLAY_ENTRY_F_VALID;
	mp = entry->ote_chead;
	entry->ote_chead = NULL;
	entry->ote_ctail = NULL;
	entry->ote_mbsize = 0;
	entry->ote_vtime = gethrtime();
	mutex_exit(&entry->ote_lock);

	/*
	 * For now do an in-situ drain.
	 */
	mp = overlay_m_tx(entry->ote_odd, mp);
	freemsgchain(mp);

	mutex_enter(&entry->ote_ott->ott_lock);
	entry->ote_ott->ott_ocount--;
	cv_signal(&entry->ote_ott->ott_cond);
	mutex_exit(&entry->ote_ott->ott_lock);

	return (0);
}

static int
overlay_target_lookup_drop(overlay_target_hdl_t *thdl, void *arg)
{
	const overlay_targ_resp_t *otr = arg;
	overlay_target_entry_t *entry;
	mblk_t *mp;
	boolean_t queue = B_FALSE;

	mutex_enter(&thdl->oth_lock);
	for (entry = list_head(&thdl->oth_outstanding); entry != NULL;
	    entry = list_next(&thdl->oth_outstanding, entry)) {
		if ((uintptr_t)entry == otr->otr_reqid)
			break;
	}

	if (entry == NULL) {
		mutex_exit(&thdl->oth_lock);
		return (EINVAL);
	}
	list_remove(&thdl->oth_outstanding, entry);
	mutex_exit(&thdl->oth_lock);

	mutex_enter(&entry->ote_lock);

	/* Safeguard against a confused varpd */
	if (entry->ote_flags & OVERLAY_ENTRY_F_VALID) {
		entry->ote_flags &= ~OVERLAY_ENTRY_F_PENDING;
		DTRACE_PROBE1(overlay__target__valid__drop,
		    overlay_target_entry_t *, entry);
		mutex_exit(&entry->ote_lock);
		goto done;
	}

	mp = entry->ote_chead;
	if (mp != NULL) {
		entry->ote_chead = mp->b_next;
		mp->b_next = NULL;
		if (entry->ote_ctail == mp)
			entry->ote_ctail = entry->ote_chead;
		entry->ote_mbsize -= msgsize(mp);
	}
	if (entry->ote_chead != NULL) {
		queue = B_TRUE;
		entry->ote_flags |= OVERLAY_ENTRY_F_PENDING;
	} else {
		entry->ote_flags &= ~OVERLAY_ENTRY_F_PENDING;
	}
	mutex_exit(&entry->ote_lock);

	if (queue == B_TRUE)
		overlay_target_queue(entry);
	freemsg(mp);

done:
	mutex_enter(&entry->ote_ott->ott_lock);
	entry->ote_ott->ott_ocount--;
	cv_signal(&entry->ote_ott->ott_cond);
	mutex_exit(&entry->ote_ott->ott_lock);

	return (0);
}

/* ARGSUSED */
static int
overlay_target_pkt_copyin(const void *ubuf, void **outp, size_t *bsize,
    int flags)
{
	overlay_targ_pkt_t *pkt;
	overlay_targ_pkt32_t *pkt32;

	pkt = kmem_alloc(sizeof (overlay_targ_pkt_t), KM_SLEEP);
	*outp = pkt;
	*bsize = sizeof (overlay_targ_pkt_t);
	if (ddi_model_convert_from(flags & FMODELS) == DDI_MODEL_ILP32) {
		uintptr_t addr;

		if (ddi_copyin(ubuf, pkt, sizeof (overlay_targ_pkt32_t),
		    flags & FKIOCTL) != 0) {
			kmem_free(pkt, *bsize);
			return (EFAULT);
		}
		pkt32 = (overlay_targ_pkt32_t *)pkt;
		addr = pkt32->otp_buf;
		pkt->otp_buf = (void *)addr;
	} else {
		if (ddi_copyin(ubuf, pkt, *bsize, flags & FKIOCTL) != 0) {
			kmem_free(pkt, *bsize);
			return (EFAULT);
		}
	}
	return (0);
}

static int
overlay_target_pkt_copyout(void *ubuf, void *buf, size_t bufsize,
    int flags)
{
	if (ddi_model_convert_from(flags & FMODELS) == DDI_MODEL_ILP32) {
		overlay_targ_pkt_t *pkt = buf;
		overlay_targ_pkt32_t *pkt32 = buf;
		uintptr_t addr = (uintptr_t)pkt->otp_buf;
		pkt32->otp_buf = (caddr32_t)addr;
		if (ddi_copyout(buf, ubuf, sizeof (overlay_targ_pkt32_t),
		    flags & FKIOCTL) != 0)
			return (EFAULT);
	} else {
		if (ddi_copyout(buf, ubuf, bufsize, flags & FKIOCTL) != 0)
			return (EFAULT);
	}
	return (0);
}

static int
overlay_target_packet(overlay_target_hdl_t *thdl, void *arg)
{
	overlay_targ_pkt_t *pkt = arg;
	overlay_target_entry_t *entry;
	mblk_t *mp;
	size_t mlen;
	size_t boff;

	mutex_enter(&thdl->oth_lock);
	for (entry = list_head(&thdl->oth_outstanding); entry != NULL;
	    entry = list_next(&thdl->oth_outstanding, entry)) {
		if ((uintptr_t)entry == pkt->otp_reqid)
			break;
	}

	if (entry == NULL) {
		mutex_exit(&thdl->oth_lock);
		return (EINVAL);
	}
	mutex_enter(&entry->ote_lock);
	mutex_exit(&thdl->oth_lock);
	mp = entry->ote_chead;
	/* Protect against a rogue varpd */
	if (mp == NULL) {
		mutex_exit(&entry->ote_lock);
		return (EINVAL);
	}
	mlen = MIN(msgsize(mp), pkt->otp_size);
	pkt->otp_size = mlen;
	boff = 0;
	while (mlen > 0) {
		size_t wlen = MIN(MBLKL(mp), mlen);
		if (ddi_copyout(mp->b_rptr,
		    (void *)((uintptr_t)pkt->otp_buf + boff),
		    wlen, 0) != 0) {
			mutex_exit(&entry->ote_lock);
			return (EFAULT);
		}
		mlen -= wlen;
		boff += wlen;
		mp = mp->b_cont;
	}
	mutex_exit(&entry->ote_lock);
	return (0);
}

static int
overlay_target_inject(overlay_target_hdl_t *thdl, void *arg)
{
	overlay_targ_pkt_t *pkt = arg;
	overlay_target_entry_t *entry;
	overlay_dev_t *odd;
	mblk_t *mp;

	if (pkt->otp_size > ETHERMAX + VLAN_TAGSZ)
		return (EINVAL);

	mp = allocb(pkt->otp_size, 0);
	if (mp == NULL)
		return (ENOMEM);

	if (ddi_copyin(pkt->otp_buf, mp->b_rptr, pkt->otp_size, 0) != 0) {
		freeb(mp);
		return (EFAULT);
	}
	mp->b_wptr += pkt->otp_size;

	if (pkt->otp_linkid != UINT64_MAX) {
		odd = overlay_hold_by_dlid(pkt->otp_linkid);
		if (odd == NULL) {
			freeb(mp);
			return (ENOENT);
		}
	} else {
		mutex_enter(&thdl->oth_lock);
		for (entry = list_head(&thdl->oth_outstanding); entry != NULL;
		    entry = list_next(&thdl->oth_outstanding, entry)) {
			if ((uintptr_t)entry == pkt->otp_reqid)
				break;
		}

		if (entry == NULL) {
			mutex_exit(&thdl->oth_lock);
			freeb(mp);
			return (ENOENT);
		}
		odd = entry->ote_odd;
		mutex_exit(&thdl->oth_lock);
	}

	mutex_enter(&odd->odd_lock);
	if ((odd->odd_flags & OVERLAY_F_MDDROP) ||
	    !(odd->odd_flags & OVERLAY_F_IN_MUX)) {
		/* Can't do receive... */
		mutex_exit(&odd->odd_lock);
		OVERLAY_FREEMSG(mp, "dev dropped");
		freeb(mp);
		return (EBUSY);
	}
	overlay_io_start(odd, OVERLAY_F_IN_RX);
	mutex_exit(&odd->odd_lock);

	mac_rx(odd->odd_mh, NULL, mp);

	mutex_enter(&odd->odd_lock);
	overlay_io_done(odd, OVERLAY_F_IN_RX);
	mutex_exit(&odd->odd_lock);

	return (0);
}

static int
overlay_target_resend(overlay_target_hdl_t *thdl, void *arg)
{
	overlay_targ_pkt_t *pkt = arg;
	overlay_target_entry_t *entry;
	overlay_dev_t *odd;
	mblk_t *mp;

	if (pkt->otp_size > ETHERMAX + VLAN_TAGSZ)
		return (EINVAL);

	mp = allocb(pkt->otp_size, 0);
	if (mp == NULL)
		return (ENOMEM);

	if (ddi_copyin(pkt->otp_buf, mp->b_rptr, pkt->otp_size, 0) != 0) {
		freeb(mp);
		return (EFAULT);
	}
	mp->b_wptr += pkt->otp_size;

	if (pkt->otp_linkid != UINT64_MAX) {
		odd = overlay_hold_by_dlid(pkt->otp_linkid);
		if (odd == NULL) {
			freeb(mp);
			return (ENOENT);
		}
	} else {
		mutex_enter(&thdl->oth_lock);
		for (entry = list_head(&thdl->oth_outstanding); entry != NULL;
		    entry = list_next(&thdl->oth_outstanding, entry)) {
			if ((uintptr_t)entry == pkt->otp_reqid)
				break;
		}

		if (entry == NULL) {
			mutex_exit(&thdl->oth_lock);
			freeb(mp);
			return (ENOENT);
		}
		odd = entry->ote_odd;
		mutex_exit(&thdl->oth_lock);
	}

	mp = overlay_m_tx(odd, mp);
	freemsgchain(mp);

	return (0);
}

typedef struct overlay_targ_list_int {
	boolean_t	otli_count;
	uint32_t	otli_cur;
	uint32_t	otli_nents;
	uint32_t	otli_ents[];
} overlay_targ_list_int_t;

static int
overlay_target_list_copyin(const void *ubuf, void **outp, size_t *bsize,
    int flags)
{
	overlay_targ_list_t n;
	overlay_targ_list_int_t *otl;

	if (ddi_copyin(ubuf, &n, sizeof (overlay_targ_list_t),
	    flags & FKIOCTL) != 0)
		return (EFAULT);

	/*
	 */
	if (n.otl_nents >= INT32_MAX / sizeof (uint32_t))
		return (EINVAL);
	*bsize = sizeof (overlay_targ_list_int_t) +
	    sizeof (uint32_t) * n.otl_nents;
	otl = kmem_zalloc(*bsize, KM_SLEEP);
	otl->otli_cur = 0;
	otl->otli_nents = n.otl_nents;
	if (otl->otli_nents != 0) {
		otl->otli_count = B_FALSE;
		if (ddi_copyin((void *)((uintptr_t)ubuf +
		    offsetof(overlay_targ_list_t, otl_ents)),
		    otl->otli_ents, n.otl_nents * sizeof (uint32_t),
		    flags & FKIOCTL) != 0) {
			kmem_free(otl, *bsize);
			return (EFAULT);
		}
	} else {
		otl->otli_count = B_TRUE;
	}

	*outp = otl;
	return (0);
}

static int
overlay_target_ioctl_list_cb(overlay_dev_t *odd, void *arg)
{
	overlay_targ_list_int_t *otl = arg;

	if (otl->otli_cur < otl->otli_nents)
		otl->otli_ents[otl->otli_cur] = odd->odd_linkid;
	otl->otli_cur++;
	return (0);
}

/* ARGSUSED */
static int
overlay_target_ioctl_list(overlay_target_hdl_t *thdl, void *arg)
{
	overlay_dev_iter(overlay_target_ioctl_list_cb, arg);
	return (0);
}

/* ARGSUSED */
static int
overlay_target_list_copyout(void *ubuf, void *buf, size_t bufsize, int flags)
{
	overlay_targ_list_int_t *otl = buf;

	if (ddi_copyout(&otl->otli_cur, ubuf, sizeof (uint32_t),
	    flags & FKIOCTL) != 0)
		return (EFAULT);

	if (otl->otli_count == B_FALSE) {
		if (ddi_copyout(otl->otli_ents,
		    (void *)((uintptr_t)ubuf +
		    offsetof(overlay_targ_list_t, otl_ents)),
		    sizeof (uint32_t) * otl->otli_nents,
		    flags & FKIOCTL) != 0)
			return (EFAULT);
	}
	return (0);
}

/* ARGSUSED */
static int
overlay_target_cache_get(overlay_target_hdl_t *thdl, void *arg)
{
	int ret = 0;
	overlay_dev_t *odd;
	overlay_target_t *ott;
	overlay_targ_cache_t *otc = arg;

	odd = overlay_hold_by_dlid(otc->otc_linkid);
	if (odd == NULL)
		return (ENOENT);

	mutex_enter(&odd->odd_lock);
	if (!(odd->odd_flags & OVERLAY_F_VARPD)) {
		mutex_exit(&odd->odd_lock);
		overlay_hold_rele(odd);
		return (ENXIO);
	}
	ott = odd->odd_target;
	if (ott->ott_mode != OVERLAY_TARGET_POINT &&
	    ott->ott_mode != OVERLAY_TARGET_DYNAMIC) {
		mutex_exit(&odd->odd_lock);
		overlay_hold_rele(odd);
		return (ENOTSUP);
	}
	mutex_enter(&ott->ott_lock);
	mutex_exit(&odd->odd_lock);

	if (ott->ott_mode == OVERLAY_TARGET_POINT) {
		otc->otc_entry.otce_flags = 0;
		bcopy(&ott->ott_u.ott_point, &otc->otc_entry.otce_dest,
		    sizeof (overlay_target_point_t));
	} else {
		overlay_target_entry_t *ote;
		ote = refhash_lookup(ott->ott_u.ott_dyn.ott_dhash,
		    otc->otc_entry.otce_mac);
		if (ote != NULL) {
			mutex_enter(&ote->ote_lock);
			if ((ote->ote_flags &
			    OVERLAY_ENTRY_F_VALID_MASK) != 0) {
				if (ote->ote_flags & OVERLAY_ENTRY_F_DROP) {
					otc->otc_entry.otce_flags =
					    OVERLAY_TARGET_CACHE_DROP;
				} else {
					otc->otc_entry.otce_flags = 0;
					bcopy(&ote->ote_dest,
					    &otc->otc_entry.otce_dest,
					    sizeof (overlay_target_point_t));
				}
				ret = 0;
			} else {
				ret = ENOENT;
			}
			mutex_exit(&ote->ote_lock);
		} else {
			ret = ENOENT;
		}
	}

	mutex_exit(&ott->ott_lock);
	overlay_hold_rele(odd);

	return (ret);
}

/* ARGSUSED */
static int
overlay_target_cache_set(overlay_target_hdl_t *thdl, void *arg)
{
	overlay_dev_t *odd;
	overlay_target_t *ott;
	overlay_target_entry_t *ote;
	overlay_targ_cache_t *otc = arg;
	mblk_t *mp = NULL;

	if (otc->otc_entry.otce_flags & ~OVERLAY_TARGET_CACHE_DROP)
		return (EINVAL);

	odd = overlay_hold_by_dlid(otc->otc_linkid);
	if (odd == NULL)
		return (ENOENT);

	mutex_enter(&odd->odd_lock);
	if (!(odd->odd_flags & OVERLAY_F_VARPD)) {
		mutex_exit(&odd->odd_lock);
		overlay_hold_rele(odd);
		return (ENXIO);
	}
	ott = odd->odd_target;
	if (ott->ott_mode != OVERLAY_TARGET_DYNAMIC) {
		mutex_exit(&odd->odd_lock);
		overlay_hold_rele(odd);
		return (ENOTSUP);
	}
	mutex_enter(&ott->ott_lock);
	mutex_exit(&odd->odd_lock);

	ote = refhash_lookup(ott->ott_u.ott_dyn.ott_dhash,
	    otc->otc_entry.otce_mac);
	if (ote == NULL) {
		ote = kmem_cache_alloc(overlay_entry_cache, KM_SLEEP);
		bcopy(otc->otc_entry.otce_mac, ote->ote_addr, ETHERADDRL);
		ote->ote_chead = ote->ote_ctail = NULL;
		ote->ote_mbsize = 0;
		ote->ote_ott = ott;
		ote->ote_odd = odd;
		mutex_enter(&ote->ote_lock);
		refhash_insert(ott->ott_u.ott_dyn.ott_dhash, ote);
		avl_add(&ott->ott_u.ott_dyn.ott_tree, ote);
	} else {
		mutex_enter(&ote->ote_lock);
	}

	if (otc->otc_entry.otce_flags & OVERLAY_TARGET_CACHE_DROP) {
		ote->ote_flags |= OVERLAY_ENTRY_F_DROP;
	} else {
		ote->ote_flags |= OVERLAY_ENTRY_F_VALID;
		bcopy(&otc->otc_entry.otce_dest, &ote->ote_dest,
		    sizeof (overlay_target_point_t));
		mp = ote->ote_chead;
		ote->ote_chead = NULL;
		ote->ote_ctail = NULL;
		ote->ote_mbsize = 0;
		ote->ote_vtime = gethrtime();
	}

	mutex_exit(&ote->ote_lock);
	mutex_exit(&ott->ott_lock);

	if (mp != NULL) {
		mp = overlay_m_tx(ote->ote_odd, mp);
		freemsgchain(mp);
	}

	overlay_hold_rele(odd);

	return (0);
}

/* ARGSUSED */
static int
overlay_target_cache_remove(overlay_target_hdl_t *thdl, void *arg)
{
	int ret = 0;
	overlay_dev_t *odd;
	overlay_target_t *ott;
	overlay_target_entry_t *ote;
	overlay_targ_cache_t *otc = arg;

	odd = overlay_hold_by_dlid(otc->otc_linkid);
	if (odd == NULL)
		return (ENOENT);

	mutex_enter(&odd->odd_lock);
	if (!(odd->odd_flags & OVERLAY_F_VARPD)) {
		mutex_exit(&odd->odd_lock);
		overlay_hold_rele(odd);
		return (ENXIO);
	}
	ott = odd->odd_target;
	if (ott->ott_mode != OVERLAY_TARGET_DYNAMIC) {
		mutex_exit(&odd->odd_lock);
		overlay_hold_rele(odd);
		return (ENOTSUP);
	}
	mutex_enter(&ott->ott_lock);
	mutex_exit(&odd->odd_lock);

	ote = refhash_lookup(ott->ott_u.ott_dyn.ott_dhash,
	    otc->otc_entry.otce_mac);
	if (ote != NULL) {
		mutex_enter(&ote->ote_lock);
		ote->ote_flags &= ~OVERLAY_ENTRY_F_VALID_MASK;
		mutex_exit(&ote->ote_lock);
		ret = 0;
	} else {
		ret = ENOENT;
	}

	mutex_exit(&ott->ott_lock);
	overlay_hold_rele(odd);

	return (ret);
}

/* ARGSUSED */
static int
overlay_target_cache_flush(overlay_target_hdl_t *thdl, void *arg)
{
	avl_tree_t *avl;
	overlay_dev_t *odd;
	overlay_target_t *ott;
	overlay_target_entry_t *ote;
	overlay_targ_cache_t *otc = arg;

	odd = overlay_hold_by_dlid(otc->otc_linkid);
	if (odd == NULL)
		return (ENOENT);

	mutex_enter(&odd->odd_lock);
	if (!(odd->odd_flags & OVERLAY_F_VARPD)) {
		mutex_exit(&odd->odd_lock);
		overlay_hold_rele(odd);
		return (ENXIO);
	}
	ott = odd->odd_target;
	if (ott->ott_mode != OVERLAY_TARGET_DYNAMIC) {
		mutex_exit(&odd->odd_lock);
		overlay_hold_rele(odd);
		return (ENOTSUP);
	}
	mutex_enter(&ott->ott_lock);
	mutex_exit(&odd->odd_lock);
	avl = &ott->ott_u.ott_dyn.ott_tree;

	for (ote = avl_first(avl); ote != NULL; ote = AVL_NEXT(avl, ote)) {
		mutex_enter(&ote->ote_lock);
		ote->ote_flags &= ~OVERLAY_ENTRY_F_VALID_MASK;
		mutex_exit(&ote->ote_lock);
	}
	ote = refhash_lookup(ott->ott_u.ott_dyn.ott_dhash,
	    otc->otc_entry.otce_mac);

	mutex_exit(&ott->ott_lock);
	overlay_hold_rele(odd);

	return (0);
}

static int
overlay_target_cache_iter_copyin(const void *ubuf, void **outp, size_t *bsize,
    int flags)
{
	overlay_targ_cache_iter_t base, *iter;

	if (ddi_copyin(ubuf, &base, sizeof (overlay_targ_cache_iter_t),
	    flags & FKIOCTL) != 0)
		return (EFAULT);

	if (base.otci_count > OVERLAY_TARGET_ITER_MAX)
		return (E2BIG);

	if (base.otci_count == 0)
		return (EINVAL);

	*bsize = sizeof (overlay_targ_cache_iter_t) +
	    base.otci_count * sizeof (overlay_targ_cache_entry_t);
	iter = kmem_alloc(*bsize, KM_SLEEP);
	bcopy(&base, iter, sizeof (overlay_targ_cache_iter_t));
	*outp = iter;

	return (0);
}

typedef struct overlay_targ_cache_marker {
	uint8_t		otcm_mac[ETHERADDRL];
	uint16_t	otcm_done;
} overlay_targ_cache_marker_t;

/* ARGSUSED */
static int
overlay_target_cache_iter(overlay_target_hdl_t *thdl, void *arg)
{
	overlay_dev_t *odd;
	overlay_target_t *ott;
	overlay_target_entry_t lookup, *ent;
	overlay_targ_cache_marker_t *mark;
	avl_index_t where;
	avl_tree_t *avl;
	uint16_t written = 0;

	overlay_targ_cache_iter_t *iter = arg;
	mark = (void *)&iter->otci_marker;

	if (mark->otcm_done != 0) {
		iter->otci_count = 0;
		return (0);
	}

	odd = overlay_hold_by_dlid(iter->otci_linkid);
	if (odd == NULL)
		return (ENOENT);

	mutex_enter(&odd->odd_lock);
	if (!(odd->odd_flags & OVERLAY_F_VARPD)) {
		mutex_exit(&odd->odd_lock);
		overlay_hold_rele(odd);
		return (ENXIO);
	}
	ott = odd->odd_target;
	if (ott->ott_mode != OVERLAY_TARGET_DYNAMIC &&
	    ott->ott_mode != OVERLAY_TARGET_POINT) {
		mutex_exit(&odd->odd_lock);
		overlay_hold_rele(odd);
		return (ENOTSUP);
	}

	/*
	 * Holding this lock across the entire iteration probably isn't very
	 * good. We should perhaps add an r/w lock for the avl tree. But we'll
	 * wait until we now it's necessary before we do more.
	 */
	mutex_enter(&ott->ott_lock);
	mutex_exit(&odd->odd_lock);

	if (ott->ott_mode == OVERLAY_TARGET_POINT) {
		overlay_targ_cache_entry_t *out = &iter->otci_ents[0];
		bzero(out->otce_mac, ETHERADDRL);
		out->otce_flags = 0;
		bcopy(&ott->ott_u.ott_point, &out->otce_dest,
		    sizeof (overlay_target_point_t));
		written++;
		mark->otcm_done = 1;
	}

	avl = &ott->ott_u.ott_dyn.ott_tree;
	bcopy(mark->otcm_mac, lookup.ote_addr, ETHERADDRL);
	ent = avl_find(avl, &lookup, &where);

	/*
	 * NULL ent means that the entry does not exist, so we want to start
	 * with the closest node in the tree. This means that we implicitly rely
	 * on the tree's order and the first node will be the mac 00:00:00:00:00
	 * and the last will be ff:ff:ff:ff:ff:ff.
	 */
	if (ent == NULL) {
		ent = avl_nearest(avl, where, AVL_AFTER);
		if (ent == NULL) {
			mark->otcm_done = 1;
			goto done;
		}
	}

	for (; ent != NULL && written < iter->otci_count;
	    ent = AVL_NEXT(avl, ent)) {
		overlay_targ_cache_entry_t *out = &iter->otci_ents[written];
		mutex_enter(&ent->ote_lock);
		if ((ent->ote_flags & OVERLAY_ENTRY_F_VALID_MASK) == 0) {
			mutex_exit(&ent->ote_lock);
			continue;
		}
		bcopy(ent->ote_addr, out->otce_mac, ETHERADDRL);
		out->otce_flags = 0;
		if (ent->ote_flags & OVERLAY_ENTRY_F_DROP)
			out->otce_flags |= OVERLAY_TARGET_CACHE_DROP;
		if (ent->ote_flags & OVERLAY_ENTRY_F_VALID)
			bcopy(&ent->ote_dest, &out->otce_dest,
			    sizeof (overlay_target_point_t));
		written++;
		mutex_exit(&ent->ote_lock);
	}

	if (ent != NULL) {
		bcopy(ent->ote_addr, mark->otcm_mac, ETHERADDRL);
	} else {
		mark->otcm_done = 1;
	}

done:
	iter->otci_count = written;
	mutex_exit(&ott->ott_lock);
	overlay_hold_rele(odd);

	return (0);
}

/* ARGSUSED */
static int
overlay_target_cache_iter_copyout(void *ubuf, void *buf, size_t bufsize,
    int flags)
{
	size_t outsize;
	const overlay_targ_cache_iter_t *iter = buf;

	outsize = sizeof (overlay_targ_cache_iter_t) +
	    iter->otci_count * sizeof (overlay_targ_cache_entry_t);

	if (ddi_copyout(buf, ubuf, outsize, flags & FKIOCTL) != 0)
		return (EFAULT);

	return (0);
}

static overlay_target_ioctl_t overlay_target_ioctab[] = {
	{ OVERLAY_TARG_INFO, B_TRUE, B_TRUE,
		NULL, overlay_target_info,
		NULL, sizeof (overlay_targ_info_t)	},
	{ OVERLAY_TARG_ASSOCIATE, B_TRUE, B_FALSE,
		NULL, overlay_target_associate,
		NULL, sizeof (overlay_targ_associate_t)	},
	{ OVERLAY_TARG_DISASSOCIATE, B_TRUE, B_FALSE,
		NULL, overlay_target_disassociate,
		NULL, sizeof (overlay_targ_id_t)	},
	{ OVERLAY_TARG_DEGRADE, B_TRUE, B_FALSE,
		NULL, overlay_target_degrade,
		NULL, sizeof (overlay_targ_degrade_t)	},
	{ OVERLAY_TARG_RESTORE, B_TRUE, B_FALSE,
		NULL, overlay_target_restore,
		NULL, sizeof (overlay_targ_id_t)	},
	{ OVERLAY_TARG_LOOKUP, B_FALSE, B_TRUE,
		NULL, overlay_target_lookup_request,
		NULL, sizeof (overlay_targ_lookup_t)	},
	{ OVERLAY_TARG_RESPOND, B_TRUE, B_FALSE,
		NULL, overlay_target_lookup_respond,
		NULL, sizeof (overlay_targ_resp_t)	},
	{ OVERLAY_TARG_DROP, B_TRUE, B_FALSE,
		NULL, overlay_target_lookup_drop,
		NULL, sizeof (overlay_targ_resp_t)	},
	{ OVERLAY_TARG_PKT, B_TRUE, B_TRUE,
		overlay_target_pkt_copyin,
		overlay_target_packet,
		overlay_target_pkt_copyout,
		sizeof (overlay_targ_pkt_t)		},
	{ OVERLAY_TARG_INJECT, B_TRUE, B_FALSE,
		overlay_target_pkt_copyin,
		overlay_target_inject,
		NULL, sizeof (overlay_targ_pkt_t)	},
	{ OVERLAY_TARG_RESEND, B_TRUE, B_FALSE,
		overlay_target_pkt_copyin,
		overlay_target_resend,
		NULL, sizeof (overlay_targ_pkt_t)	},
	{ OVERLAY_TARG_LIST, B_FALSE, B_TRUE,
		overlay_target_list_copyin,
		overlay_target_ioctl_list,
		overlay_target_list_copyout,
		sizeof (overlay_targ_list_t)		},
	{ OVERLAY_TARG_CACHE_GET, B_FALSE, B_TRUE,
		NULL, overlay_target_cache_get,
		NULL, sizeof (overlay_targ_cache_t)	},
	{ OVERLAY_TARG_CACHE_SET, B_TRUE, B_TRUE,
		NULL, overlay_target_cache_set,
		NULL, sizeof (overlay_targ_cache_t)	},
	{ OVERLAY_TARG_CACHE_REMOVE, B_TRUE, B_TRUE,
		NULL, overlay_target_cache_remove,
		NULL, sizeof (overlay_targ_cache_t)	},
	{ OVERLAY_TARG_CACHE_FLUSH, B_TRUE, B_TRUE,
		NULL, overlay_target_cache_flush,
		NULL, sizeof (overlay_targ_cache_t)	},
	{ OVERLAY_TARG_CACHE_ITER, B_FALSE, B_TRUE,
		overlay_target_cache_iter_copyin,
		overlay_target_cache_iter,
		overlay_target_cache_iter_copyout,
		sizeof (overlay_targ_cache_iter_t)		},
	{ 0 }
};

int
overlay_target_open(dev_t *devp, int flags, int otype, cred_t *credp)
{
	minor_t mid;
	overlay_target_hdl_t *thdl;

	if (secpolicy_dl_config(credp) != 0)
		return (EPERM);

	if (getminor(*devp) != 0)
		return (ENXIO);

	if (otype & OTYP_BLK)
		return (EINVAL);

	if (flags & ~(FREAD | FWRITE | FEXCL))
		return (EINVAL);

	if ((flags & FWRITE) &&
	    !(flags & FEXCL))
		return (EINVAL);

	if (!(flags & FREAD) && !(flags & FWRITE))
		return (EINVAL);

	if (crgetzoneid(credp) != GLOBAL_ZONEID)
		return (EPERM);

	mid = id_alloc(overlay_thdl_idspace);
	if (ddi_soft_state_zalloc(overlay_thdl_state, mid) != 0) {
		id_free(overlay_thdl_idspace, mid);
		return (ENXIO);
	}

	thdl = ddi_get_soft_state(overlay_thdl_state, mid);
	VERIFY(thdl != NULL);
	thdl->oth_minor = mid;
	thdl->oth_zoneid = crgetzoneid(credp);
	thdl->oth_oflags = flags;
	mutex_init(&thdl->oth_lock, NULL, MUTEX_DRIVER, NULL);
	list_create(&thdl->oth_outstanding, sizeof (overlay_target_entry_t),
	    offsetof(overlay_target_entry_t, ote_qlink));
	*devp = makedevice(getmajor(*devp), mid);

	mutex_enter(&overlay_target_lock);
	if ((flags & FEXCL) && overlay_target_excl == B_TRUE) {
		mutex_exit(&overlay_target_lock);
		list_destroy(&thdl->oth_outstanding);
		mutex_destroy(&thdl->oth_lock);
		ddi_soft_state_free(overlay_thdl_state, mid);
		id_free(overlay_thdl_idspace, mid);
		return (EEXIST);
	} else if ((flags & FEXCL) != 0) {
		VERIFY(overlay_target_excl == B_FALSE);
		overlay_target_excl = B_TRUE;
	}
	list_insert_tail(&overlay_thdl_list, thdl);
	mutex_exit(&overlay_target_lock);

	return (0);
}

/* ARGSUSED */
int
overlay_target_ioctl(dev_t dev, int cmd, intptr_t arg, int mode, cred_t *credp,
    int *rvalp)
{
	overlay_target_ioctl_t *ioc;
	overlay_target_hdl_t *thdl;

	if (secpolicy_dl_config(credp) != 0)
		return (EPERM);

	if ((thdl = ddi_get_soft_state(overlay_thdl_state,
	    getminor(dev))) == NULL)
		return (ENXIO);

	for (ioc = &overlay_target_ioctab[0]; ioc->oti_cmd != 0; ioc++) {
		int ret;
		caddr_t buf;
		size_t bufsize;

		if (ioc->oti_cmd != cmd)
			continue;

		if (ioc->oti_write == B_TRUE && !(mode & FWRITE))
			return (EBADF);

		if (ioc->oti_copyin == NULL) {
			bufsize = ioc->oti_size;
			buf = kmem_alloc(bufsize, KM_SLEEP);
			if (ddi_copyin((void *)(uintptr_t)arg, buf, bufsize,
			    mode & FKIOCTL) != 0) {
				kmem_free(buf, bufsize);
				return (EFAULT);
			}
		} else {
			if ((ret = ioc->oti_copyin((void *)(uintptr_t)arg,
			    (void **)&buf, &bufsize, mode)) != 0)
				return (ret);
		}

		ret = ioc->oti_func(thdl, buf);
		if (ret == 0 && ioc->oti_size != 0 &&
		    ioc->oti_ncopyout == B_TRUE) {
			if (ioc->oti_copyout == NULL) {
				if (ddi_copyout(buf, (void *)(uintptr_t)arg,
				    bufsize, mode & FKIOCTL) != 0)
					ret = EFAULT;
			} else {
				ret = ioc->oti_copyout((void *)(uintptr_t)arg,
				    buf, bufsize, mode);
			}
		}

		kmem_free(buf, bufsize);
		return (ret);
	}

	return (ENOTTY);
}

/* ARGSUSED */
int
overlay_target_close(dev_t dev, int flags, int otype, cred_t *credp)
{
	overlay_target_hdl_t *thdl;
	overlay_target_entry_t *entry;
	minor_t mid = getminor(dev);

	if ((thdl = ddi_get_soft_state(overlay_thdl_state, mid)) == NULL)
		return (ENXIO);

	mutex_enter(&overlay_target_lock);
	list_remove(&overlay_thdl_list, thdl);
	mutex_enter(&thdl->oth_lock);
	while ((entry = list_remove_head(&thdl->oth_outstanding)) != NULL)
		list_insert_tail(&overlay_target_list, entry);
	cv_signal(&overlay_target_condvar);
	mutex_exit(&thdl->oth_lock);
	if ((thdl->oth_oflags & FEXCL) != 0) {
		VERIFY(overlay_target_excl == B_TRUE);
		overlay_target_excl = B_FALSE;
	}
	mutex_exit(&overlay_target_lock);

	list_destroy(&thdl->oth_outstanding);
	mutex_destroy(&thdl->oth_lock);
	mid = thdl->oth_minor;
	ddi_soft_state_free(overlay_thdl_state, mid);
	id_free(overlay_thdl_idspace, mid);

	return (0);
}
/*
 * This file and its contents are supplied under the terms of the
 * Common Development and Distribution License ("CDDL"), version 1.0.
 * You may only use this file in accordance with the terms of version
 * 1.0 of the CDDL.
 *
 * A full copy of the text of the CDDL should have accompanied this
 * source.  A copy of the CDDL is also available via the Internet at
 * http://www.illumos.org/license/CDDL.
 */

/*
 * Copyright 2018 Joyent, Inc.
 * Copyright 2022 MNX Cloud, Inc.
 */

/*
 * VXLAN encapsulation module
 *
 *
 * The VXLAN header looks as follows in network byte order:
 *
 * |0        3| 4 |5                     31|
 * +----------+---+------------------------+
 * | Reserved | I | Reserved               |
 * +---------------------------------------+
 * | Virtual Network ID         | Reserved |
 * +----------------------------+----------+
 * |0                         23|24      31|
 *
 * All reserved values must be 0. The I bit must be 1. We call the top
 * word the VXLAN magic field for the time being. The second word is
 * definitely not the most friendly way to operate. Specifically, the ID
 * is a 24-bit big endian value, but we have to make sure not to use the
 * reserved byte.
 *
 * For us, VXLAN encapsulation is a fairly straightforward implementation. It
 * only has two properties, a listen_ip and a listen_port. These determine on
 * what address we should be listening on. While we do not have a default
 * address to listen upon, we do have a default port, which is the IANA assigned
 * port for VXLAN -- 4789.
 */

#include <sys/overlay_plugin.h>
#include <sys/modctl.h>
#include <sys/errno.h>
#include <sys/byteorder.h>
#include <sys/vxlan.h>
#include <inet/ip.h>
#include <netinet/in.h>
#include <sys/strsun.h>
#include <netinet/udp.h>

static const char *vxlan_ident = "vxlan";
static uint16_t vxlan_defport = IPPORT_VXLAN;

/*
 * Should we enable UDP source port hashing for fanout.
 */
boolean_t vxlan_fanout = B_TRUE;

/*
 * This represents the size in bytes that we want to allocate when allocating a
 * vxlan header block. This is intended such that lower levels can try and use
 * the message block that we allocate for the IP and UPD header. The hope is
 * that even if this is tunneled, that this is enough space.
 *
 * The vxlan_noalloc_min value represents the minimum amount of space we need to
 * consider not allocating a message block and just passing it down the stack in
 * this form. This number assumes that we have a VLAN tag, so 18 byte Ethernet
 * header, 20 byte IP header, 8 byte UDP header, and 8 byte VXLAN header.
 */
uint_t vxlan_alloc_size = 128;
uint_t vxlan_noalloc_min = 54;

static const char *vxlan_props[] = {
	"vxlan/listen_ip",
	"vxlan/listen_port",
	NULL
};

typedef struct vxlan {
	kmutex_t vxl_lock;
	overlay_handle_t vxl_oh;
	uint16_t vxl_lport;
	boolean_t vxl_hladdr;
	struct in6_addr vxl_laddr;
} vxlan_t;

static int
vxlan_o_init(overlay_handle_t oh, void **outp)
{
	vxlan_t *vxl;

	vxl = kmem_alloc(sizeof (vxlan_t), KM_SLEEP);
	*outp = vxl;
	mutex_init(&vxl->vxl_lock, NULL, MUTEX_DRIVER, NULL);
	vxl->vxl_oh = oh;
	vxl->vxl_lport = vxlan_defport;
	vxl->vxl_hladdr = B_FALSE;

	return (0);
}

static void
vxlan_o_fini(void *arg)
{
	vxlan_t *vxl = arg;

	mutex_destroy(&vxl->vxl_lock);
	kmem_free(arg, sizeof (vxlan_t));
}

static int
vxlan_o_socket(void *arg, int *dp, int *fp, int *pp, struct sockaddr *addr,
    socklen_t *slenp)
{
	vxlan_t *vxl = arg;
	struct sockaddr_in6 *in;

	in = (struct sockaddr_in6 *)addr;
	*dp = AF_INET6;
	*fp = SOCK_DGRAM;
	*pp = 0;
	bzero(in, sizeof (struct sockaddr_in6));
	in->sin6_family = AF_INET6;

	/*
	 * We should consider a more expressive private errno set that
	 * provider's can use.
	 */
	mutex_enter(&vxl->vxl_lock);
	if (vxl->vxl_hladdr == B_FALSE) {
		mutex_exit(&vxl->vxl_lock);
		return (EINVAL);
	}
	in->sin6_port = htons(vxl->vxl_lport);
	in->sin6_addr = vxl->vxl_laddr;
	mutex_exit(&vxl->vxl_lock);
	*slenp = sizeof (struct sockaddr_in6);

	return (0);
}

static int
vxlan_o_sockopt(ksocket_t ksock)
{
	int val, err;
	if (vxlan_fanout == B_FALSE)
		return (0);

	val = UDP_HASH_VXLAN;
	err = ksocket_setsockopt(ksock, IPPROTO_UDP, UDP_SRCPORT_HASH, &val,
	    sizeof (val), kcred);
	return (err);
}

/* ARGSUSED */
static int
vxlan_o_encap(void *arg, mblk_t *mp, ovep_encap_info_t *einfop,
    mblk_t **outp)
{
	mblk_t *ob;
	vxlan_hdr_t *vxh;

	ASSERT(einfop->ovdi_id < (1 << 24));

	if (DB_REF(mp) != 1 || mp->b_rptr - vxlan_noalloc_min < DB_BASE(mp)) {
		/*
		 * This allocation could get hot. We may want to have a good
		 * way to cache and handle this allocation the same way that IP
		 * does with keeping around a message block per entry, or
		 * basically treating this as an immutable message block in the
		 * system. Basically freemsg() will be a nop, but we'll do the
		 * right thing with respect to the rest of the chain.
		 */
		ob = allocb(vxlan_alloc_size, 0);
		if (ob == NULL)
			return (ENOMEM);

		ob->b_wptr = DB_LIM(ob);
		ob->b_rptr = ob->b_wptr;
		ob->b_cont = mp;
	} else {
		ob = mp;
	}
	ob->b_rptr -= VXLAN_HDR_LEN;

	vxh = (vxlan_hdr_t *)ob->b_rptr;
	vxh->vxlan_flags = ntohl(VXLAN_F_VDI);
	vxh->vxlan_id = htonl((uint32_t)einfop->ovdi_id << VXLAN_ID_SHIFT);
	*outp = ob;

	return (0);
}

/* ARGSUSED */
static int
vxlan_o_decap(void *arg, mblk_t *mp, ovep_encap_info_t *dinfop)
{
	vxlan_hdr_t *vxh;

	if (MBLKL(mp) < sizeof (vxlan_hdr_t))
		return (EINVAL);
	vxh = (vxlan_hdr_t *)mp->b_rptr;
	if ((ntohl(vxh->vxlan_flags) & VXLAN_F_VDI) == 0)
		return (EINVAL);

	dinfop->ovdi_id = ntohl(vxh->vxlan_id) >> VXLAN_ID_SHIFT;
	dinfop->ovdi_hdr_size = VXLAN_HDR_LEN;

	return (0);
}

static int
vxlan_o_getprop(void *arg, const char *pr_name, void *buf, uint32_t *bufsize)
{
	vxlan_t *vxl = arg;

	/* vxlan/listen_ip */
	if (strcmp(pr_name, vxlan_props[0]) == 0) {
		if (*bufsize < sizeof (struct in6_addr))
			return (EOVERFLOW);

		mutex_enter(&vxl->vxl_lock);
		if (vxl->vxl_hladdr == B_FALSE) {
			*bufsize = 0;
		} else {
			bcopy(&vxl->vxl_laddr, buf, sizeof (struct in6_addr));
			*bufsize = sizeof (struct in6_addr);
		}
		mutex_exit(&vxl->vxl_lock);
		return (0);
	}

	/* vxlan/listen_port */
	if (strcmp(pr_name, vxlan_props[1]) == 0) {
		uint64_t val;
		if (*bufsize < sizeof (uint64_t))
			return (EOVERFLOW);

		mutex_enter(&vxl->vxl_lock);
		val = vxl->vxl_lport;
		bcopy(&val, buf, sizeof (uint64_t));
		*bufsize = sizeof (uint64_t);
		mutex_exit(&vxl->vxl_lock);
		return (0);
	}

	return (EINVAL);
}

static int
vxlan_o_setprop(void *arg, const char *pr_name, const void *buf,
    uint32_t bufsize)
{
	vxlan_t *vxl = arg;

	/* vxlan/listen_ip */
	if (strcmp(pr_name, vxlan_props[0]) == 0) {
		const struct in6_addr *ipv6 = buf;
		if (bufsize != sizeof (struct in6_addr))
			return (EINVAL);

		if (IN6_IS_ADDR_V4COMPAT(ipv6))
			return (EINVAL);

		if (IN6_IS_ADDR_MULTICAST(ipv6))
			return (EINVAL);

		if (IN6_IS_ADDR_6TO4(ipv6))
			return (EINVAL);

		if (IN6_IS_ADDR_V4MAPPED(ipv6)) {
			ipaddr_t v4;
			IN6_V4MAPPED_TO_IPADDR(ipv6, v4);
			if (IN_MULTICAST(ntohl(v4)))
				return (EINVAL);
		}

		mutex_enter(&vxl->vxl_lock);
		vxl->vxl_hladdr = B_TRUE;
		bcopy(ipv6, &vxl->vxl_laddr, sizeof (struct in6_addr));
		mutex_exit(&vxl->vxl_lock);

		return (0);
	}

	/* vxlan/listen_port */
	if (strcmp(pr_name, vxlan_props[1]) == 0) {
		const uint64_t *valp = buf;
		if (bufsize != 8)
			return (EINVAL);

		if (*valp == 0 || *valp > UINT16_MAX)
			return (EINVAL);

		mutex_enter(&vxl->vxl_lock);
		vxl->vxl_lport = *valp;
		mutex_exit(&vxl->vxl_lock);
		return (0);
	}
	return (EINVAL);
}

static int
vxlan_o_propinfo(const char *pr_name, overlay_prop_handle_t phdl)
{
	/* vxlan/listen_ip */
	if (strcmp(pr_name, vxlan_props[0]) == 0) {
		overlay_prop_set_name(phdl, vxlan_props[0]);
		overlay_prop_set_prot(phdl, OVERLAY_PROP_PERM_RRW);
		overlay_prop_set_type(phdl, OVERLAY_PROP_T_IP);
		overlay_prop_set_nodefault(phdl);
		return (0);
	}

	if (strcmp(pr_name, vxlan_props[1]) == 0) {
		overlay_prop_set_name(phdl, vxlan_props[1]);
		overlay_prop_set_prot(phdl, OVERLAY_PROP_PERM_RRW);
		overlay_prop_set_type(phdl, OVERLAY_PROP_T_UINT);
		(void) overlay_prop_set_default(phdl, &vxlan_defport,
		    sizeof (vxlan_defport));
		overlay_prop_set_range_uint32(phdl, 1, UINT16_MAX);
		return (0);
	}

	return (EINVAL);
}

static struct overlay_plugin_ops vxlan_o_ops = {
	0,
	vxlan_o_init,
	vxlan_o_fini,
	vxlan_o_encap,
	vxlan_o_decap,
	vxlan_o_socket,
	vxlan_o_sockopt,
	vxlan_o_getprop,
	vxlan_o_setprop,
	vxlan_o_propinfo
};

static struct modlmisc vxlan_modlmisc = {
	&mod_miscops,
	"VXLAN encap plugin"
};

static struct modlinkage vxlan_modlinkage = {
	MODREV_1,
	&vxlan_modlmisc
};

int
_init(void)
{
	int err;
	overlay_plugin_register_t *ovrp;

	ovrp = overlay_plugin_alloc(OVEP_VERSION);
	if (ovrp == NULL)
		return (ENOTSUP);
	ovrp->ovep_name = vxlan_ident;
	ovrp->ovep_ops = &vxlan_o_ops;
	ovrp->ovep_id_size = VXLAN_ID_LEN;
	ovrp->ovep_flags = OVEP_F_VLAN_TAG;
	ovrp->ovep_dest = OVERLAY_PLUGIN_D_IP | OVERLAY_PLUGIN_D_PORT;
	ovrp->ovep_props = vxlan_props;

	if ((err = overlay_plugin_register(ovrp)) == 0) {
		if ((err = mod_install(&vxlan_modlinkage)) != 0) {
			(void) overlay_plugin_unregister(vxlan_ident);
		}
	}

	overlay_plugin_free(ovrp);
	return (err);
}

int
_info(struct modinfo *modinfop)
{
	return (mod_info(&vxlan_modlinkage, modinfop));
}

int
_fini(void)
{
	int err;

	if ((err = overlay_plugin_unregister(vxlan_ident)) != 0)
		return (err);

	return (mod_remove(&vxlan_modlinkage));
}