Loading...
   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
/*
 * Copyright (c) 2003-2025 Apple Inc. All rights reserved.
 *
 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
 *
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. The rights granted to you under the License
 * may not be used to create, or enable the creation or redistribution of,
 * unlawful or unlicensed copies of an Apple operating system, or to
 * circumvent, violate, or enable the circumvention or violation of, any
 * terms of an Apple operating system software license agreement.
 *
 * Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this file.
 *
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 *
 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
 */

/*
 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the project nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/malloc.h>
#include <sys/mbuf.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/time.h>
#include <sys/kernel.h>
#include <sys/errno.h>
#include <sys/syslog.h>
#include <sys/queue.h>
#include <sys/mcache.h>
#include <sys/protosw.h>

#include <dev/random/randomdev.h>

#include <kern/locks.h>
#include <kern/uipc_domain.h>
#include <kern/zalloc.h>
#include <machine/machine_routines.h>

#include <net/droptap.h>
#include <net/if.h>
#include <net/if_var.h>
#include <net/if_types.h>
#include <net/if_dl.h>
#include <net/route.h>
#include <net/radix.h>

#include <netinet/in.h>
#include <netinet6/in6_var.h>
#include <netinet6/in6_ifattach.h>
#include <netinet/ip6.h>
#include <netinet6/ip6_var.h>
#include <netinet6/nd6.h>
#include <netinet/icmp6.h>
#include <netinet6/scope6_var.h>

#include <net/net_osdep.h>

#include <net/sockaddr_utils.h>

static void defrouter_addreq(struct nd_defrouter *, struct nd_route_info *, boolean_t);
static struct nd_defrouter *defrtrlist_update_common(struct nd_defrouter *,
    struct nd_drhead *, boolean_t);
static void pfxrtr_add(struct nd_prefix *, struct nd_defrouter *);
static void pfxrtr_del(struct nd_pfxrouter *, struct nd_prefix *);
static struct nd_pfxrouter *find_pfxlist_reachable_router(struct nd_prefix *);
static void nd6_rtmsg(u_char, struct rtentry *);

static int nd6_prefix_onlink_common(struct nd_prefix *, boolean_t,
    unsigned int);
static struct nd_prefix *nd6_prefix_equal_lookup(struct nd_prefix *, boolean_t);
static void nd6_prefix_sync(struct ifnet *);

static void in6_init_address_ltimes(struct in6_addrlifetime *);
static int rt6_deleteroute(struct radix_node *, void *);

static struct nd_defrouter *nddr_alloc(zalloc_flags_t);
static void nddr_free(struct nd_defrouter *);
static void nddr_trace(struct nd_defrouter *, int);

static struct nd_prefix *ndpr_alloc(int);
static void ndpr_free(struct nd_prefix *);
static void ndpr_trace(struct nd_prefix *, int);

extern int nd6_recalc_reachtm_interval;

static struct ifnet *nd6_defifp = NULL;
int nd6_defifindex = 0;
static unsigned int nd6_defrouter_genid;

int ip6_use_tempaddr = IP6_USE_TMPADDR_DEFAULT; /* use temp addr by default for testing now */
int ip6_ula_use_tempaddr = IP6_ULA_USE_TMPADDR_DEFAULT;

int nd6_accept_6to4 = 1;

int ip6_desync_factor;
u_int32_t ip6_temp_preferred_lifetime = DEF_TEMP_PREFERRED_LIFETIME;
u_int32_t ip6_temp_valid_lifetime = DEF_TEMP_VALID_LIFETIME;
/*
 * shorter lifetimes for debugging purposes.
 *	u_int32_t ip6_temp_preferred_lifetime = 800;
 *	static u_int32_t ip6_temp_valid_lifetime = 1800;
 */
int ip6_temp_regen_advance = TEMPADDR_REGEN_ADVANCE;

/* Serialization variables for single thread access to nd_prefix */
static boolean_t nd_prefix_busy;
static void *nd_prefix_waitchan = &nd_prefix_busy;
static int nd_prefix_waiters = 0;

/* Serialization variables for single thread access to nd_defrouter */
static boolean_t nd_defrouter_busy;
static void *nd_defrouter_waitchan = &nd_defrouter_busy;
static int nd_defrouter_waiters = 0;

void
nd_prefix_busy_wait(void)
{
	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);

	while (nd_prefix_busy) {
		nd_prefix_waiters++;
		msleep(nd_prefix_waitchan, nd6_mutex, (PZERO - 1),
		    __func__, NULL);
		LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
	}
	nd_prefix_busy = TRUE;
}

void
nd_prefix_busy_signal(void)
{
	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);

	VERIFY(nd_prefix_busy);
	nd_prefix_busy = FALSE;
	if (nd_prefix_waiters > 0) {
		nd_prefix_waiters = 0;
		wakeup(nd_prefix_waitchan);
	}
}

#define equal(a1, a2) (bcmp((caddr_t)(a1), (caddr_t)(a2), (a1)->sa_len) == 0)
/* RTPREF_MEDIUM has to be 0! */
#define RTPREF_HIGH     1
#define RTPREF_MEDIUM   0
#define RTPREF_LOW      (-1)
#define RTPREF_RESERVED (-2)
#define RTPREF_INVALID  (-3)    /* internal */

#define NDPR_TRACE_HIST_SIZE    32              /* size of trace history */

/* For gdb */
__private_extern__ unsigned int ndpr_trace_hist_size = NDPR_TRACE_HIST_SIZE;

struct nd_prefix_dbg {
	struct nd_prefix        ndpr_pr;                /* nd_prefix */
	u_int16_t               ndpr_refhold_cnt;       /* # of ref */
	u_int16_t               ndpr_refrele_cnt;       /* # of rele */
	/*
	 * Circular lists of ndpr_addref and ndpr_remref callers.
	 */
	ctrace_t                ndpr_refhold[NDPR_TRACE_HIST_SIZE];
	ctrace_t                ndpr_refrele[NDPR_TRACE_HIST_SIZE];
};

static unsigned int ndpr_debug;                 /* debug flags */
ZONE_DECLARE(ndpr_zone, struct nd_prefix);
#define NDPR_ZONE_NAME  "nd6_prefix"            /* zone name */
zone_t ndpr_zone;                               /* zone for nd_prefix */

#define NDDR_TRACE_HIST_SIZE    32              /* size of trace history */

/* For gdb */
__private_extern__ unsigned int nddr_trace_hist_size = NDDR_TRACE_HIST_SIZE;

struct nd_defrouter_dbg {
	struct nd_defrouter     nddr_dr;                /* nd_defrouter */
	uint16_t                nddr_refhold_cnt;       /* # of ref */
	uint16_t                nddr_refrele_cnt;       /* # of rele */
	/*
	 * Circular lists of nddr_addref and nddr_remref callers.
	 */
	ctrace_t                nddr_refhold[NDDR_TRACE_HIST_SIZE];
	ctrace_t                nddr_refrele[NDDR_TRACE_HIST_SIZE];
};

static unsigned int nddr_debug;                 /* debug flags */
ZONE_DECLARE(nddr_zone, struct nd_defrouter);
#define NDDR_ZONE_NAME  "nd6_defrouter"         /* zone name */
zone_t nddr_zone;                               /* zone for nd_defrouter */

static KALLOC_TYPE_DEFINE(ndprtr_zone, struct nd_pfxrouter, NET_KT_DEFAULT);

#define TWOHOUR         (120*60)
extern int nd6_process_rti;                     /* Default to 0 for now */


static void
nd6_prefix_glb_init(void)
{
	PE_parse_boot_argn("ifa_debug", &ndpr_debug, sizeof(ndpr_debug));
	vm_size_t ndpr_size = (ndpr_debug == 0) ? sizeof(struct nd_prefix) :
	    sizeof(struct nd_prefix_dbg);
	ndpr_zone = zone_create(NDPR_ZONE_NAME, ndpr_size, ZC_ZFREE_CLEARMEM);
}

static void
nd6_defrouter_glb_init(void)
{
	PE_parse_boot_argn("ifa_debug", &nddr_debug, sizeof(nddr_debug));
	vm_size_t nddr_size = (nddr_debug == 0) ? sizeof(struct nd_defrouter) :
	    sizeof(struct nd_defrouter_dbg);
	nddr_zone = zone_create(NDDR_ZONE_NAME, nddr_size, ZC_ZFREE_CLEARMEM);
}

void
nd6_rtr_init(void)
{
	nd6_prefix_glb_init();
	nd6_defrouter_glb_init();
}

/*
 * Receive Router Solicitation Message - just for routers.
 * Router solicitation/advertisement is mostly managed by userland program
 * (rtadvd) so here we have no function like nd6_ra_output().
 *
 * Based on RFC 2461
 */
void
nd6_rs_input(
	struct  mbuf *m,
	int off,
	int icmp6len)
{
	struct ifnet *ifp = m->m_pkthdr.rcvif;
	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
	struct nd_router_solicit *nd_rs = NULL;
	struct in6_addr saddr6 = ip6->ip6_src;
	char *lladdr = NULL;
	int lladdrlen = 0;
	union nd_opts ndopts = {};
	drop_reason_t drop_reason = DROP_REASON_UNSPECIFIED;

	/* Expect 32-bit aligned data pointer on strict-align platforms */
	MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);

	/* If I'm not a router, ignore it. */
	if (!ip6_forwarding || ifp->if_ipv6_router_mode == IPV6_ROUTER_MODE_DISABLED) {
		goto freeit;
	}

	/* Sanity checks */
	if (ip6->ip6_hlim != IPV6_MAXHLIM) {
		nd6log0(error,
		    "nd6_rs_input: invalid hlim (%d) from %s to %s on %s\n",
		    ip6->ip6_hlim, ip6_sprintf(&ip6->ip6_src),
		    ip6_sprintf(&ip6->ip6_dst), if_name(ifp));
		drop_reason = DROP_REASON_IP6_BAD_HLIM;
		goto bad;
	}

	/*
	 * Don't update the neighbor cache, if src = :: or a non-neighbor.
	 * The former case indicates that the src has no IP address assigned
	 * yet.  See nd6_ns_input() for the latter case.
	 */
	if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
		goto freeit;
	} else {
		struct sockaddr_in6 src_sa6;

		SOCKADDR_ZERO(&src_sa6, sizeof(src_sa6));
		src_sa6.sin6_family = AF_INET6;
		src_sa6.sin6_len = sizeof(src_sa6);
		src_sa6.sin6_addr = ip6->ip6_src;
		src_sa6.sin6_scope_id = (!in6_embedded_scope && IN6_IS_SCOPE_EMBED(&src_sa6.sin6_addr)) ? ip6_input_getsrcifscope(m) : IFSCOPE_NONE;
		if (!nd6_is_addr_neighbor(&src_sa6, ifp, 0)) {
			nd6log(info, "nd6_rs_input: "
			    "RS packet from non-neighbor\n");
			goto freeit;
		}
	}

	IP6_EXTHDR_CHECK(m, off, icmp6len, return );
	ip6 = mtod(m, struct ip6_hdr *);
	nd_rs = (struct nd_router_solicit *)((caddr_t)ip6 + off);

	icmp6len -= sizeof(*nd_rs);

	nd6_option_init(nd_rs + 1, icmp6len, &ndopts);
	if (nd6_options(&ndopts) < 0) {
		nd6log(info,
		    "nd6_rs_input: invalid ND option, ignored\n");
		/* nd6_options have incremented stats */
		goto freeit;
	}

	if (ndopts.nd_opts_src_lladdr) {
		ND_OPT_LLADDR(ndopts.nd_opts_src_lladdr, nd_opt_len, lladdr, lladdrlen);
	}

	if (lladdr && ((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
		nd6log(info,
		    "nd6_rs_input: lladdrlen mismatch for %s "
		    "(if %d, RS packet %d)\n",
		    ip6_sprintf(&saddr6), ifp->if_addrlen, lladdrlen - 2);
		drop_reason = DROP_REASON_IP6_RS_BAD_LLADDR_LEN;
		goto bad;
	}

	nd6_cache_lladdr(ifp, &saddr6, lladdr, lladdrlen, ND_ROUTER_SOLICIT, 0, NULL);

freeit:
	m_freem(m);
	return;

bad:
	icmp6stat.icp6s_badrs++;
	m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, drop_reason, NULL, 0);
}

#define ND_OPT_LEN_TO_BYTE_SCALE        3 /* ND opt len is in units of 8 octets */

#define ND_OPT_LEN_RTI_MIN              1
#define ND_OPT_LEN_RTI_MAX              3
#define ND_OPT_RTI_PFXLEN_MAX           128
/*
 * Receive Router Advertisement Message.
 *
 * Based on RFC 2461
 * TODO: on-link bit on prefix information
 * TODO: ND_RA_FLAG_{OTHER,MANAGED} processing
 */
void
nd6_ra_input(
	struct mbuf *m,
	int off,
	int icmp6len)
{
	ifnet_ref_t ifp = m->m_pkthdr.rcvif;
	struct nd_ifinfo *ndi = NULL;
	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
	struct nd_router_advert *nd_ra;
	struct in6_addr saddr6 = ip6->ip6_src;
	int mcast = 0;
	union nd_opts ndopts;
	struct nd_defrouter *dr = NULL;
	u_int32_t mtu = 0;
	char *lladdr = NULL;
	u_int32_t lladdrlen = 0;
	struct nd_prefix_list *nd_prefix_list_head = NULL;
	u_int32_t nd_prefix_list_length = 0;
	struct in6_ifaddr *ia6 = NULL;
	struct nd_prefix_list *__single prfl;
	struct nd_defrouter dr0 = {0};
	u_int32_t advreachable;
	boolean_t rti_defrtr_processed = FALSE;
	boolean_t is_local_ra = FALSE;
	drop_reason_t drop_reason = DROP_REASON_UNSPECIFIED;

#if (DEVELOPMENT || DEBUG)
	if (ip6_accept_rtadv == 0) {
		goto freeit;
	}
#endif /* (DEVELOPMENT || DEBUG) */
	/* Expect 32-bit aligned data pointer on strict-align platforms */
	MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);

	/*
	 * Accept the RA if IFEF_ACCEPT_RTADV is set, or when
	 * the RA is locally generated.
	 *
	 * For convenience, we allow locally generated (rtadvd)
	 * RAs to be processed on the advertising interface, as a router.
	 *
	 * Note that we don't test against ip6_forwarding as we could be
	 * both a host and a router on different interfaces, hence the
	 * check against the per-interface flags.
	 */

	is_local_ra = (ia6 = ifa_foraddr6(&saddr6)) != NULL;
	if (ia6 != NULL) {
		ifa_remref(&ia6->ia_ifa);
		ia6 = NULL;
	}

	if ((ifp->if_eflags & IFEF_ACCEPT_RTADV) == 0) {
		if (is_local_ra) {
			/* accept locally generated RA */
		} else {
			nd6log(debug,
			    "%s: skipping RA from %s to %s on %s, accept RA: %d local RA=%d\n",
			    __func__,
			    ip6_sprintf(&ip6->ip6_src),
			    ip6_sprintf(&ip6->ip6_dst), if_name(ifp),
			    (ifp->if_eflags & IFEF_ACCEPT_RTADV) == 0, is_local_ra);
			goto freeit;
		}
	}

	if (ip6->ip6_hlim != IPV6_MAXHLIM) {
		nd6log0(error,
		    "nd6_ra_input: invalid hlim (%d) from %s to %s on %s\n",
		    ip6->ip6_hlim, ip6_sprintf(&ip6->ip6_src),
		    ip6_sprintf(&ip6->ip6_dst), if_name(ifp));
		drop_reason = DROP_REASON_IP6_BAD_HLIM;
		goto bad;
	}

	if (!IN6_IS_ADDR_LINKLOCAL(&saddr6)) {
		nd6log0(error,
		    "nd6_ra_input: src %s is not link-local\n",
		    ip6_sprintf(&saddr6));
		drop_reason = DROP_REASON_IP6_RA_NOT_LL;
		goto bad;
	}

	nd6log(debug, "%s: accepting RA from %s to %s on %s, local RA=%d\n",
	    __func__,
	    ip6_sprintf(&ip6->ip6_src),
	    ip6_sprintf(&ip6->ip6_dst), if_name(ifp), is_local_ra);

	IP6_EXTHDR_CHECK(m, off, icmp6len, return );
	ip6 = mtod(m, struct ip6_hdr *);
	nd_ra = (struct nd_router_advert *)((caddr_t)ip6 + off);

	icmp6len -= sizeof(*nd_ra);

	nd6_option_init(nd_ra + 1, icmp6len, &ndopts);
	if (nd6_options(&ndopts) < 0) {
		nd6log(info,
		    "nd6_ra_input: invalid ND option, ignored\n");
		/* nd6_options have incremented stats */
		goto freeit;
	}

	advreachable = nd_ra->nd_ra_reachable;

	/* remember if this is a multicasted advertisement */
	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
		mcast = 1;
	}

	ndi = ND_IFINFO(ifp);
	VERIFY(NULL != ndi && TRUE == ndi->initialized);
	lck_mtx_lock(&ndi->lock);
	/* unspecified or not? (RFC 2461 6.3.4) */
	if (advreachable) {
		advreachable = ntohl(advreachable);
		if (advreachable <= MAX_REACHABLE_TIME &&
		    ndi->basereachable != advreachable) {
			ndi->basereachable = advreachable;
			ndi->reachable = ND_COMPUTE_RTIME(ndi->basereachable);
			ndi->recalctm = nd6_recalc_reachtm_interval; /* reset */
		}
	}
	if (nd_ra->nd_ra_retransmit) {
		u_int32_t retrans = ntohl(nd_ra->nd_ra_retransmit);
		if (retrans < MAX_RA_RETRANS_TIMER) {
			ndi->retrans = retrans;
		} else {
			nd6log0(info, "%s: ignoring retrans time of %u in RA from %s ;"
			    " Using default of %u",
			    __func__,
			    retrans, ip6_sprintf(&ip6->ip6_src), ndi->retrans);
		}
	}
	if (nd_ra->nd_ra_curhoplimit) {
		if (ndi->chlim < nd_ra->nd_ra_curhoplimit) {
			ndi->chlim = nd_ra->nd_ra_curhoplimit;
		} else if (ndi->chlim != nd_ra->nd_ra_curhoplimit) {
			nd6log0(error,
			    "RA with a lower CurHopLimit sent from "
			    "%s on %s (current = %d, received = %d). "
			    "Ignored.\n", ip6_sprintf(&ip6->ip6_src),
			    if_name(ifp), ndi->chlim,
			    nd_ra->nd_ra_curhoplimit);
		}
	}
	lck_mtx_unlock(&ndi->lock);

	/* Initialize nd_defrouter invariants for RA processing */
	bzero(&dr0, sizeof(dr0));
	dr0.rtaddr = saddr6;
	dr0.ifp = ifp;
	if (is_local_ra == TRUE) {
		dr0.stateflags |= NDDRF_LOCAL;
	}

	/*
	 * Route Information Option (RIO)
	 */
	if (ndopts.nd_opts_rti && IFNET_IS_ETHERNET(ifp)) {
		struct nd_opt_hdr *rt = NULL;
		struct sockaddr_in6 rti_gateway = {0};

		rti_gateway.sin6_family = AF_INET6;
		rti_gateway.sin6_len = sizeof(rti_gateway);
		memcpy(&rti_gateway.sin6_addr, &saddr6, sizeof(rti_gateway.sin6_addr));

		for (rt = TAKE_ND_NEXT_OPT(ndopts.nd_opts_rti, nd_opts_rti, nd_opts_last);
		    rt <= (struct nd_opt_hdr *)ndopts.nd_opts_rti_end;
		    rt = (struct nd_opt_hdr *)((caddr_t)rt +
		    (rt->nd_opt_len << ND_OPT_LEN_TO_BYTE_SCALE))) {
			struct sockaddr_in6 rti_prefix = {};
			struct nd_route_info rti = {};
			struct nd_opt_route_info *rti_opt = NULL;
			u_int32_t rounded_prefix_bytes = 0;

			if (rt->nd_opt_type != ND_OPT_ROUTE_INFO) {
				continue;
			}

			rti_opt = (struct nd_opt_route_info *)rt;
			if ((rti_opt->nd_opt_rti_len < ND_OPT_LEN_RTI_MIN) ||
			    (rti_opt->nd_opt_rti_len > ND_OPT_LEN_RTI_MAX)) {
				nd6log(info,
				    "%s: invalid option "
				    "len %d for route information option, "
				    "ignored\n", __func__,
				    rti_opt->nd_opt_rti_len);
				continue;
			}

			if (rti_opt->nd_opt_rti_prefixlen > ND_OPT_RTI_PFXLEN_MAX) {
				nd6log(info,
				    "%s: invalid prefix length %d "
				    "in the route information option, "
				    "ignored\n", __func__, rti_opt->nd_opt_rti_prefixlen);
				continue;
			}

			if (rti_opt->nd_opt_rti_prefixlen != 0 &&
			    rti_opt->nd_opt_rti_prefixlen <= 64 &&
			    rti_opt->nd_opt_rti_len == ND_OPT_LEN_RTI_MIN) {
				nd6log(info,
				    "%s: invalid prefix "
				    "len %d is OOB for route information option, "
				    "with total option length of %d. Ignored.\n",
				    __func__, rti_opt->nd_opt_rti_prefixlen,
				    rti_opt->nd_opt_rti_len);
				continue;
			}

			if (rti_opt->nd_opt_rti_prefixlen > 64 &&
			    rti_opt->nd_opt_rti_len != ND_OPT_LEN_RTI_MAX) {
				nd6log(info,
				    "%s: invalid prefix "
				    "len %d is OOB for route information option, "
				    "with total option length of %d. Ignored.\n",
				    __func__, rti_opt->nd_opt_rti_prefixlen,
				    rti_opt->nd_opt_rti_len);
				continue;
			}

			if ((rti_opt->nd_opt_rti_flags & ND_RA_FLAG_RTPREF_MASK) ==
			    ND_RA_FLAG_RTPREF_RSV) {
				nd6log(info,
				    "%s: using reserved preference mask, "
				    "ignored\n", __func__);
				continue;
			}

			rti_prefix.sin6_family = AF_INET6;
			rti_prefix.sin6_len = sizeof(rti_prefix);

			rounded_prefix_bytes = rti_opt->nd_opt_rti_prefixlen >> 3;
			if (rti_opt->nd_opt_rti_prefixlen & 0x7) {
				rounded_prefix_bytes++;
			}
			memcpy(&rti_prefix.sin6_addr, rti_opt + 1, rounded_prefix_bytes);

			nd6log(info, "%s: received RA with route opt, "
			    "prefix %s/%u pref %u lifetime %u\n", __func__,
			    ip6_sprintf(&rti_prefix.sin6_addr),
			    rti_opt->nd_opt_rti_prefixlen,
			    rti_opt->nd_opt_rti_flags,
			    ntohl(rti_opt->nd_opt_rti_lifetime));

			dr0.flags  = rti_opt->nd_opt_rti_flags;

			/*
			 * https://tools.ietf.org/html/rfc4191#section-3.1
			 * Type C Host requirements:
			 * The Router Preference and Lifetime values in a
			 * ::/0 Route Information Option override the
			 * preference and lifetime values in the Router
			 * Advertisement header.
			 */
			if (IN6_IS_ADDR_UNSPECIFIED(&rti_prefix.sin6_addr)
			    && rti_opt->nd_opt_rti_prefixlen == 0) {
				rti_defrtr_processed = TRUE;
				/*
				 * If the router lifetime is 0, set the state flag
				 * to dummy, so that it is skipped and not used as a
				 * default router.
				 * Set the lifetime to 2 hrs to make sure we get rid
				 * of the router eventually if this was indeed for a router
				 * going away.
				 *
				 * We partly have to do this to ensure advertised prefixes
				 * stay onlink.
				 * A periodic RA would also keep refreshing the cached
				 * neighbor cache entry if it contains source link layer
				 * information.
				 */
				if (rti_opt->nd_opt_rti_lifetime == 0) {
					dr0.rtlifetime = TWOHOUR;
					dr0.stateflags |= NDDRF_INELIGIBLE;
				} else {
					dr0.rtlifetime = ntohl(rti_opt->nd_opt_rti_lifetime);
				}
				dr0.expire = net_uptime() + dr0.rtlifetime;

				lck_mtx_lock(nd6_mutex);
				dr = defrtrlist_update(&dr0, NULL);
				if (dr != NULL) {
					dr->is_reachable = TRUE;
				}
				lck_mtx_unlock(nd6_mutex);
				continue;
			}

			dr0.rtlifetime = ntohl(rti_opt->nd_opt_rti_lifetime);
			dr0.expire = net_uptime() + dr0.rtlifetime;
			bzero(&rti, sizeof(rti));
			rti.nd_rti_prefixlen = rti_opt->nd_opt_rti_prefixlen;
			rti.nd_rti_prefix = rti_prefix.sin6_addr;
			nd6_rtilist_update(&rti, &dr0);
		}
	}

	if (!rti_defrtr_processed) {
		dr0.flags = nd_ra->nd_ra_flags_reserved;

		/*
		 * If the router lifetime is 0, set the state flag
		 * to dummy, so that it is skipped and not used as a
		 * default router.
		 * Set the lifetime to 2 hrs to make sure we get rid
		 * of the router eventually if this was indeed for a router
		 * going away.
		 *
		 * We partly have to do this to ensure advertised prefixes
		 * stay onlink.
		 * A periodic RA would also keep refreshing the cached
		 * neighbor cache entry if it contains source link layer
		 * information.
		 */
		if (nd_ra->nd_ra_router_lifetime == 0) {
			dr0.rtlifetime = TWOHOUR;
			dr0.stateflags |= NDDRF_INELIGIBLE;
		} else {
			dr0.rtlifetime = ntohs(nd_ra->nd_ra_router_lifetime);
		}
		dr0.expire = net_uptime() + dr0.rtlifetime;
		lck_mtx_lock(nd6_mutex);
		dr = defrtrlist_update(&dr0, NULL);
		if (dr != NULL) {
			dr->is_reachable = TRUE;
		}
		lck_mtx_unlock(nd6_mutex);
	}

	/*
	 * prefix (PIO)
	 */
	if (ndopts.nd_opts_pi) {
		struct nd_opt_hdr *pt;
		struct nd_opt_prefix_info *__single pi = NULL;
		struct nd_prefix pr;

		for (pt = TAKE_ND_NEXT_OPT(ndopts.nd_opts_pi, nd_opts_pi, nd_opts_last);
		    pt <= (struct nd_opt_hdr *)ndopts.nd_opts_pi_end;
		    pt = (struct nd_opt_hdr *)((caddr_t)pt +
		    (pt->nd_opt_len << ND_OPT_LEN_TO_BYTE_SCALE))) {
			struct in6_addr pi_mask;
			bzero(&pi_mask, sizeof(pi_mask));

			if (pt->nd_opt_type != ND_OPT_PREFIX_INFORMATION) {
				continue;
			}
			pi = (struct nd_opt_prefix_info *)pt;

			if (pi->nd_opt_pi_len != 4) {
				nd6log(info,
				    "nd6_ra_input: invalid option "
				    "len %d for prefix information option, "
				    "ignored\n", pi->nd_opt_pi_len);
				continue;
			}

			if (128 < pi->nd_opt_pi_prefix_len) {
				nd6log(info,
				    "nd6_ra_input: invalid prefix "
				    "len %d for prefix information option, "
				    "ignored\n", pi->nd_opt_pi_prefix_len);
				continue;
			}

			/*
			 * To ignore ::/64 make sure bits beyond prefixlen
			 * are set to zero
			 */
			in6_prefixlen2mask(&pi_mask, pi->nd_opt_pi_prefix_len);
			pi->nd_opt_pi_prefix.s6_addr32[0] &= pi_mask.s6_addr32[0];
			pi->nd_opt_pi_prefix.s6_addr32[1] &= pi_mask.s6_addr32[1];
			pi->nd_opt_pi_prefix.s6_addr32[2] &= pi_mask.s6_addr32[2];
			pi->nd_opt_pi_prefix.s6_addr32[3] &= pi_mask.s6_addr32[3];

			if (IN6_IS_ADDR_UNSPECIFIED(&pi->nd_opt_pi_prefix) ||
			    IN6_IS_ADDR_MULTICAST(&pi->nd_opt_pi_prefix) ||
			    IN6_IS_ADDR_LINKLOCAL(&pi->nd_opt_pi_prefix)) {
				nd6log(info,
				    "%s: invalid prefix %s, ignored\n",
				    __func__,
				    ip6_sprintf(&pi->nd_opt_pi_prefix));
				continue;
			}

			bzero(&pr, sizeof(pr));
			lck_mtx_init(&pr.ndpr_lock, &ifa_mtx_grp, &ifa_mtx_attr);
			NDPR_LOCK(&pr);
			pr.ndpr_prefix.sin6_family = AF_INET6;
			pr.ndpr_prefix.sin6_len = sizeof(pr.ndpr_prefix);
			pr.ndpr_prefix.sin6_addr = pi->nd_opt_pi_prefix;
			pr.ndpr_ifp = m->m_pkthdr.rcvif;

			pr.ndpr_raf_onlink = (pi->nd_opt_pi_flags_reserved &
			    ND_OPT_PI_FLAG_ONLINK) ? 1 : 0;
			pr.ndpr_raf_auto = (pi->nd_opt_pi_flags_reserved &
			    ND_OPT_PI_FLAG_AUTO) ? 1 : 0;
			pr.ndpr_plen = pi->nd_opt_pi_prefix_len;
			pr.ndpr_vltime = ntohl(pi->nd_opt_pi_valid_time);
			pr.ndpr_pltime =
			    ntohl(pi->nd_opt_pi_preferred_time);

			/*
			 * Exceptions to stateless autoconfiguration processing:
			 * + nd6_accept_6to4 == 0 && address has 6to4 prefix
			 * + ip6_only_allow_rfc4193_prefix != 0 &&
			 * address not RFC 4193
			 */
			if (ip6_only_allow_rfc4193_prefix &&
			    !IN6_IS_ADDR_UNIQUE_LOCAL(&pi->nd_opt_pi_prefix)) {
				nd6log(info,
				    "nd6_ra_input: no SLAAC on prefix %s "
				    "[not RFC 4193]\n",
				    ip6_sprintf(&pi->nd_opt_pi_prefix));
				pr.ndpr_raf_auto = 0;
			} else if (!nd6_accept_6to4 &&
			    IN6_IS_ADDR_6TO4(&pi->nd_opt_pi_prefix)) {
				nd6log(info,
				    "%s: no SLAAC on prefix %s "
				    "[6to4]\n", __func__,
				    ip6_sprintf(&pi->nd_opt_pi_prefix));
				pr.ndpr_raf_auto = 0;
			}

			if (in6_init_prefix_ltimes(&pr)) {
				NDPR_UNLOCK(&pr);
				lck_mtx_destroy(&pr.ndpr_lock, &ifa_mtx_grp);
				continue; /* prefix lifetime init failed */
			} else {
				NDPR_UNLOCK(&pr);
			}
			(void) prelist_update(&pr, dr, m, mcast);
			lck_mtx_destroy(&pr.ndpr_lock, &ifa_mtx_grp);

			/*
			 * We have to copy the values out after the
			 * prelist_update call since some of these values won't
			 * be properly set until after the router advertisement
			 * updating can vet the values.
			 */
			prfl = kalloc_type(struct nd_prefix_list,
			    Z_WAITOK | Z_ZERO | Z_NOFAIL);

			/* this is only for nd6_post_msg(), otherwise unused */
			SOCKADDR_COPY(&pr.ndpr_prefix, &prfl->pr.ndpr_prefix,
			    sizeof(prfl->pr.ndpr_prefix));
			prfl->pr.ndpr_raf = pr.ndpr_raf;
			prfl->pr.ndpr_plen = pr.ndpr_plen;
			prfl->pr.ndpr_vltime = pr.ndpr_vltime;
			prfl->pr.ndpr_pltime = pr.ndpr_pltime;
			prfl->pr.ndpr_expire = pr.ndpr_expire;
			prfl->pr.ndpr_base_calendartime =
			    pr.ndpr_base_calendartime;
			prfl->pr.ndpr_base_uptime = pr.ndpr_base_uptime;
			prfl->pr.ndpr_stateflags = pr.ndpr_stateflags;
			prfl->pr.ndpr_addrcnt = pr.ndpr_addrcnt;
			prfl->pr.ndpr_ifp = pr.ndpr_ifp;

			prfl->next = nd_prefix_list_head;
			nd_prefix_list_head = prfl;
			nd_prefix_list_length++;
		}
	}


	/*
	 * MTU
	 */
	if (ndopts.nd_opts_mtu && ndopts.nd_opts_mtu->nd_opt_mtu_len == 1) {
		mtu = ntohl(ndopts.nd_opts_mtu->nd_opt_mtu_mtu);
		/* lower bound */
		if (mtu < IPV6_MMTU) {
			nd6log(info, "nd6_ra_input: bogus mtu option "
			    "mtu=%d sent from %s, ignoring\n",
			    mtu, ip6_sprintf(&ip6->ip6_src));
			goto skip;
		}

		lck_mtx_lock(&ndi->lock);
		/* upper bound */
		if (ndi->maxmtu) {
			if (mtu <= ndi->maxmtu) {
				int change = (ndi->linkmtu != mtu);

				ndi->linkmtu = mtu;
				lck_mtx_unlock(&ndi->lock);
				if (change) { /* in6_maxmtu may change */
					in6_setmaxmtu();
				}
			} else {
				nd6log(info, "nd6_ra_input: bogus mtu "
				    "mtu=%d sent from %s; "
				    "exceeds maxmtu %d, ignoring\n",
				    mtu, ip6_sprintf(&ip6->ip6_src),
				    ndi->maxmtu);
				lck_mtx_unlock(&ndi->lock);
			}
		} else {
			lck_mtx_unlock(&ndi->lock);
			nd6log(info, "nd6_ra_input: mtu option "
			    "mtu=%d sent from %s; maxmtu unknown, "
			    "ignoring\n",
			    mtu, ip6_sprintf(&ip6->ip6_src));
		}
	}

skip:

	/*
	 * Source link layer address
	 */
	if (ndopts.nd_opts_src_lladdr) {
		ND_OPT_LLADDR(ndopts.nd_opts_src_lladdr, nd_opt_len, lladdr, lladdrlen);
	}

	if (lladdr && ((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
		nd6log(info,
		    "nd6_ra_input: lladdrlen mismatch for %s "
		    "(if %d, RA packet %d)\n",
		    ip6_sprintf(&saddr6), ifp->if_addrlen, lladdrlen - 2);
		drop_reason = DROP_REASON_IP6_RA_BAD_LLADDR_LEN;
		goto bad;
	}

	if (dr && dr->stateflags & NDDRF_MAPPED) {
		saddr6 = dr->rtaddr_mapped;
	}

	nd6_cache_lladdr(ifp, &saddr6, lladdr, (int)lladdrlen,
	    ND_ROUTER_ADVERT, 0, NULL);

	/* Post message */
	nd6_post_msg(KEV_ND6_RA, nd_prefix_list_head, nd_prefix_list_length,
	    mtu);

	/*
	 * Installing a link-layer address might change the state of the
	 * router's neighbor cache, which might also affect our on-link
	 * detection of adveritsed prefixes.
	 */
	lck_mtx_lock(nd6_mutex);
	pfxlist_onlink_check(false);
	lck_mtx_unlock(nd6_mutex);

freeit:
	if (m) {
		m_freem(m);
	}
	if (dr) {
		NDDR_REMREF(dr);
	}

	prfl = NULL;
	while ((prfl = nd_prefix_list_head) != NULL) {
		nd_prefix_list_head = prfl->next;
		kfree_type(struct nd_prefix_list, prfl);
	}

	return;

bad:
	m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, drop_reason, NULL, 0);
	m = NULL;

	icmp6stat.icp6s_badra++;
	goto freeit;
}

/*
 * default router list processing sub routines
 */

/* tell the change to user processes watching the routing socket. */
static void
nd6_rtmsg(u_char cmd, struct rtentry *rt)
{
	struct rt_addrinfo info;
	struct ifnet *ifp = rt->rt_ifp;

	RT_LOCK_ASSERT_HELD(rt);

	bzero((caddr_t)&info, sizeof(info));
	/* It's not necessary to lock ifp for if_lladdr */
	info.rti_info[RTAX_DST] = rt_key(rt);
	info.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
	info.rti_info[RTAX_NETMASK] = rt_mask(rt);
	/*
	 * ifa_addr pointers for both should always be valid
	 * in this context; no need to hold locks.
	 */
	info.rti_info[RTAX_IFP] = ifp->if_lladdr->ifa_addr;
	info.rti_info[RTAX_IFA] = rt->rt_ifa->ifa_addr;

	rt_missmsg(cmd, &info, rt->rt_flags, 0);
}

static void
defrouter_addreq(struct nd_defrouter *new, struct nd_route_info *rti, boolean_t scoped)
{
	struct sockaddr_in6 key, mask, gate;
	struct rtentry *newrt __single = NULL;
	unsigned int ifscope;
	int err;
	struct nd_ifinfo *ndi = ND_IFINFO(new->ifp);
	int rtflags = RTF_GATEWAY;
	if (rti) {
		nd6log(info, "%s: defrouter_addreq prefix %s scoped=%d", __func__, ip6_sprintf(&rti->nd_rti_prefix), scoped);
	} else {
		nd6log(info, "%s: defrouter_addreq scoped=%d", __func__, scoped);
	}

	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_NOTOWNED);
	NDDR_LOCK_ASSERT_NOTHELD(new);
	/*
	 * We're free to lock and unlock NDDR because our callers
	 * are holding an extra reference for us.
	 */

	NDDR_LOCK(new);
	if (new->stateflags & NDDRF_INSTALLED) {
		nd6log(info, "%s: defrouter_addreq already installed", __func__);
		goto out;
	}
	if (new->ifp->if_ipv6_router_mode == IPV6_ROUTER_MODE_EXCLUSIVE) {
		nd6log2(info, "%s: ignoring router %s, scoped=%d, "
		    "static=%d on advertising interface\n", if_name(new->ifp),
		    ip6_sprintf(&new->rtaddr), scoped,
		    (new->stateflags & NDDRF_STATIC) ? 1 : 0);
		goto out;
	}

	nd6log2(info, "%s: adding default router %s, scoped=%d, "
	    "static=%d\n", if_name(new->ifp), ip6_sprintf(&new->rtaddr),
	    scoped, (new->stateflags & NDDRF_STATIC) ? 1 : 0);

	Bzero(&key, sizeof(key));
	Bzero(&mask, sizeof(mask));
	Bzero(&gate, sizeof(gate));

	key.sin6_len = mask.sin6_len = gate.sin6_len
	            = sizeof(struct sockaddr_in6);
	key.sin6_family = mask.sin6_family = gate.sin6_family = AF_INET6;

	if (rti != NULL) {
		key.sin6_addr = rti->nd_rti_prefix;
		in6_len2mask(&mask.sin6_addr, rti->nd_rti_prefixlen);
		if (rti->nd_rti_prefixlen == ND_OPT_RTI_PFXLEN_MAX) {
			rtflags |= RTF_HOST;
		} else {
			rtflags |= RTF_PRCLONING;
		}

		if (IN6_IS_SCOPE_EMBED(&key.sin6_addr) ||
		    IN6_IS_ADDR_LOOPBACK(&key.sin6_addr)) {
			nd6log2(info, "%s: ignoring router %s, rti prefix %s, scoped=%d, "
			    "static=%d on advertising interface\n", if_name(new->ifp),
			    ip6_sprintf(&new->rtaddr), ip6_sprintf(&rti->nd_rti_prefix), scoped,
			    (new->stateflags & NDDRF_STATIC) ? 1 : 0);
			goto out;
		}
	}

	if (new->stateflags & NDDRF_MAPPED) {
		gate.sin6_addr = new->rtaddr_mapped;
	} else {
		gate.sin6_addr = new->rtaddr;
	}
	if (!in6_embedded_scope && IN6_IS_SCOPE_EMBED(&gate.sin6_addr)) {
		gate.sin6_scope_id = new->ifp->if_index;
	}

	ifscope = scoped ? new->ifp->if_index : IFSCOPE_NONE;
	NDDR_UNLOCK(new);

	/*
	 * Cellular networks may have buggy deployments
	 * with gateway IPv6 link local address with same
	 * interface identifier as the one that has been
	 * assigned for the cellular context.
	 * If gateway is same as locally configured link local
	 * interface on cellular interface, generated a different one
	 * and store it in the nd_defrouter entry and use it to work
	 * on routing table
	 */
	if (new->ifp->if_type == IFT_CELLULAR &&
	    !(new->stateflags & NDDRF_STATIC) &&
	    !(new->stateflags & NDDRF_MAPPED) &&
	    IN6_IS_ADDR_LINKLOCAL(&gate.sin6_addr) &&
	    ndi && !(ndi->flags & ND6_IFF_PERFORMNUD)) {
		struct in6_ifaddr *tmp_ia6 = in6ifa_ifpforlinklocal(new->ifp, 0);

		if (tmp_ia6 != NULL &&
		    !(tmp_ia6->ia6_flags & IN6_IFF_NOTMANUAL) &&
		    IN6_ARE_ADDR_EQUAL(&tmp_ia6->ia_addr.sin6_addr,
		    &gate.sin6_addr)) {
			gate.sin6_addr.s6_addr8[15] += 1;
			new->rtaddr_mapped = gate.sin6_addr;
			new->stateflags |= NDDRF_MAPPED;

			nd6log(info, "%s: %s Default router %s mapped "
			    "to ", __func__, if_name(new->ifp), ip6_sprintf(&new->rtaddr));
			nd6log(info, "%s\n", ip6_sprintf(&new->rtaddr_mapped));
			nd6log(info, "%s\n", ip6_sprintf(&new->rtaddr_mapped));
		}

		if (tmp_ia6 != NULL) {
			ifa_remref(&tmp_ia6->ia_ifa);
		}
	}

	err = rtrequest_scoped(RTM_ADD, SA(&key), SA(&gate), SA(&mask),
	    rtflags, &newrt, ifscope);

	if (newrt) {
		RT_LOCK(newrt);
		nd6_rtmsg(RTM_ADD, newrt);      /* tell user process */
		RT_REMREF_LOCKED(newrt);
		RT_UNLOCK(newrt);
		NDDR_LOCK(new);
		new->stateflags |= NDDRF_INSTALLED;
		if (ifscope != IFSCOPE_NONE) {
			new->stateflags |= NDDRF_IFSCOPE;
		}
	} else {
		nd6log0(error, "%s: failed to add default router "
		    "%s on %s scoped %d (errno = %d)\n", __func__,
		    ip6_sprintf(&gate.sin6_addr), if_name(new->ifp),
		    (ifscope != IFSCOPE_NONE), err);
		NDDR_LOCK(new);
	}
	new->err = err;

out:
	NDDR_UNLOCK(new);
}

void
defrouter_set_reachability(
	struct in6_addr *addr,
	struct ifnet *ifp,
	boolean_t is_reachable)
{
	struct nd_defrouter *dr = NULL;

	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_NOTOWNED);

	lck_mtx_lock(nd6_mutex);
	dr = defrouter_lookup(NULL, addr, ifp);
	if (dr != NULL) {
		dr->is_reachable = is_reachable;
		NDDR_REMREF(dr);
	}
	lck_mtx_unlock(nd6_mutex);
}

struct nd_defrouter *
defrouter_lookup(
	struct nd_drhead *nd_router_listp,
	struct in6_addr *addr,
	struct ifnet *ifp)
{
	struct nd_defrouter *dr;

	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);

	if (nd_router_listp == NULL) {
		nd_router_listp = &nd_defrouter_list;
	}

	for (dr = TAILQ_FIRST(nd_router_listp); dr;
	    dr = TAILQ_NEXT(dr, dr_entry)) {
		NDDR_LOCK(dr);
		if (dr->ifp == ifp && IN6_ARE_ADDR_EQUAL(addr, &dr->rtaddr)) {
			NDDR_ADDREF(dr);
			NDDR_UNLOCK(dr);
			return dr;
		}
		NDDR_UNLOCK(dr);
	}

	return NULL;          /* search failed */
}

/* Remove the default route for a given router */
void
defrouter_delreq(struct nd_defrouter *dr, struct nd_route_info *rti)
{
	struct sockaddr_in6 key, mask, gate;
	struct rtentry *oldrt __single = NULL;
	unsigned int ifscope;
	int err;

	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_NOTOWNED);
	NDDR_LOCK_ASSERT_NOTHELD(dr);
	/*
	 * We're free to lock and unlock NDDR because our callers
	 * are holding an extra reference for us.
	 */
	NDDR_LOCK(dr);
	/* ifp would be NULL for the "drany" case */
	if (dr->ifp != NULL && !(dr->stateflags & NDDRF_INSTALLED)) {
		goto out;
	}

	nd6log2(info, "%s: removing default router %s, scoped=%d, "
	    "static=%d\n", dr->ifp != NULL ? if_name(dr->ifp) : "ANY",
	    ip6_sprintf(&dr->rtaddr), (dr->stateflags & NDDRF_IFSCOPE) ? 1 : 0,
	    (dr->stateflags & NDDRF_STATIC) ? 1 : 0);

	Bzero(&key, sizeof(key));
	Bzero(&mask, sizeof(mask));
	Bzero(&gate, sizeof(gate));

	key.sin6_len = mask.sin6_len = gate.sin6_len
	            = sizeof(struct sockaddr_in6);
	key.sin6_family = mask.sin6_family = gate.sin6_family = AF_INET6;


	if (rti != NULL) {
		key.sin6_addr = rti->nd_rti_prefix;
		in6_len2mask(&mask.sin6_addr, rti->nd_rti_prefixlen);
	}
	/*
	 * The router entry may be mapped to a different address.
	 * If that is the case, use the mapped address as gateway
	 * to do operation on the routing table.
	 * To get more context, read the related comment in
	 * defrouter_addreq
	 */
	if (dr->stateflags & NDDRF_MAPPED) {
		gate.sin6_addr = dr->rtaddr_mapped;
	} else {
		gate.sin6_addr = dr->rtaddr;
	}

	if (dr->ifp != NULL) {
		ifscope = (dr->stateflags & NDDRF_IFSCOPE) ?
		    dr->ifp->if_index : IFSCOPE_NONE;
	} else {
		ifscope = IFSCOPE_NONE;
	}
	NDDR_UNLOCK(dr);

	err = rtrequest_scoped(RTM_DELETE, SA(&key), SA(&gate), SA(&mask),
	    RTF_GATEWAY, &oldrt, ifscope);

	if (oldrt) {
		RT_LOCK(oldrt);
		nd6_rtmsg(RTM_DELETE, oldrt);
		RT_UNLOCK(oldrt);
		rtfree(oldrt);
	} else if (err != ESRCH) {
		nd6log0(error, "%s: failed to delete default router "
		    "%s on %s scoped %d (errno = %d)\n", __func__,
		    ip6_sprintf(&gate.sin6_addr), dr->ifp != NULL ?
		    if_name(dr->ifp) : "ANY", (ifscope != IFSCOPE_NONE), err);
	}
	NDDR_LOCK(dr);
	/* ESRCH means it's no longer in the routing table; ignore it */
	if (oldrt != NULL || err == ESRCH) {
		dr->stateflags &= ~NDDRF_INSTALLED;
		if (ifscope != IFSCOPE_NONE) {
			dr->stateflags &= ~NDDRF_IFSCOPE;
		}
	}
	dr->err = 0;
out:
	NDDR_UNLOCK(dr);
}


/*
 * remove all default routes from default router list
 */
void
defrouter_reset(void)
{
	struct nd_defrouter *dr, drany;

	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);

	dr = TAILQ_FIRST(&nd_defrouter_list);
	while (dr) {
		NDDR_LOCK(dr);
		if (dr->stateflags & NDDRF_INSTALLED) {
			NDDR_ADDREF(dr);
			NDDR_UNLOCK(dr);
			lck_mtx_unlock(nd6_mutex);
			defrouter_delreq(dr, NULL);
			lck_mtx_lock(nd6_mutex);
			NDDR_REMREF(dr);
			dr = TAILQ_FIRST(&nd_defrouter_list);
		} else {
			NDDR_UNLOCK(dr);
			dr = TAILQ_NEXT(dr, dr_entry);
		}
	}

	/* Nuke primary (non-scoped) default router */
	bzero(&drany, sizeof(drany));
	lck_mtx_init(&drany.nddr_lock, &ifa_mtx_grp, &ifa_mtx_attr);
	lck_mtx_unlock(nd6_mutex);
	defrouter_delreq(&drany, NULL);
	lck_mtx_destroy(&drany.nddr_lock, &ifa_mtx_grp);
	lck_mtx_lock(nd6_mutex);
}

int
defrtrlist_ioctl(u_long cmd, caddr_t __sized_by(IOCPARM_LEN(cmd)) data)
{
	struct nd_defrouter dr0;
	unsigned int ifindex;
	struct ifnet *dr_ifp;
	int error = 0, add = 0;

	/* XXX Handle mapped default router entries */
	switch (cmd) {
	case SIOCDRADD_IN6_32:          /* struct in6_defrouter_32 */
	case SIOCDRADD_IN6_64:          /* struct in6_defrouter_64 */
		++add;
		OS_FALLTHROUGH;
	case SIOCDRDEL_IN6_32:          /* struct in6_defrouter_32 */
	case SIOCDRDEL_IN6_64:          /* struct in6_defrouter_64 */
		bzero(&dr0, sizeof(dr0));
		if (cmd == SIOCDRADD_IN6_64 || cmd == SIOCDRDEL_IN6_64) {
			struct in6_defrouter_64 *r_64 =
			    (struct in6_defrouter_64 *)(void *)data;
			u_int16_t i;

			bcopy(&r_64->rtaddr.sin6_addr, &dr0.rtaddr,
			    sizeof(dr0.rtaddr));
			dr0.flags = r_64->flags;
			bcopy(&r_64->if_index, &i, sizeof(i));
			ifindex = i;
		} else {
			struct in6_defrouter_32 *__single r_32 =
			    (struct in6_defrouter_32 *)(void *)data;
			u_int16_t i;

			bcopy(&r_32->rtaddr.sin6_addr, &dr0.rtaddr,
			    sizeof(dr0.rtaddr));
			dr0.flags = r_32->flags;
			bcopy(&r_32->if_index, &i, sizeof(i));
			ifindex = i;
		}
		ifnet_head_lock_shared();
		/* Don't need to check is ifindex is < 0 since it's unsigned */
		if (!IF_INDEX_IN_RANGE(ifindex) ||
		    (dr_ifp = ifindex2ifnet[ifindex]) == NULL) {
			ifnet_head_done();
			error = EINVAL;
			break;
		}
		dr0.ifp = dr_ifp;
		ifnet_head_done();

		if (ND_IFINFO(dr_ifp) == NULL ||
		    !ND_IFINFO(dr_ifp)->initialized) {
			error = ENXIO;
			break;
		}

		if (IN6_IS_SCOPE_EMBED(&dr0.rtaddr) && in6_embedded_scope) {
			uint16_t *scope = &dr0.rtaddr.s6_addr16[1];

			if (*scope == 0) {
				*scope = htons(dr_ifp->if_index);
			} else if (*scope != htons(dr_ifp->if_index)) {
				error = EINVAL;
				break;
			}
		}
		if (add) {
			error = defrtrlist_add_static(&dr0);
		}
		if (!add || error != 0) {
			int err = defrtrlist_del_static(&dr0);
			if (!add) {
				error = err;
			}
		}
		break;

	default:
		error = EOPNOTSUPP; /* check for safety */
		break;
	}

	return error;
}

/*
 * XXX Please make sure to remove dr from the
 * global default router tailq list before this
 * function call.
 * Also ensure that you release the list reference
 * only after calling this routine.
 */
void
defrtrlist_del(struct nd_defrouter *dr, struct nd_drhead *nd_router_listp)
{
#if (DEVELOPMENT || DEBUG)
	struct nd_defrouter *dr_itr = NULL;
#endif
	struct nd_prefix *pr;
	struct ifnet *ifp = dr->ifp;
	struct nd_ifinfo *ndi = NULL;
	boolean_t resetmtu = FALSE;
	struct nd_route_info *rti = NULL;

	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);

	if (nd_router_listp == NULL) {
		nd_router_listp = &nd_defrouter_list;
	}

	if (nd_router_listp != &nd_defrouter_list) {
		rti = (struct nd_route_info *)nd_router_listp;
	}

#if (DEVELOPMENT || DEBUG)
	/*
	 * Verify that the router is not in the global default
	 * router list.
	 * Can't use defrouter_lookup here because that just works
	 * with address and ifp pointer.
	 * We have to compare the memory here.
	 * Also we can't use ASSERT here as that is not defined
	 * for development builds.
	 */
	TAILQ_FOREACH(dr_itr, nd_router_listp, dr_entry)
	VERIFY(dr != dr_itr);
#endif
	++nd6_defrouter_genid;
	/*
	 * Flush all the routing table entries that use the router
	 * as a next hop.
	 *
	 * XXX Note that for a router advertising itself as default router
	 * and also advertising route information option, the following
	 * code will have the default router entry and router entry of
	 * RTI step over each other.
	 * The following therefore may not be efficient but won't be
	 * causing blocking issues.
	 */
	NDDR_ADDREF(dr);
	lck_mtx_unlock(nd6_mutex);
	if (dr->stateflags & NDDRF_MAPPED) {
		rt6_flush(&dr->rtaddr_mapped, ifp);
	} else {
		rt6_flush(&dr->rtaddr, ifp);
	}
	lck_mtx_lock(nd6_mutex);
	NDDR_REMREF(dr);
	nd6log2(info, "%s: freeing route to %s with gateway %s\n", if_name(dr->ifp),
	    (rti == NULL)? "::" : ip6_sprintf(&rti->nd_rti_prefix),
	    ip6_sprintf(&dr->rtaddr));
	/*
	 * Delete it from the routing table.
	 */
	NDDR_ADDREF(dr);
	lck_mtx_unlock(nd6_mutex);
	defrouter_delreq(dr, rti);
	lck_mtx_lock(nd6_mutex);
	NDDR_REMREF(dr);

	/*
	 * The following should mostly be limited to when we are working
	 * with a default router entry and not a router entry from
	 * rti router list.
	 */
	if (rti == NULL) {
		/*
		 * Also delete all the pointers to the router in each prefix lists.
		 */
		for (pr = nd_prefix.lh_first; pr; pr = pr->ndpr_next) {
			struct nd_pfxrouter *__single pfxrtr;

			NDPR_LOCK(pr);
			if ((pfxrtr = pfxrtr_lookup(pr, dr)) != NULL) {
				pfxrtr_del(pfxrtr, pr);
			}
			NDPR_UNLOCK(pr);
		}
		pfxlist_onlink_check(false);
	}
	ndi = ND_IFINFO(ifp);
	VERIFY(NULL != ndi && TRUE == ndi->initialized);
	lck_mtx_lock(&ndi->lock);
	VERIFY(ndi->ndefrouters >= 0);
	if (ndi->ndefrouters > 0 && --ndi->ndefrouters == 0) {
		nd6_ifreset(ifp);
		resetmtu = TRUE;
	}
	lck_mtx_unlock(&ndi->lock);
	/*
	 * If the router is the primary one, choose a new one.
	 * We always try to pick another eligible router
	 * on this interface as we do scoped routing
	 */
	defrouter_select(ifp, nd_router_listp);

	if (resetmtu) {
		nd6_setmtu(ifp);
	}
}

int
defrtrlist_add_static(struct nd_defrouter *new)
{
	struct nd_defrouter *dr;
	int err = 0;

	new->rtlifetime = -1;
	new->stateflags |= NDDRF_STATIC;

	/* we only want the preference level */
	new->flags &= ND_RA_FLAG_RTPREF_MASK;

	lck_mtx_lock(nd6_mutex);
	dr = defrouter_lookup(NULL, &new->rtaddr, new->ifp);
	if (dr != NULL && !(dr->stateflags & NDDRF_STATIC)) {
		err = EINVAL;
	} else {
		if (dr != NULL) {
			NDDR_REMREF(dr);
		}
		dr = defrtrlist_update(new, NULL);
		if (dr != NULL) {
			err = dr->err;
		} else {
			err = ENOMEM;
		}
	}
	if (dr != NULL) {
		NDDR_REMREF(dr);
	}
	lck_mtx_unlock(nd6_mutex);

	return err;
}

int
defrtrlist_del_static(struct nd_defrouter *new)
{
	struct nd_defrouter *dr;

	lck_mtx_lock(nd6_mutex);
	dr = defrouter_lookup(NULL, &new->rtaddr, new->ifp);
	if (dr == NULL || !(dr->stateflags & NDDRF_STATIC)) {
		if (dr != NULL) {
			NDDR_REMREF(dr);
		}
		dr = NULL;
	} else {
		TAILQ_REMOVE(&nd_defrouter_list, dr, dr_entry);
		defrtrlist_del(dr, NULL);
		NDDR_REMREF(dr);        /* remove list reference */
		NDDR_REMREF(dr);
	}
	lck_mtx_unlock(nd6_mutex);

	return dr != NULL ? 0 : EINVAL;
}

/*
 * for default router selection
 * regards router-preference field as a 2-bit signed integer
 */
static int
rtpref(struct nd_defrouter *dr)
{
	switch (dr->flags & ND_RA_FLAG_RTPREF_MASK) {
	case ND_RA_FLAG_RTPREF_HIGH:
		return RTPREF_HIGH;
	case ND_RA_FLAG_RTPREF_MEDIUM:
	case ND_RA_FLAG_RTPREF_RSV:
		return RTPREF_MEDIUM;
	case ND_RA_FLAG_RTPREF_LOW:
		return RTPREF_LOW;
	default:
		/*
		 * This case should never happen.  If it did, it would mean a
		 * serious bug of kernel internal.  We thus always bark here.
		 * Or, can we even panic?
		 */
		log(LOG_ERR, "rtpref: impossible RA flag %x\n", dr->flags);
		return RTPREF_INVALID;
	}
	/* NOTREACHED */
}

/*
 * Default Router Selection according to Section 6.3.6 of RFC 2461 and RFC 4191:
 *
 * 1) Routers that are reachable or probably reachable should be preferred.
 *    If we have more than one (probably) reachable router, prefer ones
 *    with the highest router preference.
 * 2) When no routers on the list are known to be reachable or
 *    probably reachable, routers SHOULD be selected in a round-robin
 *    fashion, regardless of router preference values.
 * 3) If the Default Router List is empty, assume that all
 *    destinations are on-link.
 *
 * When Scoped Routing is enabled, the selection logic is amended as follows:
 *
 * a) When a default interface is specified, the primary/non-scoped default
 *    router will be set to the reachable router on that link (if any) with
 *    the highest router preference.
 * b) When there are more than one routers on the same link, the one with
 *    the highest router preference will be installed, either as scoped or
 *    non-scoped route entry.  If they all share the same preference value,
 *    the one installed will be the static or the first encountered reachable
 *    router, i.e. static one wins over dynamic.
 * c) When no routers on the list are known to be reachable, or probably
 *    reachable, no round-robin selection will take place when the default
 *    interface is set.
 *
 * We assume nd_defrouter is sorted by router preference value.
 * Since the code below covers both with and without router preference cases,
 * we do not need to classify the cases by ifdef.
 */
void
defrouter_select(struct ifnet *ifp, struct nd_drhead *nd_router_listp)
{
	struct nd_defrouter *dr = NULL;
	struct nd_defrouter *selected_dr = NULL;
	struct nd_defrouter *installed_dr = NULL;
	struct llinfo_nd6 *__single ln = NULL;
	struct rtentry *rt = NULL;
	struct nd_ifinfo *ndi = NULL;
	unsigned int genid = 0;
	boolean_t is_installed_reachable = FALSE;
	struct nd_route_info *rti = NULL;
	boolean_t scoped = TRUE;
	boolean_t is_rti_rtrlist = FALSE;

	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);

	if (nd_router_listp == NULL) {
		nd_router_listp = &nd_defrouter_list;
	}

	if (nd_router_listp != &nd_defrouter_list) {
		rti = (struct nd_route_info *)nd_router_listp;
		/* XXX For now we treat RTI routes as un-scoped */
		scoped = FALSE;
		is_rti_rtrlist = TRUE;
	}


	if (ifp == NULL) {
		ifp = nd6_defifp;
		if (ifp == NULL) {
			nd6log2(info,
			    "%s:%d: Return early. NULL interface",
			    __func__, __LINE__);
			return;
		}
		nd6log2(info,
		    "%s:%d: NULL interface passed. Setting to default interface %s.\n",
		    __func__, __LINE__, if_name(ifp));
	}

	/*
	 * When we are working with RTI router list, the nd6_defifp may be
	 * NULL. That is the scenario when the network may not have WAN
	 * v6 connectivity and the only RAs we may be getting are with lifetime
	 * 0.
	 */
	if (ifp == lo_ifp && !is_rti_rtrlist) {
		nd6log2(info,
		    "%s:%d: Return early. "
		    "Default router select called for loopback.\n",
		    __func__, __LINE__);
		return;
	}

	if (ifp->if_ipv6_router_mode == IPV6_ROUTER_MODE_EXCLUSIVE) {
		nd6log2(info,
		    "%s:%d: Return early. "
		    "Default router select called for interface"
		    " %s in IPV6_ROUTER_MODE_EXCLUSIVE\n",
		    __func__, __LINE__, if_name(ifp));
		return;
	}

	/*
	 * Let's handle easy case (3) first:
	 * If default router list is empty, there's nothing to be done.
	 */
	if (!TAILQ_FIRST(nd_router_listp)) {
		nd6log2(info,
		    "%s:%d: Return early. "
		    "Default router is empty.\n", __func__, __LINE__);
		return;
	}

	/*
	 * Take an early exit if number of routers in nd_ifinfo is
	 * 0 for the interface.
	 */
	ndi = ND_IFINFO(ifp);
	if (!ndi || !ndi->initialized) {
		nd6log2(info,
		    "%s:%d: Return early. "
		    "Interface %s's nd_ifinfo not initialized.\n",
		    __func__, __LINE__, if_name(ifp));
		return;
	}

	/*
	 * RTI router list routes are installed as unscoped.
	 * Since there can be only one unscoped route, we need to
	 * go through the entire list and consider all interfaces.
	 * Further, for now, RTI option is only processed on Ethernet
	 * type interfaces only.
	 */
	if (ndi->ndefrouters == 0 && !is_rti_rtrlist) {
		nd6log2(info,
		    "%s:%d: Return early. "
		    "%s does not have any default routers.\n",
		    __func__, __LINE__, if_name(ifp));
		return;
	}

	/*
	 * Due to the number of times we drop nd6_mutex, we need to
	 * serialize this function.
	 */
	while (nd_defrouter_busy) {
		nd_defrouter_waiters++;
		msleep(nd_defrouter_waitchan, nd6_mutex, (PZERO - 1),
		    __func__, NULL);
		LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
	}
	nd_defrouter_busy = TRUE;

	/*
	 * Search for a (probably) reachable router from the list.
	 * We just pick up the first reachable one (if any), assuming that
	 * the ordering rule of the list described in defrtrlist_update().
	 *
	 * For all intents and purposes of Scoped Routing:
	 *	selected_dr	= candidate for primary router
	 *	installed_dr	= currently installed primary router
	 */
	genid = nd6_defrouter_genid;
	dr = TAILQ_FIRST(nd_router_listp);

	while (dr != NULL) {
		struct in6_addr rtaddr;
		ifnet_ref_t drifp = NULL;
		struct nd_defrouter *__single drrele = NULL;
		boolean_t nd6_mutex_unlocked = FALSE;

		NDDR_LOCK(dr);
		drifp = dr->ifp;
		if (drifp != ifp && !is_rti_rtrlist) {
			NDDR_UNLOCK(dr);
			dr = TAILQ_NEXT(dr, dr_entry);
			continue;
		}

		if (dr->stateflags & NDDRF_INELIGIBLE) {
			NDDR_UNLOCK(dr);
			dr = TAILQ_NEXT(dr, dr_entry);
			nd6log(info, "Ignoring dummy entry for default router.");
			continue;
		}

		if (dr->ifp->if_type != IFT_CELLULAR &&
		    dr->stateflags & NDDRF_LOCAL) {
			NDDR_UNLOCK(dr);
			nd6log(info, "%s: Ignoring router %s that has locally hosted address.\n",
			    if_name(dr->ifp),
			    ip6_sprintf(&dr->rtaddr));
			dr = TAILQ_NEXT(dr, dr_entry);
			continue;
		}

		/*
		 * Optimize for the common case.
		 * When the interface has only one default router
		 * there's no point checking for reachability as
		 * there's nothing else to choose from.
		 */
		if (ndi->ndefrouters == 1 && !is_rti_rtrlist) {
			nd6log2(info,
			    "%s:%d: Fast forward default router selection "
			    "as interface %s has learned only one default "
			    "router and there's nothing else to choose from.\n",
			    __func__, __LINE__, if_name(ifp));
			VERIFY(selected_dr == NULL && installed_dr == NULL);
			selected_dr = dr;
			if (dr->stateflags & NDDRF_INSTALLED) {
				installed_dr = dr;
			}
			NDDR_ADDREF(selected_dr);
			NDDR_UNLOCK(dr);
			goto install_route;
		}

		if (dr->stateflags & NDDRF_MAPPED) {
			rtaddr = dr->rtaddr_mapped;
		} else {
			rtaddr = dr->rtaddr;
		}

		NDDR_ADDREF(dr); /* for this for loop */
		NDDR_UNLOCK(dr);

		/* Callee returns a locked route upon success */
		if (selected_dr == NULL) {
			nd6_mutex_unlocked = TRUE;
			lck_mtx_unlock(nd6_mutex);
			if ((rt = nd6_lookup(&rtaddr, 0, drifp, 0)) != NULL &&
			    (ln = rt->rt_llinfo) != NULL &&
			    ND6_IS_LLINFO_PROBREACH(ln)) {
				RT_LOCK_ASSERT_HELD(rt);
				selected_dr = dr;
				NDDR_ADDREF(selected_dr);
			}
		}

		if (rt) {
			RT_REMREF_LOCKED(rt);
			RT_UNLOCK(rt);
			rt = NULL;
		}

		if (nd6_mutex_unlocked) {
			lck_mtx_lock(nd6_mutex);
		}

		/*
		 * Handle case (b)
		 * When there are more than one routers on the same link, the one with
		 * the highest router preference will be installed.
		 * Since the list is in decreasing order of preference:
		 * 1) If selected_dr is not NULL, only use dr if it is static and has
		 *    equal preference and selected_dr is not static.
		 * 2) Else if selected_dr is NULL, and dr is static make selected_dr = dr
		 */
		NDDR_LOCK(dr);
		if (((selected_dr && (rtpref(dr) >= rtpref(selected_dr)) &&
		    !(selected_dr->stateflags & NDDRF_STATIC)) ||
		    (selected_dr == NULL)) &&
		    (dr->stateflags & NDDRF_STATIC)) {
			if (selected_dr) {
				/* Release it later on */
				VERIFY(drrele == NULL);
				drrele = selected_dr;
			}
			selected_dr = dr;
			NDDR_ADDREF(selected_dr);
		}

		/* Record the currently installed router */
		if (dr->stateflags & NDDRF_INSTALLED) {
			if (installed_dr == NULL) {
				installed_dr = dr;
				NDDR_ADDREF(installed_dr);
				if (dr->stateflags & NDDRF_MAPPED) {
					rtaddr = installed_dr->rtaddr_mapped;
				} else {
					rtaddr = installed_dr->rtaddr;
				}
				NDDR_UNLOCK(dr);
				lck_mtx_unlock(nd6_mutex);
				/* Callee returns a locked route upon success */
				if ((rt = nd6_lookup(&rtaddr, 0, installed_dr->ifp, 0)) != NULL) {
					RT_LOCK_ASSERT_HELD(rt);
					if ((ln = rt->rt_llinfo) != NULL &&
					    ND6_IS_LLINFO_PROBREACH(ln)) {
						is_installed_reachable = TRUE;
					}

					RT_REMREF_LOCKED(rt);
					RT_UNLOCK(rt);
					rt = NULL;
				}
				lck_mtx_lock(nd6_mutex);
			} else {
				/* this should not happen; warn for diagnosis */
				nd6log0(error, "%s: more than one "
				    "default router is installed for interface: %s\n",
				    __func__, if_name(installed_dr->ifp));
				NDDR_UNLOCK(dr);
			}
		} else {
			NDDR_UNLOCK(dr);
		}

		NDDR_REMREF(dr);        /* for this for loop */
		if (drrele != NULL) {
			NDDR_REMREF(drrele);
		}

		/*
		 * Check if the list changed when we gave up
		 * the nd6_mutex lock
		 */
		if (genid != nd6_defrouter_genid) {
			if (selected_dr) {
				NDDR_REMREF(selected_dr);
				selected_dr = NULL;
			}

			if (installed_dr) {
				NDDR_REMREF(installed_dr);
				installed_dr = NULL;
			}

			if (ndi->ndefrouters == 0 && !is_rti_rtrlist) {
				nd6log2(info,
				    "%s:%d: Interface %s no longer "
				    "has any default routers. Abort.\n",
				    __func__, __LINE__, if_name(ifp));
				goto out;
			}
			nd6log2(info,
			    "%s:%d: Iterate default router list again "
			    "for interface %s, as the list seems to have "
			    "changed during release-reaquire of global "
			    "nd6_mutex lock.\n",
			    __func__, __LINE__, if_name(ifp));

			is_installed_reachable = FALSE;
			genid = nd6_defrouter_genid;
			dr = TAILQ_FIRST(nd_router_listp);
		} else {
			dr = TAILQ_NEXT(dr, dr_entry);
		}
	}

	/*
	 * If none of the default routers was found to be reachable,
	 * round-robin the list regardless of preference.
	 * Please note selected_dr equal to NULL implies that even
	 * installed default router is not reachable
	 */
	if (selected_dr == NULL) {
		if (installed_dr) {
			for (dr = TAILQ_NEXT(installed_dr, dr_entry); dr;
			    dr = TAILQ_NEXT(dr, dr_entry)) {
				if (installed_dr->ifp != dr->ifp && !is_rti_rtrlist) {
					continue;
				}
				if (dr->stateflags & NDDRF_INELIGIBLE) {
					continue;
				}
				selected_dr = dr;
				break;
			}
		}

		/*
		 * If none was installed or the installed one if the last
		 * one on the list, select the first one from the list
		 */
		if ((installed_dr == NULL) || (selected_dr == NULL)) {
			for (dr = TAILQ_FIRST(nd_router_listp); dr;
			    dr = TAILQ_NEXT(dr, dr_entry)) {
				if (dr->stateflags & NDDRF_INELIGIBLE) {
					continue;
				}
				if (dr->ifp == ifp || is_rti_rtrlist) {
					selected_dr = dr;
					break;
				}
			}
		}

		if ((selected_dr == NULL) && (installed_dr == NULL)) {
			nd6log2(info,
			    "%s:%d: Between release and re-acquire of global "
			    "nd6_mutex lock, the list seems to have changed "
			    "and it does not have any default routers for "
			    "interface %s.\n",
			    __func__, __LINE__, if_name(ifp));
			goto out;
		}

		if (selected_dr != installed_dr) {
			NDDR_ADDREF(selected_dr);
		}
	} else if (installed_dr != NULL) {
		if (installed_dr != selected_dr) {
			/*
			 * This means that selected default router is reachable
			 * while installed one may or may not be.
			 * Static router should always be considered as reachable
			 * for router selection process.
			 */
			if ((installed_dr->stateflags & NDDRF_STATIC) &&
			    rtpref(installed_dr) >= rtpref(selected_dr)) {
				NDDR_REMREF(selected_dr);
				selected_dr = installed_dr;
			} else if (is_installed_reachable) {
				if (rtpref(selected_dr) <= rtpref(installed_dr)) {
					NDDR_REMREF(selected_dr);
					selected_dr = installed_dr;
				}
			}
		} else {
			NDDR_REMREF(selected_dr);
		}
	}

install_route:
	/*
	 * If the selected router is different than the installed one,
	 * remove the installed router and install the selected one.
	 * Note that the selected router is never NULL here.
	 * Else check if the route entry scope has to be changed.
	 */
	lck_mtx_unlock(nd6_mutex);
	if (installed_dr != selected_dr) {
		if (rti) {
			nd6log(info,
			    "%s:%d: Found a better router for interface "
			    "%s. Installing new default route: %s/%p\n",
			    __func__, __LINE__, if_name(ifp),
			    ip6_sprintf(&rti->nd_rti_prefix), &rti->nd_rti_prefix);
		} else {
			nd6log(info,
			    "%s:%d: Found a better router for interface "
			    "%s. Installing new default route. NO RTI\n",
			    __func__, __LINE__, if_name(ifp));
		}
		if (installed_dr != NULL) {
			defrouter_delreq(installed_dr, rti);
		}
		/*
		 * Install scoped route if the interface is not
		 * the default nd6 interface.
		 */
		defrouter_addreq(selected_dr, rti,
		    scoped && (selected_dr->ifp != nd6_defifp));
	} else if (((installed_dr->stateflags & NDDRF_IFSCOPE) &&
	    (installed_dr->ifp == nd6_defifp)) ||
	    (scoped && !(installed_dr->stateflags & NDDRF_IFSCOPE) &&
	    (installed_dr->ifp != nd6_defifp))) {
		nd6log(info,
		    "%s:%d: Need to reinstall default route for interface "
		    "%s as its scope has changed.\n",
		    __func__, __LINE__, if_name(ifp));
		defrouter_delreq(installed_dr, rti);
		defrouter_addreq(installed_dr, rti,
		    scoped && (installed_dr->ifp != nd6_defifp));
	} else {
		nd6log2(info,
		    "%s:%d: No need to change the default "
		    "route for interface %s.\n",
		    __func__, __LINE__, if_name(ifp));
	}
	lck_mtx_lock(nd6_mutex);
out:
	if (selected_dr && (selected_dr != installed_dr)) {
		NDDR_REMREF(selected_dr);
	}
	if (installed_dr) {
		NDDR_REMREF(installed_dr);
	}
	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
	VERIFY(nd_defrouter_busy);
	nd_defrouter_busy = FALSE;
	if (nd_defrouter_waiters > 0) {
		nd_defrouter_waiters = 0;
		wakeup(nd_defrouter_waitchan);
	}
}

static struct nd_defrouter *
defrtrlist_update_common(struct nd_defrouter *new, struct nd_drhead *nd_router_listp, boolean_t scoped)
{
	struct nd_defrouter *dr, *n;
	struct ifnet *ifp = new->ifp;
	struct nd_ifinfo *ndi = NULL;
	struct timeval caltime;

	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);

	if (nd_router_listp == NULL) {
		nd_router_listp = &nd_defrouter_list;
	}

	/*
	 * If we are not operating on default router list,
	 * it implies we are operating on RTI's router list.
	 * XXX For now we manage RTI routes un-scoped.
	 */
	if (nd_router_listp != &nd_defrouter_list) {
		scoped = FALSE;
	}

	if ((dr = defrouter_lookup(nd_router_listp, &new->rtaddr, ifp)) != NULL) {
		/* entry exists */
		/*
		 * 1. If previous entry was not dummy and new is,
		 * delete it and return NULL.
		 * 2. If previous entry was dummy and the new one
		 * is also dummy, simply return dr.
		 * 3. If previous was dummy but new one is not,
		 * make sure we perform default router selection again.
		 */
		/* If the router was not added as a dummy and there's
		 * been a change (lifetime advertised was 0, communicated
		 * as NDDRF_INELIGIBLE flag), remove the entry.
		 */
		if ((new->stateflags & NDDRF_INELIGIBLE) != 0 &&
		    (dr->stateflags & NDDRF_INELIGIBLE) == 0) {
			TAILQ_REMOVE(nd_router_listp, dr, dr_entry);
			defrtrlist_del(dr, nd_router_listp);
			NDDR_REMREF(dr);        /* remove list reference */
			NDDR_REMREF(dr);
			dr = NULL;
			return NULL;
		} else {
			int oldpref = rtpref(dr);
			struct nd_defrouter *__single p = NULL;
			boolean_t dummy_change = FALSE;
			/*
			 * If new one is not dummy but the old one was,
			 * reset the stateflag.
			 */
			if ((new->stateflags & NDDRF_INELIGIBLE) == 0 &&
			    (dr->stateflags & NDDRF_INELIGIBLE) != 0) {
				dummy_change = TRUE;
				dr->stateflags &= ~NDDRF_INELIGIBLE;
			}

			/* override */
			dr->flags = new->flags; /* xxx flag check */
			dr->rtlifetime = new->rtlifetime;
			dr->expire = new->expire;

			/*
			 * If the preference does not change, there's no need
			 * to sort the entries.  If Scoped Routing is enabled,
			 * put the primary/non-scoped router at the top of the
			 * list of routers in the same preference band, unless
			 * it's already at that position.
			 */
			/* same preference and scoped; just return */
			if (rtpref(new) == oldpref && scoped && dummy_change == FALSE) {
				return dr;
			}

			n = TAILQ_FIRST(nd_router_listp);
			while (n != NULL) {
				/* preference changed; sort it */
				if (rtpref(new) != oldpref) {
					break;
				}

				/* not at the top of band; sort it */
				if (n != dr && rtpref(n) == oldpref &&
				    (!p || rtpref(p) > rtpref(n))) {
					break;
				}

				p = n;
				n = TAILQ_NEXT(n, dr_entry);
			}

			/* nothing has changed, just return */
			if (n == NULL && (scoped ||
			    !(dr->stateflags & NDDRF_IFSCOPE)) && dummy_change == FALSE) {
				return dr;
			}

			/*
			 * preferred router may be changed, so relocate
			 * this router.
			 * XXX: calling TAILQ_REMOVE directly is bad manners.
			 * However, since defrtrlist_del() has many side
			 * effects, we intentionally do so here.
			 * defrouter_select() below will handle routing
			 * changes later.
			 */
			TAILQ_REMOVE(nd_router_listp, dr, dr_entry);
			new->stateflags = dr->stateflags;

			n = dr;
			goto insert;
		}
	}

	VERIFY(dr == NULL);
	n = nddr_alloc(Z_WAITOK);

	ndi = ND_IFINFO(ifp);
	VERIFY((NULL != ndi) && (TRUE == ndi->initialized));
	lck_mtx_lock(&ndi->lock);

	if (ip6_maxifdefrouters >= 0 &&
	    ndi->ndefrouters >= ip6_maxifdefrouters) {
		lck_mtx_unlock(&ndi->lock);
		nddr_free(n);
		nd6log0(error, "%s: ignoring router addition as we have hit the "
		    "max limit of %d for max default routers.\n", __func__,
		    ip6_maxifdefrouters);
		return NULL;
	}

	NDDR_ADDREF(n); /* for the nd_defrouter list */
	NDDR_ADDREF(n); /* for the caller */

	++nd6_defrouter_genid;
	ndi->ndefrouters++;
	VERIFY(ndi->ndefrouters != 0);
	lck_mtx_unlock(&ndi->lock);

	nd6log2(info, "%s: allocating defrouter %s\n", if_name(ifp),
	    ip6_sprintf(&new->rtaddr));

	getmicrotime(&caltime);
	NDDR_LOCK(n);
	memcpy(&n->rtaddr, &new->rtaddr, sizeof(n->rtaddr));
	n->flags = new->flags;
	n->stateflags = new->stateflags;
	n->rtlifetime = new->rtlifetime;
	n->expire = new->expire;
	n->base_calendartime = caltime.tv_sec;
	n->base_uptime = net_uptime();
	n->ifp = new->ifp;
	n->err = new->err;
	n->is_reachable = TRUE;
	NDDR_UNLOCK(n);
insert:
	/* get nd6_service() to be scheduled as soon as it's convenient */
	++nd6_sched_timeout_want;

	/*
	 * Insert the new router in the Default Router List;
	 * The Default Router List should be in the descending order
	 * of router-preferece.  When Scoped Routing is disabled, routers
	 * with the same preference are sorted in the arriving time order;
	 * otherwise, the first entry in the list of routers having the same
	 * preference is the primary default router, when the interface used
	 * by the entry is the default interface.
	 */

	/* insert at the end of the group */
	for (dr = TAILQ_FIRST(nd_router_listp); dr;
	    dr = TAILQ_NEXT(dr, dr_entry)) {
		if (rtpref(n) > rtpref(dr) ||
		    (!scoped && rtpref(n) == rtpref(dr))) {
			break;
		}
	}
	if (dr) {
		TAILQ_INSERT_BEFORE(dr, n, dr_entry);
	} else {
		TAILQ_INSERT_TAIL(nd_router_listp, n, dr_entry);
	}

	defrouter_select(ifp, nd_router_listp);

	return n;
}

struct nd_defrouter *
defrtrlist_update(struct nd_defrouter *new, struct nd_drhead *nd_router_list)
{
	struct nd_defrouter *dr;

	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
	dr = defrtrlist_update_common(new, nd_router_list,
	    (nd6_defifp != NULL && new->ifp != nd6_defifp));

	return dr;
}

struct nd_pfxrouter *
pfxrtr_lookup(struct nd_prefix *pr, struct nd_defrouter *dr)
{
	struct nd_pfxrouter *search;

	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
	NDPR_LOCK_ASSERT_HELD(pr);

	for (search = pr->ndpr_advrtrs.lh_first; search;
	    search = search->pfr_next) {
		if (search->router == dr) {
			break;
		}
	}

	return search;
}

static void
pfxrtr_add(struct nd_prefix *pr, struct nd_defrouter *dr)
{
	struct nd_pfxrouter *__single new;

	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
	NDPR_LOCK_ASSERT_NOTHELD(pr);

	new = zalloc_flags(ndprtr_zone, Z_WAITOK | Z_ZERO | Z_NOFAIL);
	new->router = dr;

	NDPR_LOCK(pr);
	LIST_INSERT_HEAD(&pr->ndpr_advrtrs, new, pfr_entry);
	pr->ndpr_genid++;
	NDPR_UNLOCK(pr);
	// callers of pfxrtr_add already in busy state
	pfxlist_onlink_check(true);
}

static void
pfxrtr_del(struct nd_pfxrouter *pfr, struct nd_prefix *pr)
{
	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
	NDPR_LOCK_ASSERT_HELD(pr);
	pr->ndpr_genid++;
	LIST_REMOVE(pfr, pfr_entry);
	zfree(ndprtr_zone, pfr);
}

/*
 * The routine has been modified to atomically refresh expiry
 * time for nd6 prefix as the part of lookup.
 * There's a corner case where a system going
 * in sleep gets rid of manual addresses configured in the system
 * and then schedules the prefix for deletion.
 * However before the prefix gets deleted, if system comes out
 * from sleep and configures same address before prefix deletion
 * , the later prefix deletion will remove the prefix route and
 * the system will not be able to communicate with other IPv6
 * neighbor nodes in the same subnet.
 */
struct nd_prefix *
nd6_prefix_lookup(struct nd_prefix *pr, int nd6_prefix_expiry)
{
	struct nd_prefix *__single search;

	lck_mtx_lock(nd6_mutex);
	for (search = nd_prefix.lh_first; search; search = search->ndpr_next) {
		NDPR_LOCK(search);
		if (pr->ndpr_ifp == search->ndpr_ifp &&
		    pr->ndpr_plen == search->ndpr_plen &&
		    in6_are_prefix_equal(&pr->ndpr_prefix.sin6_addr, pr->ndpr_prefix.sin6_scope_id,
		    &search->ndpr_prefix.sin6_addr, search->ndpr_prefix.sin6_scope_id, pr->ndpr_plen)) {
			if (nd6_prefix_expiry != ND6_PREFIX_EXPIRY_UNSPEC) {
				search->ndpr_expire = nd6_prefix_expiry;
			}
			NDPR_ADDREF(search);
			NDPR_UNLOCK(search);
			break;
		}
		NDPR_UNLOCK(search);
	}
	lck_mtx_unlock(nd6_mutex);

	return search;
}

int
nd6_prelist_add(struct nd_prefix *pr, struct nd_defrouter *dr,
    struct nd_prefix **newp, boolean_t force_scoped)
{
	struct nd_prefix *__single new = NULL;
	ifnet_ref_t ifp = pr->ndpr_ifp;
	struct nd_ifinfo *__single ndi = NULL;
	int i, error;

	if (ip6_maxifprefixes >= 0) {
		ndi = ND_IFINFO(ifp);
		VERIFY((NULL != ndi) && (TRUE == ndi->initialized));
		lck_mtx_lock(&ndi->lock);
		if (ndi->nprefixes >= ip6_maxifprefixes) {
			lck_mtx_unlock(&ndi->lock);
			return ENOMEM;
		}
		lck_mtx_unlock(&ndi->lock);
	}

	new = ndpr_alloc(M_WAITOK);
	if (new == NULL) {
		return ENOMEM;
	}

	NDPR_LOCK(new);
	NDPR_LOCK(pr);
	new->ndpr_ifp = pr->ndpr_ifp;
	new->ndpr_prefix = pr->ndpr_prefix;
	new->ndpr_plen = pr->ndpr_plen;
	new->ndpr_vltime = pr->ndpr_vltime;
	new->ndpr_pltime = pr->ndpr_pltime;
	new->ndpr_flags = pr->ndpr_flags;
	if (pr->ndpr_stateflags & NDPRF_STATIC) {
		new->ndpr_stateflags |= NDPRF_STATIC;
	}
	NDPR_UNLOCK(pr);
	if ((error = in6_init_prefix_ltimes(new)) != 0) {
		NDPR_UNLOCK(new);
		ndpr_free(new);
		return error;
	}
	new->ndpr_lastupdate = net_uptime();
	if (newp != NULL) {
		*newp = new;
		NDPR_ADDREF(new);        /* for caller */
	}
	/* initialization */
	LIST_INIT(&new->ndpr_advrtrs);
	in6_prefixlen2mask(&new->ndpr_mask, new->ndpr_plen);
	/* make prefix in the canonical form */
	for (i = 0; i < 4; i++) {
		new->ndpr_prefix.sin6_addr.s6_addr32[i] &=
		    new->ndpr_mask.s6_addr32[i];
	}

	NDPR_UNLOCK(new);

	/* get nd6_service() to be scheduled as soon as it's convenient */
	++nd6_sched_timeout_want;

	lck_mtx_lock(nd6_mutex);
	nd_prefix_busy_wait();
	/* link ndpr_entry to nd_prefix list */
	LIST_INSERT_HEAD(&nd_prefix, new, ndpr_entry);
	new->ndpr_debug |= IFD_ATTACHED;
	NDPR_ADDREF(new);       /* for nd_prefix list */

	lck_mtx_lock(&ndi->lock);
	ndi->nprefixes++;
	VERIFY(ndi->nprefixes != 0);
	lck_mtx_unlock(&ndi->lock);

	/* ND_OPT_PI_FLAG_ONLINK processing */
	if (new->ndpr_raf_onlink) {
		int e;

		if ((e = nd6_prefix_onlink_common(new, force_scoped,
		    new->ndpr_ifp->if_index)) != 0) {
			nd6log0(error, "nd6_prelist_add: failed to make "
			    "the prefix %s/%d on-link %s on %s (errno=%d)\n",
			    ip6_sprintf(&new->ndpr_prefix.sin6_addr),
			    new->ndpr_plen, force_scoped ? "scoped" :
			    "non-scoped", if_name(ifp), e);
			/* proceed anyway. XXX: is it correct? */
		}
	}

	if (dr) {
		pfxrtr_add(new, dr);
	}

	nd_prefix_busy_signal();
	lck_mtx_unlock(nd6_mutex);

	return 0;
}

/*
 * Caller must have held an extra reference on nd_prefix.
 */
void
prelist_remove(struct nd_prefix *pr)
{
	struct nd_pfxrouter *__single pfr = NULL, *__single next = NULL;
	ifnet_ref_t ifp = pr->ndpr_ifp;
	struct nd_ifinfo *__single ndi = NULL;
	struct nd_prefix *__single tmp_pr = NULL;
	boolean_t pr_scoped;
	int err;

	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
	NDPR_LOCK_ASSERT_HELD(pr);

	if (pr->ndpr_stateflags & NDPRF_DEFUNCT) {
		return;
	}

	pr_scoped = (pr->ndpr_stateflags & NDPRF_IFSCOPE) != 0;
	/*
	 * If there are no more addresses, defunct the prefix.  This is needed
	 * because we don't want multiple threads calling prelist_remove() for
	 * the same prefix and this might happen because we unlock nd6_mutex
	 * down below.
	 */
	if (pr->ndpr_addrcnt == 0) {
		pr->ndpr_stateflags |= NDPRF_DEFUNCT;
	}

	/* make sure to invalidate the prefix until it is really freed. */
	pr->ndpr_vltime = 0;
	pr->ndpr_pltime = 0;

	/*
	 * Though these flags are now meaningless, we'd rather keep the value
	 * of pr->ndpr_raf_onlink and pr->ndpr_raf_auto not to confuse users
	 * when executing "ndp -p".
	 */
	if (pr->ndpr_stateflags & NDPRF_ONLINK) {
		int error = 0;
		NDPR_ADDREF(pr);
		NDPR_UNLOCK(pr);
		nd_prefix_busy_signal();
		lck_mtx_unlock(nd6_mutex);
		if ((error = nd6_prefix_offlink(pr)) != 0) {
			nd6log0(error, "prelist_remove: failed to make "
			    "%s/%d offlink on %s, errno=%d\n",
			    ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
			    pr->ndpr_plen, if_name(ifp), error);
			/* what should we do? */
		}
		lck_mtx_lock(nd6_mutex);
		nd_prefix_busy_wait();
		NDPR_LOCK(pr);
		if (NDPR_REMREF(pr) == NULL) {
			// We entered in the busy state and should return in the busy state
			return;
		}
	}

	/*
	 * Check if there is a scoped version of this PR, if so
	 * make it unscoped.
	 */
	if (!pr_scoped && IN6_IS_ADDR_UNIQUE_LOCAL(&pr->ndpr_prefix.sin6_addr)) {
		tmp_pr = nd6_prefix_equal_lookup(pr, FALSE);
		if (tmp_pr != NULL) {
			NDPR_ADDREF(pr);
			NDPR_UNLOCK(pr);

			nd_prefix_busy_signal();
			lck_mtx_unlock(nd6_mutex);
			err = nd6_prefix_offlink(tmp_pr);
			lck_mtx_lock(nd6_mutex);
			nd_prefix_busy_wait();
			if (err != 0) {
				nd6log0(error,
				    "%s: failed to make %s/%d offlink on %s, "
				    "errno=%d\n", __func__,
				    ip6_sprintf(&tmp_pr->ndpr_prefix.sin6_addr),
				    tmp_pr->ndpr_plen, if_name(tmp_pr->ndpr_ifp), err);
			}

			err = nd6_prefix_onlink_scoped(tmp_pr, IFSCOPE_NONE);
			if (err != 0) {
				nd6log0(error,
				    "%s: failed to make %s/%d onlink on %s, errno=%d\n",
				    __func__, ip6_sprintf(&tmp_pr->ndpr_prefix.sin6_addr),
				    tmp_pr->ndpr_plen, if_name(tmp_pr->ndpr_ifp), err);
			}

			if (err != 0) {
				nd6log0(error,
				    "%s: error unscoping %s/%d from %s\n",
				    __func__, ip6_sprintf(&tmp_pr->ndpr_prefix.sin6_addr),
				    tmp_pr->ndpr_plen, if_name(tmp_pr->ndpr_ifp));
			} else {
				nd6log2(info,
				    "%s: %s/%d unscoped, previously on %s\n",
				    __func__, ip6_sprintf(&tmp_pr->ndpr_prefix.sin6_addr),
				    tmp_pr->ndpr_plen, if_name(tmp_pr->ndpr_ifp));
			}

			NDPR_REMREF(tmp_pr);

			NDPR_LOCK(pr);
			if (NDPR_REMREF(pr) == NULL) {
				return;
			}
		}
	}

	if (pr->ndpr_addrcnt > 0) {
		/*
		 * The state might have changed if we called
		 * nd6_prefix_offlink().
		 */
		pr->ndpr_stateflags &= ~NDPRF_DEFUNCT;
		return; /* notice here? */
	}

	/* unlink ndpr_entry from nd_prefix list */
	LIST_REMOVE(pr, ndpr_entry);
	pr->ndpr_debug &= ~IFD_ATTACHED;

	/* free list of routers that adversed the prefix */
	for (pfr = pr->ndpr_advrtrs.lh_first; pfr; pfr = next) {
		next = pfr->pfr_next;
		pfxrtr_del(pfr, pr);
	}

	ndi = ND_IFINFO(ifp);
	VERIFY((NULL != ndi) && (TRUE == ndi->initialized));
	lck_mtx_lock(&ndi->lock);
	VERIFY(ndi->nprefixes > 0);
	ndi->nprefixes--;
	lck_mtx_unlock(&ndi->lock);

	/* This must not be the last reference to the nd_prefix */
	if (NDPR_REMREF(pr) == NULL) {
		panic("%s: unexpected (missing) refcnt ndpr=%p", __func__, pr);
		/* NOTREACHED */
	}

	/*
	 * Don't call pfxlist_onlink_check() here because we are
	 * holding the NDPR lock and this could cause a deadlock when
	 * there are multiple threads executing pfxlist_onlink_check().
	 */
}

int
prelist_update(
	struct nd_prefix *new,
	struct nd_defrouter *dr, /* may be NULL */
	struct mbuf *m,
	int mcast)
{
	struct in6_ifaddr *__single ia6 = NULL, *__single ia6_match = NULL;
	struct ifaddr *__single ifa;
	ifnet_ref_t ifp = new->ndpr_ifp;
	struct nd_prefix *__single pr;
	int error = 0;
	int newprefix = 0;
	int auth;
	uint64_t timenow = net_uptime();

	/* no need to lock "new" here, as it is local to the caller */
	NDPR_LOCK_ASSERT_NOTHELD(new);

	auth = 0;
	if (m) {
		/*
		 * Authenticity for NA consists authentication for
		 * both IP header and IP datagrams, doesn't it ?
		 */
#if defined(M_AUTHIPHDR) && defined(M_AUTHIPDGM)
		auth = (m->m_flags & M_AUTHIPHDR) && (m->m_flags & M_AUTHIPDGM);
#endif
	}

	if ((pr = nd6_prefix_lookup(new, ND6_PREFIX_EXPIRY_UNSPEC)) != NULL) {
		/*
		 * nd6_prefix_lookup() ensures that pr and new have the same
		 * prefix on a same interface.
		 */

		/*
		 * Update prefix information.  Note that the on-link (L) bit
		 * and the autonomous (A) bit should NOT be changed from 1
		 * to 0.
		 */
		lck_mtx_lock(nd6_mutex);
		NDPR_LOCK(pr);
		if (new->ndpr_raf_onlink == 1) {
			pr->ndpr_raf_onlink = 1;
		}
		if (new->ndpr_raf_auto == 1) {
			pr->ndpr_raf_auto = 1;
		}
		if (new->ndpr_raf_onlink) {
			pr->ndpr_vltime = new->ndpr_vltime;
			pr->ndpr_pltime = new->ndpr_pltime;
			(void) in6_init_prefix_ltimes(pr); /* XXX error case? */
			pr->ndpr_lastupdate = net_uptime();
		}

		NDPR_ADDREF(pr);
		if (new->ndpr_raf_onlink &&
		    (pr->ndpr_stateflags & NDPRF_ONLINK) == 0) {
			int e;

			NDPR_UNLOCK(pr);
			if ((e = nd6_prefix_onlink(pr)) != 0) {
				nd6log0(error,
				    "prelist_update: failed to make "
				    "the prefix %s/%d on-link on %s "
				    "(errno=%d)\n",
				    ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
				    pr->ndpr_plen, if_name(pr->ndpr_ifp), e);
				/* proceed anyway. XXX: is it correct? */
			}
			NDPR_LOCK(pr);
		}

		if (dr && pfxrtr_lookup(pr, dr) == NULL) {
			NDPR_UNLOCK(pr);
			nd_prefix_busy_wait();
			pfxrtr_add(pr, dr);
			nd_prefix_busy_signal();
		} else {
			NDPR_UNLOCK(pr);
		}
		NDPR_REMREF(pr);
		lck_mtx_unlock(nd6_mutex);
	} else {
		newprefix = 1;

		if (new->ndpr_vltime == 0) {
			goto end;
		}
		if (new->ndpr_raf_onlink == 0 && new->ndpr_raf_auto == 0) {
			goto end;
		}

		bzero(&new->ndpr_addr, sizeof(struct in6_addr));

		error = nd6_prelist_add(new, dr, &pr, FALSE);
		if (error != 0 || pr == NULL) {
			nd6log(info, "prelist_update: "
			    "nd6_prelist_add failed for %s/%d on %s "
			    "errno=%d, returnpr=0x%llx\n",
			    ip6_sprintf(&new->ndpr_prefix.sin6_addr),
			    new->ndpr_plen, if_name(new->ndpr_ifp),
			    error, (uint64_t)VM_KERNEL_ADDRPERM(pr));
			goto end; /* we should just give up in this case. */
		}
	}

	/*
	 * Address autoconfiguration based on Section 5.5.3 of RFC 4862.
	 * Note that pr must be non NULL at this point.
	 */

	/* 5.5.3 (a). Ignore the prefix without the A bit set. */
	if (!new->ndpr_raf_auto) {
		goto end;
	}

	/*
	 * 5.5.3 (b). the link-local prefix should have been ignored in
	 * nd6_ra_input.
	 */

	/* 5.5.3 (c). Consistency check on lifetimes: pltime <= vltime. */
	if (new->ndpr_pltime > new->ndpr_vltime) {
		error = EINVAL; /* XXX: won't be used */
		goto end;
	}

	/*
	 * 5.5.3 (d).  If the prefix advertised is not equal to the prefix of
	 * an address configured by stateless autoconfiguration already in the
	 * list of addresses associated with the interface, and the Valid
	 * Lifetime is not 0, form an address.  We first check if we have
	 * a matching prefix.
	 */
	ifnet_lock_shared(ifp);
	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
		struct in6_ifaddr *__single ifa6 = NULL;
		u_int32_t remaininglifetime = 0;
		struct in6_addrlifetime lt6_tmp = {};

		IFA_LOCK(ifa);
		if (ifa->ifa_addr->sa_family != AF_INET6) {
			IFA_UNLOCK(ifa);
			continue;
		}
		ifa6 = ifatoia6(ifa);

		/*
		 * We only consider autoconfigured addresses as per RFC 4862.
		 */
		if (!(ifa6->ia6_flags & IN6_IFF_AUTOCONF)) {
			IFA_UNLOCK(ifa);
			continue;
		}
		/*
		 * Spec is not clear here, but I believe we should concentrate
		 * on unicast (i.e. not anycast) addresses.
		 * XXX: other ia6_flags? detached or duplicated?
		 */
		if ((ifa6->ia6_flags & IN6_IFF_ANYCAST) != 0) {
			IFA_UNLOCK(ifa);
			continue;
		}
		/*
		 * Ignore the address if it is not associated with a prefix
		 * or is associated with a prefix that is different from this
		 * one.  (pr is never NULL here)
		 */
		if (ifa6->ia6_ndpr != pr) {
			IFA_UNLOCK(ifa);
			continue;
		}

		if (ia6_match == NULL) { /* remember the first one */
			ia6_match = ifa6;
			ifa_addref(ifa); /* for ia6_match */
		}

		/*
		 * An already autoconfigured address matched.  Now that we
		 * are sure there is at least one matched address, we can
		 * proceed to 5.5.3. (e): update the lifetimes according to the
		 * "two hours" rule and the privacy extension.
		 */
		/* retrieve time as uptime (last arg is 0) */
		in6ifa_getlifetime(ifa6, &lt6_tmp, 0);

		if (lt6_tmp.ia6t_vltime == ND6_INFINITE_LIFETIME) {
			remaininglifetime = ND6_INFINITE_LIFETIME;
		} else if (timenow - ifa6->ia6_updatetime > lt6_tmp.ia6t_vltime) {
			/*
			 * The case of "invalid" address.  We should usually
			 * not see this case.
			 */
			remaininglifetime = 0;
		} else {
			remaininglifetime = lt6_tmp.ia6t_vltime -
			    (uint32_t)(timenow - ifa6->ia6_updatetime);
		}
		/* when not updating, keep the current stored lifetime. */
		lt6_tmp.ia6t_vltime = remaininglifetime;

		if (TWOHOUR < new->ndpr_vltime ||
		    remaininglifetime < new->ndpr_vltime) {
			lt6_tmp.ia6t_vltime = new->ndpr_vltime;
		} else if (remaininglifetime <= TWOHOUR) {
			if (auth) {
				lt6_tmp.ia6t_vltime = new->ndpr_vltime;
			}
		} else {
			/*
			 * new->ndpr_vltime <= TWOHOUR &&
			 * TWOHOUR < remaininglifetime
			 */
			lt6_tmp.ia6t_vltime = TWOHOUR;
		}

		/* The 2 hour rule is not imposed for preferred lifetime. */
		lt6_tmp.ia6t_pltime = new->ndpr_pltime;

		/* Special handling for lifetimes of temporary addresses. */
		if ((ifa6->ia6_flags & IN6_IFF_TEMPORARY) != 0) {
			u_int32_t maxvltime, maxpltime;

			/* Constrain lifetimes to system limits. */
			if (lt6_tmp.ia6t_vltime > ip6_temp_valid_lifetime) {
				lt6_tmp.ia6t_vltime = ip6_temp_valid_lifetime;
			}
			if (lt6_tmp.ia6t_pltime > ip6_temp_preferred_lifetime) {
				lt6_tmp.ia6t_pltime =
				    ip6_temp_preferred_lifetime -
				    ip6_desync_factor;
			}

			/*
			 * According to RFC 4941, section 3.3 (1), we only
			 * update the lifetimes when they are in the maximum
			 * intervals.
			 */
			if (ip6_temp_valid_lifetime >
			    (u_int32_t)((timenow - ifa6->ia6_createtime) +
			    ip6_desync_factor)) {
				maxvltime = ip6_temp_valid_lifetime -
				    (uint32_t)((timenow - ifa6->ia6_createtime) +
				    ip6_desync_factor);
			} else {
				maxvltime = 0;
			}
			if (ip6_temp_preferred_lifetime >
			    (u_int32_t)((timenow - ifa6->ia6_createtime) +
			    ip6_desync_factor)) {
				maxpltime = ip6_temp_preferred_lifetime -
				    (uint32_t)((timenow - ifa6->ia6_createtime) +
				    ip6_desync_factor);
			} else {
				maxpltime = 0;
			}

			if (lt6_tmp.ia6t_vltime == ND6_INFINITE_LIFETIME ||
			    lt6_tmp.ia6t_vltime > maxvltime) {
				lt6_tmp.ia6t_vltime = maxvltime;
			}

			if (lt6_tmp.ia6t_pltime == ND6_INFINITE_LIFETIME ||
			    lt6_tmp.ia6t_pltime > maxpltime) {
				lt6_tmp.ia6t_pltime = maxpltime;
			}
		}

		in6_init_address_ltimes(&lt6_tmp);
		in6ifa_setlifetime(ifa6, &lt6_tmp);
		ifa6->ia6_updatetime = timenow;
		IFA_UNLOCK(ifa);
	}
	ifnet_lock_done(ifp);
	if (ia6_match == NULL && new->ndpr_vltime) {
		/*
		 * 5.5.3 (d) (continued)
		 * No address matched and the valid lifetime is non-zero.
		 * Create a new address.
		 */
		if ((ia6 = in6_pfx_newpersistaddr(new, mcast, &error, FALSE, 0))
		    != NULL) {
			/*
			 * note that we should use pr (not new) for reference.
			 */
			IFA_LOCK(&ia6->ia_ifa);
			NDPR_LOCK(pr);
			ia6->ia6_ndpr = pr;
			NDPR_ADDREF(pr); /* for addr reference */
			pr->ndpr_addrcnt++;
			VERIFY(pr->ndpr_addrcnt != 0);
			NDPR_UNLOCK(pr);
			IFA_UNLOCK(&ia6->ia_ifa);

			/*
			 * RFC 4941 3.3 (2).
			 * When a new public address is created as described
			 * in RFC 4862, also create a new temporary address.
			 *
			 * RFC 4941 3.5.
			 * When an interface connects to a new link, a new
			 * randomized interface identifier should be generated
			 * immediately together with a new set of temporary
			 * addresses.  Thus, we specify 1 as the 2nd arg of
			 * in6_tmpifadd().
			 */
			if (ip6_use_tempaddr &&
			    (!IN6_IS_ADDR_UNIQUE_LOCAL(&new->ndpr_prefix.sin6_addr)
			    || ip6_ula_use_tempaddr)) {
				int e;
				if ((e = in6_tmpifadd(ia6, 1)) != 0) {
					nd6log(info, "prelist_update: "
					    "failed to create a temporary "
					    "address, errno=%d\n",
					    e);
				}
			}
			ifa_remref(&ia6->ia_ifa);
			ia6 = NULL;

			/*
			 * If the interface is marked for CLAT46 configuration
			 * try and configure the reserved IPv6 address for
			 * stateless translation.
			 */
			if (IS_INTF_CLAT46(ifp)) {
				if ((ia6 = in6_pfx_newpersistaddr(new, mcast,
				    &error, TRUE, CLAT46_COLLISION_COUNT_OFFSET))
				    != NULL) {
					IFA_LOCK(&ia6->ia_ifa);
					NDPR_LOCK(pr);
					ia6->ia6_ndpr = pr;
					NDPR_ADDREF(pr); /* for addr reference */
					pr->ndpr_addrcnt++;
					VERIFY(pr->ndpr_addrcnt != 0);
					pr->ndpr_stateflags |= NDPRF_CLAT46;
					NDPR_UNLOCK(pr);
					IFA_UNLOCK(&ia6->ia_ifa);
					ifa_remref(&ia6->ia_ifa);
					ia6 = NULL;
				} else if (error != EEXIST) {
					uuid_t tmp_uuid = {};
					/*
					 * Only report the error if it is not
					 * EEXIST.
					 */
					ip6stat.ip6s_clat464_v6addr_conffail++;
					in6_clat46_event_enqueue_nwk_wq_entry(
						IN6_CLAT46_EVENT_V6_ADDR_CONFFAIL,
						0,
						tmp_uuid);
					nd6log0(error, "Could not configure CLAT46 address on interface %s.\n", ifp->if_xname);
				}
				/*
				 * Reset the error as we do not want to
				 * treat failure of CLAT46 address configuration
				 * as complete failure in prelist update path.
				 */
				error = 0;
			}

			/*
			 * A newly added address might affect the status
			 * of other addresses, so we check and update it.
			 * XXX: what if address duplication happens?
			 */
			lck_mtx_lock(nd6_mutex);
			pfxlist_onlink_check(false);
			lck_mtx_unlock(nd6_mutex);
		}
	}
end:
	if (pr != NULL) {
		NDPR_REMREF(pr);
	}
	if (ia6_match != NULL) {
		ifa_remref(&ia6_match->ia_ifa);
	}
	return error;
}

/*
 * Neighbor Discover Default Router structure reference counting routines.
 */
static struct nd_defrouter *
nddr_alloc(zalloc_flags_t how)
{
	struct nd_defrouter *__single dr;

	dr = zalloc_flags(nddr_zone, how | Z_ZERO);
	if (dr) {
		lck_mtx_init(&dr->nddr_lock, &ifa_mtx_grp, &ifa_mtx_attr);
		lck_mtx_init(&dr->nddr_ref_lock, &ifa_mtx_grp, &ifa_mtx_attr);
		dr->nddr_debug |= IFD_ALLOC;
		if (nddr_debug != 0) {
			dr->nddr_debug |= IFD_DEBUG;
			dr->nddr_trace = nddr_trace;
		}
	}
	return dr;
}

static void
nddr_free(struct nd_defrouter *dr)
{
	if (dr->nddr_debug & IFD_ATTACHED) {
		panic("%s: attached nddr %p is being freed", __func__, dr);
		/* NOTREACHED */
	} else if (!(dr->nddr_debug & IFD_ALLOC)) {
		panic("%s: nddr %p cannot be freed", __func__, dr);
		/* NOTREACHED */
	}
	dr->nddr_debug &= ~IFD_ALLOC;
	lck_mtx_destroy(&dr->nddr_lock, &ifa_mtx_grp);
	lck_mtx_destroy(&dr->nddr_ref_lock, &ifa_mtx_grp);
	zfree(nddr_zone, dr);
}

static void
nddr_trace(struct nd_defrouter *dr, int refhold)
{
	struct nd_defrouter_dbg *__single dr_dbg = (struct nd_defrouter_dbg *)dr;
	ctrace_t *tr;
	uint32_t idx;
	uint16_t *cnt;

	if (!(dr->nddr_debug & IFD_DEBUG)) {
		panic("%s: nddr %p has no debug structure", __func__, dr);
		/* NOTREACHED */
	}
	if (refhold) {
		cnt = &dr_dbg->nddr_refhold_cnt;
		tr = dr_dbg->nddr_refhold;
	} else {
		cnt = &dr_dbg->nddr_refrele_cnt;
		tr = dr_dbg->nddr_refrele;
	}

	idx = os_atomic_inc_orig(cnt, relaxed) % NDDR_TRACE_HIST_SIZE;
	ctrace_record(&tr[idx]);
}

void
nddr_addref(struct nd_defrouter *nddr)
{
	NDDR_REF_LOCK_SPIN(nddr);
	if (++nddr->nddr_refcount == 0) {
		panic("%s: nddr %p wraparound refcnt", __func__, nddr);
		/* NOTREACHED */
	} else if (nddr->nddr_trace != NULL) {
		(*nddr->nddr_trace)(nddr, TRUE);
	}
	NDDR_REF_UNLOCK(nddr);
}

struct nd_defrouter *
nddr_remref(struct nd_defrouter *nddr)
{
	NDDR_REF_LOCK_SPIN(nddr);
	if (nddr->nddr_refcount == 0) {
		panic("%s: nddr %p negative refcnt", __func__, nddr);
		/* NOTREACHED */
	} else if (nddr->nddr_trace != NULL) {
		(*nddr->nddr_trace)(nddr, FALSE);
	}

	if (--nddr->nddr_refcount == 0) {
		NDDR_REF_UNLOCK(nddr);
		nddr_free(nddr);
		nddr = NULL;
	} else {
		NDDR_REF_UNLOCK(nddr);
	}
	return nddr;
}

uint64_t
nddr_getexpire(struct nd_defrouter *dr)
{
	struct timeval caltime;
	uint64_t expiry;

	if (dr->expire != 0) {
		/* account for system time change */
		getmicrotime(&caltime);

		dr->base_calendartime +=
		    NET_CALCULATE_CLOCKSKEW(caltime,
		    dr->base_calendartime, net_uptime(), dr->base_uptime);

		expiry = dr->base_calendartime +
		    dr->expire - dr->base_uptime;
	} else {
		expiry = 0;
	}
	return expiry;
}

/*
 * Neighbor Discover Prefix structure reference counting routines.
 */
static struct nd_prefix *
ndpr_alloc(int how)
{
	struct nd_prefix *__single pr;

	pr = zalloc_flags(ndpr_zone, how | Z_ZERO);
	if (pr != NULL) {
		lck_mtx_init(&pr->ndpr_lock, &ifa_mtx_grp, &ifa_mtx_attr);
		lck_mtx_init(&pr->ndpr_ref_lock, &ifa_mtx_grp, &ifa_mtx_attr);
		RB_INIT(&pr->ndpr_prproxy_sols);
		pr->ndpr_debug |= IFD_ALLOC;
		if (ndpr_debug != 0) {
			pr->ndpr_debug |= IFD_DEBUG;
			pr->ndpr_trace = ndpr_trace;
		}
	}
	return pr;
}

static void
ndpr_free(struct nd_prefix *pr)
{
	if (pr->ndpr_debug & IFD_ATTACHED) {
		panic("%s: attached ndpr %p is being freed", __func__, pr);
		/* NOTREACHED */
	} else if (!(pr->ndpr_debug & IFD_ALLOC)) {
		panic("%s: ndpr %p cannot be freed", __func__, pr);
		/* NOTREACHED */
	} else if (pr->ndpr_rt != NULL) {
		panic("%s: ndpr %p route %p not freed", __func__, pr,
		    pr->ndpr_rt);
		/* NOTREACHED */
	} else if (pr->ndpr_prproxy_sols_cnt != 0) {
		panic("%s: ndpr %p non-zero solicitors count (%d)",
		    __func__, pr, pr->ndpr_prproxy_sols_cnt);
		/* NOTREACHED */
	} else if (!RB_EMPTY(&pr->ndpr_prproxy_sols)) {
		panic("%s: ndpr %p non-empty solicitors tree", __func__, pr);
		/* NOTREACHED */
	}
	pr->ndpr_debug &= ~IFD_ALLOC;
	lck_mtx_destroy(&pr->ndpr_lock, &ifa_mtx_grp);
	lck_mtx_destroy(&pr->ndpr_ref_lock, &ifa_mtx_grp);
	zfree(ndpr_zone, pr);
}

static void
ndpr_trace(struct nd_prefix *pr, int refhold)
{
	struct nd_prefix_dbg *__single pr_dbg = (struct nd_prefix_dbg *)pr;
	ctrace_t *tr;
	u_int32_t idx;
	u_int16_t *cnt;

	if (!(pr->ndpr_debug & IFD_DEBUG)) {
		panic("%s: ndpr %p has no debug structure", __func__, pr);
		/* NOTREACHED */
	}
	if (refhold) {
		cnt = &pr_dbg->ndpr_refhold_cnt;
		tr = pr_dbg->ndpr_refhold;
	} else {
		cnt = &pr_dbg->ndpr_refrele_cnt;
		tr = pr_dbg->ndpr_refrele;
	}

	idx = os_atomic_inc_orig(cnt, relaxed) % NDPR_TRACE_HIST_SIZE;
	ctrace_record(&tr[idx]);
}

void
ndpr_addref(struct nd_prefix *ndpr)
{
	NDPR_REF_LOCK_SPIN(ndpr);
	if (++ndpr->ndpr_refcount == 0) {
		panic("%s: ndpr %p wraparound refcnt", __func__, ndpr);
		/* NOTREACHED */
	} else if (ndpr->ndpr_trace != NULL) {
		(*ndpr->ndpr_trace)(ndpr, TRUE);
	}
	NDPR_REF_UNLOCK(ndpr);
}

struct nd_prefix *
ndpr_remref(struct nd_prefix *ndpr)
{
	NDPR_REF_LOCK_SPIN(ndpr);
	if (ndpr->ndpr_refcount == 0) {
		panic("%s: ndpr %p negative refcnt", __func__, ndpr);
		/* NOTREACHED */
	} else if (ndpr->ndpr_trace != NULL) {
		(*ndpr->ndpr_trace)(ndpr, FALSE);
	}

	if (--ndpr->ndpr_refcount == 0) {
		if (ndpr->ndpr_addrcnt != 0) {
			panic("%s: freeing ndpr %p with outstanding address "
			    "reference (%d)", __func__, ndpr,
			    ndpr->ndpr_addrcnt);
			/* NOTREACHED */
		}
		NDPR_REF_UNLOCK(ndpr);
		ndpr_free(ndpr);
		ndpr = NULL;
	} else {
		NDPR_REF_UNLOCK(ndpr);
	}
	return ndpr;
}

uint64_t
ndpr_getexpire(struct nd_prefix *pr)
{
	struct timeval caltime;
	uint64_t expiry;

	if (pr->ndpr_expire != 0 && pr->ndpr_vltime != ND6_INFINITE_LIFETIME) {
		/* account for system time change */
		getmicrotime(&caltime);

		pr->ndpr_base_calendartime +=
		    NET_CALCULATE_CLOCKSKEW(caltime,
		    pr->ndpr_base_calendartime, net_uptime(),
		    pr->ndpr_base_uptime);

		expiry = pr->ndpr_base_calendartime +
		    pr->ndpr_expire - pr->ndpr_base_uptime;
	} else {
		expiry = 0;
	}
	return expiry;
}

/*
 * A supplement function used in the on-link detection below;
 * detect if a given prefix has a (probably) reachable advertising router.
 * XXX: lengthy function name...
 */
static struct nd_pfxrouter *
find_pfxlist_reachable_router(struct nd_prefix *pr)
{
	struct nd_pfxrouter *__single pfxrtr = NULL;
	ifnet_ref_t ifp = NULL;

	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
	NDPR_LOCK_ASSERT_HELD(pr);

	pfxrtr = LIST_FIRST(&pr->ndpr_advrtrs);
	while (pfxrtr) {
		/* XXX This should be same as prefixes interface. */
		ifp = pfxrtr->router->ifp;

		/*
		 * As long as there's a router advertisting this prefix
		 * on cellular (for that matter any interface that is point
		 * to point really), we treat the router as reachable.
		 */
		if (ifp != NULL && ifp->if_type == IFT_CELLULAR) {
			break;
		}

		if (pfxrtr->router->is_reachable) {
			break;
		}
		pfxrtr = LIST_NEXT(pfxrtr, pfr_entry);
	}
	return pfxrtr;
}

/*
 * Check if each prefix in the prefix list has at least one available router
 * that advertised the prefix (a router is "available" if its neighbor cache
 * entry is reachable or probably reachable).
 * If the check fails, the prefix may be off-link, because, for example,
 * we have moved from the network but the lifetime of the prefix has not
 * expired yet.  So we should not use the prefix if there is another prefix
 * that has an available router.
 * But, if there is no prefix that has an available router, we still regards
 * all the prefixes as on-link.  This is because we can't tell if all the
 * routers are simply dead or if we really moved from the network and there
 * is no router around us.
 */
void
pfxlist_onlink_check(bool already_locked)
{
	struct nd_prefix *__single pr, *__single prclear;
	struct in6_ifaddr *__single ifa;
	struct nd_defrouter *__single dr;
	struct nd_pfxrouter *__single pfxrtr = NULL;
	int err, i, found = 0;
	u_int16_t addresses_count;
	struct ifaddr **__single __counted_by(addresses_count) ifap = NULL;
	struct nd_prefix *__single ndpr;
	u_int64_t timenow = net_uptime();

	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);

	if (!already_locked) {
		nd_prefix_busy_wait();
	} else {
		VERIFY(nd_prefix_busy);
	}

	/*
	 * Check if there is a prefix that has a reachable advertising
	 * router.
	 */
	pr = nd_prefix.lh_first;
	while (pr) {
		NDPR_LOCK(pr);
		if (pr->ndpr_raf_onlink && find_pfxlist_reachable_router(pr) &&
		    (pr->ndpr_debug & IFD_ATTACHED)) {
			NDPR_UNLOCK(pr);
			break;
		}
		NDPR_UNLOCK(pr);
		pr = pr->ndpr_next;
	}
	/*
	 * If we have no such prefix, check whether we still have a router
	 * that does not advertise any prefixes.
	 */
	if (pr == NULL) {
		for (dr = TAILQ_FIRST(&nd_defrouter_list); dr;
		    dr = TAILQ_NEXT(dr, dr_entry)) {
			struct nd_prefix *__single pr0;

			for (pr0 = nd_prefix.lh_first; pr0;
			    pr0 = pr0->ndpr_next) {
				NDPR_LOCK(pr0);
				if ((pfxrtr = pfxrtr_lookup(pr0, dr)) != NULL) {
					NDPR_UNLOCK(pr0);
					break;
				}
				NDPR_UNLOCK(pr0);
			}
			if (pfxrtr != NULL) {
				break;
			}
		}
	}
	if (pr != NULL || (TAILQ_FIRST(&nd_defrouter_list) && pfxrtr == NULL)) {
		/*
		 * There is at least one prefix that has a reachable router,
		 * or at least a router which probably does not advertise
		 * any prefixes.  The latter would be the case when we move
		 * to a new link where we have a router that does not provide
		 * prefixes and we configure an address by hand.
		 * Detach prefixes which have no reachable advertising
		 * router, and attach other prefixes.
		 */
		pr = nd_prefix.lh_first;
		while (pr) {
			NDPR_LOCK(pr);
			/*
			 * We aren't interested prefixes already processed,
			 * nor in prefixes without the L bit
			 * set nor in static prefixes
			 */
			if (pr->ndpr_raf_onlink == 0 ||
			    pr->ndpr_stateflags & NDPRF_STATIC) {
				NDPR_UNLOCK(pr);
				pr = pr->ndpr_next;
				continue;
			}
			if ((pr->ndpr_stateflags & NDPRF_DETACHED) == 0 &&
			    find_pfxlist_reachable_router(pr) == NULL &&
			    (pr->ndpr_debug & IFD_ATTACHED)) {
				pr->ndpr_stateflags |= NDPRF_DETACHED;
			}
			if ((pr->ndpr_stateflags & NDPRF_DETACHED) != 0 &&
			    find_pfxlist_reachable_router(pr) != NULL &&
			    (pr->ndpr_debug & IFD_ATTACHED)) {
				pr->ndpr_stateflags &= ~NDPRF_DETACHED;
			}
			NDPR_UNLOCK(pr);
			pr = pr->ndpr_next;
		}
	} else {
		/* there is no prefix that has a reachable router */
		for (pr = nd_prefix.lh_first; pr; pr = pr->ndpr_next) {
			NDPR_LOCK(pr);
			if (pr->ndpr_raf_onlink == 0 ||
			    pr->ndpr_stateflags & NDPRF_STATIC) {
				NDPR_UNLOCK(pr);
				continue;
			}
			if ((pr->ndpr_stateflags & NDPRF_DETACHED) != 0) {
				pr->ndpr_stateflags &= ~NDPRF_DETACHED;
			}
			NDPR_UNLOCK(pr);
		}
	}
	/*
	 * Instead of removing interface route for detached prefix,
	 * keep the route and treat unreachability similar to the processing
	 * of an RA that has just deprecated the prefix.
	 * Keep around the detached flag just to be able to be able
	 * to differentiate the scenario from explicit RA deprecation
	 * of prefix.
	 * Keep the logic to install the interface route for a (just) attached
	 * prefix. Note that all attempt of reinstallation does not
	 * necessarily success, when a same prefix is shared among multiple
	 * interfaces.  Such cases will be handled in nd6_prefix_onlink,
	 * so we don't have to care about them.
	 */
	pr = nd_prefix.lh_first;
	while (pr) {
		int error;

		NDPR_LOCK(pr);
		if (pr->ndpr_raf_onlink == 0 ||
		    pr->ndpr_stateflags & NDPRF_STATIC ||
		    pr->ndpr_stateflags & NDPRF_PROCESSED_ONLINK ||
		    pr->ndpr_stateflags & NDPRF_DEFUNCT) {
			NDPR_UNLOCK(pr);
			pr = pr->ndpr_next;
			continue;
		}
		pr->ndpr_stateflags |= NDPRF_PROCESSED_ONLINK;
		NDPR_ADDREF(pr);
		if (pr->ndpr_stateflags & NDPRF_DETACHED) {
			/*
			 * When a prefix is detached, make it deprecated by setting pltime
			 * to 0, and let it expire according to its advertised vltime.
			 * If its original vltime is infinite or longer than 2hr,
			 * set it to 2hr.
			 */
			pr->ndpr_pltime = 0;
			uint32_t pr_remaining_lifetime;
			uint32_t original_lifetime = (uint32_t)(timenow - pr->ndpr_base_uptime);
			if (pr->ndpr_vltime > original_lifetime) {
				pr_remaining_lifetime = pr->ndpr_vltime - original_lifetime;
			} else {
				pr_remaining_lifetime = 0;
			}
			if (pr->ndpr_vltime == ND6_INFINITE_LIFETIME ||
			    pr_remaining_lifetime >= TWOHOUR) {
				pr->ndpr_vltime = TWOHOUR;
			} else {
				pr->ndpr_vltime = pr_remaining_lifetime;
			}
			in6_init_prefix_ltimes(pr);
			NDPR_UNLOCK(pr);
		} else if ((pr->ndpr_stateflags & NDPRF_DETACHED) == 0 &&
		    (pr->ndpr_stateflags & NDPRF_ONLINK) == 0 &&
		    pr->ndpr_raf_onlink) {
			NDPR_UNLOCK(pr);
			if ((error = nd6_prefix_onlink(pr)) != 0) {
				nd6log0(error,
				    "pfxlist_onlink_check: failed to "
				    "make %s/%d offlink, errno=%d\n",
				    ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
				    pr->ndpr_plen, error);
			}
			NDPR_REMREF(pr);
			pr = nd_prefix.lh_first;
			continue;
		} else {
			NDPR_UNLOCK(pr);
		}
		NDPR_REMREF(pr);
		pr = pr->ndpr_next;
	}
	LIST_FOREACH(prclear, &nd_prefix, ndpr_entry) {
		NDPR_LOCK(prclear);
		prclear->ndpr_stateflags &= ~NDPRF_PROCESSED_ONLINK;
		NDPR_UNLOCK(prclear);
	}

	if (!already_locked) {
		nd_prefix_busy_signal();
	}

	/*
	 * Changes on the prefix status might affect address status as well.
	 * Make sure that all addresses derived from an attached prefix are
	 * attached, and that all addresses derived from a detached prefix are
	 * detached.  Note, however, that a manually configured address should
	 * always be attached.
	 * The precise detection logic is same as the one for prefixes.
	 *
	 * ifnet_get_address_list_family_internal() may fail due to memory
	 * pressure, but we will eventually be called again when we receive
	 * another NA, RA, or when the link status changes.
	 */
	err = ifnet_get_address_list_family_internal(NULL, &ifap, &addresses_count,
	    AF_INET6, 0, M_NOWAIT, 0);
	if (err != 0 || ifap == NULL) {
		nd6log0(error, "%s: ifnet_get_address_list_family_internal "
		    "failed. err=%d", __func__, err);
		return;
	}
	for (i = 0; ifap[i]; i++) {
		ifa = ifatoia6(ifap[i]);
		IFA_LOCK(&ifa->ia_ifa);
		if ((ifa->ia6_flags & IN6_IFF_AUTOCONF) == 0 ||
		    (ifap[i]->ifa_debug & IFD_ATTACHED) == 0) {
			IFA_UNLOCK(&ifa->ia_ifa);
			continue;
		}
		if ((ndpr = ifa->ia6_ndpr) == NULL) {
			/*
			 * This can happen when we first configure the address
			 * (i.e. the address exists, but the prefix does not).
			 * XXX: complicated relationships...
			 */
			IFA_UNLOCK(&ifa->ia_ifa);
			continue;
		}
		IFA_UNLOCK(&ifa->ia_ifa);

		NDPR_LOCK(ndpr);
		if (find_pfxlist_reachable_router(ndpr)) {
			NDPR_UNLOCK(ndpr);
			found = 1;
			break;
		}
		NDPR_UNLOCK(ndpr);
	}
	if (found) {
		for (i = 0; ifap[i]; i++) {
			struct in6_addrlifetime lt6_tmp = {};

			ifa = ifatoia6(ifap[i]);
			IFA_LOCK(&ifa->ia_ifa);
			if ((ifa->ia6_flags & IN6_IFF_AUTOCONF) == 0 ||
			    (ifap[i]->ifa_debug & IFD_ATTACHED) == 0) {
				IFA_UNLOCK(&ifa->ia_ifa);
				continue;
			}
			if ((ndpr = ifa->ia6_ndpr) == NULL) {
				/* XXX: see above. */
				IFA_UNLOCK(&ifa->ia_ifa);
				continue;
			}
			IFA_UNLOCK(&ifa->ia_ifa);
			NDPR_LOCK(ndpr);
			if (find_pfxlist_reachable_router(ndpr) == NULL) {
				/*
				 * When the prefix of an addr is detached, make the address
				 * deprecated by setting pltime to 0, and let it expire according
				 * to its advertised vltime. If its original vltime is infinite
				 * or longer than 2hr, set it to 2hr.
				 */
				NDPR_UNLOCK(ndpr);
				IFA_LOCK(&ifa->ia_ifa);
				in6ifa_getlifetime(ifa, &lt6_tmp, 0);
				/* We want to immediately deprecate the address */
				lt6_tmp.ia6t_pltime = 0;
				/* Do not extend its valid lifetime */
				uint32_t remaining_lifetime;
				uint32_t original_lifetime = (uint32_t)(timenow - ifa->ia6_updatetime);
				if (lt6_tmp.ia6t_vltime > original_lifetime) {
					remaining_lifetime = lt6_tmp.ia6t_vltime - original_lifetime;
				} else {
					remaining_lifetime = 0;
				}
				if (lt6_tmp.ia6t_vltime == ND6_INFINITE_LIFETIME || remaining_lifetime >= TWOHOUR) {
					lt6_tmp.ia6t_vltime = TWOHOUR;
				} else {
					lt6_tmp.ia6t_vltime = remaining_lifetime;
				}

				in6_init_address_ltimes(&lt6_tmp);
				in6ifa_setlifetime(ifa, &lt6_tmp);
				ifa->ia6_updatetime = timenow;

				/*
				 * The next nd6 service timer expiry will take
				 * care of marking the addresses as deprecated
				 * and issuing the notifications as well.
				 */
				IFA_UNLOCK(&ifa->ia_ifa);
			} else {
				NDPR_UNLOCK(ndpr);
			}
		}
	}
	ifnet_address_list_free_counted_by(ifap, addresses_count);
}

static struct nd_prefix *
nd6_prefix_equal_lookup(struct nd_prefix *pr, boolean_t primary_only)
{
	struct nd_prefix *__single opr;

	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);

	for (opr = nd_prefix.lh_first; opr; opr = opr->ndpr_next) {
		if (opr == pr) {
			continue;
		}

		NDPR_LOCK(opr);
		if ((opr->ndpr_stateflags & NDPRF_ONLINK) == 0) {
			NDPR_UNLOCK(opr);
			continue;
		}
		if (opr->ndpr_plen == pr->ndpr_plen &&
		    in6_are_prefix_equal(&pr->ndpr_prefix.sin6_addr, pr->ndpr_prefix.sin6_scope_id,
		    &opr->ndpr_prefix.sin6_addr, opr->ndpr_prefix.sin6_scope_id, pr->ndpr_plen) &&
		    (!primary_only ||
		    !(opr->ndpr_stateflags & NDPRF_IFSCOPE))) {
			NDPR_ADDREF(opr);
			NDPR_UNLOCK(opr);
			return opr;
		}
		NDPR_UNLOCK(opr);
	}
	return NULL;
}

/*
 * Synchronize the interface routes of similar prefixes on different
 * interfaces; the one using the default interface would be (re)installed
 * as a primary/non-scoped entry, and the rest as scoped entri(es).
 */
static void
nd6_prefix_sync(struct ifnet *ifp)
{
	struct nd_prefix *__single pr, *__single opr;
	int err = 0;
	uint64_t timenow;

	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);

	if (ifp == NULL) {
		return;
	}


	net_update_uptime();
	timenow = net_uptime();

	LIST_FOREACH(pr, &nd_prefix, ndpr_entry) {
		NDPR_LOCK(pr);
		if ((pr->ndpr_stateflags & NDPRF_ONLINK) == 0) {
			NDPR_UNLOCK(pr);
			continue;
		}
		if (pr->ndpr_expire != 0 && pr->ndpr_expire < timenow) {
			NDPR_UNLOCK(pr);
			continue;
		}
		if (pr->ndpr_ifp == ifp &&
		    (pr->ndpr_stateflags & NDPRF_IFSCOPE) &&
		    !IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr)) {
			NDPR_UNLOCK(pr);
			break;
		}
		NDPR_UNLOCK(pr);
	}

	if (pr == NULL) {
		return;
	}

	/* Remove conflicting entries */
	opr = nd6_prefix_equal_lookup(pr, TRUE);
	if (opr != NULL) {
		lck_mtx_unlock(nd6_mutex);
		err = nd6_prefix_offlink(opr);
		lck_mtx_lock(nd6_mutex);
		if (err != 0) {
			nd6log0(error,
			    "%s: failed to make %s/%d offlink on %s, "
			    "errno=%d\n", __func__,
			    ip6_sprintf(&opr->ndpr_prefix.sin6_addr),
			    opr->ndpr_plen, if_name(opr->ndpr_ifp), err);
		}
	} else {
		nd6log0(error,
		    "%s: scoped %s/%d on %s has no matching unscoped prefix\n",
		    __func__, ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
		    pr->ndpr_plen, if_name(pr->ndpr_ifp));
	}

	lck_mtx_unlock(nd6_mutex);
	err = nd6_prefix_offlink(pr);
	lck_mtx_lock(nd6_mutex);
	if (err != 0) {
		nd6log0(error,
		    "%s: failed to make %s/%d offlink on %s, errno=%d\n",
		    __func__, ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
		    pr->ndpr_plen, if_name(pr->ndpr_ifp), err);
	}

	/* Add the entries back */
	if (opr != NULL) {
		err = nd6_prefix_onlink_scoped(opr, opr->ndpr_ifp->if_index);
		if (err != 0) {
			nd6log0(error,
			    "%s: failed to make %s/%d scoped onlink on %s, "
			    "errno=%d\n", __func__,
			    ip6_sprintf(&opr->ndpr_prefix.sin6_addr),
			    opr->ndpr_plen, if_name(opr->ndpr_ifp), err);
		}
	}

	err = nd6_prefix_onlink_scoped(pr, IFSCOPE_NONE);
	if (err != 0) {
		nd6log0(error,
		    "%s: failed to make %s/%d onlink on %s, errno=%d\n",
		    __func__, ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
		    pr->ndpr_plen, if_name(pr->ndpr_ifp), err);
	}

	if (err != 0) {
		nd6log0(error,
		    "%s: error promoting %s/%d to %s from %s\n",
		    __func__, ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
		    pr->ndpr_plen, if_name(pr->ndpr_ifp),
		    (opr != NULL) ? if_name(opr->ndpr_ifp) : "NONE");
	} else {
		nd6log2(info,
		    "%s: %s/%d promoted, previously on %s\n",
		    if_name(pr->ndpr_ifp),
		    ip6_sprintf(&pr->ndpr_prefix.sin6_addr), pr->ndpr_plen,
		    (opr != NULL) ? if_name(opr->ndpr_ifp) : "NONE");
	}

	if (opr != NULL) {
		NDPR_REMREF(opr);
	}
}

static int
nd6_prefix_onlink_common(struct nd_prefix *pr, boolean_t force_scoped,
    unsigned int ifscope)
{
	struct ifaddr *__single ifa;
	ifnet_ref_t ifp = pr->ndpr_ifp;
	struct sockaddr_in6 mask6, prefix;
	struct nd_prefix *__single opr;
	u_int32_t rtflags;
	int error = 0, prproxy = 0;
	rtentry_ref_t rt = NULL;
	u_char prefix_len = 0;

	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);

	/* sanity check */
	NDPR_LOCK(pr);
	if ((pr->ndpr_stateflags & NDPRF_ONLINK) != 0) {
		nd6log0(error,
		    "%s: %s/%d on %s scoped=%d is already on-link\n",
		    __func__, ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
		    pr->ndpr_plen, if_name(pr->ndpr_ifp),
		    (pr->ndpr_stateflags & NDPRF_IFSCOPE) ? 1 : 0);
		NDPR_UNLOCK(pr);
		return EEXIST;
	}
	NDPR_UNLOCK(pr);

	/*
	 * Add the interface route associated with the prefix.  Before
	 * installing the route, check if there's the same prefix on another
	 * interface, and the prefix has already installed the interface route.
	 */
	opr = nd6_prefix_equal_lookup(pr, FALSE);
	if (opr != NULL) {
		NDPR_REMREF(opr);
	}

	if (!force_scoped) {
		/*
		 * If a primary/non-scoped interface route already exists,
		 * install the new one as a scoped entry.  If the existing
		 * interface route is scoped, install new as non-scoped.
		 */
		ifscope = (opr != NULL) ? ifp->if_index : IFSCOPE_NONE;
		opr = nd6_prefix_equal_lookup(pr, TRUE);
		if (opr != NULL) {
			NDPR_REMREF(opr);
		} else if (ifscope != IFSCOPE_NONE) {
			ifscope = IFSCOPE_NONE;
		}
	}

	/*
	 * We prefer link-local addresses as the associated interface address.
	 */
	/* search for a link-local addr */
	ifa = (struct ifaddr *)in6ifa_ifpforlinklocal(ifp,
	    IN6_IFF_NOTREADY | IN6_IFF_ANYCAST);
	if (ifa == NULL) {
		struct in6_ifaddr *__single ia6;
		ifnet_lock_shared(ifp);
		IFP_TO_IA6(ifp, ia6);
		ifnet_lock_done(ifp);
		if (ia6 != NULL) {
			ifa = &ia6->ia_ifa;
		}
		/* should we care about ia6_flags? */
	}
	NDPR_LOCK(pr);
	if (ifa == NULL) {
		/*
		 * This can still happen, when, for example, we receive an RA
		 * containing a prefix with the L bit set and the A bit clear,
		 * after removing all IPv6 addresses on the receiving
		 * interface.  This should, of course, be rare though.
		 */
		nd6log(info,
		    "nd6_prefix_onlink: failed to find any ifaddr"
		    " to add route for a prefix(%s/%d) on %s\n",
		    ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
		    pr->ndpr_plen, if_name(ifp));
		NDPR_UNLOCK(pr);
		return 0;
	}

	/*
	 * in6_ifinit() sets nd6_rtrequest to ifa_rtrequest for all ifaddrs.
	 * ifa->ifa_rtrequest = nd6_rtrequest;
	 */
	SOCKADDR_ZERO(&mask6, sizeof(mask6));
	mask6.sin6_len = sizeof(mask6);
	mask6.sin6_addr = pr->ndpr_mask;
	prefix = pr->ndpr_prefix;
	prefix_len = pr->ndpr_plen;
	if ((rt = pr->ndpr_rt) != NULL) {
		pr->ndpr_rt = NULL;
	}
	NDPR_ADDREF(pr);         /* keep reference for this routine */
	NDPR_UNLOCK(pr);

	IFA_LOCK_SPIN(ifa);
	rtflags = ifa->ifa_flags | RTF_CLONING | RTF_UP;
	IFA_UNLOCK(ifa);
	if (nd6_need_cache(ifp)) {
		/* explicitly set in case ifa_flags does not set the flag. */
		rtflags |= RTF_CLONING;
	} else {
		/*
		 * explicitly clear the cloning bit in case ifa_flags sets it.
		 */
		rtflags &= ~RTF_CLONING;
	}

	lck_mtx_unlock(nd6_mutex);

	/*
	 * check if it conflicts with a indirect prefix route added by RIO
	 * if so, remove the rti entry.
	 */
	if (ifscope == IFSCOPE_NONE) {
		rtentry_ref_t temp_route = NULL;
		LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
		lck_mtx_lock(rnh_lock);
		temp_route = rt_lookup(TRUE, SA(&prefix), SA(&mask6), rt_tables[AF_INET6], IFSCOPE_NONE);
		lck_mtx_unlock(rnh_lock);

		if (temp_route != NULL && temp_route->rt_flags & RTF_GATEWAY && temp_route->rt_ifp != NULL) {
			struct nd_route_info rti = {};
			bzero(&rti, sizeof(rti));
			rti.nd_rti_prefixlen = prefix_len;
			rti.nd_rti_prefix = prefix.sin6_addr;
			lck_mtx_lock(nd6_mutex);
			nd6_rti_delreq(&rti);
			lck_mtx_unlock(nd6_mutex);
		}
		if (temp_route != NULL) {
			rtfree(temp_route);
		}
	}

	if (rt != NULL) {
		rtfree(rt);
		rt = NULL;
	}

	error = rtrequest_scoped(RTM_ADD, SA(&prefix), ifa->ifa_addr, SA(&mask6),
	    rtflags, &rt, ifscope);

	/*
	 * Serialize the setting of NDPRF_PRPROXY.
	 */
	lck_mtx_lock(&proxy6_lock);

	if (rt != NULL) {
		RT_LOCK(rt);
		nd6_rtmsg(RTM_ADD, rt);
		RT_UNLOCK(rt);
		NDPR_LOCK(pr);
	} else {
		NDPR_LOCK(pr);
		nd6log0(error, "nd6_prefix_onlink: failed to add route for a"
		    " prefix (%s/%d) on %s, gw=%s, mask=%s, flags=%x,"
		    " scoped=%d, errno = %d\n",
		    ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
		    pr->ndpr_plen, if_name(ifp),
		    ip6_sprintf(&SIN6(ifa->ifa_addr)->sin6_addr),
		    ip6_sprintf(&mask6.sin6_addr), rtflags,
		    (ifscope != IFSCOPE_NONE), error);
	}
	NDPR_LOCK_ASSERT_HELD(pr);

	pr->ndpr_stateflags &= ~(NDPRF_IFSCOPE | NDPRF_PRPROXY);

	/*
	 * TODO: If the prefix route exists, we should really find it and
	 * refer the prefix to it; otherwise ndpr_rt is NULL.
	 */
	if (!(pr->ndpr_stateflags & NDPRF_DEFUNCT) &&
	    (rt != NULL || error == EEXIST)) {
		struct nd_ifinfo *__single ndi = NULL;

		VERIFY(pr->ndpr_prproxy_sols_cnt == 0);
		VERIFY(RB_EMPTY(&pr->ndpr_prproxy_sols));

		ndi = ND_IFINFO(ifp);
		VERIFY((NULL != ndi) && (TRUE == ndi->initialized));
		lck_mtx_lock(&ndi->lock);

		pr->ndpr_rt = rt;       /* keep reference from rtrequest */
		pr->ndpr_stateflags |= NDPRF_ONLINK;
		if (ifscope != IFSCOPE_NONE) {
			pr->ndpr_stateflags |= NDPRF_IFSCOPE;
		} else if ((rtflags & RTF_CLONING) &&
		    (ndi->flags & ND6_IFF_PROXY_PREFIXES) &&
		    !IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr)) {
			/*
			 * At present, in order for the prefix to be eligible
			 * as a proxying/proxied prefix, we require that the
			 * prefix route entry be marked as a cloning route with
			 * RTF_PROXY; i.e. nd6_need_cache() needs to return
			 * true for the interface type, hence the test for
			 * RTF_CLONING above.
			 */
			pr->ndpr_stateflags |= NDPRF_PRPROXY;
		}

		lck_mtx_unlock(&ndi->lock);
	} else if (rt != NULL && pr->ndpr_stateflags & NDPRF_DEFUNCT) {
		rtfree(rt);
	}

	prproxy = (pr->ndpr_stateflags & NDPRF_PRPROXY);
	VERIFY(!prproxy || !(pr->ndpr_stateflags & NDPRF_IFSCOPE));
	NDPR_UNLOCK(pr);

	ifa_remref(ifa);

	/*
	 * If this is an upstream prefix, find the downstream ones (if any)
	 * and re-configure their prefix routes accordingly.  Otherwise,
	 * this could be potentially be a downstream prefix, and so find the
	 * upstream prefix, if any.
	 */
	nd6_prproxy_prelist_update(pr, prproxy ? pr : NULL);

	NDPR_REMREF(pr);        /* release reference for this routine */
	lck_mtx_unlock(&proxy6_lock);

	lck_mtx_lock(nd6_mutex);

	return error;
}

int
nd6_prefix_onlink(struct nd_prefix *pr)
{
	return nd6_prefix_onlink_common(pr, FALSE, IFSCOPE_NONE);
}

int
nd6_prefix_onlink_scoped(struct nd_prefix *pr, unsigned int ifscope)
{
	return nd6_prefix_onlink_common(pr, TRUE, ifscope);
}

int
nd6_prefix_offlink(struct nd_prefix *pr)
{
	int error = 0, prproxy;
	ifnet_ref_t ifp = pr->ndpr_ifp;
	struct sockaddr_in6 sa6, mask6, prefix;
	rtentry_ref_t rt = NULL, ndpr_rt = NULL;
	unsigned int ifscope;
	u_char prefix_len = 0;

	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_NOTOWNED);

	/* sanity check */
	NDPR_LOCK(pr);
	if ((pr->ndpr_stateflags & NDPRF_ONLINK) == 0) {
		nd6log0(error,
		    "nd6_prefix_offlink: %s/%d on %s scoped=%d is already "
		    "off-link\n", ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
		    pr->ndpr_plen, if_name(pr->ndpr_ifp),
		    (pr->ndpr_stateflags & NDPRF_IFSCOPE) ? 1 : 0);
		NDPR_UNLOCK(pr);
		return EEXIST;
	}

	SOCKADDR_ZERO(&sa6, sizeof(sa6));
	sa6.sin6_family = AF_INET6;
	sa6.sin6_len = sizeof(sa6);
	bcopy(&pr->ndpr_prefix.sin6_addr, &sa6.sin6_addr,
	    sizeof(struct in6_addr));
	SOCKADDR_ZERO(&mask6, sizeof(mask6));
	mask6.sin6_family = AF_INET6;
	mask6.sin6_len = sizeof(sa6);
	bcopy(&pr->ndpr_mask, &mask6.sin6_addr, sizeof(struct in6_addr));
	prefix = pr->ndpr_prefix;
	prefix_len = pr->ndpr_plen;
	if ((ndpr_rt = pr->ndpr_rt) != NULL) {
		pr->ndpr_rt = NULL;
	}
	NDPR_ADDREF(pr);         /* keep reference for this routine */
	NDPR_UNLOCK(pr);

	ifscope = (pr->ndpr_stateflags & NDPRF_IFSCOPE) ?
	    ifp->if_index : IFSCOPE_NONE;

	error = rtrequest_scoped(RTM_DELETE, SA(&sa6), NULL, SA(&mask6),
	    0, &rt, ifscope);

	if (rt != NULL) {
		/* report the route deletion to the routing socket. */
		RT_LOCK(rt);
		nd6_rtmsg(RTM_DELETE, rt);
		RT_UNLOCK(rt);
		rtfree(rt);
	} else {
		nd6log0(error,
		    "nd6_prefix_offlink: failed to delete route: "
		    "%s/%d on %s, scoped %d, (errno = %d)\n",
		    ip6_sprintf(&sa6.sin6_addr), prefix_len, if_name(ifp),
		    (ifscope != IFSCOPE_NONE), error);
	}

	struct nd_route_info rti = {};
	bzero(&rti, sizeof(rti));
	rti.nd_rti_prefixlen = prefix_len;
	rti.nd_rti_prefix = prefix.sin6_addr;

	lck_mtx_lock(nd6_mutex);
	nd6_rti_select(&rti, ifp);
	lck_mtx_unlock(nd6_mutex);

	if (ndpr_rt != NULL) {
		rtfree(ndpr_rt);
	}

	lck_mtx_lock(&proxy6_lock);

	NDPR_LOCK(pr);
	prproxy = (pr->ndpr_stateflags & NDPRF_PRPROXY);
	VERIFY(!prproxy || !(pr->ndpr_stateflags & NDPRF_IFSCOPE));
	pr->ndpr_stateflags &= ~(NDPRF_ONLINK | NDPRF_IFSCOPE | NDPRF_PRPROXY);
	if (pr->ndpr_prproxy_sols_cnt > 0) {
		VERIFY(prproxy);
		nd6_prproxy_sols_reap(pr);
		VERIFY(pr->ndpr_prproxy_sols_cnt == 0);
		VERIFY(RB_EMPTY(&pr->ndpr_prproxy_sols));
	}
	NDPR_UNLOCK(pr);

	/*
	 * If this was an upstream prefix, find the downstream ones and do
	 * some cleanups.  If this was a downstream prefix, the prefix route
	 * has been removed from the routing table above, but there may be
	 * other tasks to perform.
	 */
	nd6_prproxy_prelist_update(pr, prproxy ? pr : NULL);

	NDPR_REMREF(pr);        /* release reference for this routine */
	lck_mtx_unlock(&proxy6_lock);

	return error;
}

struct in6_ifaddr *
in6_pfx_newpersistaddr(struct nd_prefix *pr, int mcast, int *errorp,
    boolean_t is_clat46, uint8_t collision_count)
{
	struct in6_ifaddr *__single ia6 = NULL;
	ifnet_ref_t ifp = NULL;
	struct nd_ifinfo *__single ndi = NULL;
	struct in6_addr mask;
	struct in6_aliasreq ifra;
	int error, ifaupdate, iidlen, notcga;

	VERIFY(pr != NULL);
	VERIFY(errorp != NULL);

	NDPR_LOCK(pr);
	ifp = pr->ndpr_ifp;
	ia6 = NULL;
	error = 0;

	/*
	 * Prefix Length check:
	 * If the sum of the prefix length and interface identifier
	 * length does not equal 128 bits, the Prefix Information
	 * option MUST be ignored.  The length of the interface
	 * identifier is defined in a separate link-type specific
	 * document.
	 */
	iidlen = in6_if2idlen(ifp);
	if (iidlen < 0) {
		error = EADDRNOTAVAIL;
		/* this should not happen, so we always log it. */
		log(LOG_ERR, "%s: IID length undefined (%s)\n",
		    __func__, if_name(ifp));
		goto unlock1;
	} else if (iidlen != 64) {
		error = EADDRNOTAVAIL;
		/*
		 * stateless autoconfiguration not yet well-defined for IID
		 * lengths other than 64 octets. Just give up for now.
		 */
		nd6log(info, "%s: IID length not 64 octets (%s)\n",
		    __func__, if_name(ifp));
		goto unlock1;
	}

	if (iidlen + pr->ndpr_plen != 128) {
		error = EADDRNOTAVAIL;
		nd6log(info,
		    "%s: invalid prefix length %d for %s, ignored\n",
		    __func__, pr->ndpr_plen, if_name(ifp));
		goto unlock1;
	}

	bzero(&ifra, sizeof(ifra));
	strlcpy(ifra.ifra_name, if_name(ifp), sizeof(ifra.ifra_name));
	ifra.ifra_addr.sin6_family = AF_INET6;
	ifra.ifra_addr.sin6_len = sizeof(struct sockaddr_in6);

	/* prefix */
	bcopy(&pr->ndpr_prefix.sin6_addr, &ifra.ifra_addr.sin6_addr,
	    sizeof(ifra.ifra_addr.sin6_addr));
	in6_len2mask(&mask, pr->ndpr_plen);
	ifra.ifra_addr.sin6_addr.s6_addr32[0] &= mask.s6_addr32[0];
	ifra.ifra_addr.sin6_addr.s6_addr32[1] &= mask.s6_addr32[1];
	ifra.ifra_addr.sin6_addr.s6_addr32[2] &= mask.s6_addr32[2];
	ifra.ifra_addr.sin6_addr.s6_addr32[3] &= mask.s6_addr32[3];

	ndi = ND_IFINFO(ifp);
	VERIFY(ndi->initialized);
	lck_mtx_lock(&ndi->lock);

	notcga = nd6_send_opstate == ND6_SEND_OPMODE_DISABLED ||
	    (ndi->flags & ND6_IFF_INSECURE) != 0;

	lck_mtx_unlock(&ndi->lock);
	NDPR_UNLOCK(pr);

	if (notcga && !is_clat46) {
		ia6 = in6ifa_ifpforlinklocal(ifp, 0);
		if (ia6 == NULL) {
			error = EADDRNOTAVAIL;
			nd6log(info, "%s: no link-local address (%s)\n",
			    __func__, if_name(ifp));
			goto done;
		}

		IFA_LOCK(&ia6->ia_ifa);
		ifra.ifra_addr.sin6_addr.s6_addr32[0] |=
		    (ia6->ia_addr.sin6_addr.s6_addr32[0] & ~mask.s6_addr32[0]);
		ifra.ifra_addr.sin6_addr.s6_addr32[1] |=
		    (ia6->ia_addr.sin6_addr.s6_addr32[1] & ~mask.s6_addr32[1]);
		ifra.ifra_addr.sin6_addr.s6_addr32[2] |=
		    (ia6->ia_addr.sin6_addr.s6_addr32[2] & ~mask.s6_addr32[2]);
		ifra.ifra_addr.sin6_addr.s6_addr32[3] |=
		    (ia6->ia_addr.sin6_addr.s6_addr32[3] & ~mask.s6_addr32[3]);
		IFA_UNLOCK(&ia6->ia_ifa);
		ifa_remref(&ia6->ia_ifa);
		ia6 = NULL;
	} else {
		struct in6_cga_prepare local_cga_prepare;
		struct in6_cga_prepare *__single prepare_p;


		in6_cga_node_lock();

		if (ndi->cga_initialized) {
			bcopy(&(ndi->local_cga_modifier),
			    &(local_cga_prepare.cga_modifier),
			    sizeof(local_cga_prepare.cga_modifier));
			prepare_p = &local_cga_prepare;
		} else {
			prepare_p = NULL;
		}
		error = in6_cga_generate(prepare_p, collision_count,
		    &ifra.ifra_addr.sin6_addr, ifp);
		in6_cga_node_unlock();
		if (error == 0) {
			ifra.ifra_flags |= IN6_IFF_SECURED;
			if (is_clat46) {
				ifra.ifra_flags |= IN6_IFF_CLAT46;
			}
		} else {
			if (!is_clat46) {
				nd6log0(error, "%s: no CGA available (%s) err=%d\n",
				    __func__, if_name(ifp), error);
			} else {
				nd6log0(error, "%s: no CLAT46 available (%s) err=%d\n",
				    __func__, if_name(ifp), error);
			}
			goto done;
		}
	}

	VERIFY(ia6 == NULL);

	/* new prefix mask. */
	ifra.ifra_prefixmask.sin6_len = sizeof(struct sockaddr_in6);
	ifra.ifra_prefixmask.sin6_family = AF_INET6;
	bcopy(&mask, &ifra.ifra_prefixmask.sin6_addr,
	    sizeof(ifra.ifra_prefixmask.sin6_addr));

	/* lifetimes. */
	ifra.ifra_lifetime.ia6t_vltime = pr->ndpr_vltime;
	ifra.ifra_lifetime.ia6t_pltime = pr->ndpr_pltime;

	/* address flags */
	ifra.ifra_flags |= IN6_IFF_AUTOCONF; /* obey autoconf */

	/*
	 * Make sure that we do not have this address already.  This should
	 * usually not happen, but we can still see this case, e.g., if we
	 * have manually configured the exact address to be configured.
	 */
	if ((ia6 = in6ifa_ifpwithaddr(ifp, &ifra.ifra_addr.sin6_addr))
	    != NULL) {
		error = EEXIST;
		ifa_remref(&ia6->ia_ifa);
		ia6 = NULL;

		/* this should be rare enough to make an explicit log */
		log(LOG_INFO, "%s: %s is already configured!\n",
		    __func__, ip6_sprintf(&ifra.ifra_addr.sin6_addr));
		goto done;
	}

	/*
	 * Allocate ifaddr structure, link into chain, etc.
	 * If we are going to create a new address upon receiving a multicasted
	 * RA, we need to impose a random delay before starting DAD.
	 * [RFC 4862, Section 5.4.2]
	 */
	ifaupdate = IN6_IFAUPDATE_NOWAIT;
	if (mcast) {
		ifaupdate |= IN6_IFAUPDATE_DADDELAY;
	}
	error = in6_update_ifa(ifp, &ifra, ifaupdate, &ia6);
	if (error != 0) {
		nd6log0(error,
		    "%s: failed to make ifaddr %s on %s (errno=%d)\n",
		    __func__, ip6_sprintf(&ifra.ifra_addr.sin6_addr),
		    if_name(ifp), error);
		error = EADDRNOTAVAIL;
		goto done;
	} else {
		/* remember the collision count */
		ia6->ia6_cga_collision_count = collision_count;
	}

	VERIFY(ia6 != NULL);
	in6_post_msg(ifp, KEV_INET6_NEW_RTADV_ADDR, ia6, NULL, 0);
	goto done;

unlock1:
	NDPR_UNLOCK(pr);

done:
	*errorp = error;
	return ia6;
}

#define IA6_NONCONST(ifa) __DECONST(struct in6_ifaddr *, (ifa))

int
in6_tmpifadd(const struct in6_ifaddr *ia0, int forcegen)
{
	ifnet_ref_t ifp = ia0->ia_ifa.ifa_ifp;
	struct in6_ifaddr *__single ia, *__single newia;
	struct in6_aliasreq ifra;
	int i, error, ifaupdate;
	int trylimit = 3;       /* XXX: adhoc value */
	u_int32_t randid[2];
	uint32_t vltime0, pltime0;
	uint64_t timenow = net_uptime();
	struct in6_addr addr;
	struct nd_prefix *__single ndpr;

	bzero(&ifra, sizeof(ifra));
	strlcpy(ifra.ifra_name, if_name(ifp), sizeof(ifra.ifra_name));
	IFA_LOCK(&IA6_NONCONST(ia0)->ia_ifa);
	ifra.ifra_addr = ia0->ia_addr;
	/* copy prefix mask */
	ifra.ifra_prefixmask = ia0->ia_prefixmask;
	/* clear the old IFID */
	for (i = 0; i < 4; i++) {
		ifra.ifra_addr.sin6_addr.s6_addr32[i]
		        &= ifra.ifra_prefixmask.sin6_addr.s6_addr32[i];
	}
	addr = ia0->ia_addr.sin6_addr;
	IFA_UNLOCK(&IA6_NONCONST(ia0)->ia_ifa);

again:
	in6_iid_mktmp(ifp, (u_int8_t *)randid,
	    (const u_int8_t *)&addr.s6_addr[8], forcegen);

	ifra.ifra_addr.sin6_addr.s6_addr32[2] |=
	    (randid[0] & ~(ifra.ifra_prefixmask.sin6_addr.s6_addr32[2]));
	ifra.ifra_addr.sin6_addr.s6_addr32[3] |=
	    (randid[1] & ~(ifra.ifra_prefixmask.sin6_addr.s6_addr32[3]));

	/*
	 * in6_iid_mktmp() quite likely provided a unique interface ID.
	 * However, we may still have a chance to see collision, because
	 * there may be a time lag between generation of the ID and generation
	 * of the address.  So, we'll do one more sanity check.
	 */
	if ((ia = in6ifa_ifpwithaddr(ifp, &ifra.ifra_addr.sin6_addr)) != NULL) {
		ifa_remref(&ia->ia_ifa);
		if (trylimit-- == 0) {
			nd6log(info, "in6_tmpifadd: failed to find "
			    "a unique random IFID\n");
			return EEXIST;
		}
		forcegen = 1;
		goto again;
	}

	/*
	 * The Valid Lifetime is the lower of the Valid Lifetime of the
	 * public address or TEMP_VALID_LIFETIME.
	 * The Preferred Lifetime is the lower of the Preferred Lifetime
	 * of the public address or TEMP_PREFERRED_LIFETIME -
	 * DESYNC_FACTOR.
	 */
	IFA_LOCK(&IA6_NONCONST(ia0)->ia_ifa);
	if (ia0->ia6_lifetime.ia6ti_vltime != ND6_INFINITE_LIFETIME) {
		vltime0 = IFA6_IS_INVALID(ia0, timenow) ? 0 :
		    (ia0->ia6_lifetime.ia6ti_vltime -
		    (uint32_t)(timenow - ia0->ia6_updatetime));
		if (vltime0 > ip6_temp_valid_lifetime) {
			vltime0 = ip6_temp_valid_lifetime;
		}
	} else {
		vltime0 = ip6_temp_valid_lifetime;
	}
	if (ia0->ia6_lifetime.ia6ti_pltime != ND6_INFINITE_LIFETIME) {
		pltime0 = IFA6_IS_DEPRECATED(ia0, timenow) ? 0 :
		    (ia0->ia6_lifetime.ia6ti_pltime -
		    (uint32_t)(timenow - ia0->ia6_updatetime));
		if (pltime0 > ip6_temp_preferred_lifetime - ip6_desync_factor) {
			pltime0 = ip6_temp_preferred_lifetime -
			    ip6_desync_factor;
		}
	} else {
		pltime0 = ip6_temp_preferred_lifetime - ip6_desync_factor;
	}
	ifra.ifra_lifetime.ia6t_vltime = vltime0;
	ifra.ifra_lifetime.ia6t_pltime = pltime0;
	IFA_UNLOCK(&IA6_NONCONST(ia0)->ia_ifa);
	/*
	 * A temporary address is created only if this calculated Preferred
	 * Lifetime is greater than REGEN_ADVANCE time units.
	 */
	if (ifra.ifra_lifetime.ia6t_pltime <= ip6_temp_regen_advance) {
		return 0;
	}

	/* XXX: scope zone ID? */

	ifra.ifra_flags |= (IN6_IFF_AUTOCONF | IN6_IFF_TEMPORARY);

	/* allocate ifaddr structure, link into chain, etc. */
	ifaupdate = IN6_IFAUPDATE_NOWAIT | IN6_IFAUPDATE_DADDELAY;
	error = in6_update_ifa(ifp, &ifra, ifaupdate, &newia);
	if (error != 0) {
		nd6log0(error, "%s: failed to add address. err=%d\n",
		    __func__, error);
		return error;
	}
	VERIFY(newia != NULL);

	IFA_LOCK(&IA6_NONCONST(ia0)->ia_ifa);
	ndpr = ia0->ia6_ndpr;
	if (ndpr == NULL) {
		/*
		 * We lost the race with another thread that has purged
		 * ia0 address; in this case, purge the tmp addr as well.
		 */
		nd6log0(error, "in6_tmpifadd: no public address\n");
		VERIFY(!(ia0->ia6_flags & IN6_IFF_AUTOCONF));
		IFA_UNLOCK(&IA6_NONCONST(ia0)->ia_ifa);
		in6_purgeaddr(&newia->ia_ifa);
		ifa_remref(&newia->ia_ifa);
		return EADDRNOTAVAIL;
	}
	NDPR_ADDREF(ndpr);      /* for us */
	IFA_UNLOCK(&IA6_NONCONST(ia0)->ia_ifa);
	IFA_LOCK(&newia->ia_ifa);
	if (newia->ia6_ndpr != NULL) {
		NDPR_LOCK(newia->ia6_ndpr);
		VERIFY(newia->ia6_ndpr->ndpr_addrcnt != 0);
		newia->ia6_ndpr->ndpr_addrcnt--;
		NDPR_UNLOCK(newia->ia6_ndpr);
		NDPR_REMREF(newia->ia6_ndpr);   /* release addr reference */
	}
	newia->ia6_ndpr = ndpr;
	NDPR_LOCK(newia->ia6_ndpr);
	newia->ia6_ndpr->ndpr_addrcnt++;
	VERIFY(newia->ia6_ndpr->ndpr_addrcnt != 0);
	NDPR_ADDREF(newia->ia6_ndpr);    /* for addr reference */
	NDPR_UNLOCK(newia->ia6_ndpr);
	IFA_UNLOCK(&newia->ia_ifa);
	/*
	 * A newly added address might affect the status of other addresses.
	 * XXX: when the temporary address is generated with a new public
	 * address, the onlink check is redundant.  However, it would be safe
	 * to do the check explicitly everywhere a new address is generated,
	 * and, in fact, we surely need the check when we create a new
	 * temporary address due to deprecation of an old temporary address.
	 */
	lck_mtx_lock(nd6_mutex);
	pfxlist_onlink_check(false);
	lck_mtx_unlock(nd6_mutex);
	ifa_remref(&newia->ia_ifa);

	/* remove our reference */
	NDPR_REMREF(ndpr);

	return 0;
}
#undef IA6_NONCONST

int
in6_init_prefix_ltimes(struct nd_prefix *ndpr)
{
	struct timeval caltime;
	u_int64_t timenow = net_uptime();

	NDPR_LOCK_ASSERT_HELD(ndpr);

	getmicrotime(&caltime);
	ndpr->ndpr_base_calendartime = caltime.tv_sec;
	ndpr->ndpr_base_uptime = timenow;

	/* check if preferred lifetime > valid lifetime.  RFC 4862 5.5.3 (c) */
	if (ndpr->ndpr_pltime > ndpr->ndpr_vltime) {
		nd6log(info, "in6_init_prefix_ltimes: preferred lifetime"
		    "(%d) is greater than valid lifetime(%d)\n",
		    (u_int)ndpr->ndpr_pltime, (u_int)ndpr->ndpr_vltime);
		return EINVAL;
	}
	if (ndpr->ndpr_pltime == ND6_INFINITE_LIFETIME) {
		ndpr->ndpr_preferred = 0;
	} else {
		ndpr->ndpr_preferred = timenow + ndpr->ndpr_pltime;
	}
	if (ndpr->ndpr_vltime == ND6_INFINITE_LIFETIME) {
		ndpr->ndpr_expire = 0;
	} else {
		ndpr->ndpr_expire = timenow + ndpr->ndpr_vltime;
	}

	return 0;
}

static void
in6_init_address_ltimes(struct in6_addrlifetime *lt6)
{
	uint64_t timenow = net_uptime();

	/* Valid lifetime must not be updated unless explicitly specified. */
	/* init ia6t_expire */
	if (lt6->ia6t_vltime == ND6_INFINITE_LIFETIME) {
		lt6->ia6t_expire = 0;
	} else {
		lt6->ia6t_expire = timenow;
		lt6->ia6t_expire += lt6->ia6t_vltime;
	}

	/* init ia6t_preferred */
	if (lt6->ia6t_pltime == ND6_INFINITE_LIFETIME) {
		lt6->ia6t_preferred = 0;
	} else {
		lt6->ia6t_preferred = timenow;
		lt6->ia6t_preferred += lt6->ia6t_pltime;
	}
}

/*
 * Delete all the routing table entries that use the specified gateway.
 * XXX: this function causes search through all entries of routing table, so
 * it shouldn't be called when acting as a router.
 *
 * This should really be working on entries that have a specific
 * parent route.
 */
void
rt6_flush(
	struct in6_addr *gateway,
	struct ifnet *ifp)
{
	radix_node_head_ref_t rnh = rt_tables[AF_INET6];

	/* We'll care only link-local addresses */
	if (!IN6_IS_ADDR_LINKLOCAL(gateway)) {
		return;
	}
	lck_mtx_lock(rnh_lock);
	/* XXX: hack for KAME's link-local address kludge */
	if (in6_embedded_scope) {
		gateway->s6_addr16[1] = htons(ifp->if_index);
	}

	rnh->rnh_walktree(rnh, rt6_deleteroute, (void *)gateway);
	lck_mtx_unlock(rnh_lock);
}

static int
rt6_deleteroute(
	struct radix_node *rn,
	void *arg)
{
	rtentry_ref_t rt = (struct rtentry *)rn;
	struct in6_addr *__single gate = (struct in6_addr *)arg;

	LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);

	RT_LOCK(rt);
	if (rt->rt_gateway == NULL || rt->rt_gateway->sa_family != AF_INET6) {
		RT_UNLOCK(rt);
		return 0;
	}

	if (!IN6_ARE_ADDR_EQUAL(gate, &SIN6(rt->rt_gateway)->sin6_addr)) {
		RT_UNLOCK(rt);
		return 0;
	}
	/*
	 * Do not delete a static route.
	 * XXX: this seems to be a bit ad-hoc. Should we consider the
	 * 'cloned' bit instead?
	 */
	if ((rt->rt_flags & RTF_STATIC) != 0) {
		RT_UNLOCK(rt);
		return 0;
	}
	/*
	 * We delete only host route. This means, in particular, we don't
	 * delete default route.
	 */
	if ((rt->rt_flags & RTF_HOST) == 0) {
		RT_UNLOCK(rt);
		return 0;
	}

	/*
	 * Safe to drop rt_lock and use rt_key, rt_gateway, since holding
	 * rnh_lock here prevents another thread from calling rt_setgate()
	 * on this route.
	 */
	RT_UNLOCK(rt);
	return rtrequest_locked(RTM_DELETE, rt_key(rt), rt->rt_gateway,
	           rt_mask(rt), rt->rt_flags, 0);
}

int
nd6_setdefaultiface(
	int ifindex)
{
	int error = 0;
	ifnet_t def_ifp = NULL;

	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_NOTOWNED);

	ifnet_head_lock_shared();
	if (!IF_INDEX_IN_RANGE(ifindex)) {
		ifnet_head_done();
		return EINVAL;
	}
	def_ifp = ifindex2ifnet[ifindex];
	ifnet_head_done();

	lck_mtx_lock(nd6_mutex);
	if (nd6_defifindex != ifindex) {
		ifnet_ref_t odef_ifp = nd6_defifp;

		nd6_defifindex = ifindex;
		if (nd6_defifindex > 0) {
			nd6_defifp = def_ifp;
		} else {
			nd6_defifp = NULL;
		}

		if (nd6_defifp != NULL) {
			nd6log(info, "%s: is now the default "
			    "interface (was %s)\n", if_name(nd6_defifp),
			    odef_ifp != NULL ? if_name(odef_ifp) : "NONE");
		} else {
			nd6log(info, "No default interface set\n");
		}

		/*
		 * If the Default Router List is empty, install a route
		 * to the specified interface as default or remove the default
		 * route when the default interface becomes canceled.
		 * The check for the queue is actually redundant, but
		 * we do this here to avoid re-install the default route
		 * if the list is NOT empty.
		 */
		if (odef_ifp != NULL) {
			defrouter_select(odef_ifp, NULL);
		}

		if (nd6_defifp != NULL) {
			defrouter_select(nd6_defifp, NULL);
			nd6_prefix_sync(nd6_defifp);
		}

		/*
		 * XXX For now we managed RTI routes as un-scoped.
		 * Therefore we ignore the change in nd6_defifindex
		 * for RTI routes for now.
		 */
		/*
		 * Our current implementation assumes one-to-one mapping between
		 * interfaces and links, so it would be natural to use the
		 * default interface as the default link.
		 */
		scope6_setdefault(nd6_defifp);
	}
	lck_mtx_unlock(nd6_mutex);
	return error;
}