summaryrefslogtreecommitdiff
path: root/usr/src/uts/common/inet/ip/ip.c
blob: 274bf9b2eb2a74eb9b5ecfb755bba6c0b17fc6fe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/*
 * Copyright (c) 1991, 2010, Oracle and/or its affiliates. All rights reserved.
 * Copyright (c) 1990 Mentat Inc.
 * Copyright (c) 2017 OmniTI Computer Consulting, Inc. All rights reserved.
 * Copyright (c) 2016 by Delphix. All rights reserved.
 * Copyright 2020 OmniOS Community Edition (OmniOSce) Association.
 * Copyright 2021 Joyent, Inc.
 */

#include <sys/types.h>
#include <sys/stream.h>
#include <sys/dlpi.h>
#include <sys/stropts.h>
#include <sys/sysmacros.h>
#include <sys/strsubr.h>
#include <sys/strlog.h>
#include <sys/strsun.h>
#include <sys/zone.h>
#define	_SUN_TPI_VERSION 2
#include <sys/tihdr.h>
#include <sys/xti_inet.h>
#include <sys/ddi.h>
#include <sys/suntpi.h>
#include <sys/cmn_err.h>
#include <sys/debug.h>
#include <sys/kobj.h>
#include <sys/modctl.h>
#include <sys/atomic.h>
#include <sys/policy.h>
#include <sys/priv.h>
#include <sys/taskq.h>

#include <sys/systm.h>
#include <sys/param.h>
#include <sys/kmem.h>
#include <sys/sdt.h>
#include <sys/socket.h>
#include <sys/vtrace.h>
#include <sys/isa_defs.h>
#include <sys/mac.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <net/route.h>
#include <sys/sockio.h>
#include <netinet/in.h>
#include <net/if_dl.h>

#include <inet/common.h>
#include <inet/mi.h>
#include <inet/mib2.h>
#include <inet/nd.h>
#include <inet/arp.h>
#include <inet/snmpcom.h>
#include <inet/optcom.h>
#include <inet/kstatcom.h>

#include <netinet/igmp_var.h>
#include <netinet/ip6.h>
#include <netinet/icmp6.h>
#include <netinet/sctp.h>

#include <inet/ip.h>
#include <inet/ip_impl.h>
#include <inet/ip6.h>
#include <inet/ip6_asp.h>
#include <inet/tcp.h>
#include <inet/tcp_impl.h>
#include <inet/ip_multi.h>
#include <inet/ip_if.h>
#include <inet/ip_ire.h>
#include <inet/ip_ftable.h>
#include <inet/ip_rts.h>
#include <inet/ip_ndp.h>
#include <inet/ip_listutils.h>
#include <netinet/igmp.h>
#include <netinet/ip_mroute.h>
#include <inet/ipp_common.h>
#include <inet/cc.h>

#include <net/pfkeyv2.h>
#include <inet/sadb.h>
#include <inet/ipsec_impl.h>
#include <inet/iptun/iptun_impl.h>
#include <inet/ipdrop.h>
#include <inet/ip_netinfo.h>
#include <inet/ilb_ip.h>

#include <sys/ethernet.h>
#include <net/if_types.h>
#include <sys/cpuvar.h>

#include <ipp/ipp.h>
#include <ipp/ipp_impl.h>
#include <ipp/ipgpc/ipgpc.h>

#include <sys/pattr.h>
#include <inet/ipclassifier.h>
#include <inet/sctp_ip.h>
#include <inet/sctp/sctp_impl.h>
#include <inet/udp_impl.h>
#include <inet/rawip_impl.h>
#include <inet/rts_impl.h>

#include <sys/tsol/label.h>
#include <sys/tsol/tnet.h>

#include <sys/squeue_impl.h>
#include <inet/ip_arp.h>

#include <sys/clock_impl.h>	/* For LBOLT_FASTPATH{,64} */

/*
 * Values for squeue switch:
 * IP_SQUEUE_ENTER_NODRAIN: SQ_NODRAIN
 * IP_SQUEUE_ENTER: SQ_PROCESS
 * IP_SQUEUE_FILL: SQ_FILL
 */
int ip_squeue_enter = IP_SQUEUE_ENTER;	/* Setable in /etc/system */

int ip_squeue_flag;

/*
 * Setable in /etc/system
 */
int ip_poll_normal_ms = 100;
int ip_poll_normal_ticks = 0;
int ip_modclose_ackwait_ms = 3000;

/*
 * It would be nice to have these present only in DEBUG systems, but the
 * current design of the global symbol checking logic requires them to be
 * unconditionally present.
 */
uint_t ip_thread_data;			/* TSD key for debug support */
krwlock_t ip_thread_rwlock;
list_t	ip_thread_list;

/*
 * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
 */

struct listptr_s {
	mblk_t	*lp_head;	/* pointer to the head of the list */
	mblk_t	*lp_tail;	/* pointer to the tail of the list */
};

typedef struct listptr_s listptr_t;

/*
 * This is used by ip_snmp_get_mib2_ip_route_media and
 * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
 */
typedef struct iproutedata_s {
	uint_t		ird_idx;
	uint_t		ird_flags;	/* see below */
	listptr_t	ird_route;	/* ipRouteEntryTable */
	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
} iproutedata_t;

/* Include ire_testhidden and IRE_IF_CLONE routes */
#define	IRD_REPORT_ALL	0x01

/*
 * Cluster specific hooks. These should be NULL when booted as a non-cluster
 */

/*
 * Hook functions to enable cluster networking
 * On non-clustered systems these vectors must always be NULL.
 *
 * Hook function to Check ip specified ip address is a shared ip address
 * in the cluster
 *
 */
int (*cl_inet_isclusterwide)(netstackid_t stack_id, uint8_t protocol,
    sa_family_t addr_family, uint8_t *laddrp, void *args) = NULL;

/*
 * Hook function to generate cluster wide ip fragment identifier
 */
uint32_t (*cl_inet_ipident)(netstackid_t stack_id, uint8_t protocol,
    sa_family_t addr_family, uint8_t *laddrp, uint8_t *faddrp,
    void *args) = NULL;

/*
 * Hook function to generate cluster wide SPI.
 */
void (*cl_inet_getspi)(netstackid_t, uint8_t, uint8_t *, size_t,
    void *) = NULL;

/*
 * Hook function to verify if the SPI is already utlized.
 */

int (*cl_inet_checkspi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;

/*
 * Hook function to delete the SPI from the cluster wide repository.
 */

void (*cl_inet_deletespi)(netstackid_t, uint8_t, uint32_t, void *) = NULL;

/*
 * Hook function to inform the cluster when packet received on an IDLE SA
 */

void (*cl_inet_idlesa)(netstackid_t, uint8_t, uint32_t, sa_family_t,
    in6_addr_t, in6_addr_t, void *) = NULL;

/*
 * Synchronization notes:
 *
 * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
 * MT level protection given by STREAMS. IP uses a combination of its own
 * internal serialization mechanism and standard Solaris locking techniques.
 * The internal serialization is per phyint.  This is used to serialize
 * plumbing operations, IPMP operations, most set ioctls, etc.
 *
 * Plumbing is a long sequence of operations involving message
 * exchanges between IP, ARP and device drivers. Many set ioctls are typically
 * involved in plumbing operations. A natural model is to serialize these
 * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
 * parallel without any interference. But various set ioctls on hme0 are best
 * serialized, along with IPMP operations and processing of DLPI control
 * messages received from drivers on a per phyint basis. This serialization is
 * provided by the ipsq_t and primitives operating on this. Details can
 * be found in ip_if.c above the core primitives operating on ipsq_t.
 *
 * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
 * Simiarly lookup of an ire by a thread also returns a refheld ire.
 * In addition ipif's and ill's referenced by the ire are also indirectly
 * refheld. Thus no ipif or ill can vanish as long as an ipif is refheld
 * directly or indirectly. For example an SIOCSLIFADDR ioctl that changes the
 * address of an ipif has to go through the ipsq_t. This ensures that only
 * one such exclusive operation proceeds at any time on the ipif. It then
 * waits for all refcnts
 * associated with this ipif to come down to zero. The address is changed
 * only after the ipif has been quiesced. Then the ipif is brought up again.
 * More details are described above the comment in ip_sioctl_flags.
 *
 * Packet processing is based mostly on IREs and are fully multi-threaded
 * using standard Solaris MT techniques.
 *
 * There are explicit locks in IP to handle:
 * - The ip_g_head list maintained by mi_open_link() and friends.
 *
 * - The reassembly data structures (one lock per hash bucket)
 *
 * - conn_lock is meant to protect conn_t fields. The fields actually
 *   protected by conn_lock are documented in the conn_t definition.
 *
 * - ire_lock to protect some of the fields of the ire, IRE tables
 *   (one lock per hash bucket). Refer to ip_ire.c for details.
 *
 * - ndp_g_lock and ncec_lock for protecting NCEs.
 *
 * - ill_lock protects fields of the ill and ipif. Details in ip.h
 *
 * - ill_g_lock: This is a global reader/writer lock. Protects the following
 *	* The AVL tree based global multi list of all ills.
 *	* The linked list of all ipifs of an ill
 *	* The <ipsq-xop> mapping
 *	* <ill-phyint> association
 *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
 *   into an ill, changing the <ipsq-xop> mapping of an ill, changing the
 *   <ill-phyint> assoc of an ill will all have to hold the ill_g_lock as
 *   writer for the actual duration of the insertion/deletion/change.
 *
 * - ill_lock:  This is a per ill mutex.
 *   It protects some members of the ill_t struct; see ip.h for details.
 *   It also protects the <ill-phyint> assoc.
 *   It also protects the list of ipifs hanging off the ill.
 *
 * - ipsq_lock: This is a per ipsq_t mutex lock.
 *   This protects some members of the ipsq_t struct; see ip.h for details.
 *   It also protects the <ipsq-ipxop> mapping
 *
 * - ipx_lock: This is a per ipxop_t mutex lock.
 *   This protects some members of the ipxop_t struct; see ip.h for details.
 *
 * - phyint_lock: This is a per phyint mutex lock. Protects just the
 *   phyint_flags
 *
 * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
 *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
 *   uniqueness check also done atomically.
 *
 * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
 *   group list linked by ill_usesrc_grp_next. It also protects the
 *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
 *   group is being added or deleted.  This lock is taken as a reader when
 *   walking the list/group(eg: to get the number of members in a usesrc group).
 *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
 *   field is changing state i.e from NULL to non-NULL or vice-versa. For
 *   example, it is not necessary to take this lock in the initial portion
 *   of ip_sioctl_slifusesrc or at all in ip_sioctl_flags since these
 *   operations are executed exclusively and that ensures that the "usesrc
 *   group state" cannot change. The "usesrc group state" change can happen
 *   only in the latter part of ip_sioctl_slifusesrc and in ill_delete.
 *
 * Changing <ill-phyint>, <ipsq-xop> assocications:
 *
 * To change the <ill-phyint> association, the ill_g_lock must be held
 * as writer, and the ill_locks of both the v4 and v6 instance of the ill
 * must be held.
 *
 * To change the <ipsq-xop> association, the ill_g_lock must be held as
 * writer, the ipsq_lock must be held, and one must be writer on the ipsq.
 * This is only done when ills are added or removed from IPMP groups.
 *
 * To add or delete an ipif from the list of ipifs hanging off the ill,
 * ill_g_lock (writer) and ill_lock must be held and the thread must be
 * a writer on the associated ipsq.
 *
 * To add or delete an ill to the system, the ill_g_lock must be held as
 * writer and the thread must be a writer on the associated ipsq.
 *
 * To add or delete an ilm to an ill, the ill_lock must be held and the thread
 * must be a writer on the associated ipsq.
 *
 * Lock hierarchy
 *
 * Some lock hierarchy scenarios are listed below.
 *
 * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock -> ipx_lock
 * ill_g_lock -> ill_lock(s) -> phyint_lock
 * ill_g_lock -> ndp_g_lock -> ill_lock -> ncec_lock
 * ill_g_lock -> ip_addr_avail_lock
 * conn_lock -> irb_lock -> ill_lock -> ire_lock
 * ill_g_lock -> ip_g_nd_lock
 * ill_g_lock -> ips_ipmp_lock -> ill_lock -> nce_lock
 * ill_g_lock -> ndp_g_lock -> ill_lock -> ncec_lock -> nce_lock
 * arl_lock -> ill_lock
 * ips_ire_dep_lock -> irb_lock
 *
 * When more than 1 ill lock is needed to be held, all ill lock addresses
 * are sorted on address and locked starting from highest addressed lock
 * downward.
 *
 * Multicast scenarios
 * ips_ill_g_lock -> ill_mcast_lock
 * conn_ilg_lock -> ips_ill_g_lock -> ill_lock
 * ill_mcast_serializer -> ill_mcast_lock -> ips_ipmp_lock -> ill_lock
 * ill_mcast_serializer -> ill_mcast_lock -> connf_lock -> conn_lock
 * ill_mcast_serializer -> ill_mcast_lock -> conn_ilg_lock
 * ill_mcast_serializer -> ill_mcast_lock -> ips_igmp_timer_lock
 *
 * IPsec scenarios
 *
 * ipsa_lock -> ill_g_lock -> ill_lock
 * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
 *
 * Trusted Solaris scenarios
 *
 * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
 * igsa_lock -> gcdb_lock
 * gcgrp_rwlock -> ire_lock
 * gcgrp_rwlock -> gcdb_lock
 *
 * squeue(sq_lock), flow related (ft_lock, fe_lock) locking
 *
 * cpu_lock --> ill_lock --> sqset_lock --> sq_lock
 * sq_lock -> conn_lock -> QLOCK(q)
 * ill_lock -> ft_lock -> fe_lock
 *
 * Routing/forwarding table locking notes:
 *
 * Lock acquisition order: Radix tree lock, irb_lock.
 * Requirements:
 * i.  Walker must not hold any locks during the walker callback.
 * ii  Walker must not see a truncated tree during the walk because of any node
 *     deletion.
 * iii Existing code assumes ire_bucket is valid if it is non-null and is used
 *     in many places in the code to walk the irb list. Thus even if all the
 *     ires in a bucket have been deleted, we still can't free the radix node
 *     until the ires have actually been inactive'd (freed).
 *
 * Tree traversal - Need to hold the global tree lock in read mode.
 * Before dropping the global tree lock, need to either increment the ire_refcnt
 * to ensure that the radix node can't be deleted.
 *
 * Tree add - Need to hold the global tree lock in write mode to add a
 * radix node. To prevent the node from being deleted, increment the
 * irb_refcnt, after the node is added to the tree. The ire itself is
 * added later while holding the irb_lock, but not the tree lock.
 *
 * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
 * All associated ires must be inactive (i.e. freed), and irb_refcnt
 * must be zero.
 *
 * Walker - Increment irb_refcnt before calling the walker callback. Hold the
 * global tree lock (read mode) for traversal.
 *
 * IRE dependencies - In some cases we hold ips_ire_dep_lock across ire_refrele
 * hence we will acquire irb_lock while holding ips_ire_dep_lock.
 *
 * IPsec notes :
 *
 * IP interacts with the IPsec code (AH/ESP) by storing IPsec attributes
 * in the ip_xmit_attr_t ip_recv_attr_t. For outbound datagrams, the
 * ip_xmit_attr_t has the
 * information used by the IPsec code for applying the right level of
 * protection. The information initialized by IP in the ip_xmit_attr_t
 * is determined by the per-socket policy or global policy in the system.
 * For inbound datagrams, the ip_recv_attr_t
 * starts out with nothing in it. It gets filled
 * with the right information if it goes through the AH/ESP code, which
 * happens if the incoming packet is secure. The information initialized
 * by AH/ESP, is later used by IP (during fanouts to ULP) to see whether
 * the policy requirements needed by per-socket policy or global policy
 * is met or not.
 *
 * For fully connected sockets i.e dst, src [addr, port] is known,
 * conn_policy_cached is set indicating that policy has been cached.
 * conn_in_enforce_policy may or may not be set depending on whether
 * there is a global policy match or per-socket policy match.
 * Policy inheriting happpens in ip_policy_set once the destination is known.
 * Once the right policy is set on the conn_t, policy cannot change for
 * this socket. This makes life simpler for TCP (UDP ?) where
 * re-transmissions go out with the same policy. For symmetry, policy
 * is cached for fully connected UDP sockets also. Thus if policy is cached,
 * it also implies that policy is latched i.e policy cannot change
 * on these sockets. As we have the right policy on the conn, we don't
 * have to lookup global policy for every outbound and inbound datagram
 * and thus serving as an optimization. Note that a global policy change
 * does not affect fully connected sockets if they have policy. If fully
 * connected sockets did not have any policy associated with it, global
 * policy change may affect them.
 *
 * IP Flow control notes:
 * ---------------------
 * Non-TCP streams are flow controlled by IP. The way this is accomplished
 * differs when ILL_CAPAB_DLD_DIRECT is enabled for that IP instance. When
 * ILL_DIRECT_CAPABLE(ill) is TRUE, IP can do direct function calls into
 * GLDv3. Otherwise packets are sent down to lower layers using STREAMS
 * functions.
 *
 * Per Tx ring udp flow control:
 * This is applicable only when ILL_CAPAB_DLD_DIRECT capability is set in
 * the ill (i.e. ILL_DIRECT_CAPABLE(ill) is true).
 *
 * The underlying link can expose multiple Tx rings to the GLDv3 mac layer.
 * To achieve best performance, outgoing traffic need to be fanned out among
 * these Tx ring. mac_tx() is called (via str_mdata_fastpath_put()) to send
 * traffic out of the NIC and it takes a fanout hint. UDP connections pass
 * the address of connp as fanout hint to mac_tx(). Under flow controlled
 * condition, mac_tx() returns a non-NULL cookie (ip_mac_tx_cookie_t). This
 * cookie points to a specific Tx ring that is blocked. The cookie is used to
 * hash into an idl_tx_list[] entry in idl_tx_list[] array. Each idl_tx_list_t
 * point to drain_lists (idl_t's). These drain list will store the blocked UDP
 * connp's. The drain list is not a single list but a configurable number of
 * lists.
 *
 * The diagram below shows idl_tx_list_t's and their drain_lists. ip_stack_t
 * has an array of idl_tx_list_t. The size of the array is TX_FANOUT_SIZE
 * which is equal to 128. This array in turn contains a pointer to idl_t[],
 * the ip drain list. The idl_t[] array size is MIN(max_ncpus, 8). The drain
 * list will point to the list of connp's that are flow controlled.
 *
 *                      ---------------   -------   -------   -------
 *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
 *                   |  ---------------   -------   -------   -------
 *                   |  ---------------   -------   -------   -------
 *                   |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
 * ----------------  |  ---------------   -------   -------   -------
 * |idl_tx_list[0]|->|  ---------------   -------   -------   -------
 * ----------------  |->|drain_list[2]|-->|connp|-->|connp|-->|connp|-->
 *                   |  ---------------   -------   -------   -------
 *                   .        .              .         .         .
 *                   |  ---------------   -------   -------   -------
 *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
 *                      ---------------   -------   -------   -------
 *                      ---------------   -------   -------   -------
 *                   |->|drain_list[0]|-->|connp|-->|connp|-->|connp|-->
 *                   |  ---------------   -------   -------   -------
 *                   |  ---------------   -------   -------   -------
 * ----------------  |->|drain_list[1]|-->|connp|-->|connp|-->|connp|-->
 * |idl_tx_list[1]|->|  ---------------   -------   -------   -------
 * ----------------  |        .              .         .         .
 *                   |  ---------------   -------   -------   -------
 *                   |->|drain_list[n]|-->|connp|-->|connp|-->|connp|-->
 *                      ---------------   -------   -------   -------
 *     .....
 * ----------------
 * |idl_tx_list[n]|-> ...
 * ----------------
 *
 * When mac_tx() returns a cookie, the cookie is hashed into an index into
 * ips_idl_tx_list[], and conn_drain_insert() is called with the idl_tx_list
 * to insert the conn onto.  conn_drain_insert() asserts flow control for the
 * sockets via su_txq_full() (non-STREAMS) or QFULL on conn_wq (STREAMS).
 * Further, conn_blocked is set to indicate that the conn is blocked.
 *
 * GLDv3 calls ill_flow_enable() when flow control is relieved.  The cookie
 * passed in the call to ill_flow_enable() identifies the blocked Tx ring and
 * is again hashed to locate the appropriate idl_tx_list, which is then
 * drained via conn_walk_drain().  conn_walk_drain() goes through each conn in
 * the drain list and calls conn_drain_remove() to clear flow control (via
 * calling su_txq_full() or clearing QFULL), and remove the conn from the
 * drain list.
 *
 * Note that the drain list is not a single list but a (configurable) array of
 * lists (8 elements by default).  Synchronization between drain insertion and
 * flow control wakeup is handled by using idl_txl->txl_lock, and only
 * conn_drain_insert() and conn_drain_remove() manipulate the drain list.
 *
 * Flow control via STREAMS is used when ILL_DIRECT_CAPABLE() returns FALSE.
 * On the send side, if the packet cannot be sent down to the driver by IP
 * (canput() fails), ip_xmit() drops the packet and returns EWOULDBLOCK to the
 * caller, who may then invoke ixa_check_drain_insert() to insert the conn on
 * the 0'th drain list.  When ip_wsrv() runs on the ill_wq because flow
 * control has been relieved, the blocked conns in the 0'th drain list are
 * drained as in the non-STREAMS case.
 *
 * In both the STREAMS and non-STREAMS cases, the sockfs upcall to set QFULL
 * is done when the conn is inserted into the drain list (conn_drain_insert())
 * and cleared when the conn is removed from the it (conn_drain_remove()).
 *
 * IPQOS notes:
 *
 * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
 * and IPQoS modules. IPPF includes hooks in IP at different control points
 * (callout positions) which direct packets to IPQoS modules for policy
 * processing. Policies, if present, are global.
 *
 * The callout positions are located in the following paths:
 *		o local_in (packets destined for this host)
 *		o local_out (packets orginating from this host )
 *		o fwd_in  (packets forwarded by this m/c - inbound)
 *		o fwd_out (packets forwarded by this m/c - outbound)
 * Hooks at these callout points can be enabled/disabled using the ndd variable
 * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
 * By default all the callout positions are enabled.
 *
 * Outbound (local_out)
 * Hooks are placed in ire_send_wire_v4 and ire_send_wire_v6.
 *
 * Inbound (local_in)
 * Hooks are placed in ip_fanout_v4 and ip_fanout_v6.
 *
 * Forwarding (in and out)
 * Hooks are placed in ire_recv_forward_v4/v6.
 *
 * IP Policy Framework processing (IPPF processing)
 * Policy processing for a packet is initiated by ip_process, which ascertains
 * that the classifier (ipgpc) is loaded and configured, failing which the
 * packet resumes normal processing in IP. If the clasifier is present, the
 * packet is acted upon by one or more IPQoS modules (action instances), per
 * filters configured in ipgpc and resumes normal IP processing thereafter.
 * An action instance can drop a packet in course of its processing.
 *
 * Zones notes:
 *
 * The partitioning rules for networking are as follows:
 * 1) Packets coming from a zone must have a source address belonging to that
 * zone.
 * 2) Packets coming from a zone can only be sent on a physical interface on
 * which the zone has an IP address.
 * 3) Between two zones on the same machine, packet delivery is only allowed if
 * there's a matching route for the destination and zone in the forwarding
 * table.
 * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
 * different zones can bind to the same port with the wildcard address
 * (INADDR_ANY).
 *
 * The granularity of interface partitioning is at the logical interface level.
 * Therefore, every zone has its own IP addresses, and incoming packets can be
 * attributed to a zone unambiguously. A logical interface is placed into a zone
 * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
 * structure. Rule (1) is implemented by modifying the source address selection
 * algorithm so that the list of eligible addresses is filtered based on the
 * sending process zone.
 *
 * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
 * across all zones, depending on their type. Here is the break-up:
 *
 * IRE type				Shared/exclusive
 * --------				----------------
 * IRE_BROADCAST			Exclusive
 * IRE_DEFAULT (default routes)		Shared (*)
 * IRE_LOCAL				Exclusive (x)
 * IRE_LOOPBACK				Exclusive
 * IRE_PREFIX (net routes)		Shared (*)
 * IRE_IF_NORESOLVER (interface routes)	Exclusive
 * IRE_IF_RESOLVER (interface routes)	Exclusive
 * IRE_IF_CLONE (interface routes)	Exclusive
 * IRE_HOST (host routes)		Shared (*)
 *
 * (*) A zone can only use a default or off-subnet route if the gateway is
 * directly reachable from the zone, that is, if the gateway's address matches
 * one of the zone's logical interfaces.
 *
 * (x) IRE_LOCAL are handled a bit differently.
 * When ip_restrict_interzone_loopback is set (the default),
 * ire_route_recursive restricts loopback using an IRE_LOCAL
 * between zone to the case when L2 would have conceptually looped the packet
 * back, i.e. the loopback which is required since neither Ethernet drivers
 * nor Ethernet hardware loops them back. This is the case when the normal
 * routes (ignoring IREs with different zoneids) would send out the packet on
 * the same ill as the ill with which is IRE_LOCAL is associated.
 *
 * Multiple zones can share a common broadcast address; typically all zones
 * share the 255.255.255.255 address. Incoming as well as locally originated
 * broadcast packets must be dispatched to all the zones on the broadcast
 * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
 * since some zones may not be on the 10.16.72/24 network. To handle this, each
 * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
 * sent to every zone that has an IRE_BROADCAST entry for the destination
 * address on the input ill, see ip_input_broadcast().
 *
 * Applications in different zones can join the same multicast group address.
 * The same logic applies for multicast as for broadcast. ip_input_multicast
 * dispatches packets to all zones that have members on the physical interface.
 */

/*
 * Squeue Fanout flags:
 *	0: No fanout.
 *	1: Fanout across all squeues
 */
boolean_t	ip_squeue_fanout = 0;

/*
 * Maximum dups allowed per packet.
 */
uint_t ip_max_frag_dups = 10;

static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
		    cred_t *credp, boolean_t isv6);
static mblk_t	*ip_xmit_attach_llhdr(mblk_t *, nce_t *);

static boolean_t icmp_inbound_verify_v4(mblk_t *, icmph_t *, ip_recv_attr_t *);
static void	icmp_inbound_too_big_v4(icmph_t *, ip_recv_attr_t *);
static void	icmp_inbound_error_fanout_v4(mblk_t *, icmph_t *,
    ip_recv_attr_t *);
static void	icmp_options_update(ipha_t *);
static void	icmp_param_problem(mblk_t *, uint8_t,  ip_recv_attr_t *);
static void	icmp_pkt(mblk_t *, void *, size_t, ip_recv_attr_t *);
static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_recv_attr_t *);
static void	icmp_redirect_v4(mblk_t *mp, ipha_t *, icmph_t *,
    ip_recv_attr_t *);
static void	icmp_send_redirect(mblk_t *, ipaddr_t, ip_recv_attr_t *);
static void	icmp_send_reply_v4(mblk_t *, ipha_t *, icmph_t *,
    ip_recv_attr_t *);

mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
char		*ip_dot_addr(ipaddr_t, char *);
mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
static char	*ip_dot_saddr(uchar_t *, char *);
static int	ip_lrput(queue_t *, mblk_t *);
ipaddr_t	ip_net_mask(ipaddr_t);
char		*ip_nv_lookup(nv_t *, int);
int		ip_rput(queue_t *, mblk_t *);
static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
		    void *dummy_arg);
int		ip_snmp_get(queue_t *, mblk_t *, int, boolean_t);
static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
		    mib2_ipIfStatsEntry_t *, ip_stack_t *, boolean_t);
static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
		    ip_stack_t *, boolean_t);
static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *,
		    boolean_t);
static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
		    ip_stack_t *ipst, boolean_t);
static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
		    ip_stack_t *ipst, boolean_t);
static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
		    ip_stack_t *ipst);
static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
		    ip_stack_t *ipst);
static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
		    ip_stack_t *ipst);
static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
		    ip_stack_t *ipst);
static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
		    ip_stack_t *ipst);
static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
		    ip_stack_t *ipst);
static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *, int,
		    ip_stack_t *ipst);
static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *, int,
		    ip_stack_t *ipst);
static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
static void	ip_snmp_get2_v4_media(ncec_t *, void *);
static void	ip_snmp_get2_v6_media(ncec_t *, void *);
int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);

static mblk_t	*ip_fragment_copyhdr(uchar_t *, int, int, ip_stack_t *,
		    mblk_t *);

static void	conn_drain_init(ip_stack_t *);
static void	conn_drain_fini(ip_stack_t *);
static void	conn_drain(conn_t *connp, boolean_t closing);

static void	conn_walk_drain(ip_stack_t *, idl_tx_list_t *);
static void	conn_walk_sctp(pfv_t, void *, zoneid_t, netstack_t *);

static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
static void	ip_stack_fini(netstackid_t stackid, void *arg);

static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
    const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
    ire_t *, conn_t *, boolean_t, const in6_addr_t *,  mcast_record_t,
    const in6_addr_t *);

static int	ip_squeue_switch(int);

static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
static void	ip_kstat_fini(netstackid_t, kstat_t *);
static int	ip_kstat_update(kstat_t *kp, int rw);
static void	*icmp_kstat_init(netstackid_t);
static void	icmp_kstat_fini(netstackid_t, kstat_t *);
static int	icmp_kstat_update(kstat_t *kp, int rw);
static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
static void	ip_kstat2_fini(netstackid_t, kstat_t *);

static void	ipobs_init(ip_stack_t *);
static void	ipobs_fini(ip_stack_t *);

static int	ip_tp_cpu_update(cpu_setup_t, int, void *);

ipaddr_t	ip_g_all_ones = IP_HOST_MASK;

static long ip_rput_pullups;
int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */

vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */

int	ip_debug;

/*
 * Multirouting/CGTP stuff
 */
int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */

/*
 * IP tunables related declarations. Definitions are in ip_tunables.c
 */
extern mod_prop_info_t ip_propinfo_tbl[];
extern int ip_propinfo_count;

/*
 * Table of IP ioctls encoding the various properties of the ioctl and
 * indexed based on the last byte of the ioctl command. Occasionally there
 * is a clash, and there is more than 1 ioctl with the same last byte.
 * In such a case 1 ioctl is encoded in the ndx table and the remaining
 * ioctls are encoded in the misc table. An entry in the ndx table is
 * retrieved by indexing on the last byte of the ioctl command and comparing
 * the ioctl command with the value in the ndx table. In the event of a
 * mismatch the misc table is then searched sequentially for the desired
 * ioctl command.
 *
 * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
 */
ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },

	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
			MISC_CMD, ip_siocaddrt, NULL },
	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
			MISC_CMD, ip_siocdelrt, NULL },

	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD,
			IF_CMD, ip_sioctl_get_addr, NULL },

	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
			IPI_GET_CMD, IF_CMD, ip_sioctl_get_dstaddr, NULL },

	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
			IPI_PRIV | IPI_WR,
			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
			IPI_MODOK | IPI_GET_CMD,
			IF_CMD, ip_sioctl_get_flags, NULL },

	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },

	/* copyin size cannot be coded for SIOCGIFCONF */
	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
			MISC_CMD, ip_sioctl_get_ifconf, NULL },

	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
			IF_CMD, ip_sioctl_mtu, NULL },
	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD,
			IF_CMD, ip_sioctl_get_mtu, NULL },
	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
			IPI_GET_CMD, IF_CMD, ip_sioctl_get_brdaddr, NULL },
	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
			IF_CMD, ip_sioctl_brdaddr, NULL },
	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
			IPI_GET_CMD, IF_CMD, ip_sioctl_get_netmask, NULL },
	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
			IPI_GET_CMD, IF_CMD, ip_sioctl_get_metric, NULL },
	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
			IF_CMD, ip_sioctl_metric, NULL },
	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },

	/* See 166-168 below for extended SIOC*XARP ioctls */
	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
			ARP_CMD, ip_sioctl_arp, NULL },
	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD,
			ARP_CMD, ip_sioctl_arp, NULL },
	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV | IPI_WR,
			ARP_CMD, ip_sioctl_arp, NULL },

	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },

	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
			MISC_CMD, if_unitsel, if_unitsel_restart },

	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },

	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
			IPI_PRIV | IPI_WR | IPI_MODOK,
			IF_CMD, ip_sioctl_sifname, NULL },

	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },

	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD,
			MISC_CMD, ip_sioctl_get_ifnum, NULL },
	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD,
			IF_CMD, ip_sioctl_get_muxid, NULL },
	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_muxid, NULL },

	/* Both if and lif variants share same func */
	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD,
			IF_CMD, ip_sioctl_get_lifindex, NULL },
	/* Both if and lif variants share same func */
	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
			IPI_PRIV | IPI_WR, IF_CMD, ip_sioctl_slifindex, NULL },

	/* copyin size cannot be coded for SIOCGIFCONF */
	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
			MISC_CMD, ip_sioctl_get_ifconf, NULL },
	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },

	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_removeif,
			ip_sioctl_removeif_restart },
	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
			IPI_GET_CMD | IPI_PRIV | IPI_WR,
			LIF_CMD, ip_sioctl_addif, NULL },
#define	SIOCLIFADDR_NDX 112
	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_addr, NULL },
	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dstaddr, NULL },
	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
			IPI_PRIV | IPI_WR,
			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
			IPI_GET_CMD | IPI_MODOK,
			LIF_CMD, ip_sioctl_get_flags, NULL },

	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },

	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
			ip_sioctl_get_lifconf, NULL },
	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
			LIF_CMD, ip_sioctl_mtu, NULL },
	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD,
			LIF_CMD, ip_sioctl_get_mtu, NULL },
	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_brdaddr, NULL },
	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
			LIF_CMD, ip_sioctl_brdaddr, NULL },
	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_netmask, NULL },
	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_metric, NULL },
	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
			LIF_CMD, ip_sioctl_metric, NULL },
	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
			IPI_PRIV | IPI_WR | IPI_MODOK,
			LIF_CMD, ip_sioctl_slifname,
			ip_sioctl_slifname_restart },

	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD,
			MISC_CMD, ip_sioctl_get_lifnum, NULL },
	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_muxid, NULL },
	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_muxid, NULL },
	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifindex, 0 },
	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifindex, 0 },
	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
			LIF_CMD, ip_sioctl_token, NULL },
	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_token, NULL },
	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_subnet, NULL },
	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
			LIF_CMD, ip_sioctl_lnkinfo, NULL },

	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
			LIF_CMD, ip_siocdelndp_v6, NULL },
	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
			LIF_CMD, ip_siocqueryndp_v6, NULL },
	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
			LIF_CMD, ip_siocsetndp_v6, NULL },
	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
			MISC_CMD, ip_sioctl_tmyaddr, NULL },
	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
			MISC_CMD, ip_sioctl_tonlink, NULL },
	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
			MISC_CMD, ip_sioctl_tmysite, NULL },
	/* 147 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 148 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },

	/* Old *IPSECONFIG ioctls are now deprecated, now see spdsock.c */
	/* 149 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 150 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 151 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 152 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },

	/* 153 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },

	/* 154 */ { SIOCGLIFBINDING, sizeof (struct lifreq), IPI_GET_CMD,
			LIF_CMD, ip_sioctl_get_binding, NULL },
	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
			IPI_PRIV | IPI_WR,
			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_groupname, NULL },
	/* 157 */ { SIOCGLIFGROUPINFO, sizeof (lifgroupinfo_t),
			IPI_GET_CMD, MISC_CMD, ip_sioctl_groupinfo, NULL },

	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },

	/* 161 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },

	/* These are handled in ip_sioctl_copyin_setup itself */
	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
			MISC_CMD, NULL, NULL },
	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
			MISC_CMD, NULL, NULL },
	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },

	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
			ip_sioctl_get_lifconf, NULL },

	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
			XARP_CMD, ip_sioctl_arp, NULL },
	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD,
			XARP_CMD, ip_sioctl_arp, NULL },
	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV | IPI_WR,
			XARP_CMD, ip_sioctl_arp, NULL },

	/* SIOCPOPSOCKFS is not handled by IP */
	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },

	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_lifzone, NULL },
	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
			IPI_PRIV | IPI_WR, LIF_CMD, ip_sioctl_slifzone,
			ip_sioctl_slifzone_restart },
	/* 172-174 are SCTP ioctls and not handled by IP */
	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
			IPI_GET_CMD, LIF_CMD,
			ip_sioctl_get_lifusesrc, 0 },
	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
			IPI_PRIV | IPI_WR,
			LIF_CMD, ip_sioctl_slifusesrc,
			NULL },
	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
			ip_sioctl_get_lifsrcof, NULL },
	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
			MSFILT_CMD, ip_sioctl_msfilter, NULL },
	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), 0,
			MSFILT_CMD, ip_sioctl_msfilter, NULL },
	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
			MSFILT_CMD, ip_sioctl_msfilter, NULL },
	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), 0,
			MSFILT_CMD, ip_sioctl_msfilter, NULL },
	/* 182 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
	/* SIOCSENABLESDP is handled by SDP */
	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
	/* 184 */ { IPI_DONTCARE /* SIOCSQPTR */, 0, 0, 0, NULL, NULL },
	/* 185 */ { SIOCGIFHWADDR, sizeof (struct ifreq), IPI_GET_CMD,
			IF_CMD, ip_sioctl_get_ifhwaddr, NULL },
	/* 186 */ { IPI_DONTCARE /* SIOCGSTAMP */, 0, 0, 0, NULL, NULL },
	/* 187 */ { SIOCILB, 0, IPI_PRIV | IPI_GET_CMD, MISC_CMD,
			ip_sioctl_ilb_cmd, NULL },
	/* 188 */ { SIOCGETPROP, 0, IPI_GET_CMD, 0, NULL, NULL },
	/* 189 */ { SIOCSETPROP, 0, IPI_PRIV | IPI_WR, 0, NULL, NULL},
	/* 190 */ { SIOCGLIFDADSTATE, sizeof (struct lifreq),
			IPI_GET_CMD, LIF_CMD, ip_sioctl_get_dadstate, NULL },
	/* 191 */ { SIOCSLIFPREFIX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
			LIF_CMD, ip_sioctl_prefix, ip_sioctl_prefix_restart },
	/* 192 */ { SIOCGLIFHWADDR, sizeof (struct lifreq), IPI_GET_CMD,
			LIF_CMD, ip_sioctl_get_lifhwaddr, NULL }
};

int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);

ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
	{ I_LINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
	{ I_UNLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
	{ I_PLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
	{ ND_GET,	0, 0, 0, NULL, NULL },
	{ ND_SET,	0, IPI_PRIV | IPI_WR, 0, NULL, NULL },
	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_GET_CMD,
		MISC_CMD, mrt_ioctl},
	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_GET_CMD,
		MISC_CMD, mrt_ioctl},
	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_GET_CMD,
		MISC_CMD, mrt_ioctl}
};

int ip_misc_ioctl_count =
    sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);

int	conn_drain_nthreads;		/* Number of drainers reqd. */
					/* Settable in /etc/system */
/* Defined in ip_ire.c */
extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;

static nv_t	ire_nv_arr[] = {
	{ IRE_BROADCAST, "BROADCAST" },
	{ IRE_LOCAL, "LOCAL" },
	{ IRE_LOOPBACK, "LOOPBACK" },
	{ IRE_DEFAULT, "DEFAULT" },
	{ IRE_PREFIX, "PREFIX" },
	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
	{ IRE_IF_RESOLVER, "IF_RESOLV" },
	{ IRE_IF_CLONE, "IF_CLONE" },
	{ IRE_HOST, "HOST" },
	{ IRE_MULTICAST, "MULTICAST" },
	{ IRE_NOROUTE, "NOROUTE" },
	{ 0 }
};

nv_t	*ire_nv_tbl = ire_nv_arr;

/* Simple ICMP IP Header Template */
static ipha_t icmp_ipha = {
	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
};

struct module_info ip_mod_info = {
	IP_MOD_ID, IP_MOD_NAME, IP_MOD_MINPSZ, IP_MOD_MAXPSZ, IP_MOD_HIWAT,
	IP_MOD_LOWAT
};

/*
 * Duplicate static symbols within a module confuses mdb; so we avoid the
 * problem by making the symbols here distinct from those in udp.c.
 */

/*
 * Entry points for IP as a device and as a module.
 * We have separate open functions for the /dev/ip and /dev/ip6 devices.
 */
static struct qinit iprinitv4 = {
	ip_rput, NULL, ip_openv4, ip_close, NULL, &ip_mod_info
};

struct qinit iprinitv6 = {
	ip_rput_v6, NULL, ip_openv6, ip_close, NULL, &ip_mod_info
};

static struct qinit ipwinit = {
	ip_wput_nondata, ip_wsrv, NULL, NULL, NULL, &ip_mod_info
};

static struct qinit iplrinit = {
	ip_lrput, NULL, ip_openv4, ip_close, NULL, &ip_mod_info
};

static struct qinit iplwinit = {
	ip_lwput, NULL, NULL, NULL, NULL, &ip_mod_info
};

/* For AF_INET aka /dev/ip */
struct streamtab ipinfov4 = {
	&iprinitv4, &ipwinit, &iplrinit, &iplwinit
};

/* For AF_INET6 aka /dev/ip6 */
struct streamtab ipinfov6 = {
	&iprinitv6, &ipwinit, &iplrinit, &iplwinit
};

#ifdef	DEBUG
boolean_t skip_sctp_cksum = B_FALSE;
#endif

/*
 * Generate an ICMP fragmentation needed message.
 * When called from ip_output side a minimal ip_recv_attr_t needs to be
 * constructed by the caller.
 */
void
icmp_frag_needed(mblk_t *mp, int mtu, ip_recv_attr_t *ira)
{
	icmph_t	icmph;
	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;

	mp = icmp_pkt_err_ok(mp, ira);
	if (mp == NULL)
		return;

	bzero(&icmph, sizeof (icmph_t));
	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
	icmph.icmph_du_mtu = htons((uint16_t)mtu);
	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);

	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
}

/*
 * icmp_inbound_v4 deals with ICMP messages that are handled by IP.
 * If the ICMP message is consumed by IP, i.e., it should not be delivered
 * to any IPPROTO_ICMP raw sockets, then it returns NULL.
 * Likewise, if the ICMP error is misformed (too short, etc), then it
 * returns NULL. The caller uses this to determine whether or not to send
 * to raw sockets.
 *
 * All error messages are passed to the matching transport stream.
 *
 * The following cases are handled by icmp_inbound:
 * 1) It needs to send a reply back and possibly delivering it
 *    to the "interested" upper clients.
 * 2) Return the mblk so that the caller can pass it to the RAW socket clients.
 * 3) It needs to change some values in IP only.
 * 4) It needs to change some values in IP and upper layers e.g TCP
 *    by delivering an error to the upper layers.
 *
 * We handle the above three cases in the context of IPsec in the
 * following way :
 *
 * 1) Send the reply back in the same way as the request came in.
 *    If it came in encrypted, it goes out encrypted. If it came in
 *    clear, it goes out in clear. Thus, this will prevent chosen
 *    plain text attack.
 * 2) The client may or may not expect things to come in secure.
 *    If it comes in secure, the policy constraints are checked
 *    before delivering it to the upper layers. If it comes in
 *    clear, ipsec_inbound_accept_clear will decide whether to
 *    accept this in clear or not. In both the cases, if the returned
 *    message (IP header + 8 bytes) that caused the icmp message has
 *    AH/ESP headers, it is sent up to AH/ESP for validation before
 *    sending up. If there are only 8 bytes of returned message, then
 *    upper client will not be notified.
 * 3) Check with global policy to see whether it matches the constaints.
 *    But this will be done only if icmp_accept_messages_in_clear is
 *    zero.
 * 4) If we need to change both in IP and ULP, then the decision taken
 *    while affecting the values in IP and while delivering up to TCP
 *    should be the same.
 *
 *	There are two cases.
 *
 *	a) If we reject data at the IP layer (ipsec_check_global_policy()
 *	   failed), we will not deliver it to the ULP, even though they
 *	   are *willing* to accept in *clear*. This is fine as our global
 *	   disposition to icmp messages asks us reject the datagram.
 *
 *	b) If we accept data at the IP layer (ipsec_check_global_policy()
 *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
 *	   to deliver it to ULP (policy failed), it can lead to
 *	   consistency problems. The cases known at this time are
 *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
 *	   values :
 *
 *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
 *	     and Upper layer rejects. Then the communication will
 *	     come to a stop. This is solved by making similar decisions
 *	     at both levels. Currently, when we are unable to deliver
 *	     to the Upper Layer (due to policy failures) while IP has
 *	     adjusted dce_pmtu, the next outbound datagram would
 *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
 *	     will be with the right level of protection. Thus the right
 *	     value will be communicated even if we are not able to
 *	     communicate when we get from the wire initially. But this
 *	     assumes there would be at least one outbound datagram after
 *	     IP has adjusted its dce_pmtu value. To make things
 *	     simpler, we accept in clear after the validation of
 *	     AH/ESP headers.
 *
 *	   - Other ICMP ERRORS : We may not be able to deliver it to the
 *	     upper layer depending on the level of protection the upper
 *	     layer expects and the disposition in ipsec_inbound_accept_clear().
 *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
 *	     should be accepted in clear when the Upper layer expects secure.
 *	     Thus the communication may get aborted by some bad ICMP
 *	     packets.
 */
mblk_t *
icmp_inbound_v4(mblk_t *mp, ip_recv_attr_t *ira)
{
	icmph_t		*icmph;
	ipha_t		*ipha;		/* Outer header */
	int		ip_hdr_length;	/* Outer header length */
	boolean_t	interested;
	ipif_t		*ipif;
	uint32_t	ts;
	uint32_t	*tsp;
	timestruc_t	now;
	ill_t		*ill = ira->ira_ill;
	ip_stack_t	*ipst = ill->ill_ipst;
	zoneid_t	zoneid = ira->ira_zoneid;
	int		len_needed;
	mblk_t		*mp_ret = NULL;

	ipha = (ipha_t *)mp->b_rptr;

	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);

	ip_hdr_length = ira->ira_ip_hdr_length;
	if ((mp->b_wptr - mp->b_rptr) < (ip_hdr_length + ICMPH_SIZE)) {
		if (ira->ira_pktlen < (ip_hdr_length + ICMPH_SIZE)) {
			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
			freemsg(mp);
			return (NULL);
		}
		/* Last chance to get real. */
		ipha = ip_pullup(mp, ip_hdr_length + ICMPH_SIZE, ira);
		if (ipha == NULL) {
			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
			freemsg(mp);
			return (NULL);
		}
	}

	/* The IP header will always be a multiple of four bytes */
	icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
	ip2dbg(("icmp_inbound_v4: type %d code %d\n", icmph->icmph_type,
	    icmph->icmph_code));

	/*
	 * We will set "interested" to "true" if we should pass a copy to
	 * the transport or if we handle the packet locally.
	 */
	interested = B_FALSE;
	switch (icmph->icmph_type) {
	case ICMP_ECHO_REPLY:
		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
		break;
	case ICMP_DEST_UNREACHABLE:
		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
		interested = B_TRUE;	/* Pass up to transport */
		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
		break;
	case ICMP_SOURCE_QUENCH:
		interested = B_TRUE;	/* Pass up to transport */
		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
		break;
	case ICMP_REDIRECT:
		if (!ipst->ips_ip_ignore_redirect)
			interested = B_TRUE;
		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
		break;
	case ICMP_ECHO_REQUEST:
		/*
		 * Whether to respond to echo requests that come in as IP
		 * broadcasts or as IP multicast is subject to debate
		 * (what isn't?).  We aim to please, you pick it.
		 * Default is do it.
		 */
		if (ira->ira_flags & IRAF_MULTICAST) {
			/* multicast: respond based on tunable */
			interested = ipst->ips_ip_g_resp_to_echo_mcast;
		} else if (ira->ira_flags & IRAF_BROADCAST) {
			/* broadcast: respond based on tunable */
			interested = ipst->ips_ip_g_resp_to_echo_bcast;
		} else {
			/* unicast: always respond */
			interested = B_TRUE;
		}
		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
		if (!interested) {
			/* We never pass these to RAW sockets */
			freemsg(mp);
			return (NULL);
		}

		/* Check db_ref to make sure we can modify the packet. */
		if (mp->b_datap->db_ref > 1) {
			mblk_t	*mp1;

			mp1 = copymsg(mp);
			freemsg(mp);
			if (!mp1) {
				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
				return (NULL);
			}
			mp = mp1;
			ipha = (ipha_t *)mp->b_rptr;
			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
		}
		icmph->icmph_type = ICMP_ECHO_REPLY;
		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
		icmp_send_reply_v4(mp, ipha, icmph, ira);
		return (NULL);

	case ICMP_ROUTER_ADVERTISEMENT:
	case ICMP_ROUTER_SOLICITATION:
		break;
	case ICMP_TIME_EXCEEDED:
		interested = B_TRUE;	/* Pass up to transport */
		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
		break;
	case ICMP_PARAM_PROBLEM:
		interested = B_TRUE;	/* Pass up to transport */
		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
		break;
	case ICMP_TIME_STAMP_REQUEST:
		/* Response to Time Stamp Requests is local policy. */
		if (ipst->ips_ip_g_resp_to_timestamp) {
			if (ira->ira_flags & IRAF_MULTIBROADCAST)
				interested =
				    ipst->ips_ip_g_resp_to_timestamp_bcast;
			else
				interested = B_TRUE;
		}
		if (!interested) {
			/* We never pass these to RAW sockets */
			freemsg(mp);
			return (NULL);
		}

		/* Make sure we have enough of the packet */
		len_needed = ip_hdr_length + ICMPH_SIZE +
		    3 * sizeof (uint32_t);

		if (mp->b_wptr - mp->b_rptr < len_needed) {
			ipha = ip_pullup(mp, len_needed, ira);
			if (ipha == NULL) {
				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
				ip_drop_input("ipIfStatsInDiscards - ip_pullup",
				    mp, ill);
				freemsg(mp);
				return (NULL);
			}
			/* Refresh following the pullup. */
			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
		}
		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
		/* Check db_ref to make sure we can modify the packet. */
		if (mp->b_datap->db_ref > 1) {
			mblk_t	*mp1;

			mp1 = copymsg(mp);
			freemsg(mp);
			if (!mp1) {
				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
				return (NULL);
			}
			mp = mp1;
			ipha = (ipha_t *)mp->b_rptr;
			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
		}
		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
		tsp = (uint32_t *)&icmph[1];
		tsp++;		/* Skip past 'originate time' */
		/* Compute # of milliseconds since midnight */
		gethrestime(&now);
		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
		    NSEC2MSEC(now.tv_nsec);
		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
		*tsp++ = htonl(ts);	/* Lay in 'send time' */
		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
		icmp_send_reply_v4(mp, ipha, icmph, ira);
		return (NULL);

	case ICMP_TIME_STAMP_REPLY:
		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
		break;
	case ICMP_INFO_REQUEST:
		/* Per RFC 1122 3.2.2.7, ignore this. */
	case ICMP_INFO_REPLY:
		break;
	case ICMP_ADDRESS_MASK_REQUEST:
		if (ira->ira_flags & IRAF_MULTIBROADCAST) {
			interested =
			    ipst->ips_ip_respond_to_address_mask_broadcast;
		} else {
			interested = B_TRUE;
		}
		if (!interested) {
			/* We never pass these to RAW sockets */
			freemsg(mp);
			return (NULL);
		}
		len_needed = ip_hdr_length + ICMPH_SIZE + IP_ADDR_LEN;
		if (mp->b_wptr - mp->b_rptr < len_needed) {
			ipha = ip_pullup(mp, len_needed, ira);
			if (ipha == NULL) {
				BUMP_MIB(ill->ill_ip_mib,
				    ipIfStatsInTruncatedPkts);
				ip_drop_input("ipIfStatsInTruncatedPkts", mp,
				    ill);
				freemsg(mp);
				return (NULL);
			}
			/* Refresh following the pullup. */
			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
		}
		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
		/* Check db_ref to make sure we can modify the packet. */
		if (mp->b_datap->db_ref > 1) {
			mblk_t	*mp1;

			mp1 = copymsg(mp);
			freemsg(mp);
			if (!mp1) {
				BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
				return (NULL);
			}
			mp = mp1;
			ipha = (ipha_t *)mp->b_rptr;
			icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
		}
		/*
		 * Need the ipif with the mask be the same as the source
		 * address of the mask reply. For unicast we have a specific
		 * ipif. For multicast/broadcast we only handle onlink
		 * senders, and use the source address to pick an ipif.
		 */
		ipif = ipif_lookup_addr(ipha->ipha_dst, ill, zoneid, ipst);
		if (ipif == NULL) {
			/* Broadcast or multicast */
			ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
			if (ipif == NULL) {
				freemsg(mp);
				return (NULL);
			}
		}
		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
		bcopy(&ipif->ipif_net_mask, &icmph[1], IP_ADDR_LEN);
		ipif_refrele(ipif);
		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
		icmp_send_reply_v4(mp, ipha, icmph, ira);
		return (NULL);

	case ICMP_ADDRESS_MASK_REPLY:
		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
		break;
	default:
		interested = B_TRUE;	/* Pass up to transport */
		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
		break;
	}
	/*
	 * See if there is an ICMP client to avoid an extra copymsg/freemsg
	 * if there isn't one.
	 */
	if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_ICMP].connf_head != NULL) {
		/* If there is an ICMP client and we want one too, copy it. */

		if (!interested) {
			/* Caller will deliver to RAW sockets */
			return (mp);
		}
		mp_ret = copymsg(mp);
		if (mp_ret == NULL) {
			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
			ip_drop_input("ipIfStatsInDiscards - copymsg", mp, ill);
		}
	} else if (!interested) {
		/* Neither we nor raw sockets are interested. Drop packet now */
		freemsg(mp);
		return (NULL);
	}

	/*
	 * ICMP error or redirect packet. Make sure we have enough of
	 * the header and that db_ref == 1 since we might end up modifying
	 * the packet.
	 */
	if (mp->b_cont != NULL) {
		if (ip_pullup(mp, -1, ira) == NULL) {
			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
			ip_drop_input("ipIfStatsInDiscards - ip_pullup",
			    mp, ill);
			freemsg(mp);
			return (mp_ret);
		}
	}

	if (mp->b_datap->db_ref > 1) {
		mblk_t	*mp1;

		mp1 = copymsg(mp);
		if (mp1 == NULL) {
			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
			ip_drop_input("ipIfStatsInDiscards - copymsg", mp, ill);
			freemsg(mp);
			return (mp_ret);
		}
		freemsg(mp);
		mp = mp1;
	}

	/*
	 * In case mp has changed, verify the message before any further
	 * processes.
	 */
	ipha = (ipha_t *)mp->b_rptr;
	icmph = (icmph_t *)&mp->b_rptr[ip_hdr_length];
	if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
		freemsg(mp);
		return (mp_ret);
	}

	switch (icmph->icmph_type) {
	case ICMP_REDIRECT:
		icmp_redirect_v4(mp, ipha, icmph, ira);
		break;
	case ICMP_DEST_UNREACHABLE:
		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
			/* Update DCE and adjust MTU is icmp header if needed */
			icmp_inbound_too_big_v4(icmph, ira);
		}
		/* FALLTHROUGH */
	default:
		icmp_inbound_error_fanout_v4(mp, icmph, ira);
		break;
	}
	return (mp_ret);
}

/*
 * Send an ICMP echo, timestamp or address mask reply.
 * The caller has already updated the payload part of the packet.
 * We handle the ICMP checksum, IP source address selection and feed
 * the packet into ip_output_simple.
 */
static void
icmp_send_reply_v4(mblk_t *mp, ipha_t *ipha, icmph_t *icmph,
    ip_recv_attr_t *ira)
{
	uint_t		ip_hdr_length = ira->ira_ip_hdr_length;
	ill_t		*ill = ira->ira_ill;
	ip_stack_t	*ipst = ill->ill_ipst;
	ip_xmit_attr_t	ixas;

	/* Send out an ICMP packet */
	icmph->icmph_checksum = 0;
	icmph->icmph_checksum = IP_CSUM(mp, ip_hdr_length, 0);
	/* Reset time to live. */
	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
	{
		/* Swap source and destination addresses */
		ipaddr_t tmp;

		tmp = ipha->ipha_src;
		ipha->ipha_src = ipha->ipha_dst;
		ipha->ipha_dst = tmp;
	}
	ipha->ipha_ident = 0;
	if (!IS_SIMPLE_IPH(ipha))
		icmp_options_update(ipha);

	bzero(&ixas, sizeof (ixas));
	ixas.ixa_flags = IXAF_BASIC_SIMPLE_V4;
	ixas.ixa_zoneid = ira->ira_zoneid;
	ixas.ixa_cred = kcred;
	ixas.ixa_cpid = NOPID;
	ixas.ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
	ixas.ixa_ifindex = 0;
	ixas.ixa_ipst = ipst;
	ixas.ixa_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;

	if (!(ira->ira_flags & IRAF_IPSEC_SECURE)) {
		/*
		 * This packet should go out the same way as it
		 * came in i.e in clear, independent of the IPsec policy
		 * for transmitting packets.
		 */
		ixas.ixa_flags |= IXAF_NO_IPSEC;
	} else {
		if (!ipsec_in_to_out(ira, &ixas, mp, ipha, NULL)) {
			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
			/* Note: mp already consumed and ip_drop_packet done */
			return;
		}
	}
	if (ira->ira_flags & IRAF_MULTIBROADCAST) {
		/*
		 * Not one or our addresses (IRE_LOCALs), thus we let
		 * ip_output_simple pick the source.
		 */
		ipha->ipha_src = INADDR_ANY;
		ixas.ixa_flags |= IXAF_SET_SOURCE;
	}
	/* Should we send with DF and use dce_pmtu? */
	if (ipst->ips_ipv4_icmp_return_pmtu) {
		ixas.ixa_flags |= IXAF_PMTU_DISCOVERY;
		ipha->ipha_fragment_offset_and_flags |= IPH_DF_HTONS;
	}

	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);

	(void) ip_output_simple(mp, &ixas);
	ixa_cleanup(&ixas);
}

/*
 * Verify the ICMP messages for either for ICMP error or redirect packet.
 * The caller should have fully pulled up the message. If it's a redirect
 * packet, only basic checks on IP header will be done; otherwise, verify
 * the packet by looking at the included ULP header.
 *
 * Called before icmp_inbound_error_fanout_v4 is called.
 */
static boolean_t
icmp_inbound_verify_v4(mblk_t *mp, icmph_t *icmph, ip_recv_attr_t *ira)
{
	ill_t		*ill = ira->ira_ill;
	int		hdr_length;
	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
	conn_t		*connp;
	ipha_t		*ipha;	/* Inner IP header */

	ipha = (ipha_t *)&icmph[1];
	if ((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH > mp->b_wptr)
		goto truncated;

	hdr_length = IPH_HDR_LENGTH(ipha);

	if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION))
		goto discard_pkt;

	if (hdr_length < sizeof (ipha_t))
		goto truncated;

	if ((uchar_t *)ipha + hdr_length > mp->b_wptr)
		goto truncated;

	/*
	 * Stop here for ICMP_REDIRECT.
	 */
	if (icmph->icmph_type == ICMP_REDIRECT)
		return (B_TRUE);

	/*
	 * ICMP errors only.
	 */
	switch (ipha->ipha_protocol) {
	case IPPROTO_UDP:
		/*
		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
		 * transport header.
		 */
		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
		    mp->b_wptr)
			goto truncated;
		break;
	case IPPROTO_TCP: {
		tcpha_t		*tcpha;

		/*
		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
		 * transport header.
		 */
		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
		    mp->b_wptr)
			goto truncated;

		tcpha = (tcpha_t *)((uchar_t *)ipha + hdr_length);
		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcpha, TCPS_LISTEN,
		    ipst);
		if (connp == NULL)
			goto discard_pkt;

		if ((connp->conn_verifyicmp != NULL) &&
		    !connp->conn_verifyicmp(connp, tcpha, icmph, NULL, ira)) {
			CONN_DEC_REF(connp);
			goto discard_pkt;
		}
		CONN_DEC_REF(connp);
		break;
	}
	case IPPROTO_SCTP:
		/*
		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
		 * transport header.
		 */
		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
		    mp->b_wptr)
			goto truncated;
		break;
	case IPPROTO_ESP:
	case IPPROTO_AH:
		break;
	case IPPROTO_ENCAP:
		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
		    mp->b_wptr)
			goto truncated;
		break;
	default:
		break;
	}

	return (B_TRUE);

discard_pkt:
	/* Bogus ICMP error. */
	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
	return (B_FALSE);

truncated:
	/* We pulled up everthing already. Must be truncated */
	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
	ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
	return (B_FALSE);
}

/* Table from RFC 1191 */
static int icmp_frag_size_table[] =
{ 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };

/*
 * Process received ICMP Packet too big.
 * Just handles the DCE create/update, including using the above table of
 * PMTU guesses. The caller is responsible for validating the packet before
 * passing it in and also to fanout the ICMP error to any matching transport
 * conns. Assumes the message has been fully pulled up and verified.
 *
 * Before getting here, the caller has called icmp_inbound_verify_v4()
 * that should have verified with ULP to prevent undoing the changes we're
 * going to make to DCE. For example, TCP might have verified that the packet
 * which generated error is in the send window.
 *
 * In some cases modified this MTU in the ICMP header packet; the caller
 * should pass to the matching ULP after this returns.
 */
static void
icmp_inbound_too_big_v4(icmph_t *icmph, ip_recv_attr_t *ira)
{
	dce_t		*dce;
	int		old_mtu;
	int		mtu, orig_mtu;
	ipaddr_t	dst;
	boolean_t	disable_pmtud;
	ill_t		*ill = ira->ira_ill;
	ip_stack_t	*ipst = ill->ill_ipst;
	uint_t		hdr_length;
	ipha_t		*ipha;

	/* Caller already pulled up everything. */
	ipha = (ipha_t *)&icmph[1];
	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
	ASSERT(ill != NULL);

	hdr_length = IPH_HDR_LENGTH(ipha);

	/*
	 * We handle path MTU for source routed packets since the DCE
	 * is looked up using the final destination.
	 */
	dst = ip_get_dst(ipha);

	dce = dce_lookup_and_add_v4(dst, ipst);
	if (dce == NULL) {
		/* Couldn't add a unique one - ENOMEM */
		ip1dbg(("icmp_inbound_too_big_v4: no dce for 0x%x\n",
		    ntohl(dst)));
		return;
	}

	/* Check for MTU discovery advice as described in RFC 1191 */
	mtu = ntohs(icmph->icmph_du_mtu);
	orig_mtu = mtu;
	disable_pmtud = B_FALSE;

	mutex_enter(&dce->dce_lock);
	if (dce->dce_flags & DCEF_PMTU)
		old_mtu = dce->dce_pmtu;
	else
		old_mtu = ill->ill_mtu;

	if (icmph->icmph_du_zero != 0 || mtu < ipst->ips_ip_pmtu_min) {
		uint32_t length;
		int	i;

		/*
		 * Use the table from RFC 1191 to figure out
		 * the next "plateau" based on the length in
		 * the original IP packet.
		 */
		length = ntohs(ipha->ipha_length);
		DTRACE_PROBE2(ip4__pmtu__guess, dce_t *, dce,
		    uint32_t, length);
		if (old_mtu <= length &&
		    old_mtu >= length - hdr_length) {
			/*
			 * Handle broken BSD 4.2 systems that
			 * return the wrong ipha_length in ICMP
			 * errors.
			 */
			ip1dbg(("Wrong mtu: sent %d, dce %d\n",
			    length, old_mtu));
			length -= hdr_length;
		}
		for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
			if (length > icmp_frag_size_table[i])
				break;
		}
		if (i == A_CNT(icmp_frag_size_table)) {
			/* Smaller than IP_MIN_MTU! */
			ip1dbg(("Too big for packet size %d\n",
			    length));
			disable_pmtud = B_TRUE;
			mtu = ipst->ips_ip_pmtu_min;
		} else {
			mtu = icmp_frag_size_table[i];
			ip1dbg(("Calculated mtu %d, packet size %d, "
			    "before %d\n", mtu, length, old_mtu));
			if (mtu < ipst->ips_ip_pmtu_min) {
				mtu = ipst->ips_ip_pmtu_min;
				disable_pmtud = B_TRUE;
			}
		}
	}
	if (disable_pmtud)
		dce->dce_flags |= DCEF_TOO_SMALL_PMTU;
	else
		dce->dce_flags &= ~DCEF_TOO_SMALL_PMTU;

	dce->dce_pmtu = MIN(old_mtu, mtu);
	/* Prepare to send the new max frag size for the ULP. */
	icmph->icmph_du_zero = 0;
	icmph->icmph_du_mtu =  htons((uint16_t)dce->dce_pmtu);
	DTRACE_PROBE4(ip4__pmtu__change, icmph_t *, icmph, dce_t *,
	    dce, int, orig_mtu, int, mtu);

	/* We now have a PMTU for sure */
	dce->dce_flags |= DCEF_PMTU;
	dce->dce_last_change_time = TICK_TO_SEC(ddi_get_lbolt64());
	mutex_exit(&dce->dce_lock);
	/*
	 * After dropping the lock the new value is visible to everyone.
	 * Then we bump the generation number so any cached values reinspect
	 * the dce_t.
	 */
	dce_increment_generation(dce);
	dce_refrele(dce);
}

/*
 * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout_v4
 * calls this function.
 */
static mblk_t *
icmp_inbound_self_encap_error_v4(mblk_t *mp, ipha_t *ipha, ipha_t *in_ipha)
{
	int length;

	ASSERT(mp->b_datap->db_type == M_DATA);

	/* icmp_inbound_v4 has already pulled up the whole error packet */
	ASSERT(mp->b_cont == NULL);

	/*
	 * The length that we want to overlay is the inner header
	 * and what follows it.
	 */
	length = msgdsize(mp) - ((uchar_t *)in_ipha - mp->b_rptr);

	/*
	 * Overlay the inner header and whatever follows it over the
	 * outer header.
	 */
	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);

	/* Adjust for what we removed */
	mp->b_wptr -= (uchar_t *)in_ipha - (uchar_t *)ipha;
	return (mp);
}

/*
 * Try to pass the ICMP message upstream in case the ULP cares.
 *
 * If the packet that caused the ICMP error is secure, we send
 * it to AH/ESP to make sure that the attached packet has a
 * valid association. ipha in the code below points to the
 * IP header of the packet that caused the error.
 *
 * For IPsec cases, we let the next-layer-up (which has access to
 * cached policy on the conn_t, or can query the SPD directly)
 * subtract out any IPsec overhead if they must.  We therefore make no
 * adjustments here for IPsec overhead.
 *
 * IFN could have been generated locally or by some router.
 *
 * LOCAL : ire_send_wire (before calling ipsec_out_process) can call
 * icmp_frag_needed/icmp_pkt2big_v6 to generated a local IFN.
 *	    This happens because IP adjusted its value of MTU on an
 *	    earlier IFN message and could not tell the upper layer,
 *	    the new adjusted value of MTU e.g. Packet was encrypted
 *	    or there was not enough information to fanout to upper
 *	    layers. Thus on the next outbound datagram, ire_send_wire
 *	    generates the IFN, where IPsec processing has *not* been
 *	    done.
 *
 *	    Note that we retain ixa_fragsize across IPsec thus once
 *	    we have picking ixa_fragsize and entered ipsec_out_process we do
 *	    no change the fragsize even if the path MTU changes before
 *	    we reach ip_output_post_ipsec.
 *
 *	    In the local case, IRAF_LOOPBACK will be set indicating
 *	    that IFN was generated locally.
 *
 * ROUTER : IFN could be secure or non-secure.
 *
 *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
 *	      packet in error has AH/ESP headers to validate the AH/ESP
 *	      headers. AH/ESP will verify whether there is a valid SA or
 *	      not and send it back. We will fanout again if we have more
 *	      data in the packet.
 *
 *	      If the packet in error does not have AH/ESP, we handle it
 *	      like any other case.
 *
 *	    * NON_SECURE : If the packet in error has AH/ESP headers, we send it
 *	      up to AH/ESP for validation. AH/ESP will verify whether there is a
 *	      valid SA or not and send it back. We will fanout again if
 *	      we have more data in the packet.
 *
 *	      If the packet in error does not have AH/ESP, we handle it
 *	      like any other case.
 *
 * The caller must have called icmp_inbound_verify_v4.
 */
static void
icmp_inbound_error_fanout_v4(mblk_t *mp, icmph_t *icmph, ip_recv_attr_t *ira)
{
	uint16_t	*up;	/* Pointer to ports in ULP header */
	uint32_t	ports;	/* reversed ports for fanout */
	ipha_t		ripha;	/* With reversed addresses */
	ipha_t		*ipha;  /* Inner IP header */
	uint_t		hdr_length; /* Inner IP header length */
	tcpha_t		*tcpha;
	conn_t		*connp;
	ill_t		*ill = ira->ira_ill;
	ip_stack_t	*ipst = ill->ill_ipst;
	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
	ill_t		*rill = ira->ira_rill;

	/* Caller already pulled up everything. */
	ipha = (ipha_t *)&icmph[1];
	ASSERT((uchar_t *)&ipha[1] <= mp->b_wptr);
	ASSERT(mp->b_cont == NULL);

	hdr_length = IPH_HDR_LENGTH(ipha);
	ira->ira_protocol = ipha->ipha_protocol;

	/*
	 * We need a separate IP header with the source and destination
	 * addresses reversed to do fanout/classification because the ipha in
	 * the ICMP error is in the form we sent it out.
	 */
	ripha.ipha_src = ipha->ipha_dst;
	ripha.ipha_dst = ipha->ipha_src;
	ripha.ipha_protocol = ipha->ipha_protocol;
	ripha.ipha_version_and_hdr_length = ipha->ipha_version_and_hdr_length;

	ip2dbg(("icmp_inbound_error_v4: proto %d %x to %x: %d/%d\n",
	    ripha.ipha_protocol, ntohl(ipha->ipha_src),
	    ntohl(ipha->ipha_dst),
	    icmph->icmph_type, icmph->icmph_code));

	switch (ipha->ipha_protocol) {
	case IPPROTO_UDP:
		up = (uint16_t *)((uchar_t *)ipha + hdr_length);

		/* Attempt to find a client stream based on port. */
		ip2dbg(("icmp_inbound_error_v4: UDP ports %d to %d\n",
		    ntohs(up[0]), ntohs(up[1])));

		/* Note that we send error to all matches. */
		ira->ira_flags |= IRAF_ICMP_ERROR;
		ip_fanout_udp_multi_v4(mp, &ripha, up[0], up[1], ira);
		ira->ira_flags &= ~IRAF_ICMP_ERROR;
		return;

	case IPPROTO_TCP:
		/*
		 * Find a TCP client stream for this packet.
		 * Note that we do a reverse lookup since the header is
		 * in the form we sent it out.
		 */
		tcpha = (tcpha_t *)((uchar_t *)ipha + hdr_length);
		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcpha, TCPS_LISTEN,
		    ipst);
		if (connp == NULL)
			goto discard_pkt;

		if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
		    (ira->ira_flags & IRAF_IPSEC_SECURE)) {
			mp = ipsec_check_inbound_policy(mp, connp,
			    ipha, NULL, ira);
			if (mp == NULL) {
				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
				/* Note that mp is NULL */
				ip_drop_input("ipIfStatsInDiscards", mp, ill);
				CONN_DEC_REF(connp);
				return;
			}
		}

		ira->ira_flags |= IRAF_ICMP_ERROR;
		ira->ira_ill = ira->ira_rill = NULL;
		if (IPCL_IS_TCP(connp)) {
			SQUEUE_ENTER_ONE(connp->conn_sqp, mp,
			    connp->conn_recvicmp, connp, ira, SQ_FILL,
			    SQTAG_TCP_INPUT_ICMP_ERR);
		} else {
			/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
			(connp->conn_recv)(connp, mp, NULL, ira);
			CONN_DEC_REF(connp);
		}
		ira->ira_ill = ill;
		ira->ira_rill = rill;
		ira->ira_flags &= ~IRAF_ICMP_ERROR;
		return;

	case IPPROTO_SCTP:
		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
		/* Find a SCTP client stream for this packet. */
		((uint16_t *)&ports)[0] = up[1];
		((uint16_t *)&ports)[1] = up[0];

		ira->ira_flags |= IRAF_ICMP_ERROR;
		ip_fanout_sctp(mp, &ripha, NULL, ports, ira);
		ira->ira_flags &= ~IRAF_ICMP_ERROR;
		return;

	case IPPROTO_ESP:
	case IPPROTO_AH:
		if (!ipsec_loaded(ipss)) {
			ip_proto_not_sup(mp, ira);
			return;
		}

		if (ipha->ipha_protocol == IPPROTO_ESP)
			mp = ipsecesp_icmp_error(mp, ira);
		else
			mp = ipsecah_icmp_error(mp, ira);
		if (mp == NULL)
			return;

		/* Just in case ipsec didn't preserve the NULL b_cont */
		if (mp->b_cont != NULL) {
			if (!pullupmsg(mp, -1))
				goto discard_pkt;
		}

		/*
		 * Note that ira_pktlen and ira_ip_hdr_length are no longer
		 * correct, but we don't use them any more here.
		 *
		 * If succesful, the mp has been modified to not include
		 * the ESP/AH header so we can fanout to the ULP's icmp
		 * error handler.
		 */
		if (mp->b_wptr - mp->b_rptr < IP_SIMPLE_HDR_LENGTH)
			goto truncated;

		/* Verify the modified message before any further processes. */
		ipha = (ipha_t *)mp->b_rptr;
		hdr_length = IPH_HDR_LENGTH(ipha);
		icmph = (icmph_t *)&mp->b_rptr[hdr_length];
		if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
			freemsg(mp);
			return;
		}

		icmp_inbound_error_fanout_v4(mp, icmph, ira);
		return;

	case IPPROTO_ENCAP: {
		/* Look for self-encapsulated packets that caused an error */
		ipha_t *in_ipha;

		/*
		 * Caller has verified that length has to be
		 * at least the size of IP header.
		 */
		ASSERT(hdr_length >= sizeof (ipha_t));
		/*
		 * Check the sanity of the inner IP header like
		 * we did for the outer header.
		 */
		in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
		if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
			goto discard_pkt;
		}
		if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
			goto discard_pkt;
		}
		/* Check for Self-encapsulated tunnels */
		if (in_ipha->ipha_src == ipha->ipha_src &&
		    in_ipha->ipha_dst == ipha->ipha_dst) {

			mp = icmp_inbound_self_encap_error_v4(mp, ipha,
			    in_ipha);
			if (mp == NULL)
				goto discard_pkt;

			/*
			 * Just in case self_encap didn't preserve the NULL
			 * b_cont
			 */
			if (mp->b_cont != NULL) {
				if (!pullupmsg(mp, -1))
					goto discard_pkt;
			}
			/*
			 * Note that ira_pktlen and ira_ip_hdr_length are no
			 * longer correct, but we don't use them any more here.
			 */
			if (mp->b_wptr - mp->b_rptr < IP_SIMPLE_HDR_LENGTH)
				goto truncated;

			/*
			 * Verify the modified message before any further
			 * processes.
			 */
			ipha = (ipha_t *)mp->b_rptr;
			hdr_length = IPH_HDR_LENGTH(ipha);
			icmph = (icmph_t *)&mp->b_rptr[hdr_length];
			if (!icmp_inbound_verify_v4(mp, icmph, ira)) {
				freemsg(mp);
				return;
			}

			/*
			 * The packet in error is self-encapsualted.
			 * And we are finding it further encapsulated
			 * which we could not have possibly generated.
			 */
			if (ipha->ipha_protocol == IPPROTO_ENCAP) {
				goto discard_pkt;
			}
			icmp_inbound_error_fanout_v4(mp, icmph, ira);
			return;
		}
		/* No self-encapsulated */
	}
	/* FALLTHROUGH */
	case IPPROTO_IPV6:
		if ((connp = ipcl_iptun_classify_v4(&ripha.ipha_src,
		    &ripha.ipha_dst, ipst)) != NULL) {
			ira->ira_flags |= IRAF_ICMP_ERROR;
			connp->conn_recvicmp(connp, mp, NULL, ira);
			CONN_DEC_REF(connp);
			ira->ira_flags &= ~IRAF_ICMP_ERROR;
			return;
		}
		/*
		 * No IP tunnel is interested, fallthrough and see
		 * if a raw socket will want it.
		 */
		/* FALLTHROUGH */
	default:
		ira->ira_flags |= IRAF_ICMP_ERROR;
		ip_fanout_proto_v4(mp, &ripha, ira);
		ira->ira_flags &= ~IRAF_ICMP_ERROR;
		return;
	}
	/* NOTREACHED */
discard_pkt:
	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
	ip1dbg(("icmp_inbound_error_fanout_v4: drop pkt\n"));
	ip_drop_input("ipIfStatsInDiscards", mp, ill);
	freemsg(mp);
	return;

truncated:
	/* We pulled up everthing already. Must be truncated */
	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
	ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
	freemsg(mp);
}

/*
 * Common IP options parser.
 *
 * Setup routine: fill in *optp with options-parsing state, then
 * tail-call ipoptp_next to return the first option.
 */
uint8_t
ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
{
	uint32_t totallen; /* total length of all options */

	totallen = ipha->ipha_version_and_hdr_length -
	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
	totallen <<= 2;
	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
	optp->ipoptp_end = optp->ipoptp_next + totallen;
	optp->ipoptp_flags = 0;
	return (ipoptp_next(optp));
}

/* Like above but without an ipha_t */
uint8_t
ipoptp_first2(ipoptp_t *optp, uint32_t totallen, uint8_t *opt)
{
	optp->ipoptp_next = opt;
	optp->ipoptp_end = optp->ipoptp_next + totallen;
	optp->ipoptp_flags = 0;
	return (ipoptp_next(optp));
}

/*
 * Common IP options parser: extract next option.
 */
uint8_t
ipoptp_next(ipoptp_t *optp)
{
	uint8_t *end = optp->ipoptp_end;
	uint8_t *cur = optp->ipoptp_next;
	uint8_t opt, len, pointer;

	/*
	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
	 * has been corrupted.
	 */
	ASSERT(cur <= end);

	if (cur == end)
		return (IPOPT_EOL);

	opt = cur[IPOPT_OPTVAL];

	/*
	 * Skip any NOP options.
	 */
	while (opt == IPOPT_NOP) {
		cur++;
		if (cur == end)
			return (IPOPT_EOL);
		opt = cur[IPOPT_OPTVAL];
	}

	if (opt == IPOPT_EOL)
		return (IPOPT_EOL);

	/*
	 * Option requiring a length.
	 */
	if ((cur + 1) >= end) {
		optp->ipoptp_flags |= IPOPTP_ERROR;
		return (IPOPT_EOL);
	}
	len = cur[IPOPT_OLEN];
	if (len < 2) {
		optp->ipoptp_flags |= IPOPTP_ERROR;
		return (IPOPT_EOL);
	}
	optp->ipoptp_cur = cur;
	optp->ipoptp_len = len;
	optp->ipoptp_next = cur + len;
	if (cur + len > end) {
		optp->ipoptp_flags |= IPOPTP_ERROR;
		return (IPOPT_EOL);
	}

	/*
	 * For the options which require a pointer field, make sure
	 * its there, and make sure it points to either something
	 * inside this option, or the end of the option.
	 */
	pointer = IPOPT_EOL;
	switch (opt) {
	case IPOPT_RR:
	case IPOPT_TS:
	case IPOPT_LSRR:
	case IPOPT_SSRR:
		if (len <= IPOPT_OFFSET) {
			optp->ipoptp_flags |= IPOPTP_ERROR;
			return (opt);
		}
		pointer = cur[IPOPT_OFFSET];
		if (pointer - 1 > len) {
			optp->ipoptp_flags |= IPOPTP_ERROR;
			return (opt);
		}
		break;
	}

	/*
	 * Sanity check the pointer field based on the type of the
	 * option.
	 */
	switch (opt) {
	case IPOPT_RR:
	case IPOPT_SSRR:
	case IPOPT_LSRR:
		if (pointer < IPOPT_MINOFF_SR)
			optp->ipoptp_flags |= IPOPTP_ERROR;
		break;
	case IPOPT_TS:
		if (pointer < IPOPT_MINOFF_IT)
			optp->ipoptp_flags |= IPOPTP_ERROR;
		/*
		 * Note that the Internet Timestamp option also
		 * contains two four bit fields (the Overflow field,
		 * and the Flag field), which follow the pointer
		 * field.  We don't need to check that these fields
		 * fall within the length of the option because this
		 * was implicitely done above.  We've checked that the
		 * pointer value is at least IPOPT_MINOFF_IT, and that
		 * it falls within the option.  Since IPOPT_MINOFF_IT >
		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
		 */
		ASSERT(len > IPOPT_POS_OV_FLG);
		break;
	}

	return (opt);
}

/*
 * Use the outgoing IP header to create an IP_OPTIONS option the way
 * it was passed down from the application.
 *
 * This is compatible with BSD in that it returns
 * the reverse source route with the final destination
 * as the last entry. The first 4 bytes of the option
 * will contain the final destination.
 */
int
ip_opt_get_user(conn_t *connp, uchar_t *buf)
{
	ipoptp_t	opts;
	uchar_t		*opt;
	uint8_t		optval;
	uint8_t		optlen;
	uint32_t	len = 0;
	uchar_t		*buf1 = buf;
	uint32_t	totallen;
	ipaddr_t	dst;
	ip_pkt_t	*ipp = &connp->conn_xmit_ipp;

	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
		return (0);

	totallen = ipp->ipp_ipv4_options_len;
	if (totallen & 0x3)
		return (0);

	buf += IP_ADDR_LEN;	/* Leave room for final destination */
	len += IP_ADDR_LEN;
	bzero(buf1, IP_ADDR_LEN);

	dst = connp->conn_faddr_v4;

	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
	    optval != IPOPT_EOL;
	    optval = ipoptp_next(&opts)) {
		int	off;

		opt = opts.ipoptp_cur;
		if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
			break;
		}
		optlen = opts.ipoptp_len;

		switch (optval) {
		case IPOPT_SSRR:
		case IPOPT_LSRR:

			/*
			 * Insert destination as the first entry in the source
			 * route and move down the entries on step.
			 * The last entry gets placed at buf1.
			 */
			buf[IPOPT_OPTVAL] = optval;
			buf[IPOPT_OLEN] = optlen;
			buf[IPOPT_OFFSET] = optlen;

			off = optlen - IP_ADDR_LEN;
			if (off < 0) {
				/* No entries in source route */
				break;
			}
			/* Last entry in source route if not already set */
			if (dst == INADDR_ANY)
				bcopy(opt + off, buf1, IP_ADDR_LEN);
			off -= IP_ADDR_LEN;

			while (off > 0) {
				bcopy(opt + off,
				    buf + off + IP_ADDR_LEN,
				    IP_ADDR_LEN);
				off -= IP_ADDR_LEN;
			}
			/* ipha_dst into first slot */
			bcopy(&dst, buf + off + IP_ADDR_LEN,
			    IP_ADDR_LEN);
			buf += optlen;
			len += optlen;
			break;

		default:
			bcopy(opt, buf, optlen);
			buf += optlen;
			len += optlen;
			break;
		}
	}
done:
	/* Pad the resulting options */
	while (len & 0x3) {
		*buf++ = IPOPT_EOL;
		len++;
	}
	return (len);
}

/*
 * Update any record route or timestamp options to include this host.
 * Reverse any source route option.
 * This routine assumes that the options are well formed i.e. that they
 * have already been checked.
 */
static void
icmp_options_update(ipha_t *ipha)
{
	ipoptp_t	opts;
	uchar_t		*opt;
	uint8_t		optval;
	ipaddr_t	src;		/* Our local address */
	ipaddr_t	dst;

	ip2dbg(("icmp_options_update\n"));
	src = ipha->ipha_src;
	dst = ipha->ipha_dst;

	for (optval = ipoptp_first(&opts, ipha);
	    optval != IPOPT_EOL;
	    optval = ipoptp_next(&opts)) {
		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
		opt = opts.ipoptp_cur;
		ip2dbg(("icmp_options_update: opt %d, len %d\n",
		    optval, opts.ipoptp_len));
		switch (optval) {
			int off1, off2;
		case IPOPT_SSRR:
		case IPOPT_LSRR:
			/*
			 * Reverse the source route.  The first entry
			 * should be the next to last one in the current
			 * source route (the last entry is our address).
			 * The last entry should be the final destination.
			 */
			off1 = IPOPT_MINOFF_SR - 1;
			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
			if (off2 < 0) {
				/* No entries in source route */
				ip1dbg((
				    "icmp_options_update: bad src route\n"));
				break;
			}
			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
			off2 -= IP_ADDR_LEN;

			while (off1 < off2) {
				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
				bcopy((char *)opt + off2, (char *)opt + off1,
				    IP_ADDR_LEN);
				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
				off1 += IP_ADDR_LEN;
				off2 -= IP_ADDR_LEN;
			}
			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
			break;
		}
	}
}

/*
 * Process received ICMP Redirect messages.
 * Assumes the caller has verified that the headers are in the pulled up mblk.
 * Consumes mp.
 */
static void
icmp_redirect_v4(mblk_t *mp, ipha_t *ipha, icmph_t *icmph, ip_recv_attr_t *ira)
{
	ire_t		*ire, *nire;
	ire_t		*prev_ire;
	ipaddr_t	src, dst, gateway;
	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
	ipha_t		*inner_ipha;	/* Inner IP header */

	/* Caller already pulled up everything. */
	inner_ipha = (ipha_t *)&icmph[1];
	src = ipha->ipha_src;
	dst = inner_ipha->ipha_dst;
	gateway = icmph->icmph_rd_gateway;
	/* Make sure the new gateway is reachable somehow. */
	ire = ire_ftable_lookup_v4(gateway, 0, 0, IRE_ONLINK, NULL,
	    ALL_ZONES, NULL, MATCH_IRE_TYPE, 0, ipst, NULL);
	/*
	 * Make sure we had a route for the dest in question and that
	 * that route was pointing to the old gateway (the source of the
	 * redirect packet.)
	 * We do longest match and then compare ire_gateway_addr below.
	 */
	prev_ire = ire_ftable_lookup_v4(dst, 0, 0, 0, NULL, ALL_ZONES,
	    NULL, MATCH_IRE_DSTONLY, 0, ipst, NULL);
	/*
	 * Check that
	 *	the redirect was not from ourselves
	 *	the new gateway and the old gateway are directly reachable
	 */
	if (prev_ire == NULL || ire == NULL ||
	    (prev_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) ||
	    (prev_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
	    !(ire->ire_type & IRE_IF_ALL) ||
	    prev_ire->ire_gateway_addr != src) {
		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
		ip_drop_input("icmpInBadRedirects - ire", mp, ira->ira_ill);
		freemsg(mp);
		if (ire != NULL)
			ire_refrele(ire);
		if (prev_ire != NULL)
			ire_refrele(prev_ire);
		return;
	}

	ire_refrele(prev_ire);
	ire_refrele(ire);

	/*
	 * TODO: more precise handling for cases 0, 2, 3, the latter two
	 * require TOS routing
	 */
	switch (icmph->icmph_code) {
	case 0:
	case 1:
		/* TODO: TOS specificity for cases 2 and 3 */
	case 2:
	case 3:
		break;
	default:
		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
		ip_drop_input("icmpInBadRedirects - code", mp, ira->ira_ill);
		freemsg(mp);
		return;
	}
	/*
	 * Create a Route Association.  This will allow us to remember that
	 * someone we believe told us to use the particular gateway.
	 */
	ire = ire_create(
	    (uchar_t *)&dst,			/* dest addr */
	    (uchar_t *)&ip_g_all_ones,		/* mask */
	    (uchar_t *)&gateway,		/* gateway addr */
	    IRE_HOST,
	    NULL,				/* ill */
	    ALL_ZONES,
	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
	    NULL,				/* tsol_gc_t */
	    ipst);

	if (ire == NULL) {
		freemsg(mp);
		return;
	}
	nire = ire_add(ire);
	/* Check if it was a duplicate entry */
	if (nire != NULL && nire != ire) {
		ASSERT(nire->ire_identical_ref > 1);
		ire_delete(nire);
		ire_refrele(nire);
		nire = NULL;
	}
	ire = nire;
	if (ire != NULL) {
		ire_refrele(ire);		/* Held in ire_add */

		/* tell routing sockets that we received a redirect */
		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
	}

	/*
	 * Delete any existing IRE_HOST type redirect ires for this destination.
	 * This together with the added IRE has the effect of
	 * modifying an existing redirect.
	 */
	prev_ire = ire_ftable_lookup_v4(dst, 0, src, IRE_HOST, NULL,
	    ALL_ZONES, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), 0, ipst, NULL);
	if (prev_ire != NULL) {
		if (prev_ire ->ire_flags & RTF_DYNAMIC)
			ire_delete(prev_ire);
		ire_refrele(prev_ire);
	}

	freemsg(mp);
}

/*
 * Generate an ICMP parameter problem message.
 * When called from ip_output side a minimal ip_recv_attr_t needs to be
 * constructed by the caller.
 */
static void
icmp_param_problem(mblk_t *mp, uint8_t ptr, ip_recv_attr_t *ira)
{
	icmph_t	icmph;
	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;

	mp = icmp_pkt_err_ok(mp, ira);
	if (mp == NULL)
		return;

	bzero(&icmph, sizeof (icmph_t));
	icmph.icmph_type = ICMP_PARAM_PROBLEM;
	icmph.icmph_pp_ptr = ptr;
	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
}

/*
 * Build and ship an IPv4 ICMP message using the packet data in mp, and
 * the ICMP header pointed to by "stuff".  (May be called as writer.)
 * Note: assumes that icmp_pkt_err_ok has been called to verify that
 * an icmp error packet can be sent.
 * Assigns an appropriate source address to the packet. If ipha_dst is
 * one of our addresses use it for source. Otherwise let ip_output_simple
 * pick the source address.
 */
static void
icmp_pkt(mblk_t *mp, void *stuff, size_t len, ip_recv_attr_t *ira)
{
	ipaddr_t dst;
	icmph_t	*icmph;
	ipha_t	*ipha;
	uint_t	len_needed;
	size_t	msg_len;
	mblk_t	*mp1;
	ipaddr_t src;
	ire_t	*ire;
	ip_xmit_attr_t ixas;
	ip_stack_t *ipst = ira->ira_ill->ill_ipst;

	ipha = (ipha_t *)mp->b_rptr;

	bzero(&ixas, sizeof (ixas));
	ixas.ixa_flags = IXAF_BASIC_SIMPLE_V4;
	ixas.ixa_zoneid = ira->ira_zoneid;
	ixas.ixa_ifindex = 0;
	ixas.ixa_ipst = ipst;
	ixas.ixa_cred = kcred;
	ixas.ixa_cpid = NOPID;
	ixas.ixa_tsl = ira->ira_tsl;	/* Behave as a multi-level responder */
	ixas.ixa_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;

	if (ira->ira_flags & IRAF_IPSEC_SECURE) {
		/*
		 * Apply IPsec based on how IPsec was applied to
		 * the packet that had the error.
		 *
		 * If it was an outbound packet that caused the ICMP
		 * error, then the caller will have setup the IRA
		 * appropriately.
		 */
		if (!ipsec_in_to_out(ira, &ixas, mp, ipha, NULL)) {
			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
			/* Note: mp already consumed and ip_drop_packet done */
			return;
		}
	} else {
		/*
		 * This is in clear. The icmp message we are building
		 * here should go out in clear, independent of our policy.
		 */
		ixas.ixa_flags |= IXAF_NO_IPSEC;
	}

	/* Remember our eventual destination */
	dst = ipha->ipha_src;

	/*
	 * If the packet was for one of our unicast addresses, make
	 * sure we respond with that as the source. Otherwise
	 * have ip_output_simple pick the source address.
	 */
	ire = ire_ftable_lookup_v4(ipha->ipha_dst, 0, 0,
	    (IRE_LOCAL|IRE_LOOPBACK), NULL, ira->ira_zoneid, NULL,
	    MATCH_IRE_TYPE|MATCH_IRE_ZONEONLY, 0, ipst, NULL);
	if (ire != NULL) {
		ire_refrele(ire);
		src = ipha->ipha_dst;
	} else {
		src = INADDR_ANY;
		ixas.ixa_flags |= IXAF_SET_SOURCE;
	}

	/*
	 * Check if we can send back more then 8 bytes in addition to
	 * the IP header.  We try to send 64 bytes of data and the internal
	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
	 */
	len_needed = IPH_HDR_LENGTH(ipha);
	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
	    ipha->ipha_protocol == IPPROTO_IPV6) {
		/*
		 * NOTE: It is posssible that the inner packet is poorly
		 * formed (e.g. IP version is corrupt, or v6 extension headers
		 * got cut off).  The receiver of the ICMP message should see
		 * what we saw.  In the absence of a sane inner-packet (which
		 * protocol types IPPPROTO_ENCAP and IPPROTO_IPV6 indicate
		 * would be an IP header), we should send the size of what is
		 * normally expected to be there (either sizeof (ipha_t) or
		 * sizeof (ip6_t).  It may be useful for diagnostic purposes.
		 *
		 * ALSO NOTE: "inner_ip6h" is the inner packet header, v4 or v6.
		 */
		ip6_t *inner_ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);

		if (!pullupmsg(mp, -1)) {
			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
			ip_drop_output("ipIfStatsOutDiscards", mp, NULL);
			freemsg(mp);
			return;
		}
		ipha = (ipha_t *)mp->b_rptr;

		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
			/*
			 * Check the inner IP version here to guard against
			 * bogons.
			 */
			if (IPH_HDR_VERSION(inner_ip6h) == IPV4_VERSION) {
				len_needed +=
				    IPH_HDR_LENGTH(((uchar_t *)inner_ip6h));
			} else {
				len_needed = sizeof (ipha_t);
			}
		} else {
			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
			/* function called next-line checks inner IP version */
			len_needed += ip_hdr_length_v6(mp, inner_ip6h);
		}
	}
	len_needed += ipst->ips_ip_icmp_return;
	msg_len = msgdsize(mp);
	if (msg_len > len_needed) {
		(void) adjmsg(mp, len_needed - msg_len);
		msg_len = len_needed;
	}
	mp1 = allocb(sizeof (icmp_ipha) + len, BPRI_MED);
	if (mp1 == NULL) {
		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
		freemsg(mp);
		return;
	}
	mp1->b_cont = mp;
	mp = mp1;

	/*
	 * Set IXAF_TRUSTED_ICMP so we can let the ICMP messages this
	 * node generates be accepted in peace by all on-host destinations.
	 * If we do NOT assume that all on-host destinations trust
	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
	 * (Look for IXAF_TRUSTED_ICMP).
	 */
	ixas.ixa_flags |= IXAF_TRUSTED_ICMP;

	ipha = (ipha_t *)mp->b_rptr;
	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
	*ipha = icmp_ipha;
	ipha->ipha_src = src;
	ipha->ipha_dst = dst;
	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
	msg_len += sizeof (icmp_ipha) + len;
	if (msg_len > IP_MAXPACKET) {
		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
		msg_len = IP_MAXPACKET;
	}
	ipha->ipha_length = htons((uint16_t)msg_len);
	icmph = (icmph_t *)&ipha[1];
	bcopy(stuff, icmph, len);
	icmph->icmph_checksum = 0;
	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);

	(void) ip_output_simple(mp, &ixas);
	ixa_cleanup(&ixas);
}

/*
 * Determine if an ICMP error packet can be sent given the rate limit.
 * The limit consists of an average frequency (icmp_pkt_err_interval measured
 * in milliseconds) and a burst size. Burst size number of packets can
 * be sent arbitrarely closely spaced.
 * The state is tracked using two variables to implement an approximate
 * token bucket filter:
 *	icmp_pkt_err_last - lbolt value when the last burst started
 *	icmp_pkt_err_sent - number of packets sent in current burst
 */
boolean_t
icmp_err_rate_limit(ip_stack_t *ipst)
{
	clock_t now = TICK_TO_MSEC(ddi_get_lbolt());
	uint_t refilled; /* Number of packets refilled in tbf since last */
	/* Guard against changes by loading into local variable */
	uint_t err_interval = ipst->ips_ip_icmp_err_interval;

	if (err_interval == 0)
		return (B_FALSE);

	if (ipst->ips_icmp_pkt_err_last > now) {
		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
		ipst->ips_icmp_pkt_err_last = 0;
		ipst->ips_icmp_pkt_err_sent = 0;
	}
	/*
	 * If we are in a burst update the token bucket filter.
	 * Update the "last" time to be close to "now" but make sure
	 * we don't loose precision.
	 */
	if (ipst->ips_icmp_pkt_err_sent != 0) {
		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
		if (refilled > ipst->ips_icmp_pkt_err_sent) {
			ipst->ips_icmp_pkt_err_sent = 0;
		} else {
			ipst->ips_icmp_pkt_err_sent -= refilled;
			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
		}
	}
	if (ipst->ips_icmp_pkt_err_sent == 0) {
		/* Start of new burst */
		ipst->ips_icmp_pkt_err_last = now;
	}
	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
		ipst->ips_icmp_pkt_err_sent++;
		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
		    ipst->ips_icmp_pkt_err_sent));
		return (B_FALSE);
	}
	ip1dbg(("icmp_err_rate_limit: dropped\n"));
	return (B_TRUE);
}

/*
 * Check if it is ok to send an IPv4 ICMP error packet in
 * response to the IPv4 packet in mp.
 * Free the message and return null if no
 * ICMP error packet should be sent.
 */
static mblk_t *
icmp_pkt_err_ok(mblk_t *mp, ip_recv_attr_t *ira)
{
	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
	icmph_t	*icmph;
	ipha_t	*ipha;
	uint_t	len_needed;

	if (!mp)
		return (NULL);
	ipha = (ipha_t *)mp->b_rptr;
	if (ip_csum_hdr(ipha)) {
		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
		ip_drop_input("ipIfStatsInCksumErrs", mp, NULL);
		freemsg(mp);
		return (NULL);
	}
	if (ip_type_v4(ipha->ipha_dst, ipst) == IRE_BROADCAST ||
	    ip_type_v4(ipha->ipha_src, ipst) == IRE_BROADCAST ||
	    CLASSD(ipha->ipha_dst) ||
	    CLASSD(ipha->ipha_src) ||
	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
		/* Note: only errors to the fragment with offset 0 */
		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
		freemsg(mp);
		return (NULL);
	}
	if (ipha->ipha_protocol == IPPROTO_ICMP) {
		/*
		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
		 * errors in response to any ICMP errors.
		 */
		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
		if (mp->b_wptr - mp->b_rptr < len_needed) {
			if (!pullupmsg(mp, len_needed)) {
				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
				freemsg(mp);
				return (NULL);
			}
			ipha = (ipha_t *)mp->b_rptr;
		}
		icmph = (icmph_t *)
		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
		switch (icmph->icmph_type) {
		case ICMP_DEST_UNREACHABLE:
		case ICMP_SOURCE_QUENCH:
		case ICMP_TIME_EXCEEDED:
		case ICMP_PARAM_PROBLEM:
		case ICMP_REDIRECT:
			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
			freemsg(mp);
			return (NULL);
		default:
			break;
		}
	}
	/*
	 * If this is a labeled system, then check to see if we're allowed to
	 * send a response to this particular sender.  If not, then just drop.
	 */
	if (is_system_labeled() && !tsol_can_reply_error(mp, ira)) {
		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
		freemsg(mp);
		return (NULL);
	}
	if (icmp_err_rate_limit(ipst)) {
		/*
		 * Only send ICMP error packets every so often.
		 * This should be done on a per port/source basis,
		 * but for now this will suffice.
		 */
		freemsg(mp);
		return (NULL);
	}
	return (mp);
}

/*
 * Called when a packet was sent out the same link that it arrived on.
 * Check if it is ok to send a redirect and then send it.
 */
void
ip_send_potential_redirect_v4(mblk_t *mp, ipha_t *ipha, ire_t *ire,
    ip_recv_attr_t *ira)
{
	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
	ipaddr_t	src, nhop;
	mblk_t		*mp1;
	ire_t		*nhop_ire;

	/*
	 * Check the source address to see if it originated
	 * on the same logical subnet it is going back out on.
	 * If so, we should be able to send it a redirect.
	 * Avoid sending a redirect if the destination
	 * is directly connected (i.e., we matched an IRE_ONLINK),
	 * or if the packet was source routed out this interface.
	 *
	 * We avoid sending a redirect if the
	 * destination is directly connected
	 * because it is possible that multiple
	 * IP subnets may have been configured on
	 * the link, and the source may not
	 * be on the same subnet as ip destination,
	 * even though they are on the same
	 * physical link.
	 */
	if ((ire->ire_type & IRE_ONLINK) ||
	    ip_source_routed(ipha, ipst))
		return;

	nhop_ire = ire_nexthop(ire);
	if (nhop_ire == NULL)
		return;

	nhop = nhop_ire->ire_addr;

	if (nhop_ire->ire_type & IRE_IF_CLONE) {
		ire_t	*ire2;

		/* Follow ire_dep_parent to find non-clone IRE_INTERFACE */
		mutex_enter(&nhop_ire->ire_lock);
		ire2 = nhop_ire->ire_dep_parent;
		if (ire2 != NULL)
			ire_refhold(ire2);
		mutex_exit(&nhop_ire->ire_lock);
		ire_refrele(nhop_ire);
		nhop_ire = ire2;
	}
	if (nhop_ire == NULL)
		return;

	ASSERT(!(nhop_ire->ire_type & IRE_IF_CLONE));

	src = ipha->ipha_src;

	/*
	 * We look at the interface ire for the nexthop,
	 * to see if ipha_src is in the same subnet
	 * as the nexthop.
	 */
	if ((src & nhop_ire->ire_mask) == (nhop & nhop_ire->ire_mask)) {
		/*
		 * The source is directly connected.
		 */
		mp1 = copymsg(mp);
		if (mp1 != NULL) {
			icmp_send_redirect(mp1, nhop, ira);
		}
	}
	ire_refrele(nhop_ire);
}

/*
 * Generate an ICMP redirect message.
 */
static void
icmp_send_redirect(mblk_t *mp, ipaddr_t gateway, ip_recv_attr_t *ira)
{
	icmph_t	icmph;
	ip_stack_t *ipst = ira->ira_ill->ill_ipst;

	mp = icmp_pkt_err_ok(mp, ira);
	if (mp == NULL)
		return;

	bzero(&icmph, sizeof (icmph_t));
	icmph.icmph_type = ICMP_REDIRECT;
	icmph.icmph_code = 1;
	icmph.icmph_rd_gateway = gateway;
	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
}

/*
 * Generate an ICMP time exceeded message.
 */
void
icmp_time_exceeded(mblk_t *mp, uint8_t code, ip_recv_attr_t *ira)
{
	icmph_t	icmph;
	ip_stack_t *ipst = ira->ira_ill->ill_ipst;

	mp = icmp_pkt_err_ok(mp, ira);
	if (mp == NULL)
		return;

	bzero(&icmph, sizeof (icmph_t));
	icmph.icmph_type = ICMP_TIME_EXCEEDED;
	icmph.icmph_code = code;
	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
}

/*
 * Generate an ICMP unreachable message.
 * When called from ip_output side a minimal ip_recv_attr_t needs to be
 * constructed by the caller.
 */
void
icmp_unreachable(mblk_t *mp, uint8_t code, ip_recv_attr_t *ira)
{
	icmph_t	icmph;
	ip_stack_t *ipst = ira->ira_ill->ill_ipst;

	mp = icmp_pkt_err_ok(mp, ira);
	if (mp == NULL)
		return;

	bzero(&icmph, sizeof (icmph_t));
	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
	icmph.icmph_code = code;
	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
	icmp_pkt(mp, &icmph, sizeof (icmph_t), ira);
}

/*
 * Latch in the IPsec state for a stream based the policy in the listener
 * and the actions in the ip_recv_attr_t.
 * Called directly from TCP and SCTP.
 */
boolean_t
ip_ipsec_policy_inherit(conn_t *connp, conn_t *lconnp, ip_recv_attr_t *ira)
{
	ASSERT(lconnp->conn_policy != NULL);
	ASSERT(connp->conn_policy == NULL);

	IPPH_REFHOLD(lconnp->conn_policy);
	connp->conn_policy = lconnp->conn_policy;

	if (ira->ira_ipsec_action != NULL) {
		if (connp->conn_latch == NULL) {
			connp->conn_latch = iplatch_create();
			if (connp->conn_latch == NULL)
				return (B_FALSE);
		}
		ipsec_latch_inbound(connp, ira);
	}
	return (B_TRUE);
}

/*
 * Verify whether or not the IP address is a valid local address.
 * Could be a unicast, including one for a down interface.
 * If allow_mcbc then a multicast or broadcast address is also
 * acceptable.
 *
 * In the case of a broadcast/multicast address, however, the
 * upper protocol is expected to reset the src address
 * to zero when we return IPVL_MCAST/IPVL_BCAST so that
 * no packets are emitted with broadcast/multicast address as
 * source address (that violates hosts requirements RFC 1122)
 * The addresses valid for bind are:
 *	(1) - INADDR_ANY (0)
 *	(2) - IP address of an UP interface
 *	(3) - IP address of a DOWN interface
 *	(4) - valid local IP broadcast addresses. In this case
 *	the conn will only receive packets destined to
 *	the specified broadcast address.
 *	(5) - a multicast address. In this case
 *	the conn will only receive packets destined to
 *	the specified multicast address. Note: the
 *	application still has to issue an
 *	IP_ADD_MEMBERSHIP socket option.
 *
 * In all the above cases, the bound address must be valid in the current zone.
 * When the address is loopback, multicast or broadcast, there might be many
 * matching IREs so bind has to look up based on the zone.
 */
ip_laddr_t
ip_laddr_verify_v4(ipaddr_t src_addr, zoneid_t zoneid,
    ip_stack_t *ipst, boolean_t allow_mcbc)
{
	ire_t *src_ire;

	ASSERT(src_addr != INADDR_ANY);

	src_ire = ire_ftable_lookup_v4(src_addr, 0, 0, 0,
	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, 0, ipst, NULL);

	/*
	 * If an address other than in6addr_any is requested,
	 * we verify that it is a valid address for bind
	 * Note: Following code is in if-else-if form for
	 * readability compared to a condition check.
	 */
	if (src_ire != NULL && (src_ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK))) {
		/*
		 * (2) Bind to address of local UP interface
		 */
		ire_refrele(src_ire);
		return (IPVL_UNICAST_UP);
	} else if (src_ire != NULL && src_ire->ire_type & IRE_BROADCAST) {
		/*
		 * (4) Bind to broadcast address
		 */
		ire_refrele(src_ire);
		if (allow_mcbc)
			return (IPVL_BCAST);
		else
			return (IPVL_BAD);
	} else if (CLASSD(src_addr)) {
		/* (5) bind to multicast address. */
		if (src_ire != NULL)
			ire_refrele(src_ire);

		if (allow_mcbc)
			return (IPVL_MCAST);
		else
			return (IPVL_BAD);
	} else {
		ipif_t *ipif;

		/*
		 * (3) Bind to address of local DOWN interface?
		 * (ipif_lookup_addr() looks up all interfaces
		 * but we do not get here for UP interfaces
		 * - case (2) above)
		 */
		if (src_ire != NULL)
			ire_refrele(src_ire);

		ipif = ipif_lookup_addr(src_addr, NULL, zoneid, ipst);
		if (ipif == NULL)
			return (IPVL_BAD);

		/* Not a useful source? */
		if (ipif->ipif_flags & (IPIF_NOLOCAL | IPIF_ANYCAST)) {
			ipif_refrele(ipif);
			return (IPVL_BAD);
		}
		ipif_refrele(ipif);
		return (IPVL_UNICAST_DOWN);
	}
}

/*
 * Insert in the bind fanout for IPv4 and IPv6.
 * The caller should already have used ip_laddr_verify_v*() before calling
 * this.
 */
int
ip_laddr_fanout_insert(conn_t *connp)
{
	int		error;

	/*
	 * Allow setting new policies. For example, disconnects result
	 * in us being called. As we would have set conn_policy_cached
	 * to B_TRUE before, we should set it to B_FALSE, so that policy
	 * can change after the disconnect.
	 */
	connp->conn_policy_cached = B_FALSE;

	error = ipcl_bind_insert(connp);
	if (error != 0) {
		if (connp->conn_anon_port) {
			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
			    connp->conn_mlp_type, connp->conn_proto,
			    ntohs(connp->conn_lport), B_FALSE);
		}
		connp->conn_mlp_type = mlptSingle;
	}
	return (error);
}

/*
 * Verify that both the source and destination addresses are valid. If
 * IPDF_VERIFY_DST is not set, then the destination address may be unreachable,
 * i.e. have no route to it.  Protocols like TCP want to verify destination
 * reachability, while tunnels do not.
 *
 * Determine the route, the interface, and (optionally) the source address
 * to use to reach a given destination.
 * Note that we allow connect to broadcast and multicast addresses when
 * IPDF_ALLOW_MCBC is set.
 * first_hop and dst_addr are normally the same, but if source routing
 * they will differ; in that case the first_hop is what we'll use for the
 * routing lookup but the dce and label checks will be done on dst_addr,
 *
 * If uinfo is set, then we fill in the best available information
 * we have for the destination. This is based on (in priority order) any
 * metrics and path MTU stored in a dce_t, route metrics, and finally the
 * ill_mtu/ill_mc_mtu.
 *
 * Tsol note: If we have a source route then dst_addr != firsthop. But we
 * always do the label check on dst_addr.
 */
int
ip_set_destination_v4(ipaddr_t *src_addrp, ipaddr_t dst_addr, ipaddr_t firsthop,
    ip_xmit_attr_t *ixa, iulp_t *uinfo, uint32_t flags, uint_t mac_mode)
{
	ire_t		*ire = NULL;
	int		error = 0;
	ipaddr_t	setsrc;				/* RTF_SETSRC */
	zoneid_t	zoneid = ixa->ixa_zoneid;	/* Honors SO_ALLZONES */
	ip_stack_t	*ipst = ixa->ixa_ipst;
	dce_t		*dce;
	uint_t		pmtu;
	uint_t		generation;
	nce_t		*nce;
	ill_t		*ill = NULL;
	boolean_t	multirt = B_FALSE;

	ASSERT(ixa->ixa_flags & IXAF_IS_IPV4);

	/*
	 * We never send to zero; the ULPs map it to the loopback address.
	 * We can't allow it since we use zero to mean unitialized in some
	 * places.
	 */
	ASSERT(dst_addr != INADDR_ANY);

	if (is_system_labeled()) {
		ts_label_t *tsl = NULL;

		error = tsol_check_dest(ixa->ixa_tsl, &dst_addr, IPV4_VERSION,
		    mac_mode, (flags & IPDF_ZONE_IS_GLOBAL) != 0, &tsl);
		if (error != 0)
			return (error);
		if (tsl != NULL) {
			/* Update the label */
			ip_xmit_attr_replace_tsl(ixa, tsl);
		}
	}

	setsrc = INADDR_ANY;
	/*
	 * Select a route; For IPMP interfaces, we would only select
	 * a "hidden" route (i.e., going through a specific under_ill)
	 * if ixa_ifindex has been specified.
	 */
	ire = ip_select_route_v4(firsthop, *src_addrp, ixa,
	    &generation, &setsrc, &error, &multirt);
	ASSERT(ire != NULL);	/* IRE_NOROUTE if none found */
	if (error != 0)
		goto bad_addr;

	/*
	 * ire can't be a broadcast or multicast unless IPDF_ALLOW_MCBC is set.
	 * If IPDF_VERIFY_DST is set, the destination must be reachable;
	 * Otherwise the destination needn't be reachable.
	 *
	 * If we match on a reject or black hole, then we've got a
	 * local failure.  May as well fail out the connect() attempt,
	 * since it's never going to succeed.
	 */
	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
		/*
		 * If we're verifying destination reachability, we always want
		 * to complain here.
		 *
		 * If we're not verifying destination reachability but the
		 * destination has a route, we still want to fail on the
		 * temporary address and broadcast address tests.
		 *
		 * In both cases do we let the code continue so some reasonable
		 * information is returned to the caller. That enables the
		 * caller to use (and even cache) the IRE. conn_ip_ouput will
		 * use the generation mismatch path to check for the unreachable
		 * case thereby avoiding any specific check in the main path.
		 */
		ASSERT(generation == IRE_GENERATION_VERIFY);
		if (flags & IPDF_VERIFY_DST) {
			/*
			 * Set errno but continue to set up ixa_ire to be
			 * the RTF_REJECT|RTF_BLACKHOLE IRE.
			 * That allows callers to use ip_output to get an
			 * ICMP error back.
			 */
			if (!(ire->ire_type & IRE_HOST))
				error = ENETUNREACH;
			else
				error = EHOSTUNREACH;
		}
	}

	if ((ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST)) &&
	    !(flags & IPDF_ALLOW_MCBC)) {
		ire_refrele(ire);
		ire = ire_reject(ipst, B_FALSE);
		generation = IRE_GENERATION_VERIFY;
		error = ENETUNREACH;
	}

	/* Cache things */
	if (ixa->ixa_ire != NULL)
		ire_refrele_notr(ixa->ixa_ire);
#ifdef DEBUG
	ire_refhold_notr(ire);
	ire_refrele(ire);
#endif
	ixa->ixa_ire = ire;
	ixa->ixa_ire_generation = generation;

	/*
	 * Ensure that ixa_dce is always set any time that ixa_ire is set,
	 * since some callers will send a packet to conn_ip_output() even if
	 * there's an error.
	 */
	if (flags & IPDF_UNIQUE_DCE) {
		/* Fallback to the default dce if allocation fails */
		dce = dce_lookup_and_add_v4(dst_addr, ipst);
		if (dce != NULL)
			generation = dce->dce_generation;
		else
			dce = dce_lookup_v4(dst_addr, ipst, &generation);
	} else {
		dce = dce_lookup_v4(dst_addr, ipst, &generation);
	}
	ASSERT(dce != NULL);
	if (ixa->ixa_dce != NULL)
		dce_refrele_notr(ixa->ixa_dce);
#ifdef DEBUG
	dce_refhold_notr(dce);
	dce_refrele(dce);
#endif
	ixa->ixa_dce = dce;
	ixa->ixa_dce_generation = generation;

	/*
	 * For multicast with multirt we have a flag passed back from
	 * ire_lookup_multi_ill_v4 since we don't have an IRE for each
	 * possible multicast address.
	 * We also need a flag for multicast since we can't check
	 * whether RTF_MULTIRT is set in ixa_ire for multicast.
	 */
	if (multirt) {
		ixa->ixa_postfragfn = ip_postfrag_multirt_v4;
		ixa->ixa_flags |= IXAF_MULTIRT_MULTICAST;
	} else {
		ixa->ixa_postfragfn = ire->ire_postfragfn;
		ixa->ixa_flags &= ~IXAF_MULTIRT_MULTICAST;
	}
	if (!(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
		/* Get an nce to cache. */
		nce = ire_to_nce(ire, firsthop, NULL);
		if (nce == NULL) {
			/* Allocation failure? */
			ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
		} else {
			if (ixa->ixa_nce != NULL)
				nce_refrele(ixa->ixa_nce);
			ixa->ixa_nce = nce;
		}
	}

	/*
	 * If the source address is a loopback address, the
	 * destination had best be local or multicast.
	 * If we are sending to an IRE_LOCAL using a loopback source then
	 * it had better be the same zoneid.
	 */
	if (*src_addrp == htonl(INADDR_LOOPBACK)) {
		if ((ire->ire_type & IRE_LOCAL) && ire->ire_zoneid != zoneid) {
			ire = NULL;	/* Stored in ixa_ire */
			error = EADDRNOTAVAIL;
			goto bad_addr;
		}
		if (!(ire->ire_type & (IRE_LOOPBACK|IRE_LOCAL|IRE_MULTICAST))) {
			ire = NULL;	/* Stored in ixa_ire */
			error = EADDRNOTAVAIL;
			goto bad_addr;
		}
	}
	if (ire->ire_type & IRE_BROADCAST) {
		/*
		 * If the ULP didn't have a specified source, then we
		 * make sure we reselect the source when sending
		 * broadcasts out different interfaces.
		 */
		if (flags & IPDF_SELECT_SRC)
			ixa->ixa_flags |= IXAF_SET_SOURCE;
		else
			ixa->ixa_flags &= ~IXAF_SET_SOURCE;
	}

	/*
	 * Does the caller want us to pick a source address?
	 */
	if (flags & IPDF_SELECT_SRC) {
		ipaddr_t	src_addr;

		/*
		 * We use use ire_nexthop_ill to avoid the under ipmp
		 * interface for source address selection. Note that for ipmp
		 * probe packets, ixa_ifindex would have been specified, and
		 * the ip_select_route() invocation would have picked an ire
		 * will ire_ill pointing at an under interface.
		 */
		ill = ire_nexthop_ill(ire);

		/* If unreachable we have no ill but need some source */
		if (ill == NULL) {
			src_addr = htonl(INADDR_LOOPBACK);
			/* Make sure we look for a better source address */
			generation = SRC_GENERATION_VERIFY;
		} else {
			error = ip_select_source_v4(ill, setsrc, dst_addr,
			    ixa->ixa_multicast_ifaddr, zoneid,
			    ipst, &src_addr, &generation, NULL);
			if (error != 0) {
				ire = NULL;	/* Stored in ixa_ire */
				goto bad_addr;
			}
		}

		/*
		 * We allow the source address to to down.
		 * However, we check that we don't use the loopback address
		 * as a source when sending out on the wire.
		 */
		if ((src_addr == htonl(INADDR_LOOPBACK)) &&
		    !(ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK|IRE_MULTICAST)) &&
		    !(ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
			ire = NULL;	/* Stored in ixa_ire */
			error = EADDRNOTAVAIL;
			goto bad_addr;
		}

		*src_addrp = src_addr;
		ixa->ixa_src_generation = generation;
	}

	/*
	 * Make sure we don't leave an unreachable ixa_nce in place
	 * since ip_select_route is used when we unplumb i.e., remove
	 * references on ixa_ire, ixa_nce, and ixa_dce.
	 */
	nce = ixa->ixa_nce;
	if (nce != NULL && nce->nce_is_condemned) {
		nce_refrele(nce);
		ixa->ixa_nce = NULL;
		ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
	}

	/*
	 * The caller has set IXAF_PMTU_DISCOVERY if path MTU is desired.
	 * However, we can't do it for IPv4 multicast or broadcast.
	 */
	if (ire->ire_type & (IRE_BROADCAST|IRE_MULTICAST))
		ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;

	/*
	 * Set initial value for fragmentation limit. Either conn_ip_output
	 * or ULP might updates it when there are routing changes.
	 * Handles a NULL ixa_ire->ire_ill or a NULL ixa_nce for RTF_REJECT.
	 */
	pmtu = ip_get_pmtu(ixa);
	ixa->ixa_fragsize = pmtu;
	/* Make sure ixa_fragsize and ixa_pmtu remain identical */
	if (ixa->ixa_flags & IXAF_VERIFY_PMTU)
		ixa->ixa_pmtu = pmtu;

	/*
	 * Extract information useful for some transports.
	 * First we look for DCE metrics. Then we take what we have in
	 * the metrics in the route, where the offlink is used if we have
	 * one.
	 */
	if (uinfo != NULL) {
		bzero(uinfo, sizeof (*uinfo));

		if (dce->dce_flags & DCEF_UINFO)
			*uinfo = dce->dce_uinfo;

		rts_merge_metrics(uinfo, &ire->ire_metrics);

		/* Allow ire_metrics to decrease the path MTU from above */
		if (uinfo->iulp_mtu == 0 || uinfo->iulp_mtu > pmtu)
			uinfo->iulp_mtu = pmtu;

		uinfo->iulp_localnet = (ire->ire_type & IRE_ONLINK) != 0;
		uinfo->iulp_loopback = (ire->ire_type & IRE_LOOPBACK) != 0;
		uinfo->iulp_local = (ire->ire_type & IRE_LOCAL) != 0;
	}

	if (ill != NULL)
		ill_refrele(ill);

	return (error);

bad_addr:
	if (ire != NULL)
		ire_refrele(ire);

	if (ill != NULL)
		ill_refrele(ill);

	/*
	 * Make sure we don't leave an unreachable ixa_nce in place
	 * since ip_select_route is used when we unplumb i.e., remove
	 * references on ixa_ire, ixa_nce, and ixa_dce.
	 */
	nce = ixa->ixa_nce;
	if (nce != NULL && nce->nce_is_condemned) {
		nce_refrele(nce);
		ixa->ixa_nce = NULL;
		ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
	}

	return (error);
}


/*
 * Get the base MTU for the case when path MTU discovery is not used.
 * Takes the MTU of the IRE into account.
 */
uint_t
ip_get_base_mtu(ill_t *ill, ire_t *ire)
{
	uint_t mtu;
	uint_t iremtu = ire->ire_metrics.iulp_mtu;

	if (ire->ire_type & (IRE_MULTICAST|IRE_BROADCAST))
		mtu = ill->ill_mc_mtu;
	else
		mtu = ill->ill_mtu;

	if (iremtu != 0 && iremtu < mtu)
		mtu = iremtu;

	return (mtu);
}

/*
 * Get the PMTU for the attributes. Handles both IPv4 and IPv6.
 * Assumes that ixa_ire, dce, and nce have already been set up.
 *
 * The caller has set IXAF_PMTU_DISCOVERY if path MTU discovery is desired.
 * We avoid path MTU discovery if it is disabled with ndd.
 * Furtermore, if the path MTU is too small, then we don't set DF for IPv4.
 *
 * NOTE: We also used to turn it off for source routed packets. That
 * is no longer required since the dce is per final destination.
 */
uint_t
ip_get_pmtu(ip_xmit_attr_t *ixa)
{
	ip_stack_t	*ipst = ixa->ixa_ipst;
	dce_t		*dce;
	nce_t		*nce;
	ire_t		*ire;
	uint_t		pmtu;

	ire = ixa->ixa_ire;
	dce = ixa->ixa_dce;
	nce = ixa->ixa_nce;

	/*
	 * If path MTU discovery has been turned off by ndd, then we ignore
	 * any dce_pmtu and for IPv4 we will not set DF.
	 */
	if (!ipst->ips_ip_path_mtu_discovery)
		ixa->ixa_flags &= ~IXAF_PMTU_DISCOVERY;

	pmtu = IP_MAXPACKET;
	/*
	 * Decide whether whether IPv4 sets DF
	 * For IPv6 "no DF" means to use the 1280 mtu
	 */
	if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
		ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
	} else {
		ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
		if (!(ixa->ixa_flags & IXAF_IS_IPV4))
			pmtu = IPV6_MIN_MTU;
	}

	/* Check if the PMTU is to old before we use it */
	if ((dce->dce_flags & DCEF_PMTU) &&
	    TICK_TO_SEC(ddi_get_lbolt64()) - dce->dce_last_change_time >
	    ipst->ips_ip_pathmtu_interval) {
		/*
		 * Older than 20 minutes. Drop the path MTU information.
		 */
		mutex_enter(&dce->dce_lock);
		dce->dce_flags &= ~(DCEF_PMTU|DCEF_TOO_SMALL_PMTU);
		dce->dce_last_change_time = TICK_TO_SEC(ddi_get_lbolt64());
		mutex_exit(&dce->dce_lock);
		dce_increment_generation(dce);
	}

	/* The metrics on the route can lower the path MTU */
	if (ire->ire_metrics.iulp_mtu != 0 &&
	    ire->ire_metrics.iulp_mtu < pmtu)
		pmtu = ire->ire_metrics.iulp_mtu;

	/*
	 * If the path MTU is smaller than some minimum, we still use dce_pmtu
	 * above (would be 576 for IPv4 and 1280 for IPv6), but we clear
	 * IXAF_PMTU_IPV4_DF so that we avoid setting DF for IPv4.
	 */
	if (ixa->ixa_flags & IXAF_PMTU_DISCOVERY) {
		if (dce->dce_flags & DCEF_PMTU) {
			if (dce->dce_pmtu < pmtu)
				pmtu = dce->dce_pmtu;

			if (dce->dce_flags & DCEF_TOO_SMALL_PMTU) {
				ixa->ixa_flags |= IXAF_PMTU_TOO_SMALL;
				ixa->ixa_flags &= ~IXAF_PMTU_IPV4_DF;
			} else {
				ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
				ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
			}
		} else {
			ixa->ixa_flags &= ~IXAF_PMTU_TOO_SMALL;
			ixa->ixa_flags |= IXAF_PMTU_IPV4_DF;
		}
	}

	/*
	 * If we have an IRE_LOCAL we use the loopback mtu instead of
	 * the ill for going out the wire i.e., IRE_LOCAL gets the same
	 * mtu as IRE_LOOPBACK.
	 */
	if (ire->ire_type & (IRE_LOCAL|IRE_LOOPBACK)) {
		uint_t loopback_mtu;

		loopback_mtu = (ire->ire_ipversion == IPV6_VERSION) ?
		    ip_loopback_mtu_v6plus : ip_loopback_mtuplus;

		if (loopback_mtu < pmtu)
			pmtu = loopback_mtu;
	} else if (nce != NULL) {
		/*
		 * Make sure we don't exceed the interface MTU.
		 * In the case of RTF_REJECT or RTF_BLACKHOLE we might not have
		 * an ill. We'd use the above IP_MAXPACKET in that case just
		 * to tell the transport something larger than zero.
		 */
		if (ire->ire_type & (IRE_MULTICAST|IRE_BROADCAST)) {
			if (nce->nce_common->ncec_ill->ill_mc_mtu < pmtu)
				pmtu = nce->nce_common->ncec_ill->ill_mc_mtu;
			if (nce->nce_common->ncec_ill != nce->nce_ill &&
			    nce->nce_ill->ill_mc_mtu < pmtu) {
				/*
				 * for interfaces in an IPMP group, the mtu of
				 * the nce_ill (under_ill) could be different
				 * from the mtu of the ncec_ill, so we take the
				 * min of the two.
				 */
				pmtu = nce->nce_ill->ill_mc_mtu;
			}
		} else {
			if (nce->nce_common->ncec_ill->ill_mtu < pmtu)
				pmtu = nce->nce_common->ncec_ill->ill_mtu;
			if (nce->nce_common->ncec_ill != nce->nce_ill &&
			    nce->nce_ill->ill_mtu < pmtu) {
				/*
				 * for interfaces in an IPMP group, the mtu of
				 * the nce_ill (under_ill) could be different
				 * from the mtu of the ncec_ill, so we take the
				 * min of the two.
				 */
				pmtu = nce->nce_ill->ill_mtu;
			}
		}
	}

	/*
	 * Handle the IPV6_USE_MIN_MTU socket option or ancillary data.
	 * Only applies to IPv6.
	 */
	if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
		if (ixa->ixa_flags & IXAF_USE_MIN_MTU) {
			switch (ixa->ixa_use_min_mtu) {
			case IPV6_USE_MIN_MTU_MULTICAST:
				if (ire->ire_type & IRE_MULTICAST)
					pmtu = IPV6_MIN_MTU;
				break;
			case IPV6_USE_MIN_MTU_ALWAYS:
				pmtu = IPV6_MIN_MTU;
				break;
			case IPV6_USE_MIN_MTU_NEVER:
				break;
			}
		} else {
			/* Default is IPV6_USE_MIN_MTU_MULTICAST */
			if (ire->ire_type & IRE_MULTICAST)
				pmtu = IPV6_MIN_MTU;
		}
	}

	/*
	 * For multirouted IPv6 packets, the IP layer will insert a 8-byte
	 * fragment header in every packet. We compensate for those cases by
	 * returning a smaller path MTU to the ULP.
	 *
	 * In the case of CGTP then ip_output will add a fragment header.
	 * Make sure there is room for it by telling a smaller number
	 * to the transport.
	 *
	 * When IXAF_IPV6_ADDR_FRAGHDR we subtract the frag hdr here
	 * so the ULPs consistently see a iulp_pmtu and ip_get_pmtu()
	 * which is the size of the packets it can send.
	 */
	if (!(ixa->ixa_flags & IXAF_IS_IPV4)) {
		if ((ire->ire_flags & RTF_MULTIRT) ||
		    (ixa->ixa_flags & IXAF_MULTIRT_MULTICAST)) {
			pmtu -= sizeof (ip6_frag_t);
			ixa->ixa_flags |= IXAF_IPV6_ADD_FRAGHDR;
		}
	}

	return (pmtu);
}

/*
 * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
 * the final piece where we don't.  Return a pointer to the first mblk in the
 * result, and update the pointer to the next mblk to chew on.  If anything
 * goes wrong (i.e., dupb fails), we waste everything in sight and return a
 * NULL pointer.
 */
mblk_t *
ip_carve_mp(mblk_t **mpp, ssize_t len)
{
	mblk_t	*mp0;
	mblk_t	*mp1;
	mblk_t	*mp2;

	if (!len || !mpp || !(mp0 = *mpp))
		return (NULL);
	/* If we aren't going to consume the first mblk, we need a dup. */
	if (mp0->b_wptr - mp0->b_rptr > len) {
		mp1 = dupb(mp0);
		if (mp1) {
			/* Partition the data between the two mblks. */
			mp1->b_wptr = mp1->b_rptr + len;
			mp0->b_rptr = mp1->b_wptr;
			/*
			 * after adjustments if mblk not consumed is now
			 * unaligned, try to align it. If this fails free
			 * all messages and let upper layer recover.
			 */
			if (!OK_32PTR(mp0->b_rptr)) {
				if (!pullupmsg(mp0, -1)) {
					freemsg(mp0);
					freemsg(mp1);
					*mpp = NULL;
					return (NULL);
				}
			}
		}
		return (mp1);
	}
	/* Eat through as many mblks as we need to get len bytes. */
	len -= mp0->b_wptr - mp0->b_rptr;
	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
		if (mp2->b_wptr - mp2->b_rptr > len) {
			/*
			 * We won't consume the entire last mblk.  Like
			 * above, dup and partition it.
			 */
			mp1->b_cont = dupb(mp2);
			mp1 = mp1->b_cont;
			if (!mp1) {
				/*
				 * Trouble.  Rather than go to a lot of
				 * trouble to clean up, we free the messages.
				 * This won't be any worse than losing it on
				 * the wire.
				 */
				freemsg(mp0);
				freemsg(mp2);
				*mpp = NULL;
				return (NULL);
			}
			mp1->b_wptr = mp1->b_rptr + len;
			mp2->b_rptr = mp1->b_wptr;
			/*
			 * after adjustments if mblk not consumed is now
			 * unaligned, try to align it. If this fails free
			 * all messages and let upper layer recover.
			 */
			if (!OK_32PTR(mp2->b_rptr)) {
				if (!pullupmsg(mp2, -1)) {
					freemsg(mp0);
					freemsg(mp2);
					*mpp = NULL;
					return (NULL);
				}
			}
			*mpp = mp2;
			return (mp0);
		}
		/* Decrement len by the amount we just got. */
		len -= mp2->b_wptr - mp2->b_rptr;
	}
	/*
	 * len should be reduced to zero now.  If not our caller has
	 * screwed up.
	 */
	if (len) {
		/* Shouldn't happen! */
		freemsg(mp0);
		*mpp = NULL;
		return (NULL);
	}
	/*
	 * We consumed up to exactly the end of an mblk.  Detach the part
	 * we are returning from the rest of the chain.
	 */
	mp1->b_cont = NULL;
	*mpp = mp2;
	return (mp0);
}

/* The ill stream is being unplumbed. Called from ip_close */
int
ip_modclose(ill_t *ill)
{
	boolean_t success;
	ipsq_t	*ipsq;
	ipif_t	*ipif;
	queue_t	*q = ill->ill_rq;
	ip_stack_t	*ipst = ill->ill_ipst;
	int	i;
	arl_ill_common_t *ai = ill->ill_common;

	/*
	 * The punlink prior to this may have initiated a capability
	 * negotiation. But ipsq_enter will block until that finishes or
	 * times out.
	 */
	success = ipsq_enter(ill, B_FALSE, NEW_OP);

	/*
	 * Open/close/push/pop is guaranteed to be single threaded
	 * per stream by STREAMS. FS guarantees that all references
	 * from top are gone before close is called. So there can't
	 * be another close thread that has set CONDEMNED on this ill.
	 * and cause ipsq_enter to return failure.
	 */
	ASSERT(success);
	ipsq = ill->ill_phyint->phyint_ipsq;

	/*
	 * Mark it condemned. No new reference will be made to this ill.
	 * Lookup functions will return an error. Threads that try to
	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
	 * that the refcnt will drop down to zero.
	 */
	mutex_enter(&ill->ill_lock);
	ill->ill_state_flags |= ILL_CONDEMNED;
	for (ipif = ill->ill_ipif; ipif != NULL;
	    ipif = ipif->ipif_next) {
		ipif->ipif_state_flags |= IPIF_CONDEMNED;
	}
	/*
	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
	 * returns  error if ILL_CONDEMNED is set
	 */
	cv_broadcast(&ill->ill_cv);
	mutex_exit(&ill->ill_lock);

	/*
	 * Send all the deferred DLPI messages downstream which came in
	 * during the small window right before ipsq_enter(). We do this
	 * without waiting for the ACKs because all the ACKs for M_PROTO
	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
	 */
	ill_dlpi_send_deferred(ill);

	/*
	 * Shut down fragmentation reassembly.
	 * ill_frag_timer won't start a timer again.
	 * Now cancel any existing timer
	 */
	(void) untimeout(ill->ill_frag_timer_id);
	(void) ill_frag_timeout(ill, 0);

	/*
	 * Call ill_delete to bring down the ipifs, ilms and ill on
	 * this ill. Then wait for the refcnts to drop to zero.
	 * ill_is_freeable checks whether the ill is really quiescent.
	 * Then make sure that threads that are waiting to enter the
	 * ipsq have seen the error returned by ipsq_enter and have
	 * gone away. Then we call ill_delete_tail which does the
	 * DL_UNBIND_REQ with the driver and then qprocsoff.
	 */
	ill_delete(ill);
	mutex_enter(&ill->ill_lock);
	while (!ill_is_freeable(ill))
		cv_wait(&ill->ill_cv, &ill->ill_lock);

	while (ill->ill_waiters)
		cv_wait(&ill->ill_cv, &ill->ill_lock);

	mutex_exit(&ill->ill_lock);

	/*
	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
	 * it held until the end of the function since the cleanup
	 * below needs to be able to use the ip_stack_t.
	 */
	netstack_hold(ipst->ips_netstack);

	/* qprocsoff is done via ill_delete_tail */
	ill_delete_tail(ill);
	/*
	 * synchronously wait for arp stream to unbind. After this, we
	 * cannot get any data packets up from the driver.
	 */
	arp_unbind_complete(ill);
	ASSERT(ill->ill_ipst == NULL);

	/*
	 * Walk through all conns and qenable those that have queued data.
	 * Close synchronization needs this to
	 * be done to ensure that all upper layers blocked
	 * due to flow control to the closing device
	 * get unblocked.
	 */
	ip1dbg(("ip_wsrv: walking\n"));
	for (i = 0; i < TX_FANOUT_SIZE; i++) {
		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[i]);
	}

	/*
	 * ai can be null if this is an IPv6 ill, or if the IPv4
	 * stream is being torn down before ARP was plumbed (e.g.,
	 * /sbin/ifconfig plumbing a stream twice, and encountering
	 * an error
	 */
	if (ai != NULL) {
		ASSERT(!ill->ill_isv6);
		mutex_enter(&ai->ai_lock);
		ai->ai_ill = NULL;
		if (ai->ai_arl == NULL) {
			mutex_destroy(&ai->ai_lock);
			kmem_free(ai, sizeof (*ai));
		} else {
			cv_signal(&ai->ai_ill_unplumb_done);
			mutex_exit(&ai->ai_lock);
		}
	}

	mutex_enter(&ipst->ips_ip_mi_lock);
	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
	mutex_exit(&ipst->ips_ip_mi_lock);

	/*
	 * credp could be null if the open didn't succeed and ip_modopen
	 * itself calls ip_close.
	 */
	if (ill->ill_credp != NULL)
		crfree(ill->ill_credp);

	mutex_destroy(&ill->ill_saved_ire_lock);
	mutex_destroy(&ill->ill_lock);
	rw_destroy(&ill->ill_mcast_lock);
	mutex_destroy(&ill->ill_mcast_serializer);
	list_destroy(&ill->ill_nce);

	/*
	 * Now we are done with the module close pieces that
	 * need the netstack_t.
	 */
	netstack_rele(ipst->ips_netstack);

	mi_close_free((IDP)ill);
	q->q_ptr = WR(q)->q_ptr = NULL;

	ipsq_exit(ipsq);

	return (0);
}

/*
 * This is called as part of close() for IP, UDP, ICMP, and RTS
 * in order to quiesce the conn.
 */
void
ip_quiesce_conn(conn_t *connp)
{
	boolean_t	drain_cleanup_reqd = B_FALSE;
	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
	boolean_t	ilg_cleanup_reqd = B_FALSE;
	ip_stack_t	*ipst;

	ASSERT(!IPCL_IS_TCP(connp));
	ipst = connp->conn_netstack->netstack_ip;

	/*
	 * Mark the conn as closing, and this conn must not be
	 * inserted in future into any list. Eg. conn_drain_insert(),
	 * won't insert this conn into the conn_drain_list.
	 *
	 * conn_idl, and conn_ilg cannot get set henceforth.
	 */
	mutex_enter(&connp->conn_lock);
	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
	connp->conn_state_flags |= CONN_CLOSING;
	if (connp->conn_idl != NULL)
		drain_cleanup_reqd = B_TRUE;
	if (connp->conn_oper_pending_ill != NULL)
		conn_ioctl_cleanup_reqd = B_TRUE;
	if (connp->conn_dhcpinit_ill != NULL) {
		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
		ill_set_inputfn(connp->conn_dhcpinit_ill);
		connp->conn_dhcpinit_ill = NULL;
	}
	if (connp->conn_ilg != NULL)
		ilg_cleanup_reqd = B_TRUE;
	mutex_exit(&connp->conn_lock);

	if (conn_ioctl_cleanup_reqd)
		conn_ioctl_cleanup(connp);

	if (is_system_labeled() && connp->conn_anon_port) {
		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
		    connp->conn_mlp_type, connp->conn_proto,
		    ntohs(connp->conn_lport), B_FALSE);
		connp->conn_anon_port = 0;
	}
	connp->conn_mlp_type = mlptSingle;

	/*
	 * Remove this conn from any fanout list it is on.
	 * and then wait for any threads currently operating
	 * on this endpoint to finish
	 */
	ipcl_hash_remove(connp);

	/*
	 * Remove this conn from the drain list, and do any other cleanup that
	 * may be required.  (TCP conns are never flow controlled, and
	 * conn_idl will be NULL.)
	 */
	if (drain_cleanup_reqd && connp->conn_idl != NULL) {
		idl_t *idl = connp->conn_idl;

		mutex_enter(&idl->idl_lock);
		conn_drain(connp, B_TRUE);
		mutex_exit(&idl->idl_lock);
	}

	if (connp == ipst->ips_ip_g_mrouter)
		(void) ip_mrouter_done(ipst);

	if (ilg_cleanup_reqd)
		ilg_delete_all(connp);

	/*
	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
	 * callers from write side can't be there now because close
	 * is in progress. The only other caller is ipcl_walk
	 * which checks for the condemned flag.
	 */
	mutex_enter(&connp->conn_lock);
	connp->conn_state_flags |= CONN_CONDEMNED;
	while (connp->conn_ref != 1)
		cv_wait(&connp->conn_cv, &connp->conn_lock);
	connp->conn_state_flags |= CONN_QUIESCED;
	mutex_exit(&connp->conn_lock);
}

/* ARGSUSED */
int
ip_close(queue_t *q, int flags, cred_t *credp __unused)
{
	conn_t		*connp;

	/*
	 * Call the appropriate delete routine depending on whether this is
	 * a module or device.
	 */
	if (WR(q)->q_next != NULL) {
		/* This is a module close */
		return (ip_modclose((ill_t *)q->q_ptr));
	}

	connp = q->q_ptr;
	ip_quiesce_conn(connp);

	qprocsoff(q);

	/*
	 * Now we are truly single threaded on this stream, and can
	 * delete the things hanging off the connp, and finally the connp.
	 * We removed this connp from the fanout list, it cannot be
	 * accessed thru the fanouts, and we already waited for the
	 * conn_ref to drop to 0. We are already in close, so
	 * there cannot be any other thread from the top. qprocsoff
	 * has completed, and service has completed or won't run in
	 * future.
	 */
	ASSERT(connp->conn_ref == 1);

	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);

	connp->conn_ref--;
	ipcl_conn_destroy(connp);

	q->q_ptr = WR(q)->q_ptr = NULL;
	return (0);
}

/*
 * Wapper around putnext() so that ip_rts_request can merely use
 * conn_recv.
 */
/*ARGSUSED2*/
static void
ip_conn_input(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
{
	conn_t *connp = (conn_t *)arg1;

	putnext(connp->conn_rq, mp);
}

/* Dummy in case ICMP error delivery is attempted to a /dev/ip instance */
/* ARGSUSED */
static void
ip_conn_input_icmp(void *arg1, mblk_t *mp, void *arg2, ip_recv_attr_t *ira)
{
	freemsg(mp);
}

/*
 * Called when the module is about to be unloaded
 */
void
ip_ddi_destroy(void)
{
	/* This needs to be called before destroying any transports. */
	mutex_enter(&cpu_lock);
	unregister_cpu_setup_func(ip_tp_cpu_update, NULL);
	mutex_exit(&cpu_lock);

	tnet_fini();

	icmp_ddi_g_destroy();
	rts_ddi_g_destroy();
	udp_ddi_g_destroy();
	sctp_ddi_g_destroy();
	tcp_ddi_g_destroy();
	ilb_ddi_g_destroy();
	dce_g_destroy();
	ipsec_policy_g_destroy();
	ipcl_g_destroy();
	ip_net_g_destroy();
	ip_ire_g_fini();
	inet_minor_destroy(ip_minor_arena_sa);
#if defined(_LP64)
	inet_minor_destroy(ip_minor_arena_la);
#endif

#ifdef DEBUG
	list_destroy(&ip_thread_list);
	rw_destroy(&ip_thread_rwlock);
	tsd_destroy(&ip_thread_data);
#endif

	netstack_unregister(NS_IP);
}

/*
 * First step in cleanup.
 */
/* ARGSUSED */
static void
ip_stack_shutdown(netstackid_t stackid, void *arg)
{
	ip_stack_t *ipst = (ip_stack_t *)arg;
	kt_did_t ktid;

#ifdef NS_DEBUG
	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
#endif

	/*
	 * Perform cleanup for special interfaces (loopback and IPMP).
	 */
	ip_interface_cleanup(ipst);

	/*
	 * The *_hook_shutdown()s start the process of notifying any
	 * consumers that things are going away.... nothing is destroyed.
	 */
	ipv4_hook_shutdown(ipst);
	ipv6_hook_shutdown(ipst);
	arp_hook_shutdown(ipst);

	mutex_enter(&ipst->ips_capab_taskq_lock);
	ktid = ipst->ips_capab_taskq_thread->t_did;
	ipst->ips_capab_taskq_quit = B_TRUE;
	cv_signal(&ipst->ips_capab_taskq_cv);
	mutex_exit(&ipst->ips_capab_taskq_lock);

	/*
	 * In rare occurrences, particularly on virtual hardware where CPUs can
	 * be de-scheduled, the thread that we just signaled will not run until
	 * after we have gotten through parts of ip_stack_fini. If that happens
	 * then we'll try to grab the ips_capab_taskq_lock as part of returning
	 * from cv_wait which no longer exists.
	 */
	thread_join(ktid);
}

/*
 * Free the IP stack instance.
 */
static void
ip_stack_fini(netstackid_t stackid, void *arg)
{
	ip_stack_t *ipst = (ip_stack_t *)arg;
	int ret;

#ifdef NS_DEBUG
	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
#endif
	/*
	 * At this point, all of the notifications that the events and
	 * protocols are going away have been run, meaning that we can
	 * now set about starting to clean things up.
	 */
	ipobs_fini(ipst);
	ipv4_hook_destroy(ipst);
	ipv6_hook_destroy(ipst);
	arp_hook_destroy(ipst);
	ip_net_destroy(ipst);

	ipmp_destroy(ipst);

	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
	ipst->ips_ip_mibkp = NULL;
	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
	ipst->ips_icmp_mibkp = NULL;
	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
	ipst->ips_ip_kstat = NULL;
	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
	ipst->ips_ip6_kstat = NULL;
	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));

	kmem_free(ipst->ips_propinfo_tbl,
	    ip_propinfo_count * sizeof (mod_prop_info_t));
	ipst->ips_propinfo_tbl = NULL;

	dce_stack_destroy(ipst);
	ip_mrouter_stack_destroy(ipst);

	/*
	 * Quiesce all of our timers. Note we set the quiesce flags before we
	 * call untimeout. The slowtimers may actually kick off another instance
	 * of the non-slow timers.
	 */
	mutex_enter(&ipst->ips_igmp_timer_lock);
	ipst->ips_igmp_timer_quiesce = B_TRUE;
	mutex_exit(&ipst->ips_igmp_timer_lock);

	mutex_enter(&ipst->ips_mld_timer_lock);
	ipst->ips_mld_timer_quiesce = B_TRUE;
	mutex_exit(&ipst->ips_mld_timer_lock);

	mutex_enter(&ipst->ips_igmp_slowtimeout_lock);
	ipst->ips_igmp_slowtimeout_quiesce = B_TRUE;
	mutex_exit(&ipst->ips_igmp_slowtimeout_lock);

	mutex_enter(&ipst->ips_mld_slowtimeout_lock);
	ipst->ips_mld_slowtimeout_quiesce = B_TRUE;
	mutex_exit(&ipst->ips_mld_slowtimeout_lock);

	ret = untimeout(ipst->ips_igmp_timeout_id);
	if (ret == -1) {
		ASSERT(ipst->ips_igmp_timeout_id == 0);
	} else {
		ASSERT(ipst->ips_igmp_timeout_id != 0);
		ipst->ips_igmp_timeout_id = 0;
	}
	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
	if (ret == -1) {
		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
	} else {
		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
		ipst->ips_igmp_slowtimeout_id = 0;
	}
	ret = untimeout(ipst->ips_mld_timeout_id);
	if (ret == -1) {
		ASSERT(ipst->ips_mld_timeout_id == 0);
	} else {
		ASSERT(ipst->ips_mld_timeout_id != 0);
		ipst->ips_mld_timeout_id = 0;
	}
	ret = untimeout(ipst->ips_mld_slowtimeout_id);
	if (ret == -1) {
		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
	} else {
		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
		ipst->ips_mld_slowtimeout_id = 0;
	}

	ip_ire_fini(ipst);
	ip6_asp_free(ipst);
	conn_drain_fini(ipst);
	ipcl_destroy(ipst);

	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
	ipst->ips_ndp4 = NULL;
	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
	ipst->ips_ndp6 = NULL;

	if (ipst->ips_loopback_ksp != NULL) {
		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
		ipst->ips_loopback_ksp = NULL;
	}

	mutex_destroy(&ipst->ips_capab_taskq_lock);
	cv_destroy(&ipst->ips_capab_taskq_cv);

	rw_destroy(&ipst->ips_srcid_lock);

	mutex_destroy(&ipst->ips_ip_mi_lock);
	rw_destroy(&ipst->ips_ill_g_usesrc_lock);

	mutex_destroy(&ipst->ips_igmp_timer_lock);
	mutex_destroy(&ipst->ips_mld_timer_lock);
	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
	rw_destroy(&ipst->ips_ill_g_lock);

	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
	ipst->ips_phyint_g_list = NULL;
	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
	ipst->ips_ill_g_heads = NULL;

	ldi_ident_release(ipst->ips_ldi_ident);
	kmem_free(ipst, sizeof (*ipst));
}

/*
 * This function is called from the TSD destructor, and is used to debug
 * reference count issues in IP. See block comment in <inet/ip_if.h> for
 * details.
 */
static void
ip_thread_exit(void *phash)
{
	th_hash_t *thh = phash;

	rw_enter(&ip_thread_rwlock, RW_WRITER);
	list_remove(&ip_thread_list, thh);
	rw_exit(&ip_thread_rwlock);
	mod_hash_destroy_hash(thh->thh_hash);
	kmem_free(thh, sizeof (*thh));
}

/*
 * Called when the IP kernel module is loaded into the kernel
 */
void
ip_ddi_init(void)
{
	ip_squeue_flag = ip_squeue_switch(ip_squeue_enter);

	/*
	 * For IP and TCP the minor numbers should start from 2 since we have 4
	 * initial devices: ip, ip6, tcp, tcp6.
	 */
	/*
	 * If this is a 64-bit kernel, then create two separate arenas -
	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
	 * other for socket apps in the range 2^^18 through 2^^32-1.
	 */
	ip_minor_arena_la = NULL;
	ip_minor_arena_sa = NULL;
#if defined(_LP64)
	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
		cmn_err(CE_PANIC,
		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
	}
	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
		cmn_err(CE_PANIC,
		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
	}
#else
	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
		cmn_err(CE_PANIC,
		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
	}
#endif
	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);

	ipcl_g_init();
	ip_ire_g_init();
	ip_net_g_init();

#ifdef DEBUG
	tsd_create(&ip_thread_data, ip_thread_exit);
	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
	list_create(&ip_thread_list, sizeof (th_hash_t),
	    offsetof(th_hash_t, thh_link));
#endif
	ipsec_policy_g_init();
	tcp_ddi_g_init();
	sctp_ddi_g_init();
	dce_g_init();

	/*
	 * We want to be informed each time a stack is created or
	 * destroyed in the kernel, so we can maintain the
	 * set of udp_stack_t's.
	 */
	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
	    ip_stack_fini);

	tnet_init();

	udp_ddi_g_init();
	rts_ddi_g_init();
	icmp_ddi_g_init();
	ilb_ddi_g_init();

	/* This needs to be called after all transports are initialized. */
	mutex_enter(&cpu_lock);
	register_cpu_setup_func(ip_tp_cpu_update, NULL);
	mutex_exit(&cpu_lock);
}

/*
 * Initialize the IP stack instance.
 */
static void *
ip_stack_init(netstackid_t stackid, netstack_t *ns)
{
	ip_stack_t	*ipst;
	size_t		arrsz;
	major_t		major;

#ifdef NS_DEBUG
	printf("ip_stack_init(stack %d)\n", stackid);
#endif

	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
	ipst->ips_netstack = ns;

	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
	    KM_SLEEP);
	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
	    KM_SLEEP);
	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);

	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
	ipst->ips_igmp_deferred_next = INFINITY;
	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
	ipst->ips_mld_deferred_next = INFINITY;
	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);

	ipcl_init(ipst);
	ip_ire_init(ipst);
	ip6_asp_init(ipst);
	ipif_init(ipst);
	conn_drain_init(ipst);
	ip_mrouter_stack_init(ipst);
	dce_stack_init(ipst);

	ipst->ips_ip_multirt_log_interval = 1000;

	ipst->ips_ill_index = 1;

	ipst->ips_saved_ip_forwarding = -1;
	ipst->ips_reg_vif_num = ALL_VIFS;	/* Index to Register vif */

	arrsz = ip_propinfo_count * sizeof (mod_prop_info_t);
	ipst->ips_propinfo_tbl = (mod_prop_info_t *)kmem_alloc(arrsz, KM_SLEEP);
	bcopy(ip_propinfo_tbl, ipst->ips_propinfo_tbl, arrsz);

	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
	ipst->ips_ip6_kstat =
	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);

	ipst->ips_ip_src_id = 1;
	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);

	ipst->ips_src_generation = SRC_GENERATION_INITIAL;

	ip_net_init(ipst, ns);
	ipv4_hook_init(ipst);
	ipv6_hook_init(ipst);
	arp_hook_init(ipst);
	ipmp_init(ipst);
	ipobs_init(ipst);

	/*
	 * Create the taskq dispatcher thread and initialize related stuff.
	 */
	mutex_init(&ipst->ips_capab_taskq_lock, NULL, MUTEX_DEFAULT, NULL);
	cv_init(&ipst->ips_capab_taskq_cv, NULL, CV_DEFAULT, NULL);
	ipst->ips_capab_taskq_thread = thread_create(NULL, 0,
	    ill_taskq_dispatch, ipst, 0, &p0, TS_RUN, minclsyspri);

	major = mod_name_to_major(INET_NAME);
	(void) ldi_ident_from_major(major, &ipst->ips_ldi_ident);
	return (ipst);
}

/*
 * Allocate and initialize a DLPI template of the specified length.  (May be
 * called as writer.)
 */
mblk_t *
ip_dlpi_alloc(size_t len, t_uscalar_t prim)
{
	mblk_t	*mp;

	mp = allocb(len, BPRI_MED);
	if (!mp)
		return (NULL);

	/*
	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
	 * of which we don't seem to use) are sent with M_PCPROTO, and
	 * that other DLPI are M_PROTO.
	 */
	if (prim == DL_INFO_REQ) {
		mp->b_datap->db_type = M_PCPROTO;
	} else {
		mp->b_datap->db_type = M_PROTO;
	}

	mp->b_wptr = mp->b_rptr + len;
	bzero(mp->b_rptr, len);
	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
	return (mp);
}

/*
 * Allocate and initialize a DLPI notification.  (May be called as writer.)
 */
mblk_t *
ip_dlnotify_alloc(uint_t notification, uint_t data)
{
	dl_notify_ind_t	*notifyp;
	mblk_t		*mp;

	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
		return (NULL);

	notifyp = (dl_notify_ind_t *)mp->b_rptr;
	notifyp->dl_notification = notification;
	notifyp->dl_data = data;
	return (mp);
}

mblk_t *
ip_dlnotify_alloc2(uint_t notification, uint_t data1, uint_t data2)
{
	dl_notify_ind_t	*notifyp;
	mblk_t		*mp;

	if ((mp = ip_dlpi_alloc(DL_NOTIFY_IND_SIZE, DL_NOTIFY_IND)) == NULL)
		return (NULL);

	notifyp = (dl_notify_ind_t *)mp->b_rptr;
	notifyp->dl_notification = notification;
	notifyp->dl_data1 = data1;
	notifyp->dl_data2 = data2;
	return (mp);
}

/*
 * Debug formatting routine.  Returns a character string representation of the
 * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
 * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
 *
 * Once the ndd table-printing interfaces are removed, this can be changed to
 * standard dotted-decimal form.
 */
char *
ip_dot_addr(ipaddr_t addr, char *buf)
{
	uint8_t *ap = (uint8_t *)&addr;

	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
	return (buf);
}

/*
 * Write the given MAC address as a printable string in the usual colon-
 * separated format.
 */
const char *
mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
{
	char *bp;

	if (alen == 0 || buflen < 4)
		return ("?");
	bp = buf;
	for (;;) {
		/*
		 * If there are more MAC address bytes available, but we won't
		 * have any room to print them, then add "..." to the string
		 * instead.  See below for the 'magic number' explanation.
		 */
		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
			(void) strcpy(bp, "...");
			break;
		}
		(void) sprintf(bp, "%02x", *addr++);
		bp += 2;
		if (--alen == 0)
			break;
		*bp++ = ':';
		buflen -= 3;
		/*
		 * At this point, based on the first 'if' statement above,
		 * either alen == 1 and buflen >= 3, or alen > 1 and
		 * buflen >= 4.  The first case leaves room for the final "xx"
		 * number and trailing NUL byte.  The second leaves room for at
		 * least "...".  Thus the apparently 'magic' numbers chosen for
		 * that statement.
		 */
	}
	return (buf);
}

/*
 * Called when it is conceptually a ULP that would sent the packet
 * e.g., port unreachable and protocol unreachable. Check that the packet
 * would have passed the IPsec global policy before sending the error.
 *
 * Send an ICMP error after patching up the packet appropriately.
 * Uses ip_drop_input and bumps the appropriate MIB.
 */
void
ip_fanout_send_icmp_v4(mblk_t *mp, uint_t icmp_type, uint_t icmp_code,
    ip_recv_attr_t *ira)
{
	ipha_t		*ipha;
	boolean_t	secure;
	ill_t		*ill = ira->ira_ill;
	ip_stack_t	*ipst = ill->ill_ipst;
	netstack_t	*ns = ipst->ips_netstack;
	ipsec_stack_t	*ipss = ns->netstack_ipsec;

	secure = ira->ira_flags & IRAF_IPSEC_SECURE;

	/*
	 * We are generating an icmp error for some inbound packet.
	 * Called from all ip_fanout_(udp, tcp, proto) functions.
	 * Before we generate an error, check with global policy
	 * to see whether this is allowed to enter the system. As
	 * there is no "conn", we are checking with global policy.
	 */
	ipha = (ipha_t *)mp->b_rptr;
	if (secure || ipss->ipsec_inbound_v4_policy_present) {
		mp = ipsec_check_global_policy(mp, NULL, ipha, NULL, ira, ns);
		if (mp == NULL)
			return;
	}

	/* We never send errors for protocols that we do implement */
	if (ira->ira_protocol == IPPROTO_ICMP ||
	    ira->ira_protocol == IPPROTO_IGMP) {
		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
		ip_drop_input("ip_fanout_send_icmp_v4", mp, ill);
		freemsg(mp);
		return;
	}
	/*
	 * Have to correct checksum since
	 * the packet might have been
	 * fragmented and the reassembly code in ip_rput
	 * does not restore the IP checksum.
	 */
	ipha->ipha_hdr_checksum = 0;
	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);

	switch (icmp_type) {
	case ICMP_DEST_UNREACHABLE:
		switch (icmp_code) {
		case ICMP_PROTOCOL_UNREACHABLE:
			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInUnknownProtos);
			ip_drop_input("ipIfStatsInUnknownProtos", mp, ill);
			break;
		case ICMP_PORT_UNREACHABLE:
			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
			ip_drop_input("ipIfStatsNoPorts", mp, ill);
			break;
		}

		icmp_unreachable(mp, icmp_code, ira);
		break;
	default:
#ifdef DEBUG
		panic("ip_fanout_send_icmp_v4: wrong type");
		/*NOTREACHED*/
#else
		freemsg(mp);
		break;
#endif
	}
}

/*
 * Used to send an ICMP error message when a packet is received for
 * a protocol that is not supported. The mblk passed as argument
 * is consumed by this function.
 */
void
ip_proto_not_sup(mblk_t *mp, ip_recv_attr_t *ira)
{
	ipha_t		*ipha;

	ipha = (ipha_t *)mp->b_rptr;
	if (ira->ira_flags & IRAF_IS_IPV4) {
		ASSERT(IPH_HDR_VERSION(ipha) == IP_VERSION);
		ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
		    ICMP_PROTOCOL_UNREACHABLE, ira);
	} else {
		ASSERT(IPH_HDR_VERSION(ipha) == IPV6_VERSION);
		ip_fanout_send_icmp_v6(mp, ICMP6_PARAM_PROB,
		    ICMP6_PARAMPROB_NEXTHEADER, ira);
	}
}

/*
 * Deliver a rawip packet to the given conn, possibly applying ipsec policy.
 * Handles IPv4 and IPv6.
 * We are responsible for disposing of mp, such as by freemsg() or putnext()
 * Caller is responsible for dropping references to the conn.
 */
void
ip_fanout_proto_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
    ip_recv_attr_t *ira)
{
	ill_t		*ill = ira->ira_ill;
	ip_stack_t	*ipst = ill->ill_ipst;
	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
	boolean_t	secure;
	uint_t		protocol = ira->ira_protocol;
	iaflags_t	iraflags = ira->ira_flags;
	queue_t		*rq;

	secure = iraflags & IRAF_IPSEC_SECURE;

	rq = connp->conn_rq;
	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
		switch (protocol) {
		case IPPROTO_ICMPV6:
			BUMP_MIB(ill->ill_icmp6_mib, ipv6IfIcmpInOverflows);
			break;
		case IPPROTO_ICMP:
			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
			break;
		default:
			BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
			break;
		}
		freemsg(mp);
		return;
	}

	ASSERT(!(IPCL_IS_IPTUN(connp)));

	if (((iraflags & IRAF_IS_IPV4) ?
	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
	    secure) {
		mp = ipsec_check_inbound_policy(mp, connp, ipha,
		    ip6h, ira);
		if (mp == NULL) {
			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
			/* Note that mp is NULL */
			ip_drop_input("ipIfStatsInDiscards", mp, ill);
			return;
		}
	}

	if (iraflags & IRAF_ICMP_ERROR) {
		(connp->conn_recvicmp)(connp, mp, NULL, ira);
	} else {
		ill_t *rill = ira->ira_rill;

		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
		ira->ira_ill = ira->ira_rill = NULL;
		/* Send it upstream */
		(connp->conn_recv)(connp, mp, NULL, ira);
		ira->ira_ill = ill;
		ira->ira_rill = rill;
	}
}

/*
 * Handle protocols with which IP is less intimate.  There
 * can be more than one stream bound to a particular
 * protocol.  When this is the case, normally each one gets a copy
 * of any incoming packets.
 *
 * IPsec NOTE :
 *
 * Don't allow a secure packet going up a non-secure connection.
 * We don't allow this because
 *
 * 1) Reply might go out in clear which will be dropped at
 *    the sending side.
 * 2) If the reply goes out in clear it will give the
 *    adversary enough information for getting the key in
 *    most of the cases.
 *
 * Moreover getting a secure packet when we expect clear
 * implies that SA's were added without checking for
 * policy on both ends. This should not happen once ISAKMP
 * is used to negotiate SAs as SAs will be added only after
 * verifying the policy.
 *
 * Zones notes:
 * Earlier in ip_input on a system with multiple shared-IP zones we
 * duplicate the multicast and broadcast packets and send them up
 * with each explicit zoneid that exists on that ill.
 * This means that here we can match the zoneid with SO_ALLZONES being special.
 */
void
ip_fanout_proto_v4(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
{
	mblk_t		*mp1;
	ipaddr_t	laddr;
	conn_t		*connp, *first_connp, *next_connp;
	connf_t		*connfp;
	ill_t		*ill = ira->ira_ill;
	ip_stack_t	*ipst = ill->ill_ipst;

	laddr = ipha->ipha_dst;

	connfp = &ipst->ips_ipcl_proto_fanout_v4[ira->ira_protocol];
	mutex_enter(&connfp->connf_lock);
	connp = connfp->connf_head;
	for (connp = connfp->connf_head; connp != NULL;
	    connp = connp->conn_next) {
		/* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
		if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp))) {
			break;
		}
	}

	if (connp == NULL) {
		/*
		 * No one bound to these addresses.  Is
		 * there a client that wants all
		 * unclaimed datagrams?
		 */
		mutex_exit(&connfp->connf_lock);
		ip_fanout_send_icmp_v4(mp, ICMP_DEST_UNREACHABLE,
		    ICMP_PROTOCOL_UNREACHABLE, ira);
		return;
	}

	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);

	CONN_INC_REF(connp);
	first_connp = connp;
	connp = connp->conn_next;

	for (;;) {
		while (connp != NULL) {
			/* Note: IPCL_PROTO_MATCH includes conn_wantpacket */
			if (IPCL_PROTO_MATCH(connp, ira, ipha) &&
			    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
			    tsol_receive_local(mp, &laddr, IPV4_VERSION,
			    ira, connp)))
				break;
			connp = connp->conn_next;
		}

		if (connp == NULL) {
			/* No more interested clients */
			connp = first_connp;
			break;
		}
		if (((mp1 = dupmsg(mp)) == NULL) &&
		    ((mp1 = copymsg(mp)) == NULL)) {
			/* Memory allocation failed */
			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
			ip_drop_input("ipIfStatsInDiscards", mp, ill);
			connp = first_connp;
			break;
		}

		CONN_INC_REF(connp);
		mutex_exit(&connfp->connf_lock);

		ip_fanout_proto_conn(connp, mp1, (ipha_t *)mp1->b_rptr, NULL,
		    ira);

		mutex_enter(&connfp->connf_lock);
		/* Follow the next pointer before releasing the conn. */
		next_connp = connp->conn_next;
		CONN_DEC_REF(connp);
		connp = next_connp;
	}

	/* Last one.  Send it upstream. */
	mutex_exit(&connfp->connf_lock);

	ip_fanout_proto_conn(connp, mp, ipha, NULL, ira);

	CONN_DEC_REF(connp);
}

/*
 * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
 * pass it along to ESP if the SPI is non-zero.  Returns the mblk if the mblk
 * is not consumed.
 *
 * One of three things can happen, all of which affect the passed-in mblk:
 *
 * 1.) The packet is stock UDP and gets its zero-SPI stripped.  Return mblk..
 *
 * 2.) The packet is ESP-in-UDP, gets transformed into an equivalent
 *     ESP packet, and is passed along to ESP for consumption.  Return NULL.
 *
 * 3.) The packet is an ESP-in-UDP Keepalive.  Drop it and return NULL.
 */
mblk_t *
zero_spi_check(mblk_t *mp, ip_recv_attr_t *ira)
{
	int shift, plen, iph_len;
	ipha_t *ipha;
	udpha_t *udpha;
	uint32_t *spi;
	uint32_t esp_ports;
	uint8_t *orptr;
	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;

	ipha = (ipha_t *)mp->b_rptr;
	iph_len = ira->ira_ip_hdr_length;
	plen = ira->ira_pktlen;

	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
		/*
		 * Most likely a keepalive for the benefit of an intervening
		 * NAT.  These aren't for us, per se, so drop it.
		 *
		 * RFC 3947/8 doesn't say for sure what to do for 2-3
		 * byte packets (keepalives are 1-byte), but we'll drop them
		 * also.
		 */
		ip_drop_packet(mp, B_TRUE, ira->ira_ill,
		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
		return (NULL);
	}

	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
		/* might as well pull it all up - it might be ESP. */
		if (!pullupmsg(mp, -1)) {
			ip_drop_packet(mp, B_TRUE, ira->ira_ill,
			    DROPPER(ipss, ipds_esp_nomem),
			    &ipss->ipsec_dropper);
			return (NULL);
		}

		ipha = (ipha_t *)mp->b_rptr;
	}
	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
	if (*spi == 0) {
		/* UDP packet - remove 0-spi. */
		shift = sizeof (uint32_t);
	} else {
		/* ESP-in-UDP packet - reduce to ESP. */
		ipha->ipha_protocol = IPPROTO_ESP;
		shift = sizeof (udpha_t);
	}

	/* Fix IP header */
	ira->ira_pktlen = (plen - shift);
	ipha->ipha_length = htons(ira->ira_pktlen);
	ipha->ipha_hdr_checksum = 0;

	orptr = mp->b_rptr;
	mp->b_rptr += shift;

	udpha = (udpha_t *)(orptr + iph_len);
	if (*spi == 0) {
		ASSERT((uint8_t *)ipha == orptr);
		udpha->uha_length = htons(plen - shift - iph_len);
		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
		esp_ports = 0;
	} else {
		esp_ports = *((uint32_t *)udpha);
		ASSERT(esp_ports != 0);
	}
	ovbcopy(orptr, orptr + shift, iph_len);
	if (esp_ports != 0) /* Punt up for ESP processing. */ {
		ipha = (ipha_t *)(orptr + shift);

		ira->ira_flags |= IRAF_ESP_UDP_PORTS;
		ira->ira_esp_udp_ports = esp_ports;
		ip_fanout_v4(mp, ipha, ira);
		return (NULL);
	}
	return (mp);
}

/*
 * Deliver a udp packet to the given conn, possibly applying ipsec policy.
 * Handles IPv4 and IPv6.
 * We are responsible for disposing of mp, such as by freemsg() or putnext()
 * Caller is responsible for dropping references to the conn.
 */
void
ip_fanout_udp_conn(conn_t *connp, mblk_t *mp, ipha_t *ipha, ip6_t *ip6h,
    ip_recv_attr_t *ira)
{
	ill_t		*ill = ira->ira_ill;
	ip_stack_t	*ipst = ill->ill_ipst;
	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
	boolean_t	secure;
	iaflags_t	iraflags = ira->ira_flags;

	secure = iraflags & IRAF_IPSEC_SECURE;

	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld :
	    !canputnext(connp->conn_rq)) {
		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
		freemsg(mp);
		return;
	}

	if (((iraflags & IRAF_IS_IPV4) ?
	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
	    secure) {
		mp = ipsec_check_inbound_policy(mp, connp, ipha,
		    ip6h, ira);
		if (mp == NULL) {
			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
			/* Note that mp is NULL */
			ip_drop_input("ipIfStatsInDiscards", mp, ill);
			return;
		}
	}

	/*
	 * Since this code is not used for UDP unicast we don't need a NAT_T
	 * check. Only ip_fanout_v4 has that check.
	 */
	if (ira->ira_flags & IRAF_ICMP_ERROR) {
		(connp->conn_recvicmp)(connp, mp, NULL, ira);
	} else {
		ill_t *rill = ira->ira_rill;

		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
		ira->ira_ill = ira->ira_rill = NULL;
		/* Send it upstream */
		(connp->conn_recv)(connp, mp, NULL, ira);
		ira->ira_ill = ill;
		ira->ira_rill = rill;
	}
}

/*
 * Fanout for UDP packets that are multicast or broadcast, and ICMP errors.
 * (Unicast fanout is handled in ip_input_v4.)
 *
 * If SO_REUSEADDR is set all multicast and broadcast packets
 * will be delivered to all conns bound to the same port.
 *
 * If there is at least one matching AF_INET receiver, then we will
 * ignore any AF_INET6 receivers.
 * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
 * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
 * packets.
 *
 * Zones notes:
 * Earlier in ip_input on a system with multiple shared-IP zones we
 * duplicate the multicast and broadcast packets and send them up
 * with each explicit zoneid that exists on that ill.
 * This means that here we can match the zoneid with SO_ALLZONES being special.
 */
void
ip_fanout_udp_multi_v4(mblk_t *mp, ipha_t *ipha, uint16_t lport, uint16_t fport,
    ip_recv_attr_t *ira)
{
	ipaddr_t	laddr;
	in6_addr_t	v6faddr;
	conn_t		*connp;
	connf_t		*connfp;
	ipaddr_t	faddr;
	ill_t		*ill = ira->ira_ill;
	ip_stack_t	*ipst = ill->ill_ipst;

	ASSERT(ira->ira_flags & (IRAF_MULTIBROADCAST|IRAF_ICMP_ERROR));

	laddr = ipha->ipha_dst;
	faddr = ipha->ipha_src;

	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
	mutex_enter(&connfp->connf_lock);
	connp = connfp->connf_head;

	/*
	 * If SO_REUSEADDR has been set on the first we send the
	 * packet to all clients that have joined the group and
	 * match the port.
	 */
	while (connp != NULL) {
		if ((IPCL_UDP_MATCH(connp, lport, laddr, fport, faddr)) &&
		    conn_wantpacket(connp, ira, ipha) &&
		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
			break;
		connp = connp->conn_next;
	}

	if (connp == NULL)
		goto notfound;

	CONN_INC_REF(connp);

	if (connp->conn_reuseaddr) {
		conn_t		*first_connp = connp;
		conn_t		*next_connp;
		mblk_t		*mp1;

		connp = connp->conn_next;
		for (;;) {
			while (connp != NULL) {
				if (IPCL_UDP_MATCH(connp, lport, laddr,
				    fport, faddr) &&
				    conn_wantpacket(connp, ira, ipha) &&
				    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
				    tsol_receive_local(mp, &laddr, IPV4_VERSION,
				    ira, connp)))
					break;
				connp = connp->conn_next;
			}
			if (connp == NULL) {
				/* No more interested clients */
				connp = first_connp;
				break;
			}
			if (((mp1 = dupmsg(mp)) == NULL) &&
			    ((mp1 = copymsg(mp)) == NULL)) {
				/* Memory allocation failed */
				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
				ip_drop_input("ipIfStatsInDiscards", mp, ill);
				connp = first_connp;
				break;
			}
			CONN_INC_REF(connp);
			mutex_exit(&connfp->connf_lock);

			IP_STAT(ipst, ip_udp_fanmb);
			ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
			    NULL, ira);
			mutex_enter(&connfp->connf_lock);
			/* Follow the next pointer before releasing the conn */
			next_connp = connp->conn_next;
			CONN_DEC_REF(connp);
			connp = next_connp;
		}
	}

	/* Last one.  Send it upstream. */
	mutex_exit(&connfp->connf_lock);
	IP_STAT(ipst, ip_udp_fanmb);
	ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
	CONN_DEC_REF(connp);
	return;

notfound:
	mutex_exit(&connfp->connf_lock);
	/*
	 * IPv6 endpoints bound to multicast IPv4-mapped addresses
	 * have already been matched above, since they live in the IPv4
	 * fanout tables. This implies we only need to
	 * check for IPv6 in6addr_any endpoints here.
	 * Thus we compare using ipv6_all_zeros instead of the destination
	 * address, except for the multicast group membership lookup which
	 * uses the IPv4 destination.
	 */
	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6faddr);
	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(lport, ipst)];
	mutex_enter(&connfp->connf_lock);
	connp = connfp->connf_head;
	/*
	 * IPv4 multicast packet being delivered to an AF_INET6
	 * in6addr_any endpoint.
	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
	 * and not conn_wantpacket_v6() since any multicast membership is
	 * for an IPv4-mapped multicast address.
	 */
	while (connp != NULL) {
		if (IPCL_UDP_MATCH_V6(connp, lport, ipv6_all_zeros,
		    fport, v6faddr) &&
		    conn_wantpacket(connp, ira, ipha) &&
		    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
		    tsol_receive_local(mp, &laddr, IPV4_VERSION, ira, connp)))
			break;
		connp = connp->conn_next;
	}

	if (connp == NULL) {
		/*
		 * No one bound to this port.  Is
		 * there a client that wants all
		 * unclaimed datagrams?
		 */
		mutex_exit(&connfp->connf_lock);

		if (ipst->ips_ipcl_proto_fanout_v4[IPPROTO_UDP].connf_head !=
		    NULL) {
			ASSERT(ira->ira_protocol == IPPROTO_UDP);
			ip_fanout_proto_v4(mp, ipha, ira);
		} else {
			/*
			 * We used to attempt to send an icmp error here, but
			 * since this is known to be a multicast packet
			 * and we don't send icmp errors in response to
			 * multicast, just drop the packet and give up sooner.
			 */
			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
			freemsg(mp);
		}
		return;
	}
	CONN_INC_REF(connp);
	ASSERT(IPCL_IS_NONSTR(connp) || connp->conn_rq != NULL);

	/*
	 * If SO_REUSEADDR has been set on the first we send the
	 * packet to all clients that have joined the group and
	 * match the port.
	 */
	if (connp->conn_reuseaddr) {
		conn_t		*first_connp = connp;
		conn_t		*next_connp;
		mblk_t		*mp1;

		connp = connp->conn_next;
		for (;;) {
			while (connp != NULL) {
				if (IPCL_UDP_MATCH_V6(connp, lport,
				    ipv6_all_zeros, fport, v6faddr) &&
				    conn_wantpacket(connp, ira, ipha) &&
				    (!(ira->ira_flags & IRAF_SYSTEM_LABELED) ||
				    tsol_receive_local(mp, &laddr, IPV4_VERSION,
				    ira, connp)))
					break;
				connp = connp->conn_next;
			}
			if (connp == NULL) {
				/* No more interested clients */
				connp = first_connp;
				break;
			}
			if (((mp1 = dupmsg(mp)) == NULL) &&
			    ((mp1 = copymsg(mp)) == NULL)) {
				/* Memory allocation failed */
				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
				ip_drop_input("ipIfStatsInDiscards", mp, ill);
				connp = first_connp;
				break;
			}
			CONN_INC_REF(connp);
			mutex_exit(&connfp->connf_lock);

			IP_STAT(ipst, ip_udp_fanmb);
			ip_fanout_udp_conn(connp, mp1, (ipha_t *)mp1->b_rptr,
			    NULL, ira);
			mutex_enter(&connfp->connf_lock);
			/* Follow the next pointer before releasing the conn */
			next_connp = connp->conn_next;
			CONN_DEC_REF(connp);
			connp = next_connp;
		}
	}

	/* Last one.  Send it upstream. */
	mutex_exit(&connfp->connf_lock);
	IP_STAT(ipst, ip_udp_fanmb);
	ip_fanout_udp_conn(connp, mp, ipha, NULL, ira);
	CONN_DEC_REF(connp);
}

/*
 * Split an incoming packet's IPv4 options into the label and the other options.
 * If 'allocate' is set it does memory allocation for the ip_pkt_t, including
 * clearing out any leftover label or options.
 * Otherwise it just makes ipp point into the packet.
 *
 * Returns zero if ok; ENOMEM if the buffer couldn't be allocated.
 */
int
ip_find_hdr_v4(ipha_t *ipha, ip_pkt_t *ipp, boolean_t allocate)
{
	uchar_t		*opt;
	uint32_t	totallen;
	uint32_t	optval;
	uint32_t	optlen;

	ipp->ipp_fields |= IPPF_HOPLIMIT | IPPF_TCLASS | IPPF_ADDR;
	ipp->ipp_hoplimit = ipha->ipha_ttl;
	ipp->ipp_type_of_service = ipha->ipha_type_of_service;
	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &ipp->ipp_addr);

	/*
	 * Get length (in 4 byte octets) of IP header options.
	 */
	totallen = ipha->ipha_version_and_hdr_length -
	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);

	if (totallen == 0) {
		if (!allocate)
			return (0);

		/* Clear out anything from a previous packet */
		if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
			kmem_free(ipp->ipp_ipv4_options,
			    ipp->ipp_ipv4_options_len);
			ipp->ipp_ipv4_options = NULL;
			ipp->ipp_ipv4_options_len = 0;
			ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
		}
		if (ipp->ipp_fields & IPPF_LABEL_V4) {
			kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
			ipp->ipp_label_v4 = NULL;
			ipp->ipp_label_len_v4 = 0;
			ipp->ipp_fields &= ~IPPF_LABEL_V4;
		}
		return (0);
	}

	totallen <<= 2;
	opt = (uchar_t *)&ipha[1];
	if (!is_system_labeled()) {

	copyall:
		if (!allocate) {
			if (totallen != 0) {
				ipp->ipp_ipv4_options = opt;
				ipp->ipp_ipv4_options_len = totallen;
				ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
			}
			return (0);
		}
		/* Just copy all of options */
		if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
			if (totallen == ipp->ipp_ipv4_options_len) {
				bcopy(opt, ipp->ipp_ipv4_options, totallen);
				return (0);
			}
			kmem_free(ipp->ipp_ipv4_options,
			    ipp->ipp_ipv4_options_len);
			ipp->ipp_ipv4_options = NULL;
			ipp->ipp_ipv4_options_len = 0;
			ipp->ipp_fields &= ~IPPF_IPV4_OPTIONS;
		}
		if (totallen == 0)
			return (0);

		ipp->ipp_ipv4_options = kmem_alloc(totallen, KM_NOSLEEP);
		if (ipp->ipp_ipv4_options == NULL)
			return (ENOMEM);
		ipp->ipp_ipv4_options_len = totallen;
		ipp->ipp_fields |= IPPF_IPV4_OPTIONS;
		bcopy(opt, ipp->ipp_ipv4_options, totallen);
		return (0);
	}

	if (allocate && (ipp->ipp_fields & IPPF_LABEL_V4)) {
		kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
		ipp->ipp_label_v4 = NULL;
		ipp->ipp_label_len_v4 = 0;
		ipp->ipp_fields &= ~IPPF_LABEL_V4;
	}

	/*
	 * Search for CIPSO option.
	 * We assume CIPSO is first in options if it is present.
	 * If it isn't, then ipp_opt_ipv4_options will not include the options
	 * prior to the CIPSO option.
	 */
	while (totallen != 0) {
		switch (optval = opt[IPOPT_OPTVAL]) {
		case IPOPT_EOL:
			return (0);
		case IPOPT_NOP:
			optlen = 1;
			break;
		default:
			if (totallen <= IPOPT_OLEN)
				return (EINVAL);
			optlen = opt[IPOPT_OLEN];
			if (optlen < 2)
				return (EINVAL);
		}
		if (optlen > totallen)
			return (EINVAL);

		switch (optval) {
		case IPOPT_COMSEC:
			if (!allocate) {
				ipp->ipp_label_v4 = opt;
				ipp->ipp_label_len_v4 = optlen;
				ipp->ipp_fields |= IPPF_LABEL_V4;
			} else {
				ipp->ipp_label_v4 = kmem_alloc(optlen,
				    KM_NOSLEEP);
				if (ipp->ipp_label_v4 == NULL)
					return (ENOMEM);
				ipp->ipp_label_len_v4 = optlen;
				ipp->ipp_fields |= IPPF_LABEL_V4;
				bcopy(opt, ipp->ipp_label_v4, optlen);
			}
			totallen -= optlen;
			opt += optlen;

			/* Skip padding bytes until we get to a multiple of 4 */
			while ((totallen & 3) != 0 && opt[0] == IPOPT_NOP) {
				totallen--;
				opt++;
			}
			/* Remaining as ipp_ipv4_options */
			goto copyall;
		}
		totallen -= optlen;
		opt += optlen;
	}
	/* No CIPSO found; return everything as ipp_ipv4_options */
	totallen = ipha->ipha_version_and_hdr_length -
	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
	totallen <<= 2;
	opt = (uchar_t *)&ipha[1];
	goto copyall;
}

/*
 * Efficient versions of lookup for an IRE when we only
 * match the address.
 * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
 * Does not handle multicast addresses.
 */
uint_t
ip_type_v4(ipaddr_t addr, ip_stack_t *ipst)
{
	ire_t *ire;
	uint_t result;

	ire = ire_ftable_lookup_simple_v4(addr, 0, ipst, NULL);
	ASSERT(ire != NULL);
	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
		result = IRE_NOROUTE;
	else
		result = ire->ire_type;
	ire_refrele(ire);
	return (result);
}

/*
 * Efficient versions of lookup for an IRE when we only
 * match the address.
 * For RTF_REJECT or BLACKHOLE we return IRE_NOROUTE.
 * Does not handle multicast addresses.
 */
uint_t
ip_type_v6(const in6_addr_t *addr, ip_stack_t *ipst)
{
	ire_t *ire;
	uint_t result;

	ire = ire_ftable_lookup_simple_v6(addr, 0, ipst, NULL);
	ASSERT(ire != NULL);
	if (ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE))
		result = IRE_NOROUTE;
	else
		result = ire->ire_type;
	ire_refrele(ire);
	return (result);
}

/*
 * Nobody should be sending
 * packets up this stream
 */
static int
ip_lrput(queue_t *q, mblk_t *mp)
{
	switch (mp->b_datap->db_type) {
	case M_FLUSH:
		/* Turn around */
		if (*mp->b_rptr & FLUSHW) {
			*mp->b_rptr &= ~FLUSHR;
			qreply(q, mp);
			return (0);
		}
		break;
	}
	freemsg(mp);
	return (0);
}

/* Nobody should be sending packets down this stream */
/* ARGSUSED */
int
ip_lwput(queue_t *q, mblk_t *mp)
{
	freemsg(mp);
	return (0);
}

/*
 * Move the first hop in any source route to ipha_dst and remove that part of
 * the source route.  Called by other protocols.  Errors in option formatting
 * are ignored - will be handled by ip_output_options. Return the final
 * destination (either ipha_dst or the last entry in a source route.)
 */
ipaddr_t
ip_massage_options(ipha_t *ipha, netstack_t *ns)
{
	ipoptp_t	opts;
	uchar_t		*opt;
	uint8_t		optval;
	uint8_t		optlen;
	ipaddr_t	dst;
	int		i;
	ip_stack_t	*ipst = ns->netstack_ip;

	ip2dbg(("ip_massage_options\n"));
	dst = ipha->ipha_dst;
	for (optval = ipoptp_first(&opts, ipha);
	    optval != IPOPT_EOL;
	    optval = ipoptp_next(&opts)) {
		opt = opts.ipoptp_cur;
		switch (optval) {
			uint8_t off;
		case IPOPT_SSRR:
		case IPOPT_LSRR:
			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
				ip1dbg(("ip_massage_options: bad src route\n"));
				break;
			}
			optlen = opts.ipoptp_len;
			off = opt[IPOPT_OFFSET];
			off--;
		redo_srr:
			if (optlen < IP_ADDR_LEN ||
			    off > optlen - IP_ADDR_LEN) {
				/* End of source route */
				ip1dbg(("ip_massage_options: end of SR\n"));
				break;
			}
			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
			ip1dbg(("ip_massage_options: next hop 0x%x\n",
			    ntohl(dst)));
			/*
			 * Check if our address is present more than
			 * once as consecutive hops in source route.
			 * XXX verify per-interface ip_forwarding
			 * for source route?
			 */
			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
				off += IP_ADDR_LEN;
				goto redo_srr;
			}
			if (dst == htonl(INADDR_LOOPBACK)) {
				ip1dbg(("ip_massage_options: loopback addr in "
				    "source route!\n"));
				break;
			}
			/*
			 * Update ipha_dst to be the first hop and remove the
			 * first hop from the source route (by overwriting
			 * part of the option with NOP options).
			 */
			ipha->ipha_dst = dst;
			/* Put the last entry in dst */
			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
			    3;
			bcopy(&opt[off], &dst, IP_ADDR_LEN);

			ip1dbg(("ip_massage_options: last hop 0x%x\n",
			    ntohl(dst)));
			/* Move down and overwrite */
			opt[IP_ADDR_LEN] = opt[0];
			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
			for (i = 0; i < IP_ADDR_LEN; i++)
				opt[i] = IPOPT_NOP;
			break;
		}
	}
	return (dst);
}

/*
 * Return the network mask
 * associated with the specified address.
 */
ipaddr_t
ip_net_mask(ipaddr_t addr)
{
	uchar_t	*up = (uchar_t *)&addr;
	ipaddr_t mask = 0;
	uchar_t	*maskp = (uchar_t *)&mask;

#if defined(__x86)
#define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
#endif
#ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
#endif
	if (CLASSD(addr)) {
		maskp[0] = 0xF0;
		return (mask);
	}

	/* We assume Class E default netmask to be 32 */
	if (CLASSE(addr))
		return (0xffffffffU);

	if (addr == 0)
		return (0);
	maskp[0] = 0xFF;
	if ((up[0] & 0x80) == 0)
		return (mask);

	maskp[1] = 0xFF;
	if ((up[0] & 0xC0) == 0x80)
		return (mask);

	maskp[2] = 0xFF;
	if ((up[0] & 0xE0) == 0xC0)
		return (mask);

	/* Otherwise return no mask */
	return ((ipaddr_t)0);
}

/* Name/Value Table Lookup Routine */
char *
ip_nv_lookup(nv_t *nv, int value)
{
	if (!nv)
		return (NULL);
	for (; nv->nv_name; nv++) {
		if (nv->nv_value == value)
			return (nv->nv_name);
	}
	return ("unknown");
}

static int
ip_wait_for_info_ack(ill_t *ill)
{
	int err;

	mutex_enter(&ill->ill_lock);
	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
		/*
		 * Return value of 0 indicates a pending signal.
		 */
		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
		if (err == 0) {
			mutex_exit(&ill->ill_lock);
			return (EINTR);
		}
	}
	mutex_exit(&ill->ill_lock);
	/*
	 * ip_rput_other could have set an error  in ill_error on
	 * receipt of M_ERROR.
	 */
	return (ill->ill_error);
}

/*
 * This is a module open, i.e. this is a control stream for access
 * to a DLPI device.  We allocate an ill_t as the instance data in
 * this case.
 */
static int
ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
{
	ill_t	*ill;
	int	err;
	zoneid_t zoneid;
	netstack_t *ns;
	ip_stack_t *ipst;

	/*
	 * Prevent unprivileged processes from pushing IP so that
	 * they can't send raw IP.
	 */
	if (secpolicy_net_rawaccess(credp) != 0)
		return (EPERM);

	ns = netstack_find_by_cred(credp);
	ASSERT(ns != NULL);
	ipst = ns->netstack_ip;
	ASSERT(ipst != NULL);

	/*
	 * For exclusive stacks we set the zoneid to zero
	 * to make IP operate as if in the global zone.
	 */
	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
		zoneid = GLOBAL_ZONEID;
	else
		zoneid = crgetzoneid(credp);

	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
	q->q_ptr = WR(q)->q_ptr = ill;
	ill->ill_ipst = ipst;
	ill->ill_zoneid = zoneid;

	/*
	 * ill_init initializes the ill fields and then sends down
	 * down a DL_INFO_REQ after calling qprocson.
	 */
	err = ill_init(q, ill);

	if (err != 0) {
		mi_free(ill);
		netstack_rele(ipst->ips_netstack);
		q->q_ptr = NULL;
		WR(q)->q_ptr = NULL;
		return (err);
	}

	/*
	 * Wait for the DL_INFO_ACK if a DL_INFO_REQ was sent.
	 *
	 * ill_init initializes the ipsq marking this thread as
	 * writer
	 */
	ipsq_exit(ill->ill_phyint->phyint_ipsq);
	err = ip_wait_for_info_ack(ill);
	if (err == 0)
		ill->ill_credp = credp;
	else
		goto fail;

	crhold(credp);

	mutex_enter(&ipst->ips_ip_mi_lock);
	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)q->q_ptr, devp, flag,
	    sflag, credp);
	mutex_exit(&ipst->ips_ip_mi_lock);
fail:
	if (err) {
		(void) ip_close(q, 0, credp);
		return (err);
	}
	return (0);
}

/* For /dev/ip aka AF_INET open */
int
ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
{
	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
}

/* For /dev/ip6 aka AF_INET6 open */
int
ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
{
	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
}

/* IP open routine. */
int
ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
    boolean_t isv6)
{
	conn_t		*connp;
	major_t		maj;
	zoneid_t	zoneid;
	netstack_t	*ns;
	ip_stack_t	*ipst;

	/* Allow reopen. */
	if (q->q_ptr != NULL)
		return (0);

	if (sflag & MODOPEN) {
		/* This is a module open */
		return (ip_modopen(q, devp, flag, sflag, credp));
	}

	if ((flag & ~(FKLYR)) == IP_HELPER_STR) {
		/*
		 * Non streams based socket looking for a stream
		 * to access IP
		 */
		return (ip_helper_stream_setup(q, devp, flag, sflag,
		    credp, isv6));
	}

	ns = netstack_find_by_cred(credp);
	ASSERT(ns != NULL);
	ipst = ns->netstack_ip;
	ASSERT(ipst != NULL);

	/*
	 * For exclusive stacks we set the zoneid to zero
	 * to make IP operate as if in the global zone.
	 */
	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
		zoneid = GLOBAL_ZONEID;
	else
		zoneid = crgetzoneid(credp);

	/*
	 * We are opening as a device. This is an IP client stream, and we
	 * allocate an conn_t as the instance data.
	 */
	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);

	/*
	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
	 * done by netstack_find_by_cred()
	 */
	netstack_rele(ipst->ips_netstack);

	connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP | IXAF_SET_ULP_CKSUM;
	/* conn_allzones can not be set this early, hence no IPCL_ZONEID */
	connp->conn_ixa->ixa_zoneid = zoneid;
	connp->conn_zoneid = zoneid;

	connp->conn_rq = q;
	q->q_ptr = WR(q)->q_ptr = connp;

	/* Minor tells us which /dev entry was opened */
	if (isv6) {
		connp->conn_family = AF_INET6;
		connp->conn_ipversion = IPV6_VERSION;
		connp->conn_ixa->ixa_flags &= ~IXAF_IS_IPV4;
		connp->conn_ixa->ixa_src_preferences = IPV6_PREFER_SRC_DEFAULT;
	} else {
		connp->conn_family = AF_INET;
		connp->conn_ipversion = IPV4_VERSION;
		connp->conn_ixa->ixa_flags |= IXAF_IS_IPV4;
	}

	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
		connp->conn_minor_arena = ip_minor_arena_la;
	} else {
		/*
		 * Either minor numbers in the large arena were exhausted
		 * or a non socket application is doing the open.
		 * Try to allocate from the small arena.
		 */
		if ((connp->conn_dev =
		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
			/* CONN_DEC_REF takes care of netstack_rele() */
			q->q_ptr = WR(q)->q_ptr = NULL;
			CONN_DEC_REF(connp);
			return (EBUSY);
		}
		connp->conn_minor_arena = ip_minor_arena_sa;
	}

	maj = getemajor(*devp);
	*devp = makedevice(maj, (minor_t)connp->conn_dev);

	/*
	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
	 */
	connp->conn_cred = credp;
	connp->conn_cpid = curproc->p_pid;
	/* Cache things in ixa without an extra refhold */
	ASSERT(!(connp->conn_ixa->ixa_free_flags & IXA_FREE_CRED));
	connp->conn_ixa->ixa_cred = connp->conn_cred;
	connp->conn_ixa->ixa_cpid = connp->conn_cpid;
	if (is_system_labeled())
		connp->conn_ixa->ixa_tsl = crgetlabel(connp->conn_cred);

	/*
	 * Handle IP_IOC_RTS_REQUEST and other ioctls which use conn_recv
	 */
	connp->conn_recv = ip_conn_input;
	connp->conn_recvicmp = ip_conn_input_icmp;

	crhold(connp->conn_cred);

	/*
	 * If the caller has the process-wide flag set, then default to MAC
	 * exempt mode.  This allows read-down to unlabeled hosts.
	 */
	if (getpflags(NET_MAC_AWARE, credp) != 0)
		connp->conn_mac_mode = CONN_MAC_AWARE;

	connp->conn_zone_is_global = (crgetzoneid(credp) == GLOBAL_ZONEID);

	connp->conn_rq = q;
	connp->conn_wq = WR(q);

	/* Non-zero default values */
	connp->conn_ixa->ixa_flags |= IXAF_MULTICAST_LOOP;

	/*
	 * Make the conn globally visible to walkers
	 */
	ASSERT(connp->conn_ref == 1);
	mutex_enter(&connp->conn_lock);
	connp->conn_state_flags &= ~CONN_INCIPIENT;
	mutex_exit(&connp->conn_lock);

	qprocson(q);

	return (0);
}

/*
 * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
 * all of them are copied to the conn_t. If the req is "zero", the policy is
 * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
 * fields.
 * We keep only the latest setting of the policy and thus policy setting
 * is not incremental/cumulative.
 *
 * Requests to set policies with multiple alternative actions will
 * go through a different API.
 */
int
ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
{
	uint_t ah_req = 0;
	uint_t esp_req = 0;
	uint_t se_req = 0;
	ipsec_act_t *actp = NULL;
	uint_t nact;
	ipsec_policy_head_t *ph;
	boolean_t is_pol_reset, is_pol_inserted = B_FALSE;
	int error = 0;
	netstack_t	*ns = connp->conn_netstack;
	ip_stack_t	*ipst = ns->netstack_ip;
	ipsec_stack_t	*ipss = ns->netstack_ipsec;

#define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)

	/*
	 * The IP_SEC_OPT option does not allow variable length parameters,
	 * hence a request cannot be NULL.
	 */
	if (req == NULL)
		return (EINVAL);

	ah_req = req->ipsr_ah_req;
	esp_req = req->ipsr_esp_req;
	se_req = req->ipsr_self_encap_req;

	/* Don't allow setting self-encap without one or more of AH/ESP. */
	if (se_req != 0 && esp_req == 0 && ah_req == 0)
		return (EINVAL);

	/*
	 * Are we dealing with a request to reset the policy (i.e.
	 * zero requests).
	 */
	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
	    (esp_req & REQ_MASK) == 0 &&
	    (se_req & REQ_MASK) == 0);

	if (!is_pol_reset) {
		/*
		 * If we couldn't load IPsec, fail with "protocol
		 * not supported".
		 * IPsec may not have been loaded for a request with zero
		 * policies, so we don't fail in this case.
		 */
		mutex_enter(&ipss->ipsec_loader_lock);
		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
			mutex_exit(&ipss->ipsec_loader_lock);
			return (EPROTONOSUPPORT);
		}
		mutex_exit(&ipss->ipsec_loader_lock);

		/*
		 * Test for valid requests. Invalid algorithms
		 * need to be tested by IPsec code because new
		 * algorithms can be added dynamically.
		 */
		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
			return (EINVAL);
		}

		/*
		 * Only privileged users can issue these
		 * requests.
		 */
		if (((ah_req & IPSEC_PREF_NEVER) ||
		    (esp_req & IPSEC_PREF_NEVER) ||
		    (se_req & IPSEC_PREF_NEVER)) &&
		    secpolicy_ip_config(cr, B_FALSE) != 0) {
			return (EPERM);
		}

		/*
		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
		 * are mutually exclusive.
		 */
		if (((ah_req & REQ_MASK) == REQ_MASK) ||
		    ((esp_req & REQ_MASK) == REQ_MASK) ||
		    ((se_req & REQ_MASK) == REQ_MASK)) {
			/* Both of them are set */
			return (EINVAL);
		}
	}

	ASSERT(MUTEX_HELD(&connp->conn_lock));

	/*
	 * If we have already cached policies in conn_connect(), don't
	 * let them change now. We cache policies for connections
	 * whose src,dst [addr, port] is known.
	 */
	if (connp->conn_policy_cached) {
		return (EINVAL);
	}

	/*
	 * We have a zero policies, reset the connection policy if already
	 * set. This will cause the connection to inherit the
	 * global policy, if any.
	 */
	if (is_pol_reset) {
		if (connp->conn_policy != NULL) {
			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
			connp->conn_policy = NULL;
		}
		connp->conn_in_enforce_policy = B_FALSE;
		connp->conn_out_enforce_policy = B_FALSE;
		return (0);
	}

	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
	    ipst->ips_netstack);
	if (ph == NULL)
		goto enomem;

	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
	if (actp == NULL)
		goto enomem;

	/*
	 * Always insert IPv4 policy entries, since they can also apply to
	 * ipv6 sockets being used in ipv4-compat mode.
	 */
	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
	    IPSEC_TYPE_INBOUND, ns))
		goto enomem;
	is_pol_inserted = B_TRUE;
	if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V4,
	    IPSEC_TYPE_OUTBOUND, ns))
		goto enomem;

	/*
	 * We're looking at a v6 socket, also insert the v6-specific
	 * entries.
	 */
	if (connp->conn_family == AF_INET6) {
		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
		    IPSEC_TYPE_INBOUND, ns))
			goto enomem;
		if (!ipsec_polhead_insert(ph, actp, nact, IPSEC_AF_V6,
		    IPSEC_TYPE_OUTBOUND, ns))
			goto enomem;
	}

	ipsec_actvec_free(actp, nact);

	/*
	 * If the requests need security, set enforce_policy.
	 * If the requests are IPSEC_PREF_NEVER, one should
	 * still set conn_out_enforce_policy so that ip_set_destination
	 * marks the ip_xmit_attr_t appropriatly. This is needed so that
	 * for connections that we don't cache policy in at connect time,
	 * if global policy matches in ip_output_attach_policy, we
	 * don't wrongly inherit global policy. Similarly, we need
	 * to set conn_in_enforce_policy also so that we don't verify
	 * policy wrongly.
	 */
	if ((ah_req & REQ_MASK) != 0 ||
	    (esp_req & REQ_MASK) != 0 ||
	    (se_req & REQ_MASK) != 0) {
		connp->conn_in_enforce_policy = B_TRUE;
		connp->conn_out_enforce_policy = B_TRUE;
	}

	return (error);
#undef REQ_MASK

	/*
	 * Common memory-allocation-failure exit path.
	 */
enomem:
	if (actp != NULL)
		ipsec_actvec_free(actp, nact);
	if (is_pol_inserted)
		ipsec_polhead_flush(ph, ns);
	return (ENOMEM);
}

/*
 * Set socket options for joining and leaving multicast groups.
 * Common to IPv4 and IPv6; inet6 indicates the type of socket.
 * The caller has already check that the option name is consistent with
 * the address family of the socket.
 */
int
ip_opt_set_multicast_group(conn_t *connp, t_scalar_t name,
    uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
{
	int		*i1 = (int *)invalp;
	int		error = 0;
	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
	struct ip_mreq	*v4_mreqp;
	struct ipv6_mreq *v6_mreqp;
	struct group_req *greqp;
	ire_t *ire;
	boolean_t done = B_FALSE;
	ipaddr_t ifaddr;
	in6_addr_t v6group;
	uint_t ifindex;
	boolean_t mcast_opt = B_TRUE;
	mcast_record_t fmode;
	int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
	    ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);

	switch (name) {
	case IP_ADD_MEMBERSHIP:
	case IPV6_JOIN_GROUP:
		mcast_opt = B_FALSE;
		/* FALLTHROUGH */
	case MCAST_JOIN_GROUP:
		fmode = MODE_IS_EXCLUDE;
		optfn = ip_opt_add_group;
		break;

	case IP_DROP_MEMBERSHIP:
	case IPV6_LEAVE_GROUP:
		mcast_opt = B_FALSE;
		/* FALLTHROUGH */
	case MCAST_LEAVE_GROUP:
		fmode = MODE_IS_INCLUDE;
		optfn = ip_opt_delete_group;
		break;
	default:
		/* Should not be reached. */
		fmode = MODE_IS_INCLUDE;
		optfn = NULL;
		ASSERT(0);
	}

	if (mcast_opt) {
		struct sockaddr_in *sin;
		struct sockaddr_in6 *sin6;

		greqp = (struct group_req *)i1;
		if (greqp->gr_group.ss_family == AF_INET) {
			sin = (struct sockaddr_in *)&(greqp->gr_group);
			IN6_INADDR_TO_V4MAPPED(&sin->sin_addr, &v6group);
		} else {
			if (!inet6)
				return (EINVAL);	/* Not on INET socket */

			sin6 = (struct sockaddr_in6 *)&(greqp->gr_group);
			v6group = sin6->sin6_addr;
		}
		ifaddr = INADDR_ANY;
		ifindex = greqp->gr_interface;
	} else if (inet6) {
		v6_mreqp = (struct ipv6_mreq *)i1;
		v6group = v6_mreqp->ipv6mr_multiaddr;
		ifaddr = INADDR_ANY;
		ifindex = v6_mreqp->ipv6mr_interface;
	} else {
		v4_mreqp = (struct ip_mreq *)i1;
		IN6_INADDR_TO_V4MAPPED(&v4_mreqp->imr_multiaddr, &v6group);
		ifaddr = (ipaddr_t)v4_mreqp->imr_interface.s_addr;
		ifindex = 0;
	}

	/*
	 * In the multirouting case, we need to replicate
	 * the request on all interfaces that will take part
	 * in replication.  We do so because multirouting is
	 * reflective, thus we will probably receive multi-
	 * casts on those interfaces.
	 * The ip_multirt_apply_membership() succeeds if
	 * the operation succeeds on at least one interface.
	 */
	if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
		ipaddr_t group;

		IN6_V4MAPPED_TO_IPADDR(&v6group, group);

		ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
	} else {
		ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
	}
	if (ire != NULL) {
		if (ire->ire_flags & RTF_MULTIRT) {
			error = ip_multirt_apply_membership(optfn, ire, connp,
			    checkonly, &v6group, fmode, &ipv6_all_zeros);
			done = B_TRUE;
		}
		ire_refrele(ire);
	}

	if (!done) {
		error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
		    fmode, &ipv6_all_zeros);
	}
	return (error);
}

/*
 * Set socket options for joining and leaving multicast groups
 * for specific sources.
 * Common to IPv4 and IPv6; inet6 indicates the type of socket.
 * The caller has already check that the option name is consistent with
 * the address family of the socket.
 */
int
ip_opt_set_multicast_sources(conn_t *connp, t_scalar_t name,
    uchar_t *invalp, boolean_t inet6, boolean_t checkonly)
{
	int		*i1 = (int *)invalp;
	int		error = 0;
	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
	struct ip_mreq_source *imreqp;
	struct group_source_req *gsreqp;
	in6_addr_t v6group, v6src;
	uint32_t ifindex;
	ipaddr_t ifaddr;
	boolean_t mcast_opt = B_TRUE;
	mcast_record_t fmode;
	ire_t *ire;
	boolean_t done = B_FALSE;
	int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
	    ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *);

	switch (name) {
	case IP_BLOCK_SOURCE:
		mcast_opt = B_FALSE;
		/* FALLTHROUGH */
	case MCAST_BLOCK_SOURCE:
		fmode = MODE_IS_EXCLUDE;
		optfn = ip_opt_add_group;
		break;

	case IP_UNBLOCK_SOURCE:
		mcast_opt = B_FALSE;
		/* FALLTHROUGH */
	case MCAST_UNBLOCK_SOURCE:
		fmode = MODE_IS_EXCLUDE;
		optfn = ip_opt_delete_group;
		break;

	case IP_ADD_SOURCE_MEMBERSHIP:
		mcast_opt = B_FALSE;
		/* FALLTHROUGH */
	case MCAST_JOIN_SOURCE_GROUP:
		fmode = MODE_IS_INCLUDE;
		optfn = ip_opt_add_group;
		break;

	case IP_DROP_SOURCE_MEMBERSHIP:
		mcast_opt = B_FALSE;
		/* FALLTHROUGH */
	case MCAST_LEAVE_SOURCE_GROUP:
		fmode = MODE_IS_INCLUDE;
		optfn = ip_opt_delete_group;
		break;
	default:
		/* Should not be reached. */
		optfn = NULL;
		fmode = 0;
		ASSERT(0);
	}

	if (mcast_opt) {
		gsreqp = (struct group_source_req *)i1;
		ifindex = gsreqp->gsr_interface;
		if (gsreqp->gsr_group.ss_family == AF_INET) {
			struct sockaddr_in *s;
			s = (struct sockaddr_in *)&gsreqp->gsr_group;
			IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6group);
			s = (struct sockaddr_in *)&gsreqp->gsr_source;
			IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
		} else {
			struct sockaddr_in6 *s6;

			if (!inet6)
				return (EINVAL);	/* Not on INET socket */

			s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
			v6group = s6->sin6_addr;
			s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
			v6src = s6->sin6_addr;
		}
		ifaddr = INADDR_ANY;
	} else {
		imreqp = (struct ip_mreq_source *)i1;
		IN6_INADDR_TO_V4MAPPED(&imreqp->imr_multiaddr, &v6group);
		IN6_INADDR_TO_V4MAPPED(&imreqp->imr_sourceaddr, &v6src);
		ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
		ifindex = 0;
	}

	/*
	 * Handle src being mapped INADDR_ANY by changing it to unspecified.
	 */
	if (IN6_IS_ADDR_V4MAPPED_ANY(&v6src))
		v6src = ipv6_all_zeros;

	/*
	 * In the multirouting case, we need to replicate
	 * the request as noted in the mcast cases above.
	 */
	if (IN6_IS_ADDR_V4MAPPED(&v6group)) {
		ipaddr_t group;

		IN6_V4MAPPED_TO_IPADDR(&v6group, group);

		ire = ire_ftable_lookup_v4(group, IP_HOST_MASK, 0,
		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
	} else {
		ire = ire_ftable_lookup_v6(&v6group, &ipv6_all_ones, 0,
		    IRE_HOST | IRE_INTERFACE, NULL, ALL_ZONES, NULL,
		    MATCH_IRE_MASK | MATCH_IRE_TYPE, 0, ipst, NULL);
	}
	if (ire != NULL) {
		if (ire->ire_flags & RTF_MULTIRT) {
			error = ip_multirt_apply_membership(optfn, ire, connp,
			    checkonly, &v6group, fmode, &v6src);
			done = B_TRUE;
		}
		ire_refrele(ire);
	}
	if (!done) {
		error = optfn(connp, checkonly, &v6group, ifaddr, ifindex,
		    fmode, &v6src);
	}
	return (error);
}

/*
 * Given a destination address and a pointer to where to put the information
 * this routine fills in the mtuinfo.
 * The socket must be connected.
 * For sctp conn_faddr is the primary address.
 */
int
ip_fill_mtuinfo(conn_t *connp, ip_xmit_attr_t *ixa, struct ip6_mtuinfo *mtuinfo)
{
	uint32_t	pmtu = IP_MAXPACKET;
	uint_t		scopeid;

	if (IN6_IS_ADDR_UNSPECIFIED(&connp->conn_faddr_v6))
		return (-1);

	/* In case we never sent or called ip_set_destination_v4/v6 */
	if (ixa->ixa_ire != NULL)
		pmtu = ip_get_pmtu(ixa);

	if (ixa->ixa_flags & IXAF_SCOPEID_SET)
		scopeid = ixa->ixa_scopeid;
	else
		scopeid = 0;

	bzero(mtuinfo, sizeof (*mtuinfo));
	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
	mtuinfo->ip6m_addr.sin6_port = connp->conn_fport;
	mtuinfo->ip6m_addr.sin6_addr = connp->conn_faddr_v6;
	mtuinfo->ip6m_addr.sin6_scope_id = scopeid;
	mtuinfo->ip6m_mtu = pmtu;

	return (sizeof (struct ip6_mtuinfo));
}

/*
 * When the src multihoming is changed from weak to [strong, preferred]
 * ip_ire_rebind_walker is called to walk the list of all ire_t entries
 * and identify routes that were created by user-applications in the
 * unbound state (i.e., without RTA_IFP), and for which an ire_ill is not
 * currently defined. These routes are then 'rebound', i.e., their ire_ill
 * is selected by finding an interface route for the gateway.
 */
/* ARGSUSED */
void
ip_ire_rebind_walker(ire_t *ire, void *notused)
{
	if (!ire->ire_unbound || ire->ire_ill != NULL)
		return;
	ire_rebind(ire);
	ire_delete(ire);
}

/*
 * When the src multihoming is changed from  [strong, preferred] to weak,
 * ip_ire_unbind_walker is called to walk the list of all ire_t entries, and
 * set any entries that were created by user-applications in the unbound state
 * (i.e., without RTA_IFP) back to having a NULL ire_ill.
 */
/* ARGSUSED */
void
ip_ire_unbind_walker(ire_t *ire, void *notused)
{
	ire_t *new_ire;

	if (!ire->ire_unbound || ire->ire_ill == NULL)
		return;
	if (ire->ire_ipversion == IPV6_VERSION) {
		new_ire = ire_create_v6(&ire->ire_addr_v6, &ire->ire_mask_v6,
		    &ire->ire_gateway_addr_v6, ire->ire_type, NULL,
		    ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
	} else {
		new_ire = ire_create((uchar_t *)&ire->ire_addr,
		    (uchar_t *)&ire->ire_mask,
		    (uchar_t *)&ire->ire_gateway_addr, ire->ire_type, NULL,
		    ire->ire_zoneid, ire->ire_flags, NULL, ire->ire_ipst);
	}
	if (new_ire == NULL)
		return;
	new_ire->ire_unbound = B_TRUE;
	/*
	 * The bound ire must first be deleted so that we don't return
	 * the existing one on the attempt to add the unbound new_ire.
	 */
	ire_delete(ire);
	new_ire = ire_add(new_ire);
	if (new_ire != NULL)
		ire_refrele(new_ire);
}

/*
 * When the settings of ip*_strict_src_multihoming tunables are changed,
 * all cached routes need to be recomputed. This recomputation needs to be
 * done when going from weaker to stronger modes so that the cached ire
 * for the connection does not violate the current ip*_strict_src_multihoming
 * setting. It also needs to be done when going from stronger to weaker modes,
 * so that we fall back to matching on the longest-matching-route (as opposed
 * to a shorter match that may have been selected in the strong mode
 * to satisfy src_multihoming settings).
 *
 * The cached ixa_ire entires for all conn_t entries are marked as
 * "verify" so that they will be recomputed for the next packet.
 */
void
conn_ire_revalidate(conn_t *connp, void *arg)
{
	boolean_t isv6 = (boolean_t)arg;

	if ((isv6 && connp->conn_ipversion != IPV6_VERSION) ||
	    (!isv6 && connp->conn_ipversion != IPV4_VERSION))
		return;
	connp->conn_ixa->ixa_ire_generation = IRE_GENERATION_VERIFY;
}

/*
 * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
 * When an ipf is passed here for the first time, if
 * we already have in-order fragments on the queue, we convert from the fast-
 * path reassembly scheme to the hard-case scheme.  From then on, additional
 * fragments are reassembled here.  We keep track of the start and end offsets
 * of each piece, and the number of holes in the chain.  When the hole count
 * goes to zero, we are done!
 *
 * The ipf_count will be updated to account for any mblk(s) added (pointed to
 * by mp) or subtracted (freeb()ed dups), upon return the caller must update
 * ipfb_count and ill_frag_count by the difference of ipf_count before and
 * after the call to ip_reassemble().
 */
int
ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
    size_t msg_len)
{
	uint_t	end;
	mblk_t	*next_mp;
	mblk_t	*mp1;
	uint_t	offset;
	boolean_t incr_dups = B_TRUE;
	boolean_t offset_zero_seen = B_FALSE;
	boolean_t pkt_boundary_checked = B_FALSE;

	/* If start == 0 then ipf_nf_hdr_len has to be set. */
	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);

	/* Add in byte count */
	ipf->ipf_count += msg_len;
	if (ipf->ipf_end) {
		/*
		 * We were part way through in-order reassembly, but now there
		 * is a hole.  We walk through messages already queued, and
		 * mark them for hard case reassembly.  We know that up till
		 * now they were in order starting from offset zero.
		 */
		offset = 0;
		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
			IP_REASS_SET_START(mp1, offset);
			if (offset == 0) {
				ASSERT(ipf->ipf_nf_hdr_len != 0);
				offset = -ipf->ipf_nf_hdr_len;
			}
			offset += mp1->b_wptr - mp1->b_rptr;
			IP_REASS_SET_END(mp1, offset);
		}
		/* One hole at the end. */
		ipf->ipf_hole_cnt = 1;
		/* Brand it as a hard case, forever. */
		ipf->ipf_end = 0;
	}
	/* Walk through all the new pieces. */
	do {
		end = start + (mp->b_wptr - mp->b_rptr);
		/*
		 * If start is 0, decrease 'end' only for the first mblk of
		 * the fragment. Otherwise 'end' can get wrong value in the
		 * second pass of the loop if first mblk is exactly the
		 * size of ipf_nf_hdr_len.
		 */
		if (start == 0 && !offset_zero_seen) {
			/* First segment */
			ASSERT(ipf->ipf_nf_hdr_len != 0);
			end -= ipf->ipf_nf_hdr_len;
			offset_zero_seen = B_TRUE;
		}
		next_mp = mp->b_cont;
		/*
		 * We are checking to see if there is any interesing data
		 * to process.  If there isn't and the mblk isn't the
		 * one which carries the unfragmentable header then we
		 * drop it.  It's possible to have just the unfragmentable
		 * header come through without any data.  That needs to be
		 * saved.
		 *
		 * If the assert at the top of this function holds then the
		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
		 * is infrequently traveled enough that the test is left in
		 * to protect against future code changes which break that
		 * invariant.
		 */
		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
			/* Empty.  Blast it. */
			IP_REASS_SET_START(mp, 0);
			IP_REASS_SET_END(mp, 0);
			/*
			 * If the ipf points to the mblk we are about to free,
			 * update ipf to point to the next mblk (or NULL
			 * if none).
			 */
			if (ipf->ipf_mp->b_cont == mp)
				ipf->ipf_mp->b_cont = next_mp;
			freeb(mp);
			continue;
		}
		mp->b_cont = NULL;
		IP_REASS_SET_START(mp, start);
		IP_REASS_SET_END(mp, end);
		if (!ipf->ipf_tail_mp) {
			ipf->ipf_tail_mp = mp;
			ipf->ipf_mp->b_cont = mp;
			if (start == 0 || !more) {
				ipf->ipf_hole_cnt = 1;
				/*
				 * if the first fragment comes in more than one
				 * mblk, this loop will be executed for each
				 * mblk. Need to adjust hole count so exiting
				 * this routine will leave hole count at 1.
				 */
				if (next_mp)
					ipf->ipf_hole_cnt++;
			} else
				ipf->ipf_hole_cnt = 2;
			continue;
		} else if (ipf->ipf_last_frag_seen && !more &&
		    !pkt_boundary_checked) {
			/*
			 * We check datagram boundary only if this fragment
			 * claims to be the last fragment and we have seen a
			 * last fragment in the past too. We do this only
			 * once for a given fragment.
			 *
			 * start cannot be 0 here as fragments with start=0
			 * and MF=0 gets handled as a complete packet. These
			 * fragments should not reach here.
			 */

			if (start + msgdsize(mp) !=
			    IP_REASS_END(ipf->ipf_tail_mp)) {
				/*
				 * We have two fragments both of which claim
				 * to be the last fragment but gives conflicting
				 * information about the whole datagram size.
				 * Something fishy is going on. Drop the
				 * fragment and free up the reassembly list.
				 */
				return (IP_REASS_FAILED);
			}

			/*
			 * We shouldn't come to this code block again for this
			 * particular fragment.
			 */
			pkt_boundary_checked = B_TRUE;
		}

		/* New stuff at or beyond tail? */
		offset = IP_REASS_END(ipf->ipf_tail_mp);
		if (start >= offset) {
			if (ipf->ipf_last_frag_seen) {
				/* current fragment is beyond last fragment */
				return (IP_REASS_FAILED);
			}
			/* Link it on end. */
			ipf->ipf_tail_mp->b_cont = mp;
			ipf->ipf_tail_mp = mp;
			if (more) {
				if (start != offset)
					ipf->ipf_hole_cnt++;
			} else if (start == offset && next_mp == NULL)
					ipf->ipf_hole_cnt--;
			continue;
		}
		mp1 = ipf->ipf_mp->b_cont;
		offset = IP_REASS_START(mp1);
		/* New stuff at the front? */
		if (start < offset) {
			if (start == 0) {
				if (end >= offset) {
					/* Nailed the hole at the begining. */
					ipf->ipf_hole_cnt--;
				}
			} else if (end < offset) {
				/*
				 * A hole, stuff, and a hole where there used
				 * to be just a hole.
				 */
				ipf->ipf_hole_cnt++;
			}
			mp->b_cont = mp1;
			/* Check for overlap. */
			while (end > offset) {
				if (end < IP_REASS_END(mp1)) {
					mp->b_wptr -= end - offset;
					IP_REASS_SET_END(mp, offset);
					BUMP_MIB(ill->ill_ip_mib,
					    ipIfStatsReasmPartDups);
					break;
				}
				/* Did we cover another hole? */
				if ((mp1->b_cont &&
				    IP_REASS_END(mp1) !=
				    IP_REASS_START(mp1->b_cont) &&
				    end >= IP_REASS_START(mp1->b_cont)) ||
				    (!ipf->ipf_last_frag_seen && !more)) {
					ipf->ipf_hole_cnt--;
				}
				/* Clip out mp1. */
				if ((mp->b_cont = mp1->b_cont) == NULL) {
					/*
					 * After clipping out mp1, this guy
					 * is now hanging off the end.
					 */
					ipf->ipf_tail_mp = mp;
				}
				IP_REASS_SET_START(mp1, 0);
				IP_REASS_SET_END(mp1, 0);
				/* Subtract byte count */
				ipf->ipf_count -= mp1->b_datap->db_lim -
				    mp1->b_datap->db_base;
				freeb(mp1);
				BUMP_MIB(ill->ill_ip_mib,
				    ipIfStatsReasmPartDups);
				mp1 = mp->b_cont;
				if (!mp1)
					break;
				offset = IP_REASS_START(mp1);
			}
			ipf->ipf_mp->b_cont = mp;
			continue;
		}
		/*
		 * The new piece starts somewhere between the start of the head
		 * and before the end of the tail.
		 */
		for (; mp1; mp1 = mp1->b_cont) {
			offset = IP_REASS_END(mp1);
			if (start < offset) {
				if (end <= offset) {
					/* Nothing new. */
					IP_REASS_SET_START(mp, 0);
					IP_REASS_SET_END(mp, 0);
					/* Subtract byte count */
					ipf->ipf_count -= mp->b_datap->db_lim -
					    mp->b_datap->db_base;
					if (incr_dups) {
						ipf->ipf_num_dups++;
						incr_dups = B_FALSE;
					}
					freeb(mp);
					BUMP_MIB(ill->ill_ip_mib,
					    ipIfStatsReasmDuplicates);
					break;
				}
				/*
				 * Trim redundant stuff off beginning of new
				 * piece.
				 */
				IP_REASS_SET_START(mp, offset);
				mp->b_rptr += offset - start;
				BUMP_MIB(ill->ill_ip_mib,
				    ipIfStatsReasmPartDups);
				start = offset;
				if (!mp1->b_cont) {
					/*
					 * After trimming, this guy is now
					 * hanging off the end.
					 */
					mp1->b_cont = mp;
					ipf->ipf_tail_mp = mp;
					if (!more) {
						ipf->ipf_hole_cnt--;
					}
					break;
				}
			}
			if (start >= IP_REASS_START(mp1->b_cont))
				continue;
			/* Fill a hole */
			if (start > offset)
				ipf->ipf_hole_cnt++;
			mp->b_cont = mp1->b_cont;
			mp1->b_cont = mp;
			mp1 = mp->b_cont;
			offset = IP_REASS_START(mp1);
			if (end >= offset) {
				ipf->ipf_hole_cnt--;
				/* Check for overlap. */
				while (end > offset) {
					if (end < IP_REASS_END(mp1)) {
						mp->b_wptr -= end - offset;
						IP_REASS_SET_END(mp, offset);
						/*
						 * TODO we might bump
						 * this up twice if there is
						 * overlap at both ends.
						 */
						BUMP_MIB(ill->ill_ip_mib,
						    ipIfStatsReasmPartDups);
						break;
					}
					/* Did we cover another hole? */
					if ((mp1->b_cont &&
					    IP_REASS_END(mp1)
					    != IP_REASS_START(mp1->b_cont) &&
					    end >=
					    IP_REASS_START(mp1->b_cont)) ||
					    (!ipf->ipf_last_frag_seen &&
					    !more)) {
						ipf->ipf_hole_cnt--;
					}
					/* Clip out mp1. */
					if ((mp->b_cont = mp1->b_cont) ==
					    NULL) {
						/*
						 * After clipping out mp1,
						 * this guy is now hanging
						 * off the end.
						 */
						ipf->ipf_tail_mp = mp;
					}
					IP_REASS_SET_START(mp1, 0);
					IP_REASS_SET_END(mp1, 0);
					/* Subtract byte count */
					ipf->ipf_count -=
					    mp1->b_datap->db_lim -
					    mp1->b_datap->db_base;
					freeb(mp1);
					BUMP_MIB(ill->ill_ip_mib,
					    ipIfStatsReasmPartDups);
					mp1 = mp->b_cont;
					if (!mp1)
						break;
					offset = IP_REASS_START(mp1);
				}
			}
			break;
		}
	} while (start = end, mp = next_mp);

	/* Fragment just processed could be the last one. Remember this fact */
	if (!more)
		ipf->ipf_last_frag_seen = B_TRUE;

	/* Still got holes? */
	if (ipf->ipf_hole_cnt)
		return (IP_REASS_PARTIAL);
	/* Clean up overloaded fields to avoid upstream disasters. */
	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
		IP_REASS_SET_START(mp1, 0);
		IP_REASS_SET_END(mp1, 0);
	}
	return (IP_REASS_COMPLETE);
}

/*
 * Fragmentation reassembly.  Each ILL has a hash table for
 * queuing packets undergoing reassembly for all IPIFs
 * associated with the ILL.  The hash is based on the packet
 * IP ident field.  The ILL frag hash table was allocated
 * as a timer block at the time the ILL was created.  Whenever
 * there is anything on the reassembly queue, the timer will
 * be running.  Returns the reassembled packet if reassembly completes.
 */
mblk_t *
ip_input_fragment(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
{
	uint32_t	frag_offset_flags;
	mblk_t		*t_mp;
	ipaddr_t	dst;
	uint8_t		proto = ipha->ipha_protocol;
	uint32_t	sum_val;
	uint16_t	sum_flags;
	ipf_t		*ipf;
	ipf_t		**ipfp;
	ipfb_t		*ipfb;
	uint16_t	ident;
	uint32_t	offset;
	ipaddr_t	src;
	uint_t		hdr_length;
	uint32_t	end;
	mblk_t		*mp1;
	mblk_t		*tail_mp;
	size_t		count;
	size_t		msg_len;
	uint8_t		ecn_info = 0;
	uint32_t	packet_size;
	boolean_t	pruned = B_FALSE;
	ill_t		*ill = ira->ira_ill;
	ip_stack_t	*ipst = ill->ill_ipst;

	/*
	 * Drop the fragmented as early as possible, if
	 * we don't have resource(s) to re-assemble.
	 */
	if (ipst->ips_ip_reass_queue_bytes == 0) {
		freemsg(mp);
		return (NULL);
	}

	/* Check for fragmentation offset; return if there's none */
	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
	    (IPH_MF | IPH_OFFSET)) == 0)
		return (mp);

	/*
	 * We utilize hardware computed checksum info only for UDP since
	 * IP fragmentation is a normal occurrence for the protocol.  In
	 * addition, checksum offload support for IP fragments carrying
	 * UDP payload is commonly implemented across network adapters.
	 */
	ASSERT(ira->ira_rill != NULL);
	if (proto == IPPROTO_UDP && dohwcksum &&
	    ILL_HCKSUM_CAPABLE(ira->ira_rill) &&
	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
		mblk_t *mp1 = mp->b_cont;
		int32_t len;

		/* Record checksum information from the packet */
		sum_val = (uint32_t)DB_CKSUM16(mp);
		sum_flags = DB_CKSUMFLAGS(mp);

		/* IP payload offset from beginning of mblk */
		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;

		if ((sum_flags & HCK_PARTIALCKSUM) &&
		    (mp1 == NULL || mp1->b_cont == NULL) &&
		    offset >= DB_CKSUMSTART(mp) &&
		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
			uint32_t adj;
			/*
			 * Partial checksum has been calculated by hardware
			 * and attached to the packet; in addition, any
			 * prepended extraneous data is even byte aligned.
			 * If any such data exists, we adjust the checksum;
			 * this would also handle any postpended data.
			 */
			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
			    mp, mp1, len, adj);

			/* One's complement subtract extraneous checksum */
			if (adj >= sum_val)
				sum_val = ~(adj - sum_val) & 0xFFFF;
			else
				sum_val -= adj;
		}
	} else {
		sum_val = 0;
		sum_flags = 0;
	}

	/* Clear hardware checksumming flag */
	DB_CKSUMFLAGS(mp) = 0;

	ident = ipha->ipha_ident;
	offset = (frag_offset_flags << 3) & 0xFFFF;
	src = ipha->ipha_src;
	dst = ipha->ipha_dst;
	hdr_length = IPH_HDR_LENGTH(ipha);
	end = ntohs(ipha->ipha_length) - hdr_length;

	/* If end == 0 then we have a packet with no data, so just free it */
	if (end == 0) {
		freemsg(mp);
		return (NULL);
	}

	/* Record the ECN field info. */
	ecn_info = (ipha->ipha_type_of_service & 0x3);
	if (offset != 0) {
		/*
		 * If this isn't the first piece, strip the header, and
		 * add the offset to the end value.
		 */
		mp->b_rptr += hdr_length;
		end += offset;
	}

	/* Handle vnic loopback of fragments */
	if (mp->b_datap->db_ref > 2)
		msg_len = 0;
	else
		msg_len = MBLKSIZE(mp);

	tail_mp = mp;
	while (tail_mp->b_cont != NULL) {
		tail_mp = tail_mp->b_cont;
		if (tail_mp->b_datap->db_ref <= 2)
			msg_len += MBLKSIZE(tail_mp);
	}

	/* If the reassembly list for this ILL will get too big, prune it */
	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
	    ipst->ips_ip_reass_queue_bytes) {
		DTRACE_PROBE3(ip_reass_queue_bytes, uint_t, msg_len,
		    uint_t, ill->ill_frag_count,
		    uint_t, ipst->ips_ip_reass_queue_bytes);
		ill_frag_prune(ill,
		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
		    (ipst->ips_ip_reass_queue_bytes - msg_len));
		pruned = B_TRUE;
	}

	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
	mutex_enter(&ipfb->ipfb_lock);

	ipfp = &ipfb->ipfb_ipf;
	/* Try to find an existing fragment queue for this packet. */
	for (;;) {
		ipf = ipfp[0];
		if (ipf != NULL) {
			/*
			 * It has to match on ident and src/dst address.
			 */
			if (ipf->ipf_ident == ident &&
			    ipf->ipf_src == src &&
			    ipf->ipf_dst == dst &&
			    ipf->ipf_protocol == proto) {
				/*
				 * If we have received too many
				 * duplicate fragments for this packet
				 * free it.
				 */
				if (ipf->ipf_num_dups > ip_max_frag_dups) {
					ill_frag_free_pkts(ill, ipfb, ipf, 1);
					freemsg(mp);
					mutex_exit(&ipfb->ipfb_lock);
					return (NULL);
				}
				/* Found it. */
				break;
			}
			ipfp = &ipf->ipf_hash_next;
			continue;
		}

		/*
		 * If we pruned the list, do we want to store this new
		 * fragment?. We apply an optimization here based on the
		 * fact that most fragments will be received in order.
		 * So if the offset of this incoming fragment is zero,
		 * it is the first fragment of a new packet. We will
		 * keep it.  Otherwise drop the fragment, as we have
		 * probably pruned the packet already (since the
		 * packet cannot be found).
		 */
		if (pruned && offset != 0) {
			mutex_exit(&ipfb->ipfb_lock);
			freemsg(mp);
			return (NULL);
		}

		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
			/*
			 * Too many fragmented packets in this hash
			 * bucket. Free the oldest.
			 */
			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
		}

		/* New guy.  Allocate a frag message. */
		mp1 = allocb(sizeof (*ipf), BPRI_MED);
		if (mp1 == NULL) {
			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
			ip_drop_input("ipIfStatsInDiscards", mp, ill);
			freemsg(mp);
reass_done:
			mutex_exit(&ipfb->ipfb_lock);
			return (NULL);
		}

		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
		mp1->b_cont = mp;

		/* Initialize the fragment header. */
		ipf = (ipf_t *)mp1->b_rptr;
		ipf->ipf_mp = mp1;
		ipf->ipf_ptphn = ipfp;
		ipfp[0] = ipf;
		ipf->ipf_hash_next = NULL;
		ipf->ipf_ident = ident;
		ipf->ipf_protocol = proto;
		ipf->ipf_src = src;
		ipf->ipf_dst = dst;
		ipf->ipf_nf_hdr_len = 0;
		/* Record reassembly start time. */
		ipf->ipf_timestamp = gethrestime_sec();
		/* Record ipf generation and account for frag header */
		ipf->ipf_gen = ill->ill_ipf_gen++;
		ipf->ipf_count = MBLKSIZE(mp1);
		ipf->ipf_last_frag_seen = B_FALSE;
		ipf->ipf_ecn = ecn_info;
		ipf->ipf_num_dups = 0;
		ipfb->ipfb_frag_pkts++;
		ipf->ipf_checksum = 0;
		ipf->ipf_checksum_flags = 0;

		/* Store checksum value in fragment header */
		if (sum_flags != 0) {
			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
			ipf->ipf_checksum = sum_val;
			ipf->ipf_checksum_flags = sum_flags;
		}

		/*
		 * We handle reassembly two ways.  In the easy case,
		 * where all the fragments show up in order, we do
		 * minimal bookkeeping, and just clip new pieces on
		 * the end.  If we ever see a hole, then we go off
		 * to ip_reassemble which has to mark the pieces and
		 * keep track of the number of holes, etc.  Obviously,
		 * the point of having both mechanisms is so we can
		 * handle the easy case as efficiently as possible.
		 */
		if (offset == 0) {
			/* Easy case, in-order reassembly so far. */
			ipf->ipf_count += msg_len;
			ipf->ipf_tail_mp = tail_mp;
			/*
			 * Keep track of next expected offset in
			 * ipf_end.
			 */
			ipf->ipf_end = end;
			ipf->ipf_nf_hdr_len = hdr_length;
		} else {
			/* Hard case, hole at the beginning. */
			ipf->ipf_tail_mp = NULL;
			/*
			 * ipf_end == 0 means that we have given up
			 * on easy reassembly.
			 */
			ipf->ipf_end = 0;

			/* Forget checksum offload from now on */
			ipf->ipf_checksum_flags = 0;

			/*
			 * ipf_hole_cnt is set by ip_reassemble.
			 * ipf_count is updated by ip_reassemble.
			 * No need to check for return value here
			 * as we don't expect reassembly to complete
			 * or fail for the first fragment itself.
			 */
			(void) ip_reassemble(mp, ipf,
			    (frag_offset_flags & IPH_OFFSET) << 3,
			    (frag_offset_flags & IPH_MF), ill, msg_len);
		}
		/* Update per ipfb and ill byte counts */
		ipfb->ipfb_count += ipf->ipf_count;
		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
		/* If the frag timer wasn't already going, start it. */
		mutex_enter(&ill->ill_lock);
		ill_frag_timer_start(ill);
		mutex_exit(&ill->ill_lock);
		goto reass_done;
	}

	/*
	 * If the packet's flag has changed (it could be coming up
	 * from an interface different than the previous, therefore
	 * possibly different checksum capability), then forget about
	 * any stored checksum states.  Otherwise add the value to
	 * the existing one stored in the fragment header.
	 */
	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
		sum_val += ipf->ipf_checksum;
		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
		ipf->ipf_checksum = sum_val;
	} else if (ipf->ipf_checksum_flags != 0) {
		/* Forget checksum offload from now on */
		ipf->ipf_checksum_flags = 0;
	}

	/*
	 * We have a new piece of a datagram which is already being
	 * reassembled.  Update the ECN info if all IP fragments
	 * are ECN capable.  If there is one which is not, clear
	 * all the info.  If there is at least one which has CE
	 * code point, IP needs to report that up to transport.
	 */
	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
		if (ecn_info == IPH_ECN_CE)
			ipf->ipf_ecn = IPH_ECN_CE;
	} else {
		ipf->ipf_ecn = IPH_ECN_NECT;
	}
	if (offset && ipf->ipf_end == offset) {
		/* The new fragment fits at the end */
		ipf->ipf_tail_mp->b_cont = mp;
		/* Update the byte count */
		ipf->ipf_count += msg_len;
		/* Update per ipfb and ill byte counts */
		ipfb->ipfb_count += msg_len;
		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
		atomic_add_32(&ill->ill_frag_count, msg_len);
		if (frag_offset_flags & IPH_MF) {
			/* More to come. */
			ipf->ipf_end = end;
			ipf->ipf_tail_mp = tail_mp;
			goto reass_done;
		}
	} else {
		/* Go do the hard cases. */
		int ret;

		if (offset == 0)
			ipf->ipf_nf_hdr_len = hdr_length;

		/* Save current byte count */
		count = ipf->ipf_count;
		ret = ip_reassemble(mp, ipf,
		    (frag_offset_flags & IPH_OFFSET) << 3,
		    (frag_offset_flags & IPH_MF), ill, msg_len);
		/* Count of bytes added and subtracted (freeb()ed) */
		count = ipf->ipf_count - count;
		if (count) {
			/* Update per ipfb and ill byte counts */
			ipfb->ipfb_count += count;
			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
			atomic_add_32(&ill->ill_frag_count, count);
		}
		if (ret == IP_REASS_PARTIAL) {
			goto reass_done;
		} else if (ret == IP_REASS_FAILED) {
			/* Reassembly failed. Free up all resources */
			ill_frag_free_pkts(ill, ipfb, ipf, 1);
			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
				IP_REASS_SET_START(t_mp, 0);
				IP_REASS_SET_END(t_mp, 0);
			}
			freemsg(mp);
			goto reass_done;
		}
		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
	}
	/*
	 * We have completed reassembly.  Unhook the frag header from
	 * the reassembly list.
	 *
	 * Before we free the frag header, record the ECN info
	 * to report back to the transport.
	 */
	ecn_info = ipf->ipf_ecn;
	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
	ipfp = ipf->ipf_ptphn;

	/* We need to supply these to caller */
	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
		sum_val = ipf->ipf_checksum;
	else
		sum_val = 0;

	mp1 = ipf->ipf_mp;
	count = ipf->ipf_count;
	ipf = ipf->ipf_hash_next;
	if (ipf != NULL)
		ipf->ipf_ptphn = ipfp;
	ipfp[0] = ipf;
	atomic_add_32(&ill->ill_frag_count, -count);
	ASSERT(ipfb->ipfb_count >= count);
	ipfb->ipfb_count -= count;
	ipfb->ipfb_frag_pkts--;
	mutex_exit(&ipfb->ipfb_lock);
	/* Ditch the frag header. */
	mp = mp1->b_cont;

	freeb(mp1);

	/* Restore original IP length in header. */
	packet_size = (uint32_t)msgdsize(mp);
	if (packet_size > IP_MAXPACKET) {
		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
		ip_drop_input("Reassembled packet too large", mp, ill);
		freemsg(mp);
		return (NULL);
	}

	if (DB_REF(mp) > 1) {
		mblk_t *mp2 = copymsg(mp);

		if (mp2 == NULL) {
			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
			ip_drop_input("ipIfStatsInDiscards", mp, ill);
			freemsg(mp);
			return (NULL);
		}
		freemsg(mp);
		mp = mp2;
	}
	ipha = (ipha_t *)mp->b_rptr;

	ipha->ipha_length = htons((uint16_t)packet_size);
	/* We're now complete, zip the frag state */
	ipha->ipha_fragment_offset_and_flags = 0;
	/* Record the ECN info. */
	ipha->ipha_type_of_service &= 0xFC;
	ipha->ipha_type_of_service |= ecn_info;

	/* Update the receive attributes */
	ira->ira_pktlen = packet_size;
	ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);

	/* Reassembly is successful; set checksum information in packet */
	DB_CKSUM16(mp) = (uint16_t)sum_val;
	DB_CKSUMFLAGS(mp) = sum_flags;
	DB_CKSUMSTART(mp) = ira->ira_ip_hdr_length;

	return (mp);
}

/*
 * Pullup function that should be used for IP input in order to
 * ensure we do not loose the L2 source address; we need the l2 source
 * address for IP_RECVSLLA and for ndp_input.
 *
 * We return either NULL or b_rptr.
 */
void *
ip_pullup(mblk_t *mp, ssize_t len, ip_recv_attr_t *ira)
{
	ill_t		*ill = ira->ira_ill;

	if (ip_rput_pullups++ == 0) {
		(void) mi_strlog(ill->ill_rq, 1, SL_ERROR|SL_TRACE,
		    "ip_pullup: %s forced us to "
		    " pullup pkt, hdr len %ld, hdr addr %p",
		    ill->ill_name, len, (void *)mp->b_rptr);
	}
	if (!(ira->ira_flags & IRAF_L2SRC_SET))
		ip_setl2src(mp, ira, ira->ira_rill);
	ASSERT(ira->ira_flags & IRAF_L2SRC_SET);
	if (!pullupmsg(mp, len))
		return (NULL);
	else
		return (mp->b_rptr);
}

/*
 * Make sure ira_l2src has an address. If we don't have one fill with zeros.
 * When called from the ULP ira_rill will be NULL hence the caller has to
 * pass in the ill.
 */
/* ARGSUSED */
void
ip_setl2src(mblk_t *mp, ip_recv_attr_t *ira, ill_t *ill)
{
	const uchar_t *addr;
	int alen;

	if (ira->ira_flags & IRAF_L2SRC_SET)
		return;

	ASSERT(ill != NULL);
	alen = ill->ill_phys_addr_length;
	ASSERT(alen <= sizeof (ira->ira_l2src));
	if (ira->ira_mhip != NULL &&
	    (addr = ira->ira_mhip->mhi_saddr) != NULL) {
		bcopy(addr, ira->ira_l2src, alen);
	} else if ((ira->ira_flags & IRAF_L2SRC_LOOPBACK) &&
	    (addr = ill->ill_phys_addr) != NULL) {
		bcopy(addr, ira->ira_l2src, alen);
	} else {
		bzero(ira->ira_l2src, alen);
	}
	ira->ira_flags |= IRAF_L2SRC_SET;
}

/*
 * check ip header length and align it.
 */
mblk_t *
ip_check_and_align_header(mblk_t *mp, uint_t min_size, ip_recv_attr_t *ira)
{
	ill_t	*ill = ira->ira_ill;
	ssize_t len;

	len = MBLKL(mp);

	if (!OK_32PTR(mp->b_rptr))
		IP_STAT(ill->ill_ipst, ip_notaligned);
	else
		IP_STAT(ill->ill_ipst, ip_recv_pullup);

	/* Guard against bogus device drivers */
	if (len < 0) {
		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
		ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
		freemsg(mp);
		return (NULL);
	}

	if (len == 0) {
		/* GLD sometimes sends up mblk with b_rptr == b_wptr! */
		mblk_t *mp1 = mp->b_cont;

		if (!(ira->ira_flags & IRAF_L2SRC_SET))
			ip_setl2src(mp, ira, ira->ira_rill);
		ASSERT(ira->ira_flags & IRAF_L2SRC_SET);

		freeb(mp);
		mp = mp1;
		if (mp == NULL)
			return (NULL);

		if (OK_32PTR(mp->b_rptr) && MBLKL(mp) >= min_size)
			return (mp);
	}
	if (ip_pullup(mp, min_size, ira) == NULL) {
		if (msgdsize(mp) < min_size) {
			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
		} else {
			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
			ip_drop_input("ipIfStatsInDiscards", mp, ill);
		}
		freemsg(mp);
		return (NULL);
	}
	return (mp);
}

/*
 * Common code for IPv4 and IPv6 to check and pullup multi-mblks
 */
mblk_t *
ip_check_length(mblk_t *mp, uchar_t *rptr, ssize_t len,	uint_t pkt_len,
    uint_t min_size, ip_recv_attr_t *ira)
{
	ill_t	*ill = ira->ira_ill;

	/*
	 * Make sure we have data length consistent
	 * with the IP header.
	 */
	if (mp->b_cont == NULL) {
		/* pkt_len is based on ipha_len, not the mblk length */
		if (pkt_len < min_size) {
			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
			freemsg(mp);
			return (NULL);
		}
		if (len < 0) {
			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
			freemsg(mp);
			return (NULL);
		}
		/* Drop any pad */
		mp->b_wptr = rptr + pkt_len;
	} else if ((len += msgdsize(mp->b_cont)) != 0) {
		ASSERT(pkt_len >= min_size);
		if (pkt_len < min_size) {
			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
			freemsg(mp);
			return (NULL);
		}
		if (len < 0) {
			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInTruncatedPkts);
			ip_drop_input("ipIfStatsInTruncatedPkts", mp, ill);
			freemsg(mp);
			return (NULL);
		}
		/* Drop any pad */
		(void) adjmsg(mp, -len);
		/*
		 * adjmsg may have freed an mblk from the chain, hence
		 * invalidate any hw checksum here. This will force IP to
		 * calculate the checksum in sw, but only for this packet.
		 */
		DB_CKSUMFLAGS(mp) = 0;
		IP_STAT(ill->ill_ipst, ip_multimblk);
	}
	return (mp);
}

/*
 * Check that the IPv4 opt_len is consistent with the packet and pullup
 * the options.
 */
mblk_t *
ip_check_optlen(mblk_t *mp, ipha_t *ipha, uint_t opt_len, uint_t pkt_len,
    ip_recv_attr_t *ira)
{
	ill_t	*ill = ira->ira_ill;
	ssize_t len;

	/* Assume no IPv6 packets arrive over the IPv4 queue */
	if (IPH_HDR_VERSION(ipha) != IPV4_VERSION) {
		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
		ip_drop_input("IPvN packet on IPv4 ill", mp, ill);
		freemsg(mp);
		return (NULL);
	}

	if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
		ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
		freemsg(mp);
		return (NULL);
	}
	/*
	 * Recompute complete header length and make sure we
	 * have access to all of it.
	 */
	len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
	if (len > (mp->b_wptr - mp->b_rptr)) {
		if (len > pkt_len) {
			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
			ip_drop_input("ipIfStatsInHdrErrors", mp, ill);
			freemsg(mp);
			return (NULL);
		}
		if (ip_pullup(mp, len, ira) == NULL) {
			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
			ip_drop_input("ipIfStatsInDiscards", mp, ill);
			freemsg(mp);
			return (NULL);
		}
	}
	return (mp);
}

/*
 * Returns a new ire, or the same ire, or NULL.
 * If a different IRE is returned, then it is held; the caller
 * needs to release it.
 * In no case is there any hold/release on the ire argument.
 */
ire_t *
ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
{
	ire_t		*new_ire;
	ill_t		*ire_ill;
	uint_t		ifindex;
	ip_stack_t	*ipst = ill->ill_ipst;
	boolean_t	strict_check = B_FALSE;

	/*
	 * IPMP common case: if IRE and ILL are in the same group, there's no
	 * issue (e.g. packet received on an underlying interface matched an
	 * IRE_LOCAL on its associated group interface).
	 */
	ASSERT(ire->ire_ill != NULL);
	if (IS_IN_SAME_ILLGRP(ill, ire->ire_ill))
		return (ire);

	/*
	 * Do another ire lookup here, using the ingress ill, to see if the
	 * interface is in a usesrc group.
	 * As long as the ills belong to the same group, we don't consider
	 * them to be arriving on the wrong interface. Thus, if the switch
	 * is doing inbound load spreading, we won't drop packets when the
	 * ip*_strict_dst_multihoming switch is on.
	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
	 * where the local address may not be unique. In this case we were
	 * at the mercy of the initial ire lookup and the IRE_LOCAL it
	 * actually returned. The new lookup, which is more specific, should
	 * only find the IRE_LOCAL associated with the ingress ill if one
	 * exists.
	 */
	if (ire->ire_ipversion == IPV4_VERSION) {
		if (ipst->ips_ip_strict_dst_multihoming)
			strict_check = B_TRUE;
		new_ire = ire_ftable_lookup_v4(*((ipaddr_t *)addr), 0, 0,
		    IRE_LOCAL, ill, ALL_ZONES, NULL,
		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
	} else {
		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
		if (ipst->ips_ipv6_strict_dst_multihoming)
			strict_check = B_TRUE;
		new_ire = ire_ftable_lookup_v6((in6_addr_t *)addr, NULL, NULL,
		    IRE_LOCAL, ill, ALL_ZONES, NULL,
		    (MATCH_IRE_TYPE|MATCH_IRE_ILL), 0, ipst, NULL);
	}
	/*
	 * If the same ire that was returned in ip_input() is found then this
	 * is an indication that usesrc groups are in use. The packet
	 * arrived on a different ill in the group than the one associated with
	 * the destination address.  If a different ire was found then the same
	 * IP address must be hosted on multiple ills. This is possible with
	 * unnumbered point2point interfaces. We switch to use this new ire in
	 * order to have accurate interface statistics.
	 */
	if (new_ire != NULL) {
		/* Note: held in one case but not the other? Caller handles */
		if (new_ire != ire)
			return (new_ire);
		/* Unchanged */
		ire_refrele(new_ire);
		return (ire);
	}

	/*
	 * Chase pointers once and store locally.
	 */
	ASSERT(ire->ire_ill != NULL);
	ire_ill = ire->ire_ill;
	ifindex = ill->ill_usesrc_ifindex;

	/*
	 * Check if it's a legal address on the 'usesrc' interface.
	 * For IPMP data addresses the IRE_LOCAL is the upper, hence we
	 * can just check phyint_ifindex.
	 */
	if (ifindex != 0 && ifindex == ire_ill->ill_phyint->phyint_ifindex) {
		return (ire);
	}

	/*
	 * If the ip*_strict_dst_multihoming switch is on then we can
	 * only accept this packet if the interface is marked as routing.
	 */
	if (!(strict_check))
		return (ire);

	if ((ill->ill_flags & ire->ire_ill->ill_flags & ILLF_ROUTER) != 0) {
		return (ire);
	}
	return (NULL);
}

/*
 * This function is used to construct a mac_header_info_s from a
 * DL_UNITDATA_IND message.
 * The address fields in the mhi structure points into the message,
 * thus the caller can't use those fields after freeing the message.
 *
 * We determine whether the packet received is a non-unicast packet
 * and in doing so, determine whether or not it is broadcast vs multicast.
 * For it to be a broadcast packet, we must have the appropriate mblk_t
 * hanging off the ill_t.  If this is either not present or doesn't match
 * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
 * to be multicast.  Thus NICs that have no broadcast address (or no
 * capability for one, such as point to point links) cannot return as
 * the packet being broadcast.
 */
void
ip_dlur_to_mhi(ill_t *ill, mblk_t *mb, struct mac_header_info_s *mhip)
{
	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
	mblk_t *bmp;
	uint_t extra_offset;

	bzero(mhip, sizeof (struct mac_header_info_s));

	mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;

	if (ill->ill_sap_length < 0)
		extra_offset = 0;
	else
		extra_offset = ill->ill_sap_length;

	mhip->mhi_daddr = (uchar_t *)ind + ind->dl_dest_addr_offset +
	    extra_offset;
	mhip->mhi_saddr = (uchar_t *)ind + ind->dl_src_addr_offset +
	    extra_offset;

	if (!ind->dl_group_address)
		return;

	/* Multicast or broadcast */
	mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;

	if (ind->dl_dest_addr_offset > sizeof (*ind) &&
	    ind->dl_dest_addr_offset + ind->dl_dest_addr_length < MBLKL(mb) &&
	    (bmp = ill->ill_bcast_mp) != NULL) {
		dl_unitdata_req_t *dlur;
		uint8_t *bphys_addr;

		dlur = (dl_unitdata_req_t *)bmp->b_rptr;
		bphys_addr = (uchar_t *)dlur + dlur->dl_dest_addr_offset +
		    extra_offset;

		if (bcmp(mhip->mhi_daddr, bphys_addr,
		    ind->dl_dest_addr_length) == 0)
			mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
	}
}

/*
 * This function is used to construct a mac_header_info_s from a
 * M_DATA fastpath message from a DLPI driver.
 * The address fields in the mhi structure points into the message,
 * thus the caller can't use those fields after freeing the message.
 *
 * We determine whether the packet received is a non-unicast packet
 * and in doing so, determine whether or not it is broadcast vs multicast.
 * For it to be a broadcast packet, we must have the appropriate mblk_t
 * hanging off the ill_t.  If this is either not present or doesn't match
 * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
 * to be multicast.  Thus NICs that have no broadcast address (or no
 * capability for one, such as point to point links) cannot return as
 * the packet being broadcast.
 */
void
ip_mdata_to_mhi(ill_t *ill, mblk_t *mp, struct mac_header_info_s *mhip)
{
	mblk_t *bmp;
	struct ether_header *pether;

	bzero(mhip, sizeof (struct mac_header_info_s));

	mhip->mhi_dsttype = MAC_ADDRTYPE_UNICAST;

	pether = (struct ether_header *)((char *)mp->b_rptr
	    - sizeof (struct ether_header));

	/*
	 * Make sure the interface is an ethernet type, since we don't
	 * know the header format for anything but Ethernet. Also make
	 * sure we are pointing correctly above db_base.
	 */
	if (ill->ill_type != IFT_ETHER)
		return;

retry:
	if ((uchar_t *)pether < mp->b_datap->db_base)
		return;

	/* Is there a VLAN tag? */
	if (ill->ill_isv6) {
		if (pether->ether_type != htons(ETHERTYPE_IPV6)) {
			pether = (struct ether_header *)((char *)pether - 4);
			goto retry;
		}
	} else {
		if (pether->ether_type != htons(ETHERTYPE_IP)) {
			pether = (struct ether_header *)((char *)pether - 4);
			goto retry;
		}
	}
	mhip->mhi_daddr = (uchar_t *)&pether->ether_dhost;
	mhip->mhi_saddr = (uchar_t *)&pether->ether_shost;

	if (!(mhip->mhi_daddr[0] & 0x01))
		return;

	/* Multicast or broadcast */
	mhip->mhi_dsttype = MAC_ADDRTYPE_MULTICAST;

	if ((bmp = ill->ill_bcast_mp) != NULL) {
		dl_unitdata_req_t *dlur;
		uint8_t *bphys_addr;
		uint_t	addrlen;

		dlur = (dl_unitdata_req_t *)bmp->b_rptr;
		addrlen = dlur->dl_dest_addr_length;
		if (ill->ill_sap_length < 0) {
			bphys_addr = (uchar_t *)dlur +
			    dlur->dl_dest_addr_offset;
			addrlen += ill->ill_sap_length;
		} else {
			bphys_addr = (uchar_t *)dlur +
			    dlur->dl_dest_addr_offset +
			    ill->ill_sap_length;
			addrlen -= ill->ill_sap_length;
		}
		if (bcmp(mhip->mhi_daddr, bphys_addr, addrlen) == 0)
			mhip->mhi_dsttype = MAC_ADDRTYPE_BROADCAST;
	}
}

/*
 * Handle anything but M_DATA messages
 * We see the DL_UNITDATA_IND which are part
 * of the data path, and also the other messages from the driver.
 */
void
ip_rput_notdata(ill_t *ill, mblk_t *mp)
{
	mblk_t		*first_mp;
	struct iocblk   *iocp;
	struct mac_header_info_s mhi;

	switch (DB_TYPE(mp)) {
	case M_PROTO:
	case M_PCPROTO: {
		if (((dl_unitdata_ind_t *)mp->b_rptr)->dl_primitive !=
		    DL_UNITDATA_IND) {
			/* Go handle anything other than data elsewhere. */
			ip_rput_dlpi(ill, mp);
			return;
		}

		first_mp = mp;
		mp = first_mp->b_cont;
		first_mp->b_cont = NULL;

		if (mp == NULL) {
			freeb(first_mp);
			return;
		}
		ip_dlur_to_mhi(ill, first_mp, &mhi);
		if (ill->ill_isv6)
			ip_input_v6(ill, NULL, mp, &mhi);
		else
			ip_input(ill, NULL, mp, &mhi);

		/* Ditch the DLPI header. */
		freeb(first_mp);
		return;
	}
	case M_IOCACK:
		iocp = (struct iocblk *)mp->b_rptr;
		switch (iocp->ioc_cmd) {
		case DL_IOC_HDR_INFO:
			ill_fastpath_ack(ill, mp);
			return;
		default:
			putnext(ill->ill_rq, mp);
			return;
		}
		/* FALLTHROUGH */
	case M_ERROR:
	case M_HANGUP:
		mutex_enter(&ill->ill_lock);
		if (ill->ill_state_flags & ILL_CONDEMNED) {
			mutex_exit(&ill->ill_lock);
			freemsg(mp);
			return;
		}
		ill_refhold_locked(ill);
		mutex_exit(&ill->ill_lock);
		qwriter_ip(ill, ill->ill_rq, mp, ip_rput_other, CUR_OP,
		    B_FALSE);
		return;
	case M_CTL:
		putnext(ill->ill_rq, mp);
		return;
	case M_IOCNAK:
		ip1dbg(("got iocnak "));
		iocp = (struct iocblk *)mp->b_rptr;
		switch (iocp->ioc_cmd) {
		case DL_IOC_HDR_INFO:
			ip_rput_other(NULL, ill->ill_rq, mp, NULL);
			return;
		default:
			break;
		}
		/* FALLTHROUGH */
	default:
		putnext(ill->ill_rq, mp);
		return;
	}
}

/* Read side put procedure.  Packets coming from the wire arrive here. */
int
ip_rput(queue_t *q, mblk_t *mp)
{
	ill_t	*ill;
	union DL_primitives *dl;

	ill = (ill_t *)q->q_ptr;

	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
		/*
		 * If things are opening or closing, only accept high-priority
		 * DLPI messages.  (On open ill->ill_ipif has not yet been
		 * created; on close, things hanging off the ill may have been
		 * freed already.)
		 */
		dl = (union DL_primitives *)mp->b_rptr;
		if (DB_TYPE(mp) != M_PCPROTO ||
		    dl->dl_primitive == DL_UNITDATA_IND) {
			inet_freemsg(mp);
			return (0);
		}
	}
	if (DB_TYPE(mp) == M_DATA) {
		struct mac_header_info_s mhi;

		ip_mdata_to_mhi(ill, mp, &mhi);
		ip_input(ill, NULL, mp, &mhi);
	} else {
		ip_rput_notdata(ill, mp);
	}
	return (0);
}

/*
 * Move the information to a copy.
 */
mblk_t *
ip_fix_dbref(mblk_t *mp, ip_recv_attr_t *ira)
{
	mblk_t		*mp1;
	ill_t		*ill = ira->ira_ill;
	ip_stack_t	*ipst = ill->ill_ipst;

	IP_STAT(ipst, ip_db_ref);

	/* Make sure we have ira_l2src before we loose the original mblk */
	if (!(ira->ira_flags & IRAF_L2SRC_SET))
		ip_setl2src(mp, ira, ira->ira_rill);

	mp1 = copymsg(mp);
	if (mp1 == NULL) {
		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
		ip_drop_input("ipIfStatsInDiscards", mp, ill);
		freemsg(mp);
		return (NULL);
	}
	/* preserve the hardware checksum flags and data, if present */
	if (DB_CKSUMFLAGS(mp) != 0) {
		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
	}
	freemsg(mp);
	return (mp1);
}

static void
ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
    t_uscalar_t err)
{
	if (dl_err == DL_SYSERR) {
		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
		    "%s: %s failed: DL_SYSERR (errno %u)\n",
		    ill->ill_name, dl_primstr(prim), err);
		return;
	}

	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
	    dl_errstr(dl_err));
}

/*
 * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
 * than DL_UNITDATA_IND messages. If we need to process this message
 * exclusively, we call qwriter_ip, in which case we also need to call
 * ill_refhold before that, since qwriter_ip does an ill_refrele.
 */
void
ip_rput_dlpi(ill_t *ill, mblk_t *mp)
{
	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
	queue_t		*q = ill->ill_rq;
	t_uscalar_t	prim = dloa->dl_primitive;
	t_uscalar_t	reqprim = DL_PRIM_INVAL;

	DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi",
	    char *, dl_primstr(prim), ill_t *, ill);
	ip1dbg(("ip_rput_dlpi"));

	/*
	 * If we received an ACK but didn't send a request for it, then it
	 * can't be part of any pending operation; discard up-front.
	 */
	switch (prim) {
	case DL_ERROR_ACK:
		reqprim = dlea->dl_error_primitive;
		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
		    dlea->dl_unix_errno));
		break;
	case DL_OK_ACK:
		reqprim = dloa->dl_correct_primitive;
		break;
	case DL_INFO_ACK:
		reqprim = DL_INFO_REQ;
		break;
	case DL_BIND_ACK:
		reqprim = DL_BIND_REQ;
		break;
	case DL_PHYS_ADDR_ACK:
		reqprim = DL_PHYS_ADDR_REQ;
		break;
	case DL_NOTIFY_ACK:
		reqprim = DL_NOTIFY_REQ;
		break;
	case DL_CAPABILITY_ACK:
		reqprim = DL_CAPABILITY_REQ;
		break;
	}

	if (prim != DL_NOTIFY_IND) {
		if (reqprim == DL_PRIM_INVAL ||
		    !ill_dlpi_pending(ill, reqprim)) {
			/* Not a DLPI message we support or expected */
			freemsg(mp);
			return;
		}
		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
		    dl_primstr(reqprim)));
	}

	switch (reqprim) {
	case DL_UNBIND_REQ:
		/*
		 * NOTE: we mark the unbind as complete even if we got a
		 * DL_ERROR_ACK, since there's not much else we can do.
		 */
		mutex_enter(&ill->ill_lock);
		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
		cv_signal(&ill->ill_cv);
		mutex_exit(&ill->ill_lock);
		break;

	case DL_ENABMULTI_REQ:
		if (prim == DL_OK_ACK) {
			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
				ill->ill_dlpi_multicast_state = IDS_OK;
		}
		break;
	}

	/*
	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
	 * need to become writer to continue to process it.  Because an
	 * exclusive operation doesn't complete until replies to all queued
	 * DLPI messages have been received, we know we're in the middle of an
	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
	 *
	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
	 * Since this is on the ill stream we unconditionally bump up the
	 * refcount without doing ILL_CAN_LOOKUP().
	 */
	ill_refhold(ill);
	if (prim == DL_NOTIFY_IND)
		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
	else
		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
}

/*
 * Handling of DLPI messages that require exclusive access to the ipsq.
 *
 * Need to do ipsq_pending_mp_get on ioctl completion, which could
 * happen here. (along with mi_copy_done)
 */
/* ARGSUSED */
static void
ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
{
	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
	int		err = 0;
	ill_t		*ill = (ill_t *)q->q_ptr;
	ipif_t		*ipif = NULL;
	mblk_t		*mp1 = NULL;
	conn_t		*connp = NULL;
	t_uscalar_t	paddrreq;
	mblk_t		*mp_hw;
	boolean_t	ioctl_aborted = B_FALSE;
	boolean_t	log = B_TRUE;

	DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer",
	    char *, dl_primstr(dloa->dl_primitive), ill_t *, ill);

	ip1dbg(("ip_rput_dlpi_writer .."));
	ASSERT(ipsq->ipsq_xop == ill->ill_phyint->phyint_ipsq->ipsq_xop);
	ASSERT(IAM_WRITER_ILL(ill));

	ipif = ipsq->ipsq_xop->ipx_pending_ipif;
	/*
	 * The current ioctl could have been aborted by the user and a new
	 * ioctl to bring up another ill could have started. We could still
	 * get a response from the driver later.
	 */
	if (ipif != NULL && ipif->ipif_ill != ill)
		ioctl_aborted = B_TRUE;

	switch (dloa->dl_primitive) {
	case DL_ERROR_ACK:
		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
		    dl_primstr(dlea->dl_error_primitive)));

		DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer error",
		    char *, dl_primstr(dlea->dl_error_primitive),
		    ill_t *, ill);

		switch (dlea->dl_error_primitive) {
		case DL_DISABMULTI_REQ:
			ill_dlpi_done(ill, dlea->dl_error_primitive);
			break;
		case DL_PROMISCON_REQ:
		case DL_PROMISCOFF_REQ:
		case DL_UNBIND_REQ:
		case DL_ATTACH_REQ:
		case DL_INFO_REQ:
			ill_dlpi_done(ill, dlea->dl_error_primitive);
			break;
		case DL_NOTIFY_REQ:
			ill_dlpi_done(ill, DL_NOTIFY_REQ);
			log = B_FALSE;
			break;
		case DL_PHYS_ADDR_REQ:
			/*
			 * For IPv6 only, there are two additional
			 * phys_addr_req's sent to the driver to get the
			 * IPv6 token and lla. This allows IP to acquire
			 * the hardware address format for a given interface
			 * without having built in knowledge of the hardware
			 * address. ill_phys_addr_pend keeps track of the last
			 * DL_PAR sent so we know which response we are
			 * dealing with. ill_dlpi_done will update
			 * ill_phys_addr_pend when it sends the next req.
			 * We don't complete the IOCTL until all three DL_PARs
			 * have been attempted, so set *_len to 0 and break.
			 */
			paddrreq = ill->ill_phys_addr_pend;
			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
			if (paddrreq == DL_IPV6_TOKEN) {
				ill->ill_token_length = 0;
				log = B_FALSE;
				break;
			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
				ill->ill_nd_lla_len = 0;
				log = B_FALSE;
				break;
			}
			/*
			 * Something went wrong with the DL_PHYS_ADDR_REQ.
			 * We presumably have an IOCTL hanging out waiting
			 * for completion. Find it and complete the IOCTL
			 * with the error noted.
			 * However, ill_dl_phys was called on an ill queue
			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
			 * set. But the ioctl is known to be pending on ill_wq.
			 */
			if (!ill->ill_ifname_pending)
				break;
			ill->ill_ifname_pending = 0;
			if (!ioctl_aborted)
				mp1 = ipsq_pending_mp_get(ipsq, &connp);
			if (mp1 != NULL) {
				/*
				 * This operation (SIOCSLIFNAME) must have
				 * happened on the ill. Assert there is no conn
				 */
				ASSERT(connp == NULL);
				q = ill->ill_wq;
			}
			break;
		case DL_BIND_REQ:
			ill_dlpi_done(ill, DL_BIND_REQ);
			if (ill->ill_ifname_pending)
				break;
			mutex_enter(&ill->ill_lock);
			ill->ill_state_flags &= ~ILL_DOWN_IN_PROGRESS;
			mutex_exit(&ill->ill_lock);
			/*
			 * Something went wrong with the bind. If this was the
			 * result of a DL_NOTE_REPLUMB, then we presumably
			 * have an IOCTL hanging out waiting for completion.
			 * Find it, take down the interface that was coming
			 * up, and complete the IOCTL with the error noted.
			 */
			if (!ioctl_aborted)
				mp1 = ipsq_pending_mp_get(ipsq, &connp);
			if (mp1 != NULL) {
				/*
				 * This might be a result of a DL_NOTE_REPLUMB
				 * notification. In that case, connp is NULL.
				 */
				if (connp != NULL)
					q = CONNP_TO_WQ(connp);

				(void) ipif_down(ipif, NULL, NULL);
				/* error is set below the switch */
			} else {
				/*
				 * There's no pending IOCTL, so the bind was
				 * most likely started by ill_dl_up(). We save
				 * the error and let it take care of responding
				 * to the IOCTL.
				 */
				ill->ill_dl_bind_err = dlea->dl_unix_errno ?
				    dlea->dl_unix_errno : ENXIO;
			}
			break;
		case DL_ENABMULTI_REQ:
			ill_dlpi_done(ill, DL_ENABMULTI_REQ);

			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
				ill->ill_dlpi_multicast_state = IDS_FAILED;
			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {

				printf("ip: joining multicasts failed (%d)"
				    " on %s - will use link layer "
				    "broadcasts for multicast\n",
				    dlea->dl_errno, ill->ill_name);

				/*
				 * Set up for multi_bcast; We are the
				 * writer, so ok to access ill->ill_ipif
				 * without any lock.
				 */
				mutex_enter(&ill->ill_phyint->phyint_lock);
				ill->ill_phyint->phyint_flags |=
				    PHYI_MULTI_BCAST;
				mutex_exit(&ill->ill_phyint->phyint_lock);

			}
			freemsg(mp);	/* Don't want to pass this up */
			return;
		case DL_CAPABILITY_REQ:
			ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for "
			    "DL_CAPABILITY REQ\n"));
			if (ill->ill_dlpi_capab_state == IDCS_PROBE_SENT)
				ill->ill_dlpi_capab_state = IDCS_FAILED;
			ill_capability_done(ill);
			freemsg(mp);
			return;
		}
		/*
		 * Note the error for IOCTL completion (mp1 is set when
		 * ready to complete ioctl). If ill_ifname_pending_err is
		 * set, an error occured during plumbing (ill_ifname_pending),
		 * so we want to report that error.
		 *
		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
		 * expected to get errack'd if the driver doesn't support
		 * these flags (e.g. ethernet). log will be set to B_FALSE
		 * if these error conditions are encountered.
		 */
		if (mp1 != NULL) {
			if (ill->ill_ifname_pending_err != 0)  {
				err = ill->ill_ifname_pending_err;
				ill->ill_ifname_pending_err = 0;
			} else {
				err = dlea->dl_unix_errno ?
				    dlea->dl_unix_errno : ENXIO;
			}
		/*
		 * If we're plumbing an interface and an error hasn't already
		 * been saved, set ill_ifname_pending_err to the error passed
		 * up. Ignore the error if log is B_FALSE (see comment above).
		 */
		} else if (log && ill->ill_ifname_pending &&
		    ill->ill_ifname_pending_err == 0) {
			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
			    dlea->dl_unix_errno : ENXIO;
		}

		if (log)
			ip_dlpi_error(ill, dlea->dl_error_primitive,
			    dlea->dl_errno, dlea->dl_unix_errno);
		break;
	case DL_CAPABILITY_ACK:
		ill_capability_ack(ill, mp);
		/*
		 * The message has been handed off to ill_capability_ack
		 * and must not be freed below
		 */
		mp = NULL;
		break;

	case DL_INFO_ACK:
		/* Call a routine to handle this one. */
		ill_dlpi_done(ill, DL_INFO_REQ);
		ip_ll_subnet_defaults(ill, mp);
		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
		return;
	case DL_BIND_ACK:
		/*
		 * We should have an IOCTL waiting on this unless
		 * sent by ill_dl_phys, in which case just return
		 */
		ill_dlpi_done(ill, DL_BIND_REQ);

		if (ill->ill_ifname_pending) {
			DTRACE_PROBE2(ip__rput__dlpi__ifname__pending,
			    ill_t *, ill, mblk_t *, mp);
			break;
		}
		mutex_enter(&ill->ill_lock);
		ill->ill_dl_up = 1;
		ill->ill_state_flags &= ~ILL_DOWN_IN_PROGRESS;
		mutex_exit(&ill->ill_lock);

		if (!ioctl_aborted)
			mp1 = ipsq_pending_mp_get(ipsq, &connp);
		if (mp1 == NULL) {
			DTRACE_PROBE1(ip__rput__dlpi__no__mblk, ill_t *, ill);
			break;
		}
		/*
		 * mp1 was added by ill_dl_up(). if that is a result of
		 * a DL_NOTE_REPLUMB notification, connp could be NULL.
		 */
		if (connp != NULL)
			q = CONNP_TO_WQ(connp);
		/*
		 * We are exclusive. So nothing can change even after
		 * we get the pending mp.
		 */
		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
		DTRACE_PROBE1(ip__rput__dlpi__bind__ack, ill_t *, ill);
		ill_nic_event_dispatch(ill, 0, NE_UP, NULL, 0);

		if (ill->ill_up_ipifs) {
			err = ill_up_ipifs(ill, q, mp1);
			if (err == EINPROGRESS) {
				freemsg(mp);
				return;
			}
		}

		break;

	case DL_NOTIFY_IND: {
		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
		uint_t orig_mtu, orig_mc_mtu;

		switch (notify->dl_notification) {
		case DL_NOTE_PHYS_ADDR:
			err = ill_set_phys_addr(ill, mp);
			break;

		case DL_NOTE_REPLUMB:
			/*
			 * Directly return after calling ill_replumb().
			 * Note that we should not free mp as it is reused
			 * in the ill_replumb() function.
			 */
			err = ill_replumb(ill, mp);
			return;

		case DL_NOTE_FASTPATH_FLUSH:
			nce_flush(ill, B_FALSE);
			break;

		case DL_NOTE_SDU_SIZE:
		case DL_NOTE_SDU_SIZE2:
			/*
			 * The dce and fragmentation code can cope with
			 * this changing while packets are being sent.
			 * When packets are sent ip_output will discover
			 * a change.
			 *
			 * Change the MTU size of the interface.
			 */
			mutex_enter(&ill->ill_lock);
			orig_mtu = ill->ill_mtu;
			orig_mc_mtu = ill->ill_mc_mtu;
			switch (notify->dl_notification) {
			case DL_NOTE_SDU_SIZE:
				ill->ill_current_frag =
				    (uint_t)notify->dl_data;
				ill->ill_mc_mtu = (uint_t)notify->dl_data;
				break;
			case DL_NOTE_SDU_SIZE2:
				ill->ill_current_frag =
				    (uint_t)notify->dl_data1;
				ill->ill_mc_mtu = (uint_t)notify->dl_data2;
				break;
			}
			if (ill->ill_current_frag > ill->ill_max_frag)
				ill->ill_max_frag = ill->ill_current_frag;

			if (!(ill->ill_flags & ILLF_FIXEDMTU)) {
				ill->ill_mtu = ill->ill_current_frag;

				/*
				 * If ill_user_mtu was set (via
				 * SIOCSLIFLNKINFO), clamp ill_mtu at it.
				 */
				if (ill->ill_user_mtu != 0 &&
				    ill->ill_user_mtu < ill->ill_mtu)
					ill->ill_mtu = ill->ill_user_mtu;

				if (ill->ill_user_mtu != 0 &&
				    ill->ill_user_mtu < ill->ill_mc_mtu)
					ill->ill_mc_mtu = ill->ill_user_mtu;

				if (ill->ill_isv6) {
					if (ill->ill_mtu < IPV6_MIN_MTU)
						ill->ill_mtu = IPV6_MIN_MTU;
					if (ill->ill_mc_mtu < IPV6_MIN_MTU)
						ill->ill_mc_mtu = IPV6_MIN_MTU;
				} else {
					if (ill->ill_mtu < IP_MIN_MTU)
						ill->ill_mtu = IP_MIN_MTU;
					if (ill->ill_mc_mtu < IP_MIN_MTU)
						ill->ill_mc_mtu = IP_MIN_MTU;
				}
			} else if (ill->ill_mc_mtu > ill->ill_mtu) {
				ill->ill_mc_mtu = ill->ill_mtu;
			}

			mutex_exit(&ill->ill_lock);
			/*
			 * Make sure all dce_generation checks find out
			 * that ill_mtu/ill_mc_mtu has changed.
			 */
			if (orig_mtu != ill->ill_mtu ||
			    orig_mc_mtu != ill->ill_mc_mtu) {
				dce_increment_all_generations(ill->ill_isv6,
				    ill->ill_ipst);
			}

			/*
			 * Refresh IPMP meta-interface MTU if necessary.
			 */
			if (IS_UNDER_IPMP(ill))
				ipmp_illgrp_refresh_mtu(ill->ill_grp);
			break;

		case DL_NOTE_LINK_UP:
		case DL_NOTE_LINK_DOWN: {
			/*
			 * We are writer. ill / phyint / ipsq assocs stable.
			 * The RUNNING flag reflects the state of the link.
			 */
			phyint_t *phyint = ill->ill_phyint;
			uint64_t new_phyint_flags;
			boolean_t changed = B_FALSE;
			boolean_t went_up;

			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
			mutex_enter(&phyint->phyint_lock);

			new_phyint_flags = went_up ?
			    phyint->phyint_flags | PHYI_RUNNING :
			    phyint->phyint_flags & ~PHYI_RUNNING;

			if (IS_IPMP(ill)) {
				new_phyint_flags = went_up ?
				    new_phyint_flags & ~PHYI_FAILED :
				    new_phyint_flags | PHYI_FAILED;
			}

			if (new_phyint_flags != phyint->phyint_flags) {
				phyint->phyint_flags = new_phyint_flags;
				changed = B_TRUE;
			}
			mutex_exit(&phyint->phyint_lock);
			/*
			 * ill_restart_dad handles the DAD restart and routing
			 * socket notification logic.
			 */
			if (changed) {
				ill_restart_dad(phyint->phyint_illv4, went_up);
				ill_restart_dad(phyint->phyint_illv6, went_up);
			}
			break;
		}
		case DL_NOTE_PROMISC_ON_PHYS: {
			phyint_t *phyint = ill->ill_phyint;

			mutex_enter(&phyint->phyint_lock);
			phyint->phyint_flags |= PHYI_PROMISC;
			mutex_exit(&phyint->phyint_lock);
			break;
		}
		case DL_NOTE_PROMISC_OFF_PHYS: {
			phyint_t *phyint = ill->ill_phyint;

			mutex_enter(&phyint->phyint_lock);
			phyint->phyint_flags &= ~PHYI_PROMISC;
			mutex_exit(&phyint->phyint_lock);
			break;
		}
		case DL_NOTE_CAPAB_RENEG:
			/*
			 * Something changed on the driver side.
			 * It wants us to renegotiate the capabilities
			 * on this ill. One possible cause is the aggregation
			 * interface under us where a port got added or
			 * went away.
			 *
			 * If the capability negotiation is already done
			 * or is in progress, reset the capabilities and
			 * mark the ill's ill_capab_reneg to be B_TRUE,
			 * so that when the ack comes back, we can start
			 * the renegotiation process.
			 *
			 * Note that if ill_capab_reneg is already B_TRUE
			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
			 * the capability resetting request has been sent
			 * and the renegotiation has not been started yet;
			 * nothing needs to be done in this case.
			 */
			ipsq_current_start(ipsq, ill->ill_ipif, 0);
			ill_capability_reset(ill, B_TRUE);
			ipsq_current_finish(ipsq);
			break;

		case DL_NOTE_ALLOWED_IPS:
			ill_set_allowed_ips(ill, mp);
			break;
		default:
			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
			    "type 0x%x for DL_NOTIFY_IND\n",
			    notify->dl_notification));
			break;
		}

		/*
		 * As this is an asynchronous operation, we
		 * should not call ill_dlpi_done
		 */
		break;
	}
	case DL_NOTIFY_ACK: {
		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;

		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
			ill->ill_note_link = 1;
		ill_dlpi_done(ill, DL_NOTIFY_REQ);
		break;
	}
	case DL_PHYS_ADDR_ACK: {
		/*
		 * As part of plumbing the interface via SIOCSLIFNAME,
		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
		 * whose answers we receive here.  As each answer is received,
		 * we call ill_dlpi_done() to dispatch the next request as
		 * we're processing the current one.  Once all answers have
		 * been received, we use ipsq_pending_mp_get() to dequeue the
		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
		 * is invoked from an ill queue, conn_oper_pending_ill is not
		 * available, but we know the ioctl is pending on ill_wq.)
		 */
		uint_t	paddrlen, paddroff;
		uint8_t	*addr;

		paddrreq = ill->ill_phys_addr_pend;
		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
		addr = mp->b_rptr + paddroff;

		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
		if (paddrreq == DL_IPV6_TOKEN) {
			/*
			 * bcopy to low-order bits of ill_token
			 *
			 * XXX Temporary hack - currently, all known tokens
			 * are 64 bits, so I'll cheat for the moment.
			 */
			bcopy(addr, &ill->ill_token.s6_addr32[2], paddrlen);
			ill->ill_token_length = paddrlen;
			break;
		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
			ASSERT(ill->ill_nd_lla_mp == NULL);
			ill_set_ndmp(ill, mp, paddroff, paddrlen);
			mp = NULL;
			break;
		} else if (paddrreq == DL_CURR_DEST_ADDR) {
			ASSERT(ill->ill_dest_addr_mp == NULL);
			ill->ill_dest_addr_mp = mp;
			ill->ill_dest_addr = addr;
			mp = NULL;
			if (ill->ill_isv6) {
				ill_setdesttoken(ill);
				ipif_setdestlinklocal(ill->ill_ipif);
			}
			break;
		}

		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
		ASSERT(ill->ill_phys_addr_mp == NULL);
		if (!ill->ill_ifname_pending)
			break;
		ill->ill_ifname_pending = 0;
		if (!ioctl_aborted)
			mp1 = ipsq_pending_mp_get(ipsq, &connp);
		if (mp1 != NULL) {
			ASSERT(connp == NULL);
			q = ill->ill_wq;
		}
		/*
		 * If any error acks received during the plumbing sequence,
		 * ill_ifname_pending_err will be set. Break out and send up
		 * the error to the pending ioctl.
		 */
		if (ill->ill_ifname_pending_err != 0) {
			err = ill->ill_ifname_pending_err;
			ill->ill_ifname_pending_err = 0;
			break;
		}

		ill->ill_phys_addr_mp = mp;
		ill->ill_phys_addr = (paddrlen == 0 ? NULL : addr);
		mp = NULL;

		/*
		 * If paddrlen or ill_phys_addr_length is zero, the DLPI
		 * provider doesn't support physical addresses.  We check both
		 * paddrlen and ill_phys_addr_length because sppp (PPP) does
		 * not have physical addresses, but historically adversises a
		 * physical address length of 0 in its DL_INFO_ACK, but 6 in
		 * its DL_PHYS_ADDR_ACK.
		 */
		if (paddrlen == 0 || ill->ill_phys_addr_length == 0) {
			ill->ill_phys_addr = NULL;
		} else if (paddrlen != ill->ill_phys_addr_length) {
			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
			    paddrlen, ill->ill_phys_addr_length));
			err = EINVAL;
			break;
		}

		if (ill->ill_nd_lla_mp == NULL) {
			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
				err = ENOMEM;
				break;
			}
			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
		}

		if (ill->ill_isv6) {
			ill_setdefaulttoken(ill);
			ipif_setlinklocal(ill->ill_ipif);
		}
		break;
	}
	case DL_OK_ACK:
		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
		    dl_primstr((int)dloa->dl_correct_primitive),
		    dloa->dl_correct_primitive));
		DTRACE_PROBE3(ill__dlpi, char *, "ip_rput_dlpi_writer ok",
		    char *, dl_primstr(dloa->dl_correct_primitive),
		    ill_t *, ill);

		switch (dloa->dl_correct_primitive) {
		case DL_ENABMULTI_REQ:
		case DL_DISABMULTI_REQ:
			ill_dlpi_done(ill, dloa->dl_correct_primitive);
			break;
		case DL_PROMISCON_REQ:
		case DL_PROMISCOFF_REQ:
		case DL_UNBIND_REQ:
		case DL_ATTACH_REQ:
			ill_dlpi_done(ill, dloa->dl_correct_primitive);
			break;
		}
		break;
	default:
		break;
	}

	freemsg(mp);
	if (mp1 == NULL)
		return;

	/*
	 * The operation must complete without EINPROGRESS since
	 * ipsq_pending_mp_get() has removed the mblk (mp1).  Otherwise,
	 * the operation will be stuck forever inside the IPSQ.
	 */
	ASSERT(err != EINPROGRESS);

	DTRACE_PROBE4(ipif__ioctl, char *, "ip_rput_dlpi_writer finish",
	    int, ipsq->ipsq_xop->ipx_current_ioctl, ill_t *, ill,
	    ipif_t *, NULL);

	switch (ipsq->ipsq_xop->ipx_current_ioctl) {
	case 0:
		ipsq_current_finish(ipsq);
		break;

	case SIOCSLIFNAME:
	case IF_UNITSEL: {
		ill_t *ill_other = ILL_OTHER(ill);

		/*
		 * If SIOCSLIFNAME or IF_UNITSEL is about to succeed, and the
		 * ill has a peer which is in an IPMP group, then place ill
		 * into the same group.  One catch: although ifconfig plumbs
		 * the appropriate IPMP meta-interface prior to plumbing this
		 * ill, it is possible for multiple ifconfig applications to
		 * race (or for another application to adjust plumbing), in
		 * which case the IPMP meta-interface we need will be missing.
		 * If so, kick the phyint out of the group.
		 */
		if (err == 0 && ill_other != NULL && IS_UNDER_IPMP(ill_other)) {
			ipmp_grp_t	*grp = ill->ill_phyint->phyint_grp;
			ipmp_illgrp_t	*illg;

			illg = ill->ill_isv6 ? grp->gr_v6 : grp->gr_v4;
			if (illg == NULL)
				ipmp_phyint_leave_grp(ill->ill_phyint);
			else
				ipmp_ill_join_illgrp(ill, illg);
		}

		if (ipsq->ipsq_xop->ipx_current_ioctl == IF_UNITSEL)
			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
		else
			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
		break;
	}
	case SIOCLIFADDIF:
		ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
		break;

	default:
		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
		break;
	}
}

/*
 * ip_rput_other is called by ip_rput to handle messages modifying the global
 * state in IP.  If 'ipsq' is non-NULL, caller is writer on it.
 */
/* ARGSUSED */
void
ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
{
	ill_t		*ill = q->q_ptr;
	struct iocblk	*iocp;

	ip1dbg(("ip_rput_other "));
	if (ipsq != NULL) {
		ASSERT(IAM_WRITER_IPSQ(ipsq));
		ASSERT(ipsq->ipsq_xop ==
		    ill->ill_phyint->phyint_ipsq->ipsq_xop);
	}

	switch (mp->b_datap->db_type) {
	case M_ERROR:
	case M_HANGUP:
		/*
		 * The device has a problem.  We force the ILL down.  It can
		 * be brought up again manually using SIOCSIFFLAGS (via
		 * ifconfig or equivalent).
		 */
		ASSERT(ipsq != NULL);
		if (mp->b_rptr < mp->b_wptr)
			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
		if (ill->ill_error == 0)
			ill->ill_error = ENXIO;
		if (!ill_down_start(q, mp))
			return;
		ipif_all_down_tail(ipsq, q, mp, NULL);
		break;
	case M_IOCNAK: {
		iocp = (struct iocblk *)mp->b_rptr;

		ASSERT(iocp->ioc_cmd == DL_IOC_HDR_INFO);
		/*
		 * If this was the first attempt, turn off the fastpath
		 * probing.
		 */
		mutex_enter(&ill->ill_lock);
		if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
			ill->ill_dlpi_fastpath_state = IDS_FAILED;
			mutex_exit(&ill->ill_lock);
			/*
			 * don't flush the nce_t entries: we use them
			 * as an index to the ncec itself.
			 */
			ip1dbg(("ip_rput: DLPI fastpath off on interface %s\n",
			    ill->ill_name));
		} else {
			mutex_exit(&ill->ill_lock);
		}
		freemsg(mp);
		break;
	}
	default:
		ASSERT(0);
		break;
	}
}

/*
 * Update any source route, record route or timestamp options
 * When it fails it has consumed the message and BUMPed the MIB.
 */
boolean_t
ip_forward_options(mblk_t *mp, ipha_t *ipha, ill_t *dst_ill,
    ip_recv_attr_t *ira)
{
	ipoptp_t	opts;
	uchar_t		*opt;
	uint8_t		optval;
	uint8_t		optlen;
	ipaddr_t	dst;
	ipaddr_t	ifaddr;
	uint32_t	ts;
	timestruc_t	now;
	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;

	ip2dbg(("ip_forward_options\n"));
	dst = ipha->ipha_dst;
	opt = NULL;

	for (optval = ipoptp_first(&opts, ipha);
	    optval != IPOPT_EOL;
	    optval = ipoptp_next(&opts)) {
		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
		opt = opts.ipoptp_cur;
		optlen = opts.ipoptp_len;
		ip2dbg(("ip_forward_options: opt %d, len %d\n",
		    optval, opts.ipoptp_len));
		switch (optval) {
			uint32_t off;
		case IPOPT_SSRR:
		case IPOPT_LSRR:
			/* Check if adminstratively disabled */
			if (!ipst->ips_ip_forward_src_routed) {
				BUMP_MIB(dst_ill->ill_ip_mib,
				    ipIfStatsForwProhibits);
				ip_drop_input("ICMP_SOURCE_ROUTE_FAILED",
				    mp, dst_ill);
				icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED,
				    ira);
				return (B_FALSE);
			}
			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
				/*
				 * Must be partial since ip_input_options
				 * checked for strict.
				 */
				break;
			}
			off = opt[IPOPT_OFFSET];
			off--;
		redo_srr:
			if (optlen < IP_ADDR_LEN ||
			    off > optlen - IP_ADDR_LEN) {
				/* End of source route */
				ip1dbg((
				    "ip_forward_options: end of SR\n"));
				break;
			}
			/* Pick a reasonable address on the outbound if */
			ASSERT(dst_ill != NULL);
			if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
			    NULL) != 0) {
				/* No source! Shouldn't happen */
				ifaddr = INADDR_ANY;
			}
			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
			ip1dbg(("ip_forward_options: next hop 0x%x\n",
			    ntohl(dst)));

			/*
			 * Check if our address is present more than
			 * once as consecutive hops in source route.
			 */
			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
				off += IP_ADDR_LEN;
				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
				goto redo_srr;
			}
			ipha->ipha_dst = dst;
			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
			break;
		case IPOPT_RR:
			off = opt[IPOPT_OFFSET];
			off--;
			if (optlen < IP_ADDR_LEN ||
			    off > optlen - IP_ADDR_LEN) {
				/* No more room - ignore */
				ip1dbg((
				    "ip_forward_options: end of RR\n"));
				break;
			}
			/* Pick a reasonable address on the outbound if */
			ASSERT(dst_ill != NULL);
			if (ip_select_source_v4(dst_ill, INADDR_ANY, dst,
			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
			    NULL) != 0) {
				/* No source! Shouldn't happen */
				ifaddr = INADDR_ANY;
			}
			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
			break;
		case IPOPT_TS:
			off = 0;
			/* Insert timestamp if there is room */
			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
			case IPOPT_TS_TSONLY:
				off = IPOPT_TS_TIMELEN;
				break;
			case IPOPT_TS_PRESPEC:
			case IPOPT_TS_PRESPEC_RFC791:
				/* Verify that the address matched */
				off = opt[IPOPT_OFFSET] - 1;
				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
					/* Not for us */
					break;
				}
				/* FALLTHROUGH */
			case IPOPT_TS_TSANDADDR:
				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
				break;
			default:
				/*
				 * ip_*put_options should have already
				 * dropped this packet.
				 */
				cmn_err(CE_PANIC, "ip_forward_options: "
				    "unknown IT - bug in ip_input_options?\n");
			}
			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
				/* Increase overflow counter */
				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
				opt[IPOPT_POS_OV_FLG] =
				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
				    (off << 4));
				break;
			}
			off = opt[IPOPT_OFFSET] - 1;
			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
			case IPOPT_TS_PRESPEC:
			case IPOPT_TS_PRESPEC_RFC791:
			case IPOPT_TS_TSANDADDR:
				/* Pick a reasonable addr on the outbound if */
				ASSERT(dst_ill != NULL);
				if (ip_select_source_v4(dst_ill, INADDR_ANY,
				    dst, INADDR_ANY, ALL_ZONES, ipst, &ifaddr,
				    NULL, NULL) != 0) {
					/* No source! Shouldn't happen */
					ifaddr = INADDR_ANY;
				}
				bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
				/* FALLTHROUGH */
			case IPOPT_TS_TSONLY:
				off = opt[IPOPT_OFFSET] - 1;
				/* Compute # of milliseconds since midnight */
				gethrestime(&now);
				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
				    NSEC2MSEC(now.tv_nsec);
				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
				break;
			}
			break;
		}
	}
	return (B_TRUE);
}

/*
 * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
 * returns 'true' if there are still fragments left on the queue, in
 * which case we restart the timer.
 */
void
ill_frag_timer(void *arg)
{
	ill_t	*ill = (ill_t *)arg;
	boolean_t frag_pending;
	ip_stack_t *ipst = ill->ill_ipst;
	time_t	timeout;

	mutex_enter(&ill->ill_lock);
	ASSERT(!ill->ill_fragtimer_executing);
	if (ill->ill_state_flags & ILL_CONDEMNED) {
		ill->ill_frag_timer_id = 0;
		mutex_exit(&ill->ill_lock);
		return;
	}
	ill->ill_fragtimer_executing = 1;
	mutex_exit(&ill->ill_lock);

	timeout = (ill->ill_isv6 ? ipst->ips_ipv6_reassembly_timeout :
	    ipst->ips_ip_reassembly_timeout);

	frag_pending = ill_frag_timeout(ill, timeout);

	/*
	 * Restart the timer, if we have fragments pending or if someone
	 * wanted us to be scheduled again.
	 */
	mutex_enter(&ill->ill_lock);
	ill->ill_fragtimer_executing = 0;
	ill->ill_frag_timer_id = 0;
	if (frag_pending || ill->ill_fragtimer_needrestart)
		ill_frag_timer_start(ill);
	mutex_exit(&ill->ill_lock);
}

void
ill_frag_timer_start(ill_t *ill)
{
	ip_stack_t *ipst = ill->ill_ipst;
	clock_t	timeo_ms;

	ASSERT(MUTEX_HELD(&ill->ill_lock));

	/* If the ill is closing or opening don't proceed */
	if (ill->ill_state_flags & ILL_CONDEMNED)
		return;

	if (ill->ill_fragtimer_executing) {
		/*
		 * ill_frag_timer is currently executing. Just record the
		 * the fact that we want the timer to be restarted.
		 * ill_frag_timer will post a timeout before it returns,
		 * ensuring it will be called again.
		 */
		ill->ill_fragtimer_needrestart = 1;
		return;
	}

	if (ill->ill_frag_timer_id == 0) {
		timeo_ms = (ill->ill_isv6 ? ipst->ips_ipv6_reassembly_timeout :
		    ipst->ips_ip_reassembly_timeout) * SECONDS;

		/*
		 * The timer is neither running nor is the timeout handler
		 * executing. Post a timeout so that ill_frag_timer will be
		 * called
		 */
		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
		    MSEC_TO_TICK(timeo_ms >> 1));
		ill->ill_fragtimer_needrestart = 0;
	}
}

/*
 * Update any source route, record route or timestamp options.
 * Check that we are at end of strict source route.
 * The options have already been checked for sanity in ip_input_options().
 */
boolean_t
ip_input_local_options(mblk_t *mp, ipha_t *ipha, ip_recv_attr_t *ira)
{
	ipoptp_t	opts;
	uchar_t		*opt;
	uint8_t		optval;
	uint8_t		optlen;
	ipaddr_t	dst;
	ipaddr_t	ifaddr;
	uint32_t	ts;
	timestruc_t	now;
	ill_t		*ill = ira->ira_ill;
	ip_stack_t	*ipst = ill->ill_ipst;

	ip2dbg(("ip_input_local_options\n"));
	opt = NULL;

	for (optval = ipoptp_first(&opts, ipha);
	    optval != IPOPT_EOL;
	    optval = ipoptp_next(&opts)) {
		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
		opt = opts.ipoptp_cur;
		optlen = opts.ipoptp_len;
		ip2dbg(("ip_input_local_options: opt %d, len %d\n",
		    optval, optlen));
		switch (optval) {
			uint32_t off;
		case IPOPT_SSRR:
		case IPOPT_LSRR:
			off = opt[IPOPT_OFFSET];
			off--;
			if (optlen < IP_ADDR_LEN ||
			    off > optlen - IP_ADDR_LEN) {
				/* End of source route */
				ip1dbg(("ip_input_local_options: end of SR\n"));
				break;
			}
			/*
			 * This will only happen if two consecutive entries
			 * in the source route contains our address or if
			 * it is a packet with a loose source route which
			 * reaches us before consuming the whole source route
			 */
			ip1dbg(("ip_input_local_options: not end of SR\n"));
			if (optval == IPOPT_SSRR) {
				goto bad_src_route;
			}
			/*
			 * Hack: instead of dropping the packet truncate the
			 * source route to what has been used by filling the
			 * rest with IPOPT_NOP.
			 */
			opt[IPOPT_OLEN] = (uint8_t)off;
			while (off < optlen) {
				opt[off++] = IPOPT_NOP;
			}
			break;
		case IPOPT_RR:
			off = opt[IPOPT_OFFSET];
			off--;
			if (optlen < IP_ADDR_LEN ||
			    off > optlen - IP_ADDR_LEN) {
				/* No more room - ignore */
				ip1dbg((
				    "ip_input_local_options: end of RR\n"));
				break;
			}
			/* Pick a reasonable address on the outbound if */
			if (ip_select_source_v4(ill, INADDR_ANY, ipha->ipha_dst,
			    INADDR_ANY, ALL_ZONES, ipst, &ifaddr, NULL,
			    NULL) != 0) {
				/* No source! Shouldn't happen */
				ifaddr = INADDR_ANY;
			}
			bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
			break;
		case IPOPT_TS:
			off = 0;
			/* Insert timestamp if there is romm */
			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
			case IPOPT_TS_TSONLY:
				off = IPOPT_TS_TIMELEN;
				break;
			case IPOPT_TS_PRESPEC:
			case IPOPT_TS_PRESPEC_RFC791:
				/* Verify that the address matched */
				off = opt[IPOPT_OFFSET] - 1;
				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
					/* Not for us */
					break;
				}
				/* FALLTHROUGH */
			case IPOPT_TS_TSANDADDR:
				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
				break;
			default:
				/*
				 * ip_*put_options should have already
				 * dropped this packet.
				 */
				cmn_err(CE_PANIC, "ip_input_local_options: "
				    "unknown IT - bug in ip_input_options?\n");
			}
			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
				/* Increase overflow counter */
				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
				opt[IPOPT_POS_OV_FLG] =
				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
				    (off << 4));
				break;
			}
			off = opt[IPOPT_OFFSET] - 1;
			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
			case IPOPT_TS_PRESPEC:
			case IPOPT_TS_PRESPEC_RFC791:
			case IPOPT_TS_TSANDADDR:
				/* Pick a reasonable addr on the outbound if */
				if (ip_select_source_v4(ill, INADDR_ANY,
				    ipha->ipha_dst, INADDR_ANY, ALL_ZONES, ipst,
				    &ifaddr, NULL, NULL) != 0) {
					/* No source! Shouldn't happen */
					ifaddr = INADDR_ANY;
				}
				bcopy(&ifaddr, (char *)opt + off, IP_ADDR_LEN);
				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
				/* FALLTHROUGH */
			case IPOPT_TS_TSONLY:
				off = opt[IPOPT_OFFSET] - 1;
				/* Compute # of milliseconds since midnight */
				gethrestime(&now);
				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
				    NSEC2MSEC(now.tv_nsec);
				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
				break;
			}
			break;
		}
	}
	return (B_TRUE);

bad_src_route:
	/* make sure we clear any indication of a hardware checksum */
	DB_CKSUMFLAGS(mp) = 0;
	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
	return (B_FALSE);

}

/*
 * Process IP options in an inbound packet.  Always returns the nexthop.
 * Normally this is the passed in nexthop, but if there is an option
 * that effects the nexthop (such as a source route) that will be returned.
 * Sets *errorp if there is an error, in which case an ICMP error has been sent
 * and mp freed.
 */
ipaddr_t
ip_input_options(ipha_t *ipha, ipaddr_t dst, mblk_t *mp,
    ip_recv_attr_t *ira, int *errorp)
{
	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
	ipoptp_t	opts;
	uchar_t		*opt;
	uint8_t		optval;
	uint8_t		optlen;
	intptr_t	code = 0;
	ire_t		*ire;

	ip2dbg(("ip_input_options\n"));
	opt = NULL;
	*errorp = 0;
	for (optval = ipoptp_first(&opts, ipha);
	    optval != IPOPT_EOL;
	    optval = ipoptp_next(&opts)) {
		opt = opts.ipoptp_cur;
		optlen = opts.ipoptp_len;
		ip2dbg(("ip_input_options: opt %d, len %d\n",
		    optval, optlen));
		/*
		 * Note: we need to verify the checksum before we
		 * modify anything thus this routine only extracts the next
		 * hop dst from any source route.
		 */
		switch (optval) {
			uint32_t off;
		case IPOPT_SSRR:
		case IPOPT_LSRR:
			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
				if (optval == IPOPT_SSRR) {
					ip1dbg(("ip_input_options: not next"
					    " strict source route 0x%x\n",
					    ntohl(dst)));
					code = (char *)&ipha->ipha_dst -
					    (char *)ipha;
					goto param_prob; /* RouterReq's */
				}
				ip2dbg(("ip_input_options: "
				    "not next source route 0x%x\n",
				    ntohl(dst)));
				break;
			}

			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
				ip1dbg((
				    "ip_input_options: bad option offset\n"));
				code = (char *)&opt[IPOPT_OLEN] -
				    (char *)ipha;
				goto param_prob;
			}
			off = opt[IPOPT_OFFSET];
			off--;
		redo_srr:
			if (optlen < IP_ADDR_LEN ||
			    off > optlen - IP_ADDR_LEN) {
				/* End of source route */
				ip1dbg(("ip_input_options: end of SR\n"));
				break;
			}
			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
			ip1dbg(("ip_input_options: next hop 0x%x\n",
			    ntohl(dst)));

			/*
			 * Check if our address is present more than
			 * once as consecutive hops in source route.
			 * XXX verify per-interface ip_forwarding
			 * for source route?
			 */
			if (ip_type_v4(dst, ipst) == IRE_LOCAL) {
				off += IP_ADDR_LEN;
				goto redo_srr;
			}

			if (dst == htonl(INADDR_LOOPBACK)) {
				ip1dbg(("ip_input_options: loopback addr in "
				    "source route!\n"));
				goto bad_src_route;
			}
			/*
			 * For strict: verify that dst is directly
			 * reachable.
			 */
			if (optval == IPOPT_SSRR) {
				ire = ire_ftable_lookup_v4(dst, 0, 0,
				    IRE_INTERFACE, NULL, ALL_ZONES,
				    ira->ira_tsl,
				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
				    NULL);
				if (ire == NULL) {
					ip1dbg(("ip_input_options: SSRR not "
					    "directly reachable: 0x%x\n",
					    ntohl(dst)));
					goto bad_src_route;
				}
				ire_refrele(ire);
			}
			/*
			 * Defer update of the offset and the record route
			 * until the packet is forwarded.
			 */
			break;
		case IPOPT_RR:
			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
				ip1dbg((
				    "ip_input_options: bad option offset\n"));
				code = (char *)&opt[IPOPT_OLEN] -
				    (char *)ipha;
				goto param_prob;
			}
			break;
		case IPOPT_TS:
			/*
			 * Verify that length >= 5 and that there is either
			 * room for another timestamp or that the overflow
			 * counter is not maxed out.
			 */
			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
			if (optlen < IPOPT_MINLEN_IT) {
				goto param_prob;
			}
			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
				ip1dbg((
				    "ip_input_options: bad option offset\n"));
				code = (char *)&opt[IPOPT_OFFSET] -
				    (char *)ipha;
				goto param_prob;
			}
			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
			case IPOPT_TS_TSONLY:
				off = IPOPT_TS_TIMELEN;
				break;
			case IPOPT_TS_TSANDADDR:
			case IPOPT_TS_PRESPEC:
			case IPOPT_TS_PRESPEC_RFC791:
				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
				break;
			default:
				code = (char *)&opt[IPOPT_POS_OV_FLG] -
				    (char *)ipha;
				goto param_prob;
			}
			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
				/*
				 * No room and the overflow counter is 15
				 * already.
				 */
				goto param_prob;
			}
			break;
		}
	}

	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
		return (dst);
	}

	ip1dbg(("ip_input_options: error processing IP options."));
	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;

param_prob:
	/* make sure we clear any indication of a hardware checksum */
	DB_CKSUMFLAGS(mp) = 0;
	ip_drop_input("ICMP_PARAM_PROBLEM", mp, ira->ira_ill);
	icmp_param_problem(mp, (uint8_t)code, ira);
	*errorp = -1;
	return (dst);

bad_src_route:
	/* make sure we clear any indication of a hardware checksum */
	DB_CKSUMFLAGS(mp) = 0;
	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ira->ira_ill);
	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, ira);
	*errorp = -1;
	return (dst);
}

/*
 * IP & ICMP info in >=14 msg's ...
 *  - ip fixed part (mib2_ip_t)
 *  - icmp fixed part (mib2_icmp_t)
 *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
 *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
 *  - ipNetToMediaEntryTable (ip 22)	all IPv4 Neighbor Cache entries
 *  - ipRouteAttributeTable (ip 102)	labeled routes
 *  - ip multicast membership (ip_member_t)
 *  - ip multicast source filtering (ip_grpsrc_t)
 *  - igmp fixed part (struct igmpstat)
 *  - multicast routing stats (struct mrtstat)
 *  - multicast routing vifs (array of struct vifctl)
 *  - multicast routing routes (array of struct mfcctl)
 *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
 *					One per ill plus one generic
 *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
 *					One per ill plus one generic
 *  - ipv6RouteEntry			all IPv6 IREs
 *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
 *  - ipv6NetToMediaEntry		all IPv6 Neighbor Cache entries
 *  - ipv6AddrEntry			all IPv6 ipifs
 *  - ipv6 multicast membership (ipv6_member_t)
 *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
 *
 * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
 * already filled in by the caller.
 * If legacy_req is true then MIB structures needs to be truncated to their
 * legacy sizes before being returned.
 * Return value of 0 indicates that no messages were sent and caller
 * should free mpctl.
 */
int
ip_snmp_get(queue_t *q, mblk_t *mpctl, int level, boolean_t legacy_req)
{
	ip_stack_t *ipst;
	sctp_stack_t *sctps;

	if (q->q_next != NULL) {
		ipst = ILLQ_TO_IPST(q);
	} else {
		ipst = CONNQ_TO_IPST(q);
	}
	ASSERT(ipst != NULL);
	sctps = ipst->ips_netstack->netstack_sctp;

	if (mpctl == NULL || mpctl->b_cont == NULL) {
		return (0);
	}

	/*
	 * For the purposes of the (broken) packet shell use
	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
	 * to make TCP and UDP appear first in the list of mib items.
	 * TBD: We could expand this and use it in netstat so that
	 * the kernel doesn't have to produce large tables (connections,
	 * routes, etc) when netstat only wants the statistics or a particular
	 * table.
	 */
	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
			return (1);
		}
	}

	if (level != MIB2_TCP) {
		if ((mpctl = udp_snmp_get(q, mpctl, legacy_req)) == NULL) {
			return (1);
		}
		if (level == MIB2_UDP) {
			goto done;
		}
	}

	if (level != MIB2_UDP) {
		if ((mpctl = tcp_snmp_get(q, mpctl, legacy_req)) == NULL) {
			return (1);
		}
		if (level == MIB2_TCP) {
			goto done;
		}
	}

	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
	    ipst, legacy_req)) == NULL) {
		return (1);
	}

	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst,
	    legacy_req)) == NULL) {
		return (1);
	}

	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
		return (1);
	}

	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
		return (1);
	}

	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
		return (1);
	}

	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
		return (1);
	}

	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst,
	    legacy_req)) == NULL) {
		return (1);
	}

	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst,
	    legacy_req)) == NULL) {
		return (1);
	}

	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
		return (1);
	}

	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
		return (1);
	}

	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
		return (1);
	}

	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
		return (1);
	}

	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
		return (1);
	}

	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
		return (1);
	}

	mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, level, ipst);
	if (mpctl == NULL)
		return (1);

	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, level, ipst);
	if (mpctl == NULL)
		return (1);

	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
		return (1);
	}
	if ((mpctl = ip_snmp_get_mib2_ip_dce(q, mpctl, ipst)) == NULL) {
		return (1);
	}
done:
	freemsg(mpctl);
	return (1);
}

/* Get global (legacy) IPv4 statistics */
static mblk_t *
ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
    ip_stack_t *ipst, boolean_t legacy_req)
{
	mib2_ip_t		old_ip_mib;
	struct opthdr		*optp;
	mblk_t			*mp2ctl;
	mib2_ipAddrEntry_t	mae;

	/*
	 * make a copy of the original message
	 */
	mp2ctl = copymsg(mpctl);

	/* fixed length IP structure... */
	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
	optp->level = MIB2_IP;
	optp->name = 0;
	SET_MIB(old_ip_mib.ipForwarding,
	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
	SET_MIB(old_ip_mib.ipDefaultTTL,
	    (uint32_t)ipst->ips_ip_def_ttl);
	SET_MIB(old_ip_mib.ipReasmTimeout,
	    ipst->ips_ip_reassembly_timeout);
	SET_MIB(old_ip_mib.ipAddrEntrySize,
	    (legacy_req) ? LEGACY_MIB_SIZE(&mae, mib2_ipAddrEntry_t) :
	    sizeof (mib2_ipAddrEntry_t));
	SET_MIB(old_ip_mib.ipRouteEntrySize,
	    sizeof (mib2_ipRouteEntry_t));
	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
	    sizeof (mib2_ipNetToMediaEntry_t));
	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
	SET_MIB(old_ip_mib.ipRouteAttributeSize,
	    sizeof (mib2_ipAttributeEntry_t));
	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
	SET_MIB(old_ip_mib.ipDestEntrySize, sizeof (dest_cache_entry_t));

	/*
	 * Grab the statistics from the new IP MIB
	 */
	SET_MIB(old_ip_mib.ipInReceives,
	    (uint32_t)ipmib->ipIfStatsHCInReceives);
	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
	SET_MIB(old_ip_mib.ipForwDatagrams,
	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
	SET_MIB(old_ip_mib.ipInUnknownProtos,
	    ipmib->ipIfStatsInUnknownProtos);
	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
	SET_MIB(old_ip_mib.ipInDelivers,
	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
	SET_MIB(old_ip_mib.ipOutRequests,
	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);

	/* ipRoutingDiscards is not being used */
	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
	SET_MIB(old_ip_mib.ipReasmDuplicates,
	    ipmib->ipIfStatsReasmDuplicates);
	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
	SET_MIB(old_ip_mib.rawipInOverflows,
	    ipmib->rawipIfStatsInOverflows);

	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
	    ipmib->ipIfStatsOutSwitchIPVersion);

	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
	    (int)sizeof (old_ip_mib))) {
		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
		    (uint_t)sizeof (old_ip_mib)));
	}

	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
	    (int)optp->level, (int)optp->name, (int)optp->len));
	qreply(q, mpctl);
	return (mp2ctl);
}

/* Per interface IPv4 statistics */
static mblk_t *
ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
    boolean_t legacy_req)
{
	struct opthdr		*optp;
	mblk_t			*mp2ctl;
	ill_t			*ill;
	ill_walk_context_t	ctx;
	mblk_t			*mp_tail = NULL;
	mib2_ipIfStatsEntry_t	global_ip_mib;
	mib2_ipAddrEntry_t	mae;

	/*
	 * Make a copy of the original message
	 */
	mp2ctl = copymsg(mpctl);

	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
	optp->level = MIB2_IP;
	optp->name = MIB2_IP_TRAFFIC_STATS;
	/* Include "unknown interface" ip_mib */
	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
	ipst->ips_ip_mib.ipIfStatsIfIndex =
	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
	    (ipst->ips_ip_forwarding ? 1 : 2));
	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
	    (uint32_t)ipst->ips_ip_def_ttl);
	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
	    sizeof (mib2_ipIfStatsEntry_t));
	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
	    sizeof (mib2_ipAddrEntry_t));
	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
	    sizeof (mib2_ipRouteEntry_t));
	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
	    sizeof (mib2_ipNetToMediaEntry_t));
	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
	    sizeof (ip_member_t));
	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
	    sizeof (ip_grpsrc_t));

	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));

	if (legacy_req) {
		SET_MIB(global_ip_mib.ipIfStatsAddrEntrySize,
		    LEGACY_MIB_SIZE(&mae, mib2_ipAddrEntry_t));
	}

	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
	    (char *)&global_ip_mib, (int)sizeof (global_ip_mib))) {
		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
		    "failed to allocate %u bytes\n",
		    (uint_t)sizeof (global_ip_mib)));
	}

	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
	ill = ILL_START_WALK_V4(&ctx, ipst);
	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
		ill->ill_ip_mib->ipIfStatsIfIndex =
		    ill->ill_phyint->phyint_ifindex;
		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
		    (ipst->ips_ip_forwarding ? 1 : 2));
		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
		    (uint32_t)ipst->ips_ip_def_ttl);

		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
		    (char *)ill->ill_ip_mib,
		    (int)sizeof (*ill->ill_ip_mib))) {
			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
			    "failed to allocate %u bytes\n",
			    (uint_t)sizeof (*ill->ill_ip_mib)));
		}
	}
	rw_exit(&ipst->ips_ill_g_lock);

	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
	    "level %d, name %d, len %d\n",
	    (int)optp->level, (int)optp->name, (int)optp->len));
	qreply(q, mpctl);

	if (mp2ctl == NULL)
		return (NULL);

	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst,
	    legacy_req));
}

/* Global IPv4 ICMP statistics */
static mblk_t *
ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
{
	struct opthdr		*optp;
	mblk_t			*mp2ctl;

	/*
	 * Make a copy of the original message
	 */
	mp2ctl = copymsg(mpctl);

	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
	optp->level = MIB2_ICMP;
	optp->name = 0;
	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
	    (int)sizeof (ipst->ips_icmp_mib))) {
		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
		    (uint_t)sizeof (ipst->ips_icmp_mib)));
	}
	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
	    (int)optp->level, (int)optp->name, (int)optp->len));
	qreply(q, mpctl);
	return (mp2ctl);
}

/* Global IPv4 IGMP statistics */
static mblk_t *
ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
{
	struct opthdr		*optp;
	mblk_t			*mp2ctl;

	/*
	 * make a copy of the original message
	 */
	mp2ctl = copymsg(mpctl);

	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
	optp->level = EXPER_IGMP;
	optp->name = 0;
	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
	    (int)sizeof (ipst->ips_igmpstat))) {
		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
		    (uint_t)sizeof (ipst->ips_igmpstat)));
	}
	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
	    (int)optp->level, (int)optp->name, (int)optp->len));
	qreply(q, mpctl);
	return (mp2ctl);
}

/* Global IPv4 Multicast Routing statistics */
static mblk_t *
ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
{
	struct opthdr		*optp;
	mblk_t			*mp2ctl;

	/*
	 * make a copy of the original message
	 */
	mp2ctl = copymsg(mpctl);

	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
	optp->level = EXPER_DVMRP;
	optp->name = 0;
	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
		ip0dbg(("ip_mroute_stats: failed\n"));
	}
	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
	    (int)optp->level, (int)optp->name, (int)optp->len));
	qreply(q, mpctl);
	return (mp2ctl);
}

/* IPv4 address information */
static mblk_t *
ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
    boolean_t legacy_req)
{
	struct opthdr		*optp;
	mblk_t			*mp2ctl;
	mblk_t			*mp_tail = NULL;
	ill_t			*ill;
	ipif_t			*ipif;
	uint_t			bitval;
	mib2_ipAddrEntry_t	mae;
	size_t			mae_size;
	zoneid_t		zoneid;
	ill_walk_context_t	ctx;

	/*
	 * make a copy of the original message
	 */
	mp2ctl = copymsg(mpctl);

	mae_size = (legacy_req) ? LEGACY_MIB_SIZE(&mae, mib2_ipAddrEntry_t) :
	    sizeof (mib2_ipAddrEntry_t);

	/* ipAddrEntryTable */

	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
	optp->level = MIB2_IP;
	optp->name = MIB2_IP_ADDR;
	zoneid = Q_TO_CONN(q)->conn_zoneid;

	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
	ill = ILL_START_WALK_V4(&ctx, ipst);
	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
		for (ipif = ill->ill_ipif; ipif != NULL;
		    ipif = ipif->ipif_next) {
			if (ipif->ipif_zoneid != zoneid &&
			    ipif->ipif_zoneid != ALL_ZONES)
				continue;
			/* Sum of count from dead IRE_LO* and our current */
			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
			if (ipif->ipif_ire_local != NULL) {
				mae.ipAdEntInfo.ae_ibcnt +=
				    ipif->ipif_ire_local->ire_ib_pkt_count;
			}
			mae.ipAdEntInfo.ae_obcnt = 0;
			mae.ipAdEntInfo.ae_focnt = 0;

			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
			    OCTET_LENGTH);
			mae.ipAdEntIfIndex.o_length =
			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
			mae.ipAdEntNetMask = ipif->ipif_net_mask;
			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
			mae.ipAdEntInfo.ae_subnet_len =
			    ip_mask_to_plen(ipif->ipif_net_mask);
			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_lcl_addr;
			for (bitval = 1;
			    bitval &&
			    !(bitval & ipif->ipif_brd_addr);
			    bitval <<= 1)
				noop;
			mae.ipAdEntBcastAddr = bitval;
			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
			mae.ipAdEntInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
			mae.ipAdEntInfo.ae_metric  = ipif->ipif_ill->ill_metric;
			mae.ipAdEntInfo.ae_broadcast_addr =
			    ipif->ipif_brd_addr;
			mae.ipAdEntInfo.ae_pp_dst_addr =
			    ipif->ipif_pp_dst_addr;
			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
			    ill->ill_flags | ill->ill_phyint->phyint_flags;
			mae.ipAdEntRetransmitTime =
			    ill->ill_reachable_retrans_time;

			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
			    (char *)&mae, (int)mae_size)) {
				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
				    "allocate %u bytes\n", (uint_t)mae_size));
			}
		}
	}
	rw_exit(&ipst->ips_ill_g_lock);

	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
	    (int)optp->level, (int)optp->name, (int)optp->len));
	qreply(q, mpctl);
	return (mp2ctl);
}

/* IPv6 address information */
static mblk_t *
ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
    boolean_t legacy_req)
{
	struct opthdr		*optp;
	mblk_t			*mp2ctl;
	mblk_t			*mp_tail = NULL;
	ill_t			*ill;
	ipif_t			*ipif;
	mib2_ipv6AddrEntry_t	mae6;
	size_t			mae6_size;
	zoneid_t		zoneid;
	ill_walk_context_t	ctx;

	/*
	 * make a copy of the original message
	 */
	mp2ctl = copymsg(mpctl);

	mae6_size = (legacy_req) ?
	    LEGACY_MIB_SIZE(&mae6, mib2_ipv6AddrEntry_t) :
	    sizeof (mib2_ipv6AddrEntry_t);

	/* ipv6AddrEntryTable */

	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
	optp->level = MIB2_IP6;
	optp->name = MIB2_IP6_ADDR;
	zoneid = Q_TO_CONN(q)->conn_zoneid;

	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
	ill = ILL_START_WALK_V6(&ctx, ipst);
	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
		for (ipif = ill->ill_ipif; ipif != NULL;
		    ipif = ipif->ipif_next) {
			if (ipif->ipif_zoneid != zoneid &&
			    ipif->ipif_zoneid != ALL_ZONES)
				continue;
			/* Sum of count from dead IRE_LO* and our current */
			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
			if (ipif->ipif_ire_local != NULL) {
				mae6.ipv6AddrInfo.ae_ibcnt +=
				    ipif->ipif_ire_local->ire_ib_pkt_count;
			}
			mae6.ipv6AddrInfo.ae_obcnt = 0;
			mae6.ipv6AddrInfo.ae_focnt = 0;

			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
			    OCTET_LENGTH);
			mae6.ipv6AddrIfIndex.o_length =
			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
			mae6.ipv6AddrPfxLength =
			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
			mae6.ipv6AddrInfo.ae_subnet_len =
			    mae6.ipv6AddrPfxLength;
			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6lcl_addr;

			/* Type: stateless(1), stateful(2), unknown(3) */
			if (ipif->ipif_flags & IPIF_ADDRCONF)
				mae6.ipv6AddrType = 1;
			else
				mae6.ipv6AddrType = 2;
			/* Anycast: true(1), false(2) */
			if (ipif->ipif_flags & IPIF_ANYCAST)
				mae6.ipv6AddrAnycastFlag = 1;
			else
				mae6.ipv6AddrAnycastFlag = 2;

			/*
			 * Address status: preferred(1), deprecated(2),
			 * invalid(3), inaccessible(4), unknown(5)
			 */
			if (ipif->ipif_flags & IPIF_NOLOCAL)
				mae6.ipv6AddrStatus = 3;
			else if (ipif->ipif_flags & IPIF_DEPRECATED)
				mae6.ipv6AddrStatus = 2;
			else
				mae6.ipv6AddrStatus = 1;
			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_ill->ill_mtu;
			mae6.ipv6AddrInfo.ae_metric  =
			    ipif->ipif_ill->ill_metric;
			mae6.ipv6AddrInfo.ae_pp_dst_addr =
			    ipif->ipif_v6pp_dst_addr;
			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
			    ill->ill_flags | ill->ill_phyint->phyint_flags;
			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
			mae6.ipv6AddrIdentifier = ill->ill_token;
			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
			mae6.ipv6AddrRetransmitTime =
			    ill->ill_reachable_retrans_time;
			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
			    (char *)&mae6, (int)mae6_size)) {
				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
				    "allocate %u bytes\n",
				    (uint_t)mae6_size));
			}
		}
	}
	rw_exit(&ipst->ips_ill_g_lock);

	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
	    (int)optp->level, (int)optp->name, (int)optp->len));
	qreply(q, mpctl);
	return (mp2ctl);
}

/* IPv4 multicast group membership. */
static mblk_t *
ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
{
	struct opthdr		*optp;
	mblk_t			*mp2ctl;
	ill_t			*ill;
	ipif_t			*ipif;
	ilm_t			*ilm;
	ip_member_t		ipm;
	mblk_t			*mp_tail = NULL;
	ill_walk_context_t	ctx;
	zoneid_t		zoneid;

	/*
	 * make a copy of the original message
	 */
	mp2ctl = copymsg(mpctl);
	zoneid = Q_TO_CONN(q)->conn_zoneid;

	/* ipGroupMember table */
	optp = (struct opthdr *)&mpctl->b_rptr[
	    sizeof (struct T_optmgmt_ack)];
	optp->level = MIB2_IP;
	optp->name = EXPER_IP_GROUP_MEMBERSHIP;

	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
	ill = ILL_START_WALK_V4(&ctx, ipst);
	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
		/* Make sure the ill isn't going away. */
		if (!ill_check_and_refhold(ill))
			continue;
		rw_exit(&ipst->ips_ill_g_lock);
		rw_enter(&ill->ill_mcast_lock, RW_READER);
		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
			if (ilm->ilm_zoneid != zoneid &&
			    ilm->ilm_zoneid != ALL_ZONES)
				continue;

			/* Is there an ipif for ilm_ifaddr? */
			for (ipif = ill->ill_ipif; ipif != NULL;
			    ipif = ipif->ipif_next) {
				if (!IPIF_IS_CONDEMNED(ipif) &&
				    ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
				    ilm->ilm_ifaddr != INADDR_ANY)
					break;
			}
			if (ipif != NULL) {
				ipif_get_name(ipif,
				    ipm.ipGroupMemberIfIndex.o_bytes,
				    OCTET_LENGTH);
			} else {
				ill_get_name(ill,
				    ipm.ipGroupMemberIfIndex.o_bytes,
				    OCTET_LENGTH);
			}
			ipm.ipGroupMemberIfIndex.o_length =
			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);

			ipm.ipGroupMemberAddress = ilm->ilm_addr;
			ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
			ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
			    (char *)&ipm, (int)sizeof (ipm))) {
				ip1dbg(("ip_snmp_get_mib2_ip_group: "
				    "failed to allocate %u bytes\n",
				    (uint_t)sizeof (ipm)));
			}
		}
		rw_exit(&ill->ill_mcast_lock);
		ill_refrele(ill);
		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
	}
	rw_exit(&ipst->ips_ill_g_lock);
	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
	    (int)optp->level, (int)optp->name, (int)optp->len));
	qreply(q, mpctl);
	return (mp2ctl);
}

/* IPv6 multicast group membership. */
static mblk_t *
ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
{
	struct opthdr		*optp;
	mblk_t			*mp2ctl;
	ill_t			*ill;
	ilm_t			*ilm;
	ipv6_member_t		ipm6;
	mblk_t			*mp_tail = NULL;
	ill_walk_context_t	ctx;
	zoneid_t		zoneid;

	/*
	 * make a copy of the original message
	 */
	mp2ctl = copymsg(mpctl);
	zoneid = Q_TO_CONN(q)->conn_zoneid;

	/* ip6GroupMember table */
	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
	optp->level = MIB2_IP6;
	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;

	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
	ill = ILL_START_WALK_V6(&ctx, ipst);
	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
		/* Make sure the ill isn't going away. */
		if (!ill_check_and_refhold(ill))
			continue;
		rw_exit(&ipst->ips_ill_g_lock);
		/*
		 * Normally we don't have any members on under IPMP interfaces.
		 * We report them as a debugging aid.
		 */
		rw_enter(&ill->ill_mcast_lock, RW_READER);
		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
			if (ilm->ilm_zoneid != zoneid &&
			    ilm->ilm_zoneid != ALL_ZONES)
				continue;	/* not this zone */
			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
			if (!snmp_append_data2(mpctl->b_cont,
			    &mp_tail,
			    (char *)&ipm6, (int)sizeof (ipm6))) {
				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
				    "failed to allocate %u bytes\n",
				    (uint_t)sizeof (ipm6)));
			}
		}
		rw_exit(&ill->ill_mcast_lock);
		ill_refrele(ill);
		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
	}
	rw_exit(&ipst->ips_ill_g_lock);

	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
	    (int)optp->level, (int)optp->name, (int)optp->len));
	qreply(q, mpctl);
	return (mp2ctl);
}

/* IP multicast filtered sources */
static mblk_t *
ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
{
	struct opthdr		*optp;
	mblk_t			*mp2ctl;
	ill_t			*ill;
	ipif_t			*ipif;
	ilm_t			*ilm;
	ip_grpsrc_t		ips;
	mblk_t			*mp_tail = NULL;
	ill_walk_context_t	ctx;
	zoneid_t		zoneid;
	int			i;
	slist_t			*sl;

	/*
	 * make a copy of the original message
	 */
	mp2ctl = copymsg(mpctl);
	zoneid = Q_TO_CONN(q)->conn_zoneid;

	/* ipGroupSource table */
	optp = (struct opthdr *)&mpctl->b_rptr[
	    sizeof (struct T_optmgmt_ack)];
	optp->level = MIB2_IP;
	optp->name = EXPER_IP_GROUP_SOURCES;

	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
	ill = ILL_START_WALK_V4(&ctx, ipst);
	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
		/* Make sure the ill isn't going away. */
		if (!ill_check_and_refhold(ill))
			continue;
		rw_exit(&ipst->ips_ill_g_lock);
		rw_enter(&ill->ill_mcast_lock, RW_READER);
		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
			sl = ilm->ilm_filter;
			if (ilm->ilm_zoneid != zoneid &&
			    ilm->ilm_zoneid != ALL_ZONES)
				continue;
			if (SLIST_IS_EMPTY(sl))
				continue;

			/* Is there an ipif for ilm_ifaddr? */
			for (ipif = ill->ill_ipif; ipif != NULL;
			    ipif = ipif->ipif_next) {
				if (!IPIF_IS_CONDEMNED(ipif) &&
				    ipif->ipif_lcl_addr == ilm->ilm_ifaddr &&
				    ilm->ilm_ifaddr != INADDR_ANY)
					break;
			}
			if (ipif != NULL) {
				ipif_get_name(ipif,
				    ips.ipGroupSourceIfIndex.o_bytes,
				    OCTET_LENGTH);
			} else {
				ill_get_name(ill,
				    ips.ipGroupSourceIfIndex.o_bytes,
				    OCTET_LENGTH);
			}
			ips.ipGroupSourceIfIndex.o_length =
			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);

			ips.ipGroupSourceGroup = ilm->ilm_addr;
			for (i = 0; i < sl->sl_numsrc; i++) {
				if (!IN6_IS_ADDR_V4MAPPED(&sl->sl_addr[i]))
					continue;
				IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
				    ips.ipGroupSourceAddress);
				if (snmp_append_data2(mpctl->b_cont, &mp_tail,
				    (char *)&ips, (int)sizeof (ips)) == 0) {
					ip1dbg(("ip_snmp_get_mib2_ip_group_src:"
					    " failed to allocate %u bytes\n",
					    (uint_t)sizeof (ips)));
				}
			}
		}
		rw_exit(&ill->ill_mcast_lock);
		ill_refrele(ill);
		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
	}
	rw_exit(&ipst->ips_ill_g_lock);
	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
	    (int)optp->level, (int)optp->name, (int)optp->len));
	qreply(q, mpctl);
	return (mp2ctl);
}

/* IPv6 multicast filtered sources. */
static mblk_t *
ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
{
	struct opthdr		*optp;
	mblk_t			*mp2ctl;
	ill_t			*ill;
	ilm_t			*ilm;
	ipv6_grpsrc_t		ips6;
	mblk_t			*mp_tail = NULL;
	ill_walk_context_t	ctx;
	zoneid_t		zoneid;
	int			i;
	slist_t			*sl;

	/*
	 * make a copy of the original message
	 */
	mp2ctl = copymsg(mpctl);
	zoneid = Q_TO_CONN(q)->conn_zoneid;

	/* ip6GroupMember table */
	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
	optp->level = MIB2_IP6;
	optp->name = EXPER_IP6_GROUP_SOURCES;

	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
	ill = ILL_START_WALK_V6(&ctx, ipst);
	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
		/* Make sure the ill isn't going away. */
		if (!ill_check_and_refhold(ill))
			continue;
		rw_exit(&ipst->ips_ill_g_lock);
		/*
		 * Normally we don't have any members on under IPMP interfaces.
		 * We report them as a debugging aid.
		 */
		rw_enter(&ill->ill_mcast_lock, RW_READER);
		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
			sl = ilm->ilm_filter;
			if (ilm->ilm_zoneid != zoneid &&
			    ilm->ilm_zoneid != ALL_ZONES)
				continue;
			if (SLIST_IS_EMPTY(sl))
				continue;
			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
			for (i = 0; i < sl->sl_numsrc; i++) {
				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
				    (char *)&ips6, (int)sizeof (ips6))) {
					ip1dbg(("ip_snmp_get_mib2_ip6_"
					    "group_src: failed to allocate "
					    "%u bytes\n",
					    (uint_t)sizeof (ips6)));
				}
			}
		}
		rw_exit(&ill->ill_mcast_lock);
		ill_refrele(ill);
		rw_enter(&ipst->ips_ill_g_lock, RW_READER);
	}
	rw_exit(&ipst->ips_ill_g_lock);

	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
	    (int)optp->level, (int)optp->name, (int)optp->len));
	qreply(q, mpctl);
	return (mp2ctl);
}

/* Multicast routing virtual interface table. */
static mblk_t *
ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
{
	struct opthdr		*optp;
	mblk_t			*mp2ctl;

	/*
	 * make a copy of the original message
	 */
	mp2ctl = copymsg(mpctl);

	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
	optp->level = EXPER_DVMRP;
	optp->name = EXPER_DVMRP_VIF;
	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
		ip0dbg(("ip_mroute_vif: failed\n"));
	}
	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
	    (int)optp->level, (int)optp->name, (int)optp->len));
	qreply(q, mpctl);
	return (mp2ctl);
}

/* Multicast routing table. */
static mblk_t *
ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
{
	struct opthdr		*optp;
	mblk_t			*mp2ctl;

	/*
	 * make a copy of the original message
	 */
	mp2ctl = copymsg(mpctl);

	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
	optp->level = EXPER_DVMRP;
	optp->name = EXPER_DVMRP_MRT;
	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
		ip0dbg(("ip_mroute_mrt: failed\n"));
	}
	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
	    (int)optp->level, (int)optp->name, (int)optp->len));
	qreply(q, mpctl);
	return (mp2ctl);
}

/*
 * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
 * in one IRE walk.
 */
static mblk_t *
ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, int level,
    ip_stack_t *ipst)
{
	struct opthdr	*optp;
	mblk_t		*mp2ctl;	/* Returned */
	mblk_t		*mp3ctl;	/* nettomedia */
	mblk_t		*mp4ctl;	/* routeattrs */
	iproutedata_t	ird;
	zoneid_t	zoneid;

	/*
	 * make copies of the original message
	 *	- mp2ctl is returned unchanged to the caller for its use
	 *	- mpctl is sent upstream as ipRouteEntryTable
	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
	 */
	mp2ctl = copymsg(mpctl);
	mp3ctl = copymsg(mpctl);
	mp4ctl = copymsg(mpctl);
	if (mp3ctl == NULL || mp4ctl == NULL) {
		freemsg(mp4ctl);
		freemsg(mp3ctl);
		freemsg(mp2ctl);
		freemsg(mpctl);
		return (NULL);
	}

	bzero(&ird, sizeof (ird));

	ird.ird_route.lp_head = mpctl->b_cont;
	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
	ird.ird_attrs.lp_head = mp4ctl->b_cont;
	/*
	 * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
	 * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
	 * intended a temporary solution until a proper MIB API is provided
	 * that provides complete filtering/caller-opt-in.
	 */
	if (level == EXPER_IP_AND_ALL_IRES)
		ird.ird_flags |= IRD_REPORT_ALL;

	zoneid = Q_TO_CONN(q)->conn_zoneid;
	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);

	/* ipRouteEntryTable in mpctl */
	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
	optp->level = MIB2_IP;
	optp->name = MIB2_IP_ROUTE;
	optp->len = msgdsize(ird.ird_route.lp_head);
	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
	    (int)optp->level, (int)optp->name, (int)optp->len));
	qreply(q, mpctl);

	/* ipNetToMediaEntryTable in mp3ctl */
	ncec_walk(NULL, ip_snmp_get2_v4_media, &ird, ipst);

	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
	optp->level = MIB2_IP;
	optp->name = MIB2_IP_MEDIA;
	optp->len = msgdsize(ird.ird_netmedia.lp_head);
	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
	    (int)optp->level, (int)optp->name, (int)optp->len));
	qreply(q, mp3ctl);

	/* ipRouteAttributeTable in mp4ctl */
	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
	optp->level = MIB2_IP;
	optp->name = EXPER_IP_RTATTR;
	optp->len = msgdsize(ird.ird_attrs.lp_head);
	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
	    (int)optp->level, (int)optp->name, (int)optp->len));
	if (optp->len == 0)
		freemsg(mp4ctl);
	else
		qreply(q, mp4ctl);

	return (mp2ctl);
}

/*
 * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
 * ipv6NetToMediaEntryTable in an NDP walk.
 */
static mblk_t *
ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, int level,
    ip_stack_t *ipst)
{
	struct opthdr	*optp;
	mblk_t		*mp2ctl;	/* Returned */
	mblk_t		*mp3ctl;	/* nettomedia */
	mblk_t		*mp4ctl;	/* routeattrs */
	iproutedata_t	ird;
	zoneid_t	zoneid;

	/*
	 * make copies of the original message
	 *	- mp2ctl is returned unchanged to the caller for its use
	 *	- mpctl is sent upstream as ipv6RouteEntryTable
	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
	 */
	mp2ctl = copymsg(mpctl);
	mp3ctl = copymsg(mpctl);
	mp4ctl = copymsg(mpctl);
	if (mp3ctl == NULL || mp4ctl == NULL) {
		freemsg(mp4ctl);
		freemsg(mp3ctl);
		freemsg(mp2ctl);
		freemsg(mpctl);
		return (NULL);
	}

	bzero(&ird, sizeof (ird));

	ird.ird_route.lp_head = mpctl->b_cont;
	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
	ird.ird_attrs.lp_head = mp4ctl->b_cont;
	/*
	 * If the level has been set the special EXPER_IP_AND_ALL_IRES value,
	 * then also include ire_testhidden IREs and IRE_IF_CLONE.  This is
	 * intended a temporary solution until a proper MIB API is provided
	 * that provides complete filtering/caller-opt-in.
	 */
	if (level == EXPER_IP_AND_ALL_IRES)
		ird.ird_flags |= IRD_REPORT_ALL;

	zoneid = Q_TO_CONN(q)->conn_zoneid;
	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);

	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
	optp->level = MIB2_IP6;
	optp->name = MIB2_IP6_ROUTE;
	optp->len = msgdsize(ird.ird_route.lp_head);
	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
	    (int)optp->level, (int)optp->name, (int)optp->len));
	qreply(q, mpctl);

	/* ipv6NetToMediaEntryTable in mp3ctl */
	ncec_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);

	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
	optp->level = MIB2_IP6;
	optp->name = MIB2_IP6_MEDIA;
	optp->len = msgdsize(ird.ird_netmedia.lp_head);
	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
	    (int)optp->level, (int)optp->name, (int)optp->len));
	qreply(q, mp3ctl);

	/* ipv6RouteAttributeTable in mp4ctl */
	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
	optp->level = MIB2_IP6;
	optp->name = EXPER_IP_RTATTR;
	optp->len = msgdsize(ird.ird_attrs.lp_head);
	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
	    (int)optp->level, (int)optp->name, (int)optp->len));
	if (optp->len == 0)
		freemsg(mp4ctl);
	else
		qreply(q, mp4ctl);

	return (mp2ctl);
}

/*
 * IPv6 mib: One per ill
 */
static mblk_t *
ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst,
    boolean_t legacy_req)
{
	struct opthdr		*optp;
	mblk_t			*mp2ctl;
	ill_t			*ill;
	ill_walk_context_t	ctx;
	mblk_t			*mp_tail = NULL;
	mib2_ipv6AddrEntry_t	mae6;
	mib2_ipIfStatsEntry_t	*ise;
	size_t			ise_size, iae_size;

	/*
	 * Make a copy of the original message
	 */
	mp2ctl = copymsg(mpctl);

	/* fixed length IPv6 structure ... */

	if (legacy_req) {
		ise_size = LEGACY_MIB_SIZE(&ipst->ips_ip6_mib,
		    mib2_ipIfStatsEntry_t);
		iae_size = LEGACY_MIB_SIZE(&mae6, mib2_ipv6AddrEntry_t);
	} else {
		ise_size = sizeof (mib2_ipIfStatsEntry_t);
		iae_size = sizeof (mib2_ipv6AddrEntry_t);
	}

	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
	optp->level = MIB2_IP6;
	optp->name = 0;
	/* Include "unknown interface" ip6_mib */
	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
	ipst->ips_ip6_mib.ipIfStatsIfIndex =
	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
	    ipst->ips_ipv6_forwarding ? 1 : 2);
	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
	    ipst->ips_ipv6_def_hops);
	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
	    sizeof (mib2_ipIfStatsEntry_t));
	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
	    sizeof (mib2_ipv6AddrEntry_t));
	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
	    sizeof (mib2_ipv6RouteEntry_t));
	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
	    sizeof (mib2_ipv6NetToMediaEntry_t));
	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
	    sizeof (ipv6_member_t));
	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
	    sizeof (ipv6_grpsrc_t));

	/*
	 * Synchronize 64- and 32-bit counters
	 */
	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
	    ipIfStatsHCInReceives);
	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
	    ipIfStatsHCInDelivers);
	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
	    ipIfStatsHCOutRequests);
	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
	    ipIfStatsHCOutForwDatagrams);
	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
	    ipIfStatsHCOutMcastPkts);
	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
	    ipIfStatsHCInMcastPkts);

	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
	    (char *)&ipst->ips_ip6_mib, (int)ise_size)) {
		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
		    (uint_t)ise_size));
	} else if (legacy_req) {
		/* Adjust the EntrySize fields for legacy requests. */
		ise =
		    (mib2_ipIfStatsEntry_t *)(mp_tail->b_wptr - (int)ise_size);
		SET_MIB(ise->ipIfStatsEntrySize, ise_size);
		SET_MIB(ise->ipIfStatsAddrEntrySize, iae_size);
	}

	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
	ill = ILL_START_WALK_V6(&ctx, ipst);
	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
		ill->ill_ip_mib->ipIfStatsIfIndex =
		    ill->ill_phyint->phyint_ifindex;
		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
		    ipst->ips_ipv6_forwarding ? 1 : 2);
		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
		    ill->ill_max_hops);

		/*
		 * Synchronize 64- and 32-bit counters
		 */
		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
		    ipIfStatsHCInReceives);
		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
		    ipIfStatsHCInDelivers);
		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
		    ipIfStatsHCOutRequests);
		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
		    ipIfStatsHCOutForwDatagrams);
		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
		    ipIfStatsHCOutMcastPkts);
		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
		    ipIfStatsHCInMcastPkts);

		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
		    (char *)ill->ill_ip_mib, (int)ise_size)) {
			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
			"%u bytes\n", (uint_t)ise_size));
		} else if (legacy_req) {
			/* Adjust the EntrySize fields for legacy requests. */
			ise = (mib2_ipIfStatsEntry_t *)(mp_tail->b_wptr -
			    (int)ise_size);
			SET_MIB(ise->ipIfStatsEntrySize, ise_size);
			SET_MIB(ise->ipIfStatsAddrEntrySize, iae_size);
		}
	}
	rw_exit(&ipst->ips_ill_g_lock);

	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
	    (int)optp->level, (int)optp->name, (int)optp->len));
	qreply(q, mpctl);
	return (mp2ctl);
}

/*
 * ICMPv6 mib: One per ill
 */
static mblk_t *
ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
{
	struct opthdr		*optp;
	mblk_t			*mp2ctl;
	ill_t			*ill;
	ill_walk_context_t	ctx;
	mblk_t			*mp_tail = NULL;
	/*
	 * Make a copy of the original message
	 */
	mp2ctl = copymsg(mpctl);

	/* fixed length ICMPv6 structure ... */

	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
	optp->level = MIB2_ICMP6;
	optp->name = 0;
	/* Include "unknown interface" icmp6_mib */
	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
	    sizeof (mib2_ipv6IfIcmpEntry_t);
	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
	    (char *)&ipst->ips_icmp6_mib,
	    (int)sizeof (ipst->ips_icmp6_mib))) {
		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
	}

	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
	ill = ILL_START_WALK_V6(&ctx, ipst);
	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
		    ill->ill_phyint->phyint_ifindex;
		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
		    (char *)ill->ill_icmp6_mib,
		    (int)sizeof (*ill->ill_icmp6_mib))) {
			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
			    "%u bytes\n",
			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
		}
	}
	rw_exit(&ipst->ips_ill_g_lock);

	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
	    (int)optp->level, (int)optp->name, (int)optp->len));
	qreply(q, mpctl);
	return (mp2ctl);
}

/*
 * ire_walk routine to create both ipRouteEntryTable and
 * ipRouteAttributeTable in one IRE walk
 */
static void
ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
{
	ill_t				*ill;
	mib2_ipRouteEntry_t		*re;
	mib2_ipAttributeEntry_t		iaes;
	tsol_ire_gw_secattr_t		*attrp;
	tsol_gc_t			*gc = NULL;
	tsol_gcgrp_t			*gcgrp = NULL;
	ip_stack_t			*ipst = ire->ire_ipst;

	ASSERT(ire->ire_ipversion == IPV4_VERSION);

	if (!(ird->ird_flags & IRD_REPORT_ALL)) {
		if (ire->ire_testhidden)
			return;
		if (ire->ire_type & IRE_IF_CLONE)
			return;
	}

	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
		return;

	if ((attrp = ire->ire_gw_secattr) != NULL) {
		mutex_enter(&attrp->igsa_lock);
		if ((gc = attrp->igsa_gc) != NULL) {
			gcgrp = gc->gc_grp;
			ASSERT(gcgrp != NULL);
			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
		}
		mutex_exit(&attrp->igsa_lock);
	}
	/*
	 * Return all IRE types for route table... let caller pick and choose
	 */
	re->ipRouteDest = ire->ire_addr;
	ill = ire->ire_ill;
	re->ipRouteIfIndex.o_length = 0;
	if (ill != NULL) {
		ill_get_name(ill, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
		re->ipRouteIfIndex.o_length =
		    mi_strlen(re->ipRouteIfIndex.o_bytes);
	}
	re->ipRouteMetric1 = -1;
	re->ipRouteMetric2 = -1;
	re->ipRouteMetric3 = -1;
	re->ipRouteMetric4 = -1;

	re->ipRouteNextHop = ire->ire_gateway_addr;
	/* indirect(4), direct(3), or invalid(2) */
	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
		re->ipRouteType = 2;
	else if (ire->ire_type & IRE_ONLINK)
		re->ipRouteType = 3;
	else
		re->ipRouteType = 4;

	re->ipRouteProto = -1;
	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
	re->ipRouteMask = ire->ire_mask;
	re->ipRouteMetric5 = -1;
	re->ipRouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
	if (ire->ire_ill != NULL && re->ipRouteInfo.re_max_frag == 0)
		re->ipRouteInfo.re_max_frag = ire->ire_ill->ill_mtu;

	re->ipRouteInfo.re_frag_flag	= 0;
	re->ipRouteInfo.re_rtt		= 0;
	re->ipRouteInfo.re_src_addr	= 0;
	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
	re->ipRouteInfo.re_flags	= ire->ire_flags;

	/* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
	if (ire->ire_type & IRE_INTERFACE) {
		ire_t *child;

		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
		child = ire->ire_dep_children;
		while (child != NULL) {
			re->ipRouteInfo.re_obpkt += child->ire_ob_pkt_count;
			re->ipRouteInfo.re_ibpkt += child->ire_ib_pkt_count;
			child = child->ire_dep_sib_next;
		}
		rw_exit(&ipst->ips_ire_dep_lock);
	}

	if (ire->ire_flags & RTF_DYNAMIC) {
		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
	} else {
		re->ipRouteInfo.re_ire_type	= ire->ire_type;
	}

	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
	    (char *)re, (int)sizeof (*re))) {
		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
		    (uint_t)sizeof (*re)));
	}

	if (gc != NULL) {
		iaes.iae_routeidx = ird->ird_idx;
		iaes.iae_doi = gc->gc_db->gcdb_doi;
		iaes.iae_slrange = gc->gc_db->gcdb_slrange;

		if (!snmp_append_data2(ird->ird_attrs.lp_head,
		    &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
			ip1dbg(("ip_snmp_get2_v4: failed to allocate %u "
			    "bytes\n", (uint_t)sizeof (iaes)));
		}
	}

	/* bump route index for next pass */
	ird->ird_idx++;

	kmem_free(re, sizeof (*re));
	if (gcgrp != NULL)
		rw_exit(&gcgrp->gcgrp_rwlock);
}

/*
 * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
 */
static void
ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
{
	ill_t				*ill;
	mib2_ipv6RouteEntry_t		*re;
	mib2_ipAttributeEntry_t		iaes;
	tsol_ire_gw_secattr_t		*attrp;
	tsol_gc_t			*gc = NULL;
	tsol_gcgrp_t			*gcgrp = NULL;
	ip_stack_t			*ipst = ire->ire_ipst;

	ASSERT(ire->ire_ipversion == IPV6_VERSION);

	if (!(ird->ird_flags & IRD_REPORT_ALL)) {
		if (ire->ire_testhidden)
			return;
		if (ire->ire_type & IRE_IF_CLONE)
			return;
	}

	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
		return;

	if ((attrp = ire->ire_gw_secattr) != NULL) {
		mutex_enter(&attrp->igsa_lock);
		if ((gc = attrp->igsa_gc) != NULL) {
			gcgrp = gc->gc_grp;
			ASSERT(gcgrp != NULL);
			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
		}
		mutex_exit(&attrp->igsa_lock);
	}
	/*
	 * Return all IRE types for route table... let caller pick and choose
	 */
	re->ipv6RouteDest = ire->ire_addr_v6;
	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
	re->ipv6RouteIfIndex.o_length = 0;
	ill = ire->ire_ill;
	if (ill != NULL) {
		ill_get_name(ill, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
		re->ipv6RouteIfIndex.o_length =
		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
	}

	ASSERT(!(ire->ire_type & IRE_BROADCAST));

	mutex_enter(&ire->ire_lock);
	re->ipv6RouteNextHop = ire->ire_gateway_addr_v6;
	mutex_exit(&ire->ire_lock);

	/* remote(4), local(3), or discard(2) */
	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
		re->ipv6RouteType = 2;
	else if (ire->ire_type & IRE_ONLINK)
		re->ipv6RouteType = 3;
	else
		re->ipv6RouteType = 4;

	re->ipv6RouteProtocol	= -1;
	re->ipv6RoutePolicy	= 0;
	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
	re->ipv6RouteNextHopRDI	= 0;
	re->ipv6RouteWeight	= 0;
	re->ipv6RouteMetric	= 0;
	re->ipv6RouteInfo.re_max_frag = ire->ire_metrics.iulp_mtu;
	if (ire->ire_ill != NULL && re->ipv6RouteInfo.re_max_frag == 0)
		re->ipv6RouteInfo.re_max_frag = ire->ire_ill->ill_mtu;

	re->ipv6RouteInfo.re_frag_flag	= 0;
	re->ipv6RouteInfo.re_rtt	= 0;
	re->ipv6RouteInfo.re_src_addr	= ipv6_all_zeros;
	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
	re->ipv6RouteInfo.re_flags	= ire->ire_flags;

	/* Add the IRE_IF_CLONE's counters to their parent IRE_INTERFACE */
	if (ire->ire_type & IRE_INTERFACE) {
		ire_t *child;

		rw_enter(&ipst->ips_ire_dep_lock, RW_READER);
		child = ire->ire_dep_children;
		while (child != NULL) {
			re->ipv6RouteInfo.re_obpkt += child->ire_ob_pkt_count;
			re->ipv6RouteInfo.re_ibpkt += child->ire_ib_pkt_count;
			child = child->ire_dep_sib_next;
		}
		rw_exit(&ipst->ips_ire_dep_lock);
	}
	if (ire->ire_flags & RTF_DYNAMIC) {
		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
	} else {
		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
	}

	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
	    (char *)re, (int)sizeof (*re))) {
		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
		    (uint_t)sizeof (*re)));
	}

	if (gc != NULL) {
		iaes.iae_routeidx = ird->ird_idx;
		iaes.iae_doi = gc->gc_db->gcdb_doi;
		iaes.iae_slrange = gc->gc_db->gcdb_slrange;

		if (!snmp_append_data2(ird->ird_attrs.lp_head,
		    &ird->ird_attrs.lp_tail, (char *)&iaes, sizeof (iaes))) {
			ip1dbg(("ip_snmp_get2_v6: failed to allocate %u "
			    "bytes\n", (uint_t)sizeof (iaes)));
		}
	}

	/* bump route index for next pass */
	ird->ird_idx++;

	kmem_free(re, sizeof (*re));
	if (gcgrp != NULL)
		rw_exit(&gcgrp->gcgrp_rwlock);
}

/*
 * ncec_walk routine to create ipv6NetToMediaEntryTable
 */
static void
ip_snmp_get2_v6_media(ncec_t *ncec, void *ptr)
{
	iproutedata_t *ird		= ptr;
	ill_t				*ill;
	mib2_ipv6NetToMediaEntry_t	ntme;

	ill = ncec->ncec_ill;
	/* skip arpce entries, and loopback ncec entries */
	if (ill->ill_isv6 == B_FALSE || ill->ill_net_type == IRE_LOOPBACK)
		return;
	/*
	 * Neighbor cache entry attached to IRE with on-link
	 * destination.
	 * We report all IPMP groups on ncec_ill which is normally the upper.
	 */
	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
	ntme.ipv6NetToMediaNetAddress = ncec->ncec_addr;
	ntme.ipv6NetToMediaPhysAddress.o_length = ill->ill_phys_addr_length;
	if (ncec->ncec_lladdr != NULL) {
		bcopy(ncec->ncec_lladdr, ntme.ipv6NetToMediaPhysAddress.o_bytes,
		    ntme.ipv6NetToMediaPhysAddress.o_length);
	}
	/*
	 * Note: Returns ND_* states. Should be:
	 * reachable(1), stale(2), delay(3), probe(4),
	 * invalid(5), unknown(6)
	 */
	ntme.ipv6NetToMediaState = ncec->ncec_state;
	ntme.ipv6NetToMediaLastUpdated = 0;

	/* other(1), dynamic(2), static(3), local(4) */
	if (NCE_MYADDR(ncec)) {
		ntme.ipv6NetToMediaType = 4;
	} else if (ncec->ncec_flags & NCE_F_PUBLISH) {
		ntme.ipv6NetToMediaType = 1; /* proxy */
	} else if (ncec->ncec_flags & NCE_F_STATIC) {
		ntme.ipv6NetToMediaType = 3;
	} else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST)) {
		ntme.ipv6NetToMediaType = 1;
	} else {
		ntme.ipv6NetToMediaType = 2;
	}

	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
		    (uint_t)sizeof (ntme)));
	}
}

int
nce2ace(ncec_t *ncec)
{
	int flags = 0;

	if (NCE_ISREACHABLE(ncec))
		flags |= ACE_F_RESOLVED;
	if (ncec->ncec_flags & NCE_F_AUTHORITY)
		flags |= ACE_F_AUTHORITY;
	if (ncec->ncec_flags & NCE_F_PUBLISH)
		flags |= ACE_F_PUBLISH;
	if ((ncec->ncec_flags & NCE_F_NONUD) != 0)
		flags |= ACE_F_PERMANENT;
	if (NCE_MYADDR(ncec))
		flags |= (ACE_F_MYADDR | ACE_F_AUTHORITY);
	if (ncec->ncec_flags & NCE_F_UNVERIFIED)
		flags |= ACE_F_UNVERIFIED;
	if (ncec->ncec_flags & NCE_F_AUTHORITY)
		flags |= ACE_F_AUTHORITY;
	if (ncec->ncec_flags & NCE_F_DELAYED)
		flags |= ACE_F_DELAYED;
	return (flags);
}

/*
 * ncec_walk routine to create ipNetToMediaEntryTable
 */
static void
ip_snmp_get2_v4_media(ncec_t *ncec, void *ptr)
{
	iproutedata_t *ird		= ptr;
	ill_t				*ill;
	mib2_ipNetToMediaEntry_t	ntme;
	const char			*name = "unknown";
	ipaddr_t			ncec_addr;

	ill = ncec->ncec_ill;
	if (ill->ill_isv6 || (ncec->ncec_flags & NCE_F_BCAST) ||
	    ill->ill_net_type == IRE_LOOPBACK)
		return;

	/* We report all IPMP groups on ncec_ill which is normally the upper. */
	name = ill->ill_name;
	/* Based on RFC 4293: other(1), inval(2), dyn(3), stat(4) */
	if (NCE_MYADDR(ncec)) {
		ntme.ipNetToMediaType = 4;
	} else if (ncec->ncec_flags & (NCE_F_MCAST|NCE_F_BCAST|NCE_F_PUBLISH)) {
		ntme.ipNetToMediaType = 1;
	} else {
		ntme.ipNetToMediaType = 3;
	}
	ntme.ipNetToMediaIfIndex.o_length = MIN(OCTET_LENGTH, strlen(name));
	bcopy(name, ntme.ipNetToMediaIfIndex.o_bytes,
	    ntme.ipNetToMediaIfIndex.o_length);

	IN6_V4MAPPED_TO_IPADDR(&ncec->ncec_addr, ncec_addr);
	bcopy(&ncec_addr, &ntme.ipNetToMediaNetAddress, sizeof (ncec_addr));

	ntme.ipNetToMediaInfo.ntm_mask.o_length = sizeof (ipaddr_t);
	ncec_addr = INADDR_BROADCAST;
	bcopy(&ncec_addr, ntme.ipNetToMediaInfo.ntm_mask.o_bytes,
	    sizeof (ncec_addr));
	/*
	 * map all the flags to the ACE counterpart.
	 */
	ntme.ipNetToMediaInfo.ntm_flags = nce2ace(ncec);

	ntme.ipNetToMediaPhysAddress.o_length =
	    MIN(OCTET_LENGTH, ill->ill_phys_addr_length);

	if (!NCE_ISREACHABLE(ncec))
		ntme.ipNetToMediaPhysAddress.o_length = 0;
	else {
		if (ncec->ncec_lladdr != NULL) {
			bcopy(ncec->ncec_lladdr,
			    ntme.ipNetToMediaPhysAddress.o_bytes,
			    ntme.ipNetToMediaPhysAddress.o_length);
		}
	}

	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
		ip1dbg(("ip_snmp_get2_v4_media: failed to allocate %u bytes\n",
		    (uint_t)sizeof (ntme)));
	}
}

/*
 * return (0) if invalid set request, 1 otherwise, including non-tcp requests
 */
/* ARGSUSED */
int
ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
{
	switch (level) {
	case MIB2_IP:
	case MIB2_ICMP:
		switch (name) {
		default:
			break;
		}
		return (1);
	default:
		return (1);
	}
}

/*
 * When there exists both a 64- and 32-bit counter of a particular type
 * (i.e., InReceives), only the 64-bit counters are added.
 */
void
ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
{
	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
	    o2->ipIfStatsInWrongIPVersion);
	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
	    o2->ipIfStatsInWrongIPVersion);
	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
	    o2->ipIfStatsOutSwitchIPVersion);
	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
	    o2->ipIfStatsHCInForwDatagrams);
	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
	    o2->ipIfStatsHCOutForwDatagrams);
	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
	    o2->ipIfStatsHCOutMcastOctets);
	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
}

void
ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
{
	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
	    o2->ipv6IfIcmpInRouterSolicits);
	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
	    o2->ipv6IfIcmpInRouterAdvertisements);
	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
	    o2->ipv6IfIcmpInNeighborSolicits);
	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
	    o2->ipv6IfIcmpInNeighborAdvertisements);
	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
	    o2->ipv6IfIcmpInGroupMembQueries);
	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
	    o2->ipv6IfIcmpInGroupMembResponses);
	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
	    o2->ipv6IfIcmpInGroupMembReductions);
	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
	    o2->ipv6IfIcmpOutDestUnreachs);
	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
	    o2->ipv6IfIcmpOutAdminProhibs);
	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
	    o2->ipv6IfIcmpOutParmProblems);
	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
	    o2->ipv6IfIcmpOutRouterSolicits);
	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
	    o2->ipv6IfIcmpOutRouterAdvertisements);
	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
	    o2->ipv6IfIcmpOutNeighborSolicits);
	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
	    o2->ipv6IfIcmpOutNeighborAdvertisements);
	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
	    o2->ipv6IfIcmpOutGroupMembQueries);
	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
	    o2->ipv6IfIcmpOutGroupMembResponses);
	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
	    o2->ipv6IfIcmpOutGroupMembReductions);
	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
	    o2->ipv6IfIcmpInBadNeighborSolicitations);
	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
	    o2->ipv6IfIcmpInGroupMembTotal);
	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
	    o2->ipv6IfIcmpInGroupMembBadQueries);
	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
	    o2->ipv6IfIcmpInGroupMembBadReports);
	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
	    o2->ipv6IfIcmpInGroupMembOurReports);
}

/*
 * Called before the options are updated to check if this packet will
 * be source routed from here.
 * This routine assumes that the options are well formed i.e. that they
 * have already been checked.
 */
boolean_t
ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
{
	ipoptp_t	opts;
	uchar_t		*opt;
	uint8_t		optval;
	uint8_t		optlen;
	ipaddr_t	dst;

	if (IS_SIMPLE_IPH(ipha)) {
		ip2dbg(("not source routed\n"));
		return (B_FALSE);
	}
	dst = ipha->ipha_dst;
	for (optval = ipoptp_first(&opts, ipha);
	    optval != IPOPT_EOL;
	    optval = ipoptp_next(&opts)) {
		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
		opt = opts.ipoptp_cur;
		optlen = opts.ipoptp_len;
		ip2dbg(("ip_source_routed: opt %d, len %d\n",
		    optval, optlen));
		switch (optval) {
			uint32_t off;
		case IPOPT_SSRR:
		case IPOPT_LSRR:
			/*
			 * If dst is one of our addresses and there are some
			 * entries left in the source route return (true).
			 */
			if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
				ip2dbg(("ip_source_routed: not next"
				    " source route 0x%x\n",
				    ntohl(dst)));
				return (B_FALSE);
			}
			off = opt[IPOPT_OFFSET];
			off--;
			if (optlen < IP_ADDR_LEN ||
			    off > optlen - IP_ADDR_LEN) {
				/* End of source route */
				ip1dbg(("ip_source_routed: end of SR\n"));
				return (B_FALSE);
			}
			return (B_TRUE);
		}
	}
	ip2dbg(("not source routed\n"));
	return (B_FALSE);
}

/*
 * ip_unbind is called by the transports to remove a conn from
 * the fanout table.
 */
void
ip_unbind(conn_t *connp)
{

	ASSERT(!MUTEX_HELD(&connp->conn_lock));

	if (is_system_labeled() && connp->conn_anon_port) {
		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
		    connp->conn_mlp_type, connp->conn_proto,
		    ntohs(connp->conn_lport), B_FALSE);
		connp->conn_anon_port = 0;
	}
	connp->conn_mlp_type = mlptSingle;

	ipcl_hash_remove(connp);
}

/*
 * Used for deciding the MSS size for the upper layer. Thus
 * we need to check the outbound policy values in the conn.
 */
int
conn_ipsec_length(conn_t *connp)
{
	ipsec_latch_t *ipl;

	ipl = connp->conn_latch;
	if (ipl == NULL)
		return (0);

	if (connp->conn_ixa->ixa_ipsec_policy == NULL)
		return (0);

	return (connp->conn_ixa->ixa_ipsec_policy->ipsp_act->ipa_ovhd);
}

/*
 * Returns an estimate of the IPsec headers size. This is used if
 * we don't want to call into IPsec to get the exact size.
 */
int
ipsec_out_extra_length(ip_xmit_attr_t *ixa)
{
	ipsec_action_t *a;

	if (!(ixa->ixa_flags & IXAF_IPSEC_SECURE))
		return (0);

	a = ixa->ixa_ipsec_action;
	if (a == NULL) {
		ASSERT(ixa->ixa_ipsec_policy != NULL);
		a = ixa->ixa_ipsec_policy->ipsp_act;
	}
	ASSERT(a != NULL);

	return (a->ipa_ovhd);
}

/*
 * If there are any source route options, return the true final
 * destination. Otherwise, return the destination.
 */
ipaddr_t
ip_get_dst(ipha_t *ipha)
{
	ipoptp_t	opts;
	uchar_t		*opt;
	uint8_t		optval;
	uint8_t		optlen;
	ipaddr_t	dst;
	uint32_t off;

	dst = ipha->ipha_dst;

	if (IS_SIMPLE_IPH(ipha))
		return (dst);

	for (optval = ipoptp_first(&opts, ipha);
	    optval != IPOPT_EOL;
	    optval = ipoptp_next(&opts)) {
		opt = opts.ipoptp_cur;
		optlen = opts.ipoptp_len;
		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
		switch (optval) {
		case IPOPT_SSRR:
		case IPOPT_LSRR:
			off = opt[IPOPT_OFFSET];
			/*
			 * If one of the conditions is true, it means
			 * end of options and dst already has the right
			 * value.
			 */
			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
				off = optlen - IP_ADDR_LEN;
				bcopy(&opt[off], &dst, IP_ADDR_LEN);
			}
			return (dst);
		default:
			break;
		}
	}

	return (dst);
}

/*
 * Outbound IP fragmentation routine.
 * Assumes the caller has checked whether or not fragmentation should
 * be allowed. Here we copy the DF bit from the header to all the generated
 * fragments.
 */
int
ip_fragment_v4(mblk_t *mp_orig, nce_t *nce, iaflags_t ixaflags,
    uint_t pkt_len, uint32_t max_frag, uint32_t xmit_hint, zoneid_t szone,
    zoneid_t nolzid, pfirepostfrag_t postfragfn, uintptr_t *ixa_cookie)
{
	int		i1;
	int		hdr_len;
	mblk_t		*hdr_mp;
	ipha_t		*ipha;
	int		ip_data_end;
	int		len;
	mblk_t		*mp = mp_orig;
	int		offset;
	ill_t		*ill = nce->nce_ill;
	ip_stack_t	*ipst = ill->ill_ipst;
	mblk_t		*carve_mp;
	uint32_t	frag_flag;
	uint_t		priority = mp->b_band;
	int		error = 0;

	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragReqds);

	if (pkt_len != msgdsize(mp)) {
		ip0dbg(("Packet length mismatch: %d, %ld\n",
		    pkt_len, msgdsize(mp)));
		freemsg(mp);
		return (EINVAL);
	}

	if (max_frag == 0) {
		ip1dbg(("ip_fragment_v4: max_frag is zero. Dropping packet\n"));
		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
		ip_drop_output("FragFails: zero max_frag", mp, ill);
		freemsg(mp);
		return (EINVAL);
	}

	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
	ipha = (ipha_t *)mp->b_rptr;
	ASSERT(ntohs(ipha->ipha_length) == pkt_len);
	frag_flag = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_DF;

	/*
	 * Establish the starting offset.  May not be zero if we are fragging
	 * a fragment that is being forwarded.
	 */
	offset = ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET;

	/* TODO why is this test needed? */
	if (((max_frag - ntohs(ipha->ipha_length)) & ~7) < 8) {
		/* TODO: notify ulp somehow */
		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
		ip_drop_output("FragFails: bad starting offset", mp, ill);
		freemsg(mp);
		return (EINVAL);
	}

	hdr_len = IPH_HDR_LENGTH(ipha);
	ipha->ipha_hdr_checksum = 0;

	/*
	 * Establish the number of bytes maximum per frag, after putting
	 * in the header.
	 */
	len = (max_frag - hdr_len) & ~7;

	/* Get a copy of the header for the trailing frags */
	hdr_mp = ip_fragment_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst,
	    mp);
	if (hdr_mp == NULL) {
		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
		ip_drop_output("FragFails: no hdr_mp", mp, ill);
		freemsg(mp);
		return (ENOBUFS);
	}

	/* Store the starting offset, with the MoreFrags flag. */
	i1 = offset | IPH_MF | frag_flag;
	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);

	/* Establish the ending byte offset, based on the starting offset. */
	offset <<= 3;
	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;

	/* Store the length of the first fragment in the IP header. */
	i1 = len + hdr_len;
	ASSERT(i1 <= IP_MAXPACKET);
	ipha->ipha_length = htons((uint16_t)i1);

	/*
	 * Compute the IP header checksum for the first frag.  We have to
	 * watch out that we stop at the end of the header.
	 */
	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);

	/*
	 * Now carve off the first frag.  Note that this will include the
	 * original IP header.
	 */
	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
		ip_drop_output("FragFails: could not carve mp", mp_orig, ill);
		freeb(hdr_mp);
		freemsg(mp_orig);
		return (ENOBUFS);
	}

	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);

	error = postfragfn(mp, nce, ixaflags, i1, xmit_hint, szone, nolzid,
	    ixa_cookie);
	if (error != 0 && error != EWOULDBLOCK) {
		/* No point in sending the other fragments */
		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
		ip_drop_output("FragFails: postfragfn failed", mp_orig, ill);
		freeb(hdr_mp);
		freemsg(mp_orig);
		return (error);
	}

	/* No need to redo state machine in loop */
	ixaflags &= ~IXAF_REACH_CONF;

	/* Advance the offset to the second frag starting point. */
	offset += len;
	/*
	 * Update hdr_len from the copied header - there might be less options
	 * in the later fragments.
	 */
	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
	/* Loop until done. */
	for (;;) {
		uint16_t	offset_and_flags;
		uint16_t	ip_len;

		if (ip_data_end - offset > len) {
			/*
			 * Carve off the appropriate amount from the original
			 * datagram.
			 */
			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
				mp = NULL;
				break;
			}
			/*
			 * More frags after this one.  Get another copy
			 * of the header.
			 */
			if (carve_mp->b_datap->db_ref == 1 &&
			    hdr_mp->b_wptr - hdr_mp->b_rptr <
			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
				/* Inline IP header */
				carve_mp->b_rptr -= hdr_mp->b_wptr -
				    hdr_mp->b_rptr;
				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
				    hdr_mp->b_wptr - hdr_mp->b_rptr);
				mp = carve_mp;
			} else {
				if (!(mp = copyb(hdr_mp))) {
					freemsg(carve_mp);
					break;
				}
				/* Get priority marking, if any. */
				mp->b_band = priority;
				mp->b_cont = carve_mp;
			}
			ipha = (ipha_t *)mp->b_rptr;
			offset_and_flags = IPH_MF;
		} else {
			/*
			 * Last frag.  Consume the header. Set len to
			 * the length of this last piece.
			 */
			len = ip_data_end - offset;

			/*
			 * Carve off the appropriate amount from the original
			 * datagram.
			 */
			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
				mp = NULL;
				break;
			}
			if (carve_mp->b_datap->db_ref == 1 &&
			    hdr_mp->b_wptr - hdr_mp->b_rptr <
			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
				/* Inline IP header */
				carve_mp->b_rptr -= hdr_mp->b_wptr -
				    hdr_mp->b_rptr;
				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
				    hdr_mp->b_wptr - hdr_mp->b_rptr);
				mp = carve_mp;
				freeb(hdr_mp);
				hdr_mp = mp;
			} else {
				mp = hdr_mp;
				/* Get priority marking, if any. */
				mp->b_band = priority;
				mp->b_cont = carve_mp;
			}
			ipha = (ipha_t *)mp->b_rptr;
			/* A frag of a frag might have IPH_MF non-zero */
			offset_and_flags =
			    ntohs(ipha->ipha_fragment_offset_and_flags) &
			    IPH_MF;
		}
		offset_and_flags |= (uint16_t)(offset >> 3);
		offset_and_flags |= (uint16_t)frag_flag;
		/* Store the offset and flags in the IP header. */
		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);

		/* Store the length in the IP header. */
		ip_len = (uint16_t)(len + hdr_len);
		ipha->ipha_length = htons(ip_len);

		/*
		 * Set the IP header checksum.	Note that mp is just
		 * the header, so this is easy to pass to ip_csum.
		 */
		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);

		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates);

		error = postfragfn(mp, nce, ixaflags, ip_len, xmit_hint, szone,
		    nolzid, ixa_cookie);
		/* All done if we just consumed the hdr_mp. */
		if (mp == hdr_mp) {
			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
			return (error);
		}
		if (error != 0 && error != EWOULDBLOCK) {
			DTRACE_PROBE2(ip__xmit__frag__fail, ill_t *, ill,
			    mblk_t *, hdr_mp);
			/* No point in sending the other fragments */
			break;
		}

		/* Otherwise, advance and loop. */
		offset += len;
	}
	/* Clean up following allocation failure. */
	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
	ip_drop_output("FragFails: loop ended", NULL, ill);
	if (mp != hdr_mp)
		freeb(hdr_mp);
	if (mp != mp_orig)
		freemsg(mp_orig);
	return (error);
}

/*
 * Copy the header plus those options which have the copy bit set
 */
static mblk_t *
ip_fragment_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst,
    mblk_t *src)
{
	mblk_t	*mp;
	uchar_t	*up;

	/*
	 * Quick check if we need to look for options without the copy bit
	 * set
	 */
	mp = allocb_tmpl(ipst->ips_ip_wroff_extra + hdr_len, src);
	if (!mp)
		return (mp);
	mp->b_rptr += ipst->ips_ip_wroff_extra;
	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
		bcopy(rptr, mp->b_rptr, hdr_len);
		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
		return (mp);
	}
	up  = mp->b_rptr;
	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
	up += IP_SIMPLE_HDR_LENGTH;
	rptr += IP_SIMPLE_HDR_LENGTH;
	hdr_len -= IP_SIMPLE_HDR_LENGTH;
	while (hdr_len > 0) {
		uint32_t optval;
		uint32_t optlen;

		optval = *rptr;
		if (optval == IPOPT_EOL)
			break;
		if (optval == IPOPT_NOP)
			optlen = 1;
		else
			optlen = rptr[1];
		if (optval & IPOPT_COPY) {
			bcopy(rptr, up, optlen);
			up += optlen;
		}
		rptr += optlen;
		hdr_len -= optlen;
	}
	/*
	 * Make sure that we drop an even number of words by filling
	 * with EOL to the next word boundary.
	 */
	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
	    hdr_len & 0x3; hdr_len++)
		*up++ = IPOPT_EOL;
	mp->b_wptr = up;
	/* Update header length */
	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
	return (mp);
}

/*
 * Update any source route, record route, or timestamp options when
 * sending a packet back to ourselves.
 * Check that we are at end of strict source route.
 * The options have been sanity checked by ip_output_options().
 */
void
ip_output_local_options(ipha_t *ipha, ip_stack_t *ipst)
{
	ipoptp_t	opts;
	uchar_t		*opt;
	uint8_t		optval;
	uint8_t		optlen;
	ipaddr_t	dst;
	uint32_t	ts;
	timestruc_t	now;
	uint32_t	off = 0;

	for (optval = ipoptp_first(&opts, ipha);
	    optval != IPOPT_EOL;
	    optval = ipoptp_next(&opts)) {
		opt = opts.ipoptp_cur;
		optlen = opts.ipoptp_len;
		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
		switch (optval) {
		case IPOPT_SSRR:
		case IPOPT_LSRR:
			off = opt[IPOPT_OFFSET];
			off--;
			if (optlen < IP_ADDR_LEN ||
			    off > optlen - IP_ADDR_LEN) {
				/* End of source route */
				break;
			}
			/*
			 * This will only happen if two consecutive entries
			 * in the source route contains our address or if
			 * it is a packet with a loose source route which
			 * reaches us before consuming the whole source route
			 */

			if (optval == IPOPT_SSRR) {
				return;
			}
			/*
			 * Hack: instead of dropping the packet truncate the
			 * source route to what has been used by filling the
			 * rest with IPOPT_NOP.
			 */
			opt[IPOPT_OLEN] = (uint8_t)off;
			while (off < optlen) {
				opt[off++] = IPOPT_NOP;
			}
			break;
		case IPOPT_RR:
			off = opt[IPOPT_OFFSET];
			off--;
			if (optlen < IP_ADDR_LEN ||
			    off > optlen - IP_ADDR_LEN) {
				/* No more room - ignore */
				ip1dbg((
				    "ip_output_local_options: end of RR\n"));
				break;
			}
			dst = htonl(INADDR_LOOPBACK);
			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
			break;
		case IPOPT_TS:
			/* Insert timestamp if there is romm */
			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
			case IPOPT_TS_TSONLY:
				off = IPOPT_TS_TIMELEN;
				break;
			case IPOPT_TS_PRESPEC:
			case IPOPT_TS_PRESPEC_RFC791:
				/* Verify that the address matched */
				off = opt[IPOPT_OFFSET] - 1;
				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
				if (ip_type_v4(dst, ipst) != IRE_LOCAL) {
					/* Not for us */
					break;
				}
				/* FALLTHROUGH */
			case IPOPT_TS_TSANDADDR:
				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
				break;
			default:
				/*
				 * ip_*put_options should have already
				 * dropped this packet.
				 */
				cmn_err(CE_PANIC, "ip_output_local_options: "
				    "unknown IT - bug in ip_output_options?\n");
			}
			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
				/* Increase overflow counter */
				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
				opt[IPOPT_POS_OV_FLG] = (uint8_t)
				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
				    (off << 4);
				break;
			}
			off = opt[IPOPT_OFFSET] - 1;
			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
			case IPOPT_TS_PRESPEC:
			case IPOPT_TS_PRESPEC_RFC791:
			case IPOPT_TS_TSANDADDR:
				dst = htonl(INADDR_LOOPBACK);
				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
				/* FALLTHROUGH */
			case IPOPT_TS_TSONLY:
				off = opt[IPOPT_OFFSET] - 1;
				/* Compute # of milliseconds since midnight */
				gethrestime(&now);
				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
				    NSEC2MSEC(now.tv_nsec);
				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
				break;
			}
			break;
		}
	}
}

/*
 * Prepend an M_DATA fastpath header, and if none present prepend a
 * DL_UNITDATA_REQ. Frees the mblk on failure.
 *
 * nce_dlur_mp and nce_fp_mp can not disappear once they have been set.
 * If there is a change to them, the nce will be deleted (condemned) and
 * a new nce_t will be created when packets are sent. Thus we need no locks
 * to access those fields.
 *
 * We preserve b_band to support IPQoS. If a DL_UNITDATA_REQ is prepended
 * we place b_band in dl_priority.dl_max.
 */
static mblk_t *
ip_xmit_attach_llhdr(mblk_t *mp, nce_t *nce)
{
	uint_t	hlen;
	mblk_t *mp1;
	uint_t	priority;
	uchar_t *rptr;

	rptr = mp->b_rptr;

	ASSERT(DB_TYPE(mp) == M_DATA);
	priority = mp->b_band;

	ASSERT(nce != NULL);
	if ((mp1 = nce->nce_fp_mp) != NULL) {
		hlen = MBLKL(mp1);
		/*
		 * Check if we have enough room to prepend fastpath
		 * header
		 */
		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
			rptr -= hlen;
			bcopy(mp1->b_rptr, rptr, hlen);
			/*
			 * Set the b_rptr to the start of the link layer
			 * header
			 */
			mp->b_rptr = rptr;
			return (mp);
		}
		mp1 = copyb(mp1);
		if (mp1 == NULL) {
			ill_t *ill = nce->nce_ill;

			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
			ip_drop_output("ipIfStatsOutDiscards", mp, ill);
			freemsg(mp);
			return (NULL);
		}
		mp1->b_band = priority;
		mp1->b_cont = mp;
		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
		DB_LSOMSS(mp1) = DB_LSOMSS(mp);
		DTRACE_PROBE1(ip__xmit__copyb, (mblk_t *), mp1);
		/*
		 * XXX disable ICK_VALID and compute checksum
		 * here; can happen if nce_fp_mp changes and
		 * it can't be copied now due to insufficient
		 * space. (unlikely, fp mp can change, but it
		 * does not increase in length)
		 */
		return (mp1);
	}
	mp1 = copyb(nce->nce_dlur_mp);

	if (mp1 == NULL) {
		ill_t *ill = nce->nce_ill;

		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
		ip_drop_output("ipIfStatsOutDiscards", mp, ill);
		freemsg(mp);
		return (NULL);
	}
	mp1->b_cont = mp;
	if (priority != 0) {
		mp1->b_band = priority;
		((dl_unitdata_req_t *)(mp1->b_rptr))->dl_priority.dl_max =
		    priority;
	}
	return (mp1);
}

/*
 * Finish the outbound IPsec processing. This function is called from
 * ipsec_out_process() if the IPsec packet was processed
 * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
 * asynchronously.
 *
 * This is common to IPv4 and IPv6.
 */
int
ip_output_post_ipsec(mblk_t *mp, ip_xmit_attr_t *ixa)
{
	iaflags_t	ixaflags = ixa->ixa_flags;
	uint_t		pktlen;


	/* AH/ESP don't update ixa_pktlen when they modify the packet */
	if (ixaflags & IXAF_IS_IPV4) {
		ipha_t		*ipha = (ipha_t *)mp->b_rptr;

		ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
		pktlen = ntohs(ipha->ipha_length);
	} else {
		ip6_t		*ip6h = (ip6_t *)mp->b_rptr;

		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
		pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
	}

	/*
	 * We release any hard reference on the SAs here to make
	 * sure the SAs can be garbage collected. ipsr_sa has a soft reference
	 * on the SAs.
	 * If in the future we want the hard latching of the SAs in the
	 * ip_xmit_attr_t then we should remove this.
	 */
	if (ixa->ixa_ipsec_esp_sa != NULL) {
		IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
		ixa->ixa_ipsec_esp_sa = NULL;
	}
	if (ixa->ixa_ipsec_ah_sa != NULL) {
		IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
		ixa->ixa_ipsec_ah_sa = NULL;
	}

	/* Do we need to fragment? */
	if ((ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR) ||
	    pktlen > ixa->ixa_fragsize) {
		if (ixaflags & IXAF_IS_IPV4) {
			ASSERT(!(ixa->ixa_flags & IXAF_IPV6_ADD_FRAGHDR));
			/*
			 * We check for the DF case in ipsec_out_process
			 * hence this only handles the non-DF case.
			 */
			return (ip_fragment_v4(mp, ixa->ixa_nce, ixa->ixa_flags,
			    pktlen, ixa->ixa_fragsize,
			    ixa->ixa_xmit_hint, ixa->ixa_zoneid,
			    ixa->ixa_no_loop_zoneid, ixa->ixa_postfragfn,
			    &ixa->ixa_cookie));
		} else {
			mp = ip_fraghdr_add_v6(mp, ixa->ixa_ident, ixa);
			if (mp == NULL) {
				/* MIB and ip_drop_output already done */
				return (ENOMEM);
			}
			pktlen += sizeof (ip6_frag_t);
			if (pktlen > ixa->ixa_fragsize) {
				return (ip_fragment_v6(mp, ixa->ixa_nce,
				    ixa->ixa_flags, pktlen,
				    ixa->ixa_fragsize, ixa->ixa_xmit_hint,
				    ixa->ixa_zoneid, ixa->ixa_no_loop_zoneid,
				    ixa->ixa_postfragfn, &ixa->ixa_cookie));
			}
		}
	}
	return ((ixa->ixa_postfragfn)(mp, ixa->ixa_nce, ixa->ixa_flags,
	    pktlen, ixa->ixa_xmit_hint, ixa->ixa_zoneid,
	    ixa->ixa_no_loop_zoneid, NULL));
}

/*
 * Finish the inbound IPsec processing. This function is called from
 * ipsec_out_process() if the IPsec packet was processed
 * synchronously, or from {ah,esp}_kcf_callback_outbound() if it was processed
 * asynchronously.
 *
 * This is common to IPv4 and IPv6.
 */
void
ip_input_post_ipsec(mblk_t *mp, ip_recv_attr_t *ira)
{
	iaflags_t	iraflags = ira->ira_flags;

	/* Length might have changed */
	if (iraflags & IRAF_IS_IPV4) {
		ipha_t		*ipha = (ipha_t *)mp->b_rptr;

		ASSERT(IPH_HDR_VERSION(ipha) == IPV4_VERSION);
		ira->ira_pktlen = ntohs(ipha->ipha_length);
		ira->ira_ip_hdr_length = IPH_HDR_LENGTH(ipha);
		ira->ira_protocol = ipha->ipha_protocol;

		ip_fanout_v4(mp, ipha, ira);
	} else {
		ip6_t		*ip6h = (ip6_t *)mp->b_rptr;
		uint8_t		*nexthdrp;

		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV6_VERSION);
		ira->ira_pktlen = ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN;
		if (!ip_hdr_length_nexthdr_v6(mp, ip6h, &ira->ira_ip_hdr_length,
		    &nexthdrp)) {
			/* Malformed packet */
			BUMP_MIB(ira->ira_ill->ill_ip_mib, ipIfStatsInDiscards);
			ip_drop_input("ipIfStatsInDiscards", mp, ira->ira_ill);
			freemsg(mp);
			return;
		}
		ira->ira_protocol = *nexthdrp;
		ip_fanout_v6(mp, ip6h, ira);
	}
}

/*
 * Select which AH & ESP SA's to use (if any) for the outbound packet.
 *
 * If this function returns B_TRUE, the requested SA's have been filled
 * into the ixa_ipsec_*_sa pointers.
 *
 * If the function returns B_FALSE, the packet has been "consumed", most
 * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
 *
 * The SA references created by the protocol-specific "select"
 * function will be released in ip_output_post_ipsec.
 */
static boolean_t
ipsec_out_select_sa(mblk_t *mp, ip_xmit_attr_t *ixa)
{
	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
	ipsec_policy_t *pp;
	ipsec_action_t *ap;

	ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);
	ASSERT((ixa->ixa_ipsec_policy != NULL) ||
	    (ixa->ixa_ipsec_action != NULL));

	ap = ixa->ixa_ipsec_action;
	if (ap == NULL) {
		pp = ixa->ixa_ipsec_policy;
		ASSERT(pp != NULL);
		ap = pp->ipsp_act;
		ASSERT(ap != NULL);
	}

	/*
	 * We have an action.  now, let's select SA's.
	 * A side effect of setting ixa_ipsec_*_sa is that it will
	 * be cached in the conn_t.
	 */
	if (ap->ipa_want_esp) {
		if (ixa->ixa_ipsec_esp_sa == NULL) {
			need_esp_acquire = !ipsec_outbound_sa(mp, ixa,
			    IPPROTO_ESP);
		}
		ASSERT(need_esp_acquire || ixa->ixa_ipsec_esp_sa != NULL);
	}

	if (ap->ipa_want_ah) {
		if (ixa->ixa_ipsec_ah_sa == NULL) {
			need_ah_acquire = !ipsec_outbound_sa(mp, ixa,
			    IPPROTO_AH);
		}
		ASSERT(need_ah_acquire || ixa->ixa_ipsec_ah_sa != NULL);
		/*
		 * The ESP and AH processing order needs to be preserved
		 * when both protocols are required (ESP should be applied
		 * before AH for an outbound packet). Force an ESP ACQUIRE
		 * when both ESP and AH are required, and an AH ACQUIRE
		 * is needed.
		 */
		if (ap->ipa_want_esp && need_ah_acquire)
			need_esp_acquire = B_TRUE;
	}

	/*
	 * Send an ACQUIRE (extended, regular, or both) if we need one.
	 * Release SAs that got referenced, but will not be used until we
	 * acquire _all_ of the SAs we need.
	 */
	if (need_ah_acquire || need_esp_acquire) {
		if (ixa->ixa_ipsec_ah_sa != NULL) {
			IPSA_REFRELE(ixa->ixa_ipsec_ah_sa);
			ixa->ixa_ipsec_ah_sa = NULL;
		}
		if (ixa->ixa_ipsec_esp_sa != NULL) {
			IPSA_REFRELE(ixa->ixa_ipsec_esp_sa);
			ixa->ixa_ipsec_esp_sa = NULL;
		}

		sadb_acquire(mp, ixa, need_ah_acquire, need_esp_acquire);
		return (B_FALSE);
	}

	return (B_TRUE);
}

/*
 * Handle IPsec output processing.
 * This function is only entered once for a given packet.
 * We try to do things synchronously, but if we need to have user-level
 * set up SAs, or ESP or AH uses asynchronous kEF, then the operation
 * will be completed
 *  - when the SAs are added in esp_add_sa_finish/ah_add_sa_finish
 *  - when asynchronous ESP is done it will do AH
 *
 * In all cases we come back in ip_output_post_ipsec() to fragment and
 * send out the packet.
 */
int
ipsec_out_process(mblk_t *mp, ip_xmit_attr_t *ixa)
{
	ill_t		*ill = ixa->ixa_nce->nce_ill;
	ip_stack_t	*ipst = ixa->ixa_ipst;
	ipsec_stack_t	*ipss;
	ipsec_policy_t	*pp;
	ipsec_action_t	*ap;

	ASSERT(ixa->ixa_flags & IXAF_IPSEC_SECURE);

	ASSERT((ixa->ixa_ipsec_policy != NULL) ||
	    (ixa->ixa_ipsec_action != NULL));

	ipss = ipst->ips_netstack->netstack_ipsec;
	if (!ipsec_loaded(ipss)) {
		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
		ip_drop_packet(mp, B_TRUE, ill,
		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
		    &ipss->ipsec_dropper);
		return (ENOTSUP);
	}

	ap = ixa->ixa_ipsec_action;
	if (ap == NULL) {
		pp = ixa->ixa_ipsec_policy;
		ASSERT(pp != NULL);
		ap = pp->ipsp_act;
		ASSERT(ap != NULL);
	}

	/* Handle explicit drop action and bypass. */
	switch (ap->ipa_act.ipa_type) {
	case IPSEC_ACT_DISCARD:
	case IPSEC_ACT_REJECT:
		ip_drop_packet(mp, B_FALSE, ill,
		    DROPPER(ipss, ipds_spd_explicit), &ipss->ipsec_spd_dropper);
		return (EHOSTUNREACH);	/* IPsec policy failure */
	case IPSEC_ACT_BYPASS:
		return (ip_output_post_ipsec(mp, ixa));
	}

	/*
	 * The order of processing is first insert a IP header if needed.
	 * Then insert the ESP header and then the AH header.
	 */
	if ((ixa->ixa_flags & IXAF_IS_IPV4) && ap->ipa_want_se) {
		/*
		 * First get the outer IP header before sending
		 * it to ESP.
		 */
		ipha_t *oipha, *iipha;
		mblk_t *outer_mp, *inner_mp;

		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
			(void) mi_strlog(ill->ill_rq, 0,
			    SL_ERROR|SL_TRACE|SL_CONSOLE,
			    "ipsec_out_process: "
			    "Self-Encapsulation failed: Out of memory\n");
			BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
			ip_drop_output("ipIfStatsOutDiscards", mp, ill);
			freemsg(mp);
			return (ENOBUFS);
		}
		inner_mp = mp;
		ASSERT(inner_mp->b_datap->db_type == M_DATA);
		oipha = (ipha_t *)outer_mp->b_rptr;
		iipha = (ipha_t *)inner_mp->b_rptr;
		*oipha = *iipha;
		outer_mp->b_wptr += sizeof (ipha_t);
		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
		    sizeof (ipha_t));
		oipha->ipha_protocol = IPPROTO_ENCAP;
		oipha->ipha_version_and_hdr_length =
		    IP_SIMPLE_HDR_VERSION;
		oipha->ipha_hdr_checksum = 0;
		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
		outer_mp->b_cont = inner_mp;
		mp = outer_mp;

		ixa->ixa_flags |= IXAF_IPSEC_TUNNEL;
	}

	/* If we need to wait for a SA then we can't return any errno */
	if (((ap->ipa_want_ah && (ixa->ixa_ipsec_ah_sa == NULL)) ||
	    (ap->ipa_want_esp && (ixa->ixa_ipsec_esp_sa == NULL))) &&
	    !ipsec_out_select_sa(mp, ixa))
		return (0);

	/*
	 * By now, we know what SA's to use.  Toss over to ESP & AH
	 * to do the heavy lifting.
	 */
	if (ap->ipa_want_esp) {
		ASSERT(ixa->ixa_ipsec_esp_sa != NULL);

		mp = ixa->ixa_ipsec_esp_sa->ipsa_output_func(mp, ixa);
		if (mp == NULL) {
			/*
			 * Either it failed or is pending. In the former case
			 * ipIfStatsInDiscards was increased.
			 */
			return (0);
		}
	}

	if (ap->ipa_want_ah) {
		ASSERT(ixa->ixa_ipsec_ah_sa != NULL);

		mp = ixa->ixa_ipsec_ah_sa->ipsa_output_func(mp, ixa);
		if (mp == NULL) {
			/*
			 * Either it failed or is pending. In the former case
			 * ipIfStatsInDiscards was increased.
			 */
			return (0);
		}
	}
	/*
	 * We are done with IPsec processing. Send it over
	 * the wire.
	 */
	return (ip_output_post_ipsec(mp, ixa));
}

/*
 * ioctls that go through a down/up sequence may need to wait for the down
 * to complete. This involves waiting for the ire and ipif refcnts to go down
 * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
 */
/* ARGSUSED */
void
ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
{
	struct iocblk *iocp;
	mblk_t *mp1;
	ip_ioctl_cmd_t *ipip;
	int err;
	sin_t	*sin;
	struct lifreq *lifr;
	struct ifreq *ifr;

	iocp = (struct iocblk *)mp->b_rptr;
	ASSERT(ipsq != NULL);
	/* Existence of mp1 verified in ip_wput_nondata */
	mp1 = mp->b_cont->b_cont;
	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
		/*
		 * Special case where ipx_current_ipif is not set:
		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
		 * We are here as were not able to complete the operation in
		 * ipif_set_values because we could not become exclusive on
		 * the new ipsq.
		 */
		ill_t *ill = q->q_ptr;
		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
	}
	ASSERT(ipsq->ipsq_xop->ipx_current_ipif != NULL);

	if (ipip->ipi_cmd_type == IF_CMD) {
		/* This a old style SIOC[GS]IF* command */
		ifr = (struct ifreq *)mp1->b_rptr;
		sin = (sin_t *)&ifr->ifr_addr;
	} else if (ipip->ipi_cmd_type == LIF_CMD) {
		/* This a new style SIOC[GS]LIF* command */
		lifr = (struct lifreq *)mp1->b_rptr;
		sin = (sin_t *)&lifr->lifr_addr;
	} else {
		sin = NULL;
	}

	err = (*ipip->ipi_func_restart)(ipsq->ipsq_xop->ipx_current_ipif, sin,
	    q, mp, ipip, mp1->b_rptr);

	DTRACE_PROBE4(ipif__ioctl, char *, "ip_reprocess_ioctl finish",
	    int, ipip->ipi_cmd,
	    ill_t *, ipsq->ipsq_xop->ipx_current_ipif->ipif_ill,
	    ipif_t *, ipsq->ipsq_xop->ipx_current_ipif);

	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
}

/*
 * ioctl processing
 *
 * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
 * the ioctl command in the ioctl tables, determines the copyin data size
 * from the ipi_copyin_size field, and does an mi_copyin() of that size.
 *
 * ioctl processing then continues when the M_IOCDATA makes its way down to
 * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
 * associated 'conn' is refheld till the end of the ioctl and the general
 * ioctl processing function ip_process_ioctl() is called to extract the
 * arguments and process the ioctl.  To simplify extraction, ioctl commands
 * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
 * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
 * is used to extract the ioctl's arguments.
 *
 * ip_process_ioctl determines if the ioctl needs to be serialized, and if
 * so goes thru the serialization primitive ipsq_try_enter. Then the
 * appropriate function to handle the ioctl is called based on the entry in
 * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
 * which also refreleases the 'conn' that was refheld at the start of the
 * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
 *
 * Many exclusive ioctls go thru an internal down up sequence as part of
 * the operation. For example an attempt to change the IP address of an
 * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
 * does all the cleanup such as deleting all ires that use this address.
 * Then we need to wait till all references to the interface go away.
 */
void
ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
{
	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
	ip_ioctl_cmd_t *ipip = arg;
	ip_extract_func_t *extract_funcp;
	ill_t *ill;
	cmd_info_t ci;
	int err;
	boolean_t entered_ipsq = B_FALSE;

	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));

	if (ipip == NULL)
		ipip = ip_sioctl_lookup(iocp->ioc_cmd);

	/*
	 * SIOCLIFADDIF needs to go thru a special path since the
	 * ill may not exist yet. This happens in the case of lo0
	 * which is created using this ioctl.
	 */
	if (ipip->ipi_cmd == SIOCLIFADDIF) {
		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
		DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish",
		    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
		return;
	}

	ci.ci_ipif = NULL;
	extract_funcp = NULL;
	switch (ipip->ipi_cmd_type) {
	case MISC_CMD:
	case MSFILT_CMD:
		/*
		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
		 */
		if (ipip->ipi_cmd == IF_UNITSEL) {
			/* ioctl comes down the ill */
			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
			ipif_refhold(ci.ci_ipif);
		}
		err = 0;
		ci.ci_sin = NULL;
		ci.ci_sin6 = NULL;
		ci.ci_lifr = NULL;
		extract_funcp = NULL;
		break;

	case IF_CMD:
	case LIF_CMD:
		extract_funcp = ip_extract_lifreq;
		break;

	case ARP_CMD:
	case XARP_CMD:
		extract_funcp = ip_extract_arpreq;
		break;

	default:
		ASSERT(0);
	}

	if (extract_funcp != NULL) {
		err = (*extract_funcp)(q, mp, ipip, &ci);
		if (err != 0) {
			DTRACE_PROBE4(ipif__ioctl,
			    char *, "ip_process_ioctl finish err",
			    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
			return;
		}

		/*
		 * All of the extraction functions return a refheld ipif.
		 */
		ASSERT(ci.ci_ipif != NULL);
	}

	if (!(ipip->ipi_flags & IPI_WR)) {
		/*
		 * A return value of EINPROGRESS means the ioctl is
		 * either queued and waiting for some reason or has
		 * already completed.
		 */
		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
		    ci.ci_lifr);
		if (ci.ci_ipif != NULL) {
			DTRACE_PROBE4(ipif__ioctl,
			    char *, "ip_process_ioctl finish RD",
			    int, ipip->ipi_cmd, ill_t *, ci.ci_ipif->ipif_ill,
			    ipif_t *, ci.ci_ipif);
			ipif_refrele(ci.ci_ipif);
		} else {
			DTRACE_PROBE4(ipif__ioctl,
			    char *, "ip_process_ioctl finish RD",
			    int, ipip->ipi_cmd, ill_t *, NULL, ipif_t *, NULL);
		}
		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
		return;
	}

	ASSERT(ci.ci_ipif != NULL);

	/*
	 * If ipsq is non-NULL, we are already being called exclusively
	 */
	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
	if (ipsq == NULL) {
		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp, ip_process_ioctl,
		    NEW_OP, B_TRUE);
		if (ipsq == NULL) {
			ipif_refrele(ci.ci_ipif);
			return;
		}
		entered_ipsq = B_TRUE;
	}
	/*
	 * Release the ipif so that ipif_down and friends that wait for
	 * references to go away are not misled about the current ipif_refcnt
	 * values. We are writer so we can access the ipif even after releasing
	 * the ipif.
	 */
	ipif_refrele(ci.ci_ipif);

	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);

	/*
	 * We need to cache the ill_t that we're going to use as the argument
	 * to the ipif-ioctl DTrace probe (below) because the ci_ipif can be
	 * blown away by calling ipi_func.
	 */
	ill = ci.ci_ipif == NULL ? NULL : ci.ci_ipif->ipif_ill;

	/*
	 * A return value of EINPROGRESS means the ioctl is
	 * either queued and waiting for some reason or has
	 * already completed.
	 */
	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);

	DTRACE_PROBE4(ipif__ioctl, char *, "ip_process_ioctl finish WR",
	    int, ipip->ipi_cmd, ill_t *, ill, ipif_t *, ci.ci_ipif);
	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);

	if (entered_ipsq)
		ipsq_exit(ipsq);
}

/*
 * Complete the ioctl. Typically ioctls use the mi package and need to
 * do mi_copyout/mi_copy_done.
 */
void
ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
{
	conn_t	*connp = NULL;

	if (err == EINPROGRESS)
		return;

	if (CONN_Q(q)) {
		connp = Q_TO_CONN(q);
		ASSERT(connp->conn_ref >= 2);
	}

	switch (mode) {
	case COPYOUT:
		if (err == 0)
			mi_copyout(q, mp);
		else
			mi_copy_done(q, mp, err);
		break;

	case NO_COPYOUT:
		mi_copy_done(q, mp, err);
		break;

	default:
		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
		break;
	}

	/*
	 * The conn refhold and ioctlref placed on the conn at the start of the
	 * ioctl are released here.
	 */
	if (connp != NULL) {
		CONN_DEC_IOCTLREF(connp);
		CONN_OPER_PENDING_DONE(connp);
	}

	if (ipsq != NULL)
		ipsq_current_finish(ipsq);
}

/* Handles all non data messages */
int
ip_wput_nondata(queue_t *q, mblk_t *mp)
{
	mblk_t		*mp1;
	struct iocblk	*iocp;
	ip_ioctl_cmd_t	*ipip;
	conn_t		*connp;
	cred_t		*cr;
	char		*proto_str;

	if (CONN_Q(q))
		connp = Q_TO_CONN(q);
	else
		connp = NULL;

	iocp = NULL;
	switch (DB_TYPE(mp)) {
	case M_IOCTL:
		/*
		 * IOCTL processing begins in ip_sioctl_copyin_setup which
		 * will arrange to copy in associated control structures.
		 */
		ip_sioctl_copyin_setup(q, mp);
		return (0);
	case M_IOCDATA:
		/*
		 * Ensure that this is associated with one of our trans-
		 * parent ioctls.  If it's not ours, discard it if we're
		 * running as a driver, or pass it on if we're a module.
		 */
		iocp = (struct iocblk *)mp->b_rptr;
		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
		if (ipip == NULL) {
			if (q->q_next == NULL) {
				goto nak;
			} else {
				putnext(q, mp);
			}
			return (0);
		}
		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
			/*
			 * The ioctl is one we recognise, but is not consumed
			 * by IP as a module and we are a module, so we drop
			 */
			goto nak;
		}

		/* IOCTL continuation following copyin or copyout. */
		if (mi_copy_state(q, mp, NULL) == -1) {
			/*
			 * The copy operation failed.  mi_copy_state already
			 * cleaned up, so we're out of here.
			 */
			return (0);
		}
		/*
		 * If we just completed a copy in, we become writer and
		 * continue processing in ip_sioctl_copyin_done.  If it
		 * was a copy out, we call mi_copyout again.  If there is
		 * nothing more to copy out, it will complete the IOCTL.
		 */
		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
				mi_copy_done(q, mp, EPROTO);
				return (0);
			}
			/*
			 * Check for cases that need more copying.  A return
			 * value of 0 means a second copyin has been started,
			 * so we return; a return value of 1 means no more
			 * copying is needed, so we continue.
			 */
			if (ipip->ipi_cmd_type == MSFILT_CMD &&
			    MI_COPY_COUNT(mp) == 1) {
				if (ip_copyin_msfilter(q, mp) == 0)
					return (0);
			}
			/*
			 * Refhold the conn, till the ioctl completes. This is
			 * needed in case the ioctl ends up in the pending mp
			 * list. Every mp in the ipx_pending_mp list must have
			 * a refhold on the conn to resume processing. The
			 * refhold is released when the ioctl completes
			 * (whether normally or abnormally). An ioctlref is also
			 * placed on the conn to prevent TCP from removing the
			 * queue needed to send the ioctl reply back.
			 * In all cases ip_ioctl_finish is called to finish
			 * the ioctl and release the refholds.
			 */
			if (connp != NULL) {
				/* This is not a reentry */
				CONN_INC_REF(connp);
				CONN_INC_IOCTLREF(connp);
			} else {
				if (!(ipip->ipi_flags & IPI_MODOK)) {
					mi_copy_done(q, mp, EINVAL);
					return (0);
				}
			}

			ip_process_ioctl(NULL, q, mp, ipip);

		} else {
			mi_copyout(q, mp);
		}
		return (0);

	case M_IOCNAK:
		/*
		 * The only way we could get here is if a resolver didn't like
		 * an IOCTL we sent it.	 This shouldn't happen.
		 */
		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
		    "ip_wput_nondata: unexpected M_IOCNAK, ioc_cmd 0x%x",
		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
		freemsg(mp);
		return (0);
	case M_IOCACK:
		/* /dev/ip shouldn't see this */
		goto nak;
	case M_FLUSH:
		if (*mp->b_rptr & FLUSHW)
			flushq(q, FLUSHALL);
		if (q->q_next) {
			putnext(q, mp);
			return (0);
		}
		if (*mp->b_rptr & FLUSHR) {
			*mp->b_rptr &= ~FLUSHW;
			qreply(q, mp);
			return (0);
		}
		freemsg(mp);
		return (0);
	case M_CTL:
		break;
	case M_PROTO:
	case M_PCPROTO:
		/*
		 * The only PROTO messages we expect are SNMP-related.
		 */
		switch (((union T_primitives *)mp->b_rptr)->type) {
		case T_SVR4_OPTMGMT_REQ:
			ip2dbg(("ip_wput_nondata: T_SVR4_OPTMGMT_REQ "
			    "flags %x\n",
			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));

			if (connp == NULL) {
				proto_str = "T_SVR4_OPTMGMT_REQ";
				goto protonak;
			}

			/*
			 * All Solaris components should pass a db_credp
			 * for this TPI message, hence we ASSERT.
			 * But in case there is some other M_PROTO that looks
			 * like a TPI message sent by some other kernel
			 * component, we check and return an error.
			 */
			cr = msg_getcred(mp, NULL);
			ASSERT(cr != NULL);
			if (cr == NULL) {
				mp = mi_tpi_err_ack_alloc(mp, TSYSERR, EINVAL);
				if (mp != NULL)
					qreply(q, mp);
				return (0);
			}

			if (!snmpcom_req(q, mp, ip_snmp_set, ip_snmp_get, cr)) {
				proto_str = "Bad SNMPCOM request?";
				goto protonak;
			}
			return (0);
		default:
			ip1dbg(("ip_wput_nondata: dropping M_PROTO prim %u\n",
			    (int)*(uint_t *)mp->b_rptr));
			freemsg(mp);
			return (0);
		}
	default:
		break;
	}
	if (q->q_next) {
		putnext(q, mp);
	} else
		freemsg(mp);
	return (0);

nak:
	iocp->ioc_error = EINVAL;
	mp->b_datap->db_type = M_IOCNAK;
	iocp->ioc_count = 0;
	qreply(q, mp);
	return (0);

protonak:
	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
		qreply(q, mp);
	return (0);
}

/*
 * Process IP options in an outbound packet.  Verify that the nexthop in a
 * strict source route is onlink.
 * Returns non-zero if something fails in which case an ICMP error has been
 * sent and mp freed.
 *
 * Assumes the ULP has called ip_massage_options to move nexthop into ipha_dst.
 */
int
ip_output_options(mblk_t *mp, ipha_t *ipha, ip_xmit_attr_t *ixa, ill_t *ill)
{
	ipoptp_t	opts;
	uchar_t		*opt;
	uint8_t		optval;
	uint8_t		optlen;
	ipaddr_t	dst;
	intptr_t	code = 0;
	ire_t		*ire;
	ip_stack_t	*ipst = ixa->ixa_ipst;
	ip_recv_attr_t	iras;

	ip2dbg(("ip_output_options\n"));

	opt = NULL;
	dst = ipha->ipha_dst;
	for (optval = ipoptp_first(&opts, ipha);
	    optval != IPOPT_EOL;
	    optval = ipoptp_next(&opts)) {
		opt = opts.ipoptp_cur;
		optlen = opts.ipoptp_len;
		ip2dbg(("ip_output_options: opt %d, len %d\n",
		    optval, optlen));
		switch (optval) {
			uint32_t off;
		case IPOPT_SSRR:
		case IPOPT_LSRR:
			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
				ip1dbg((
				    "ip_output_options: bad option offset\n"));
				code = (char *)&opt[IPOPT_OLEN] -
				    (char *)ipha;
				goto param_prob;
			}
			off = opt[IPOPT_OFFSET];
			ip1dbg(("ip_output_options: next hop 0x%x\n",
			    ntohl(dst)));
			/*
			 * For strict: verify that dst is directly
			 * reachable.
			 */
			if (optval == IPOPT_SSRR) {
				ire = ire_ftable_lookup_v4(dst, 0, 0,
				    IRE_INTERFACE, NULL, ALL_ZONES,
				    ixa->ixa_tsl,
				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, 0, ipst,
				    NULL);
				if (ire == NULL) {
					ip1dbg(("ip_output_options: SSRR not"
					    " directly reachable: 0x%x\n",
					    ntohl(dst)));
					goto bad_src_route;
				}
				ire_refrele(ire);
			}
			break;
		case IPOPT_RR:
			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
				ip1dbg((
				    "ip_output_options: bad option offset\n"));
				code = (char *)&opt[IPOPT_OLEN] -
				    (char *)ipha;
				goto param_prob;
			}
			break;
		case IPOPT_TS:
			/*
			 * Verify that length >=5 and that there is either
			 * room for another timestamp or that the overflow
			 * counter is not maxed out.
			 */
			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
			if (optlen < IPOPT_MINLEN_IT) {
				goto param_prob;
			}
			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
				ip1dbg((
				    "ip_output_options: bad option offset\n"));
				code = (char *)&opt[IPOPT_OFFSET] -
				    (char *)ipha;
				goto param_prob;
			}
			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
			case IPOPT_TS_TSONLY:
				off = IPOPT_TS_TIMELEN;
				break;
			case IPOPT_TS_TSANDADDR:
			case IPOPT_TS_PRESPEC:
			case IPOPT_TS_PRESPEC_RFC791:
				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
				break;
			default:
				code = (char *)&opt[IPOPT_POS_OV_FLG] -
				    (char *)ipha;
				goto param_prob;
			}
			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
				/*
				 * No room and the overflow counter is 15
				 * already.
				 */
				goto param_prob;
			}
			break;
		}
	}

	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
		return (0);

	ip1dbg(("ip_output_options: error processing IP options."));
	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;

param_prob:
	bzero(&iras, sizeof (iras));
	iras.ira_ill = iras.ira_rill = ill;
	iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
	iras.ira_rifindex = iras.ira_ruifindex;
	iras.ira_flags = IRAF_IS_IPV4;

	ip_drop_output("ip_output_options", mp, ill);
	icmp_param_problem(mp, (uint8_t)code, &iras);
	ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
	return (-1);

bad_src_route:
	bzero(&iras, sizeof (iras));
	iras.ira_ill = iras.ira_rill = ill;
	iras.ira_ruifindex = ill->ill_phyint->phyint_ifindex;
	iras.ira_rifindex = iras.ira_ruifindex;
	iras.ira_flags = IRAF_IS_IPV4;

	ip_drop_input("ICMP_SOURCE_ROUTE_FAILED", mp, ill);
	icmp_unreachable(mp, ICMP_SOURCE_ROUTE_FAILED, &iras);
	ASSERT(!(iras.ira_flags & IRAF_IPSEC_SECURE));
	return (-1);
}

/*
 * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
 * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
 * thru /etc/system.
 */
#define	CONN_MAXDRAINCNT	64

static void
conn_drain_init(ip_stack_t *ipst)
{
	int i, j;
	idl_tx_list_t *itl_tx;

	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;

	if ((ipst->ips_conn_drain_list_cnt == 0) ||
	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
		/*
		 * Default value of the number of drainers is the
		 * number of cpus, subject to maximum of 8 drainers.
		 */
		if (boot_max_ncpus != -1)
			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
		else
			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
	}

	ipst->ips_idl_tx_list =
	    kmem_zalloc(TX_FANOUT_SIZE * sizeof (idl_tx_list_t), KM_SLEEP);
	for (i = 0; i < TX_FANOUT_SIZE; i++) {
		itl_tx =  &ipst->ips_idl_tx_list[i];
		itl_tx->txl_drain_list =
		    kmem_zalloc(ipst->ips_conn_drain_list_cnt *
		    sizeof (idl_t), KM_SLEEP);
		mutex_init(&itl_tx->txl_lock, NULL, MUTEX_DEFAULT, NULL);
		for (j = 0; j < ipst->ips_conn_drain_list_cnt; j++) {
			mutex_init(&itl_tx->txl_drain_list[j].idl_lock, NULL,
			    MUTEX_DEFAULT, NULL);
			itl_tx->txl_drain_list[j].idl_itl = itl_tx;
		}
	}
}

static void
conn_drain_fini(ip_stack_t *ipst)
{
	int i;
	idl_tx_list_t *itl_tx;

	for (i = 0; i < TX_FANOUT_SIZE; i++) {
		itl_tx =  &ipst->ips_idl_tx_list[i];
		kmem_free(itl_tx->txl_drain_list,
		    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
	}
	kmem_free(ipst->ips_idl_tx_list,
	    TX_FANOUT_SIZE * sizeof (idl_tx_list_t));
	ipst->ips_idl_tx_list = NULL;
}

/*
 * Flow control has blocked us from proceeding.  Insert the given conn in one
 * of the conn drain lists.  When flow control is unblocked, either ip_wsrv()
 * (STREAMS) or ill_flow_enable() (direct) will be called back, which in turn
 * will call conn_walk_drain().  See the flow control notes at the top of this
 * file for more details.
 */
void
conn_drain_insert(conn_t *connp, idl_tx_list_t *tx_list)
{
	idl_t	*idl = tx_list->txl_drain_list;
	uint_t	index;
	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;

	mutex_enter(&connp->conn_lock);
	if (connp->conn_state_flags & CONN_CLOSING) {
		/*
		 * The conn is closing as a result of which CONN_CLOSING
		 * is set. Return.
		 */
		mutex_exit(&connp->conn_lock);
		return;
	} else if (connp->conn_idl == NULL) {
		/*
		 * Assign the next drain list round robin. We dont' use
		 * a lock, and thus it may not be strictly round robin.
		 * Atomicity of load/stores is enough to make sure that
		 * conn_drain_list_index is always within bounds.
		 */
		index = tx_list->txl_drain_index;
		ASSERT(index < ipst->ips_conn_drain_list_cnt);
		connp->conn_idl = &tx_list->txl_drain_list[index];
		index++;
		if (index == ipst->ips_conn_drain_list_cnt)
			index = 0;
		tx_list->txl_drain_index = index;
	} else {
		ASSERT(connp->conn_idl->idl_itl == tx_list);
	}
	mutex_exit(&connp->conn_lock);

	idl = connp->conn_idl;
	mutex_enter(&idl->idl_lock);
	if ((connp->conn_drain_prev != NULL) ||
	    (connp->conn_state_flags & CONN_CLOSING)) {
		/*
		 * The conn is either already in the drain list or closing.
		 * (We needed to check for CONN_CLOSING again since close can
		 * sneak in between dropping conn_lock and acquiring idl_lock.)
		 */
		mutex_exit(&idl->idl_lock);
		return;
	}

	/*
	 * The conn is not in the drain list. Insert it at the
	 * tail of the drain list. The drain list is circular
	 * and doubly linked. idl_conn points to the 1st element
	 * in the list.
	 */
	if (idl->idl_conn == NULL) {
		idl->idl_conn = connp;
		connp->conn_drain_next = connp;
		connp->conn_drain_prev = connp;
	} else {
		conn_t *head = idl->idl_conn;

		connp->conn_drain_next = head;
		connp->conn_drain_prev = head->conn_drain_prev;
		head->conn_drain_prev->conn_drain_next = connp;
		head->conn_drain_prev = connp;
	}
	/*
	 * For non streams based sockets assert flow control.
	 */
	conn_setqfull(connp, NULL);
	mutex_exit(&idl->idl_lock);
}

static void
conn_drain_remove(conn_t *connp)
{
	idl_t *idl = connp->conn_idl;

	if (idl != NULL) {
		/*
		 * Remove ourself from the drain list.
		 */
		if (connp->conn_drain_next == connp) {
			/* Singleton in the list */
			ASSERT(connp->conn_drain_prev == connp);
			idl->idl_conn = NULL;
		} else {
			connp->conn_drain_prev->conn_drain_next =
			    connp->conn_drain_next;
			connp->conn_drain_next->conn_drain_prev =
			    connp->conn_drain_prev;
			if (idl->idl_conn == connp)
				idl->idl_conn = connp->conn_drain_next;
		}

		/*
		 * NOTE: because conn_idl is associated with a specific drain
		 * list which in turn is tied to the index the TX ring
		 * (txl_cookie) hashes to, and because the TX ring can change
		 * over the lifetime of the conn_t, we must clear conn_idl so
		 * a subsequent conn_drain_insert() will set conn_idl again
		 * based on the latest txl_cookie.
		 */
		connp->conn_idl = NULL;
	}
	connp->conn_drain_next = NULL;
	connp->conn_drain_prev = NULL;

	conn_clrqfull(connp, NULL);
	/*
	 * For streams based sockets open up flow control.
	 */
	if (!IPCL_IS_NONSTR(connp))
		enableok(connp->conn_wq);
}

/*
 * This conn is closing, and we are called from ip_close. OR
 * this conn is draining because flow-control on the ill has been relieved.
 *
 * We must also need to remove conn's on this idl from the list, and also
 * inform the sockfs upcalls about the change in flow-control.
 */
static void
conn_drain(conn_t *connp, boolean_t closing)
{
	idl_t *idl;
	conn_t *next_connp;

	/*
	 * connp->conn_idl is stable at this point, and no lock is needed
	 * to check it. If we are called from ip_close, close has already
	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
	 * called us only because conn_idl is non-null. If we are called thru
	 * service, conn_idl could be null, but it cannot change because
	 * service is single-threaded per queue, and there cannot be another
	 * instance of service trying to call conn_drain_insert on this conn
	 * now.
	 */
	ASSERT(!closing || connp == NULL || connp->conn_idl != NULL);

	/*
	 * If the conn doesn't exist or is not on a drain list, bail.
	 */
	if (connp == NULL || connp->conn_idl == NULL ||
	    connp->conn_drain_prev == NULL) {
		return;
	}

	idl = connp->conn_idl;
	ASSERT(MUTEX_HELD(&idl->idl_lock));

	if (!closing) {
		next_connp = connp->conn_drain_next;
		while (next_connp != connp) {
			conn_t *delconnp = next_connp;

			next_connp = next_connp->conn_drain_next;
			conn_drain_remove(delconnp);
		}
		ASSERT(connp->conn_drain_next == idl->idl_conn);
	}
	conn_drain_remove(connp);
}

/*
 * Write service routine. Shared perimeter entry point.
 * The device queue's messages has fallen below the low water mark and STREAMS
 * has backenabled the ill_wq. Send sockfs notification about flow-control on
 * each waiting conn.
 */
int
ip_wsrv(queue_t *q)
{
	ill_t	*ill;

	ill = (ill_t *)q->q_ptr;
	if (ill->ill_state_flags == 0) {
		ip_stack_t *ipst = ill->ill_ipst;

		/*
		 * The device flow control has opened up.
		 * Walk through conn drain lists and qenable the
		 * first conn in each list. This makes sense only
		 * if the stream is fully plumbed and setup.
		 * Hence the ill_state_flags check above.
		 */
		ip1dbg(("ip_wsrv: walking\n"));
		conn_walk_drain(ipst, &ipst->ips_idl_tx_list[0]);
		enableok(ill->ill_wq);
	}
	return (0);
}

/*
 * Callback to disable flow control in IP.
 *
 * This is a mac client callback added when the DLD_CAPAB_DIRECT capability
 * is enabled.
 *
 * When MAC_TX() is not able to send any more packets, dld sets its queue
 * to QFULL and enable the STREAMS flow control. Later, when the underlying
 * driver is able to continue to send packets, it calls mac_tx_(ring_)update()
 * function and wakes up corresponding mac worker threads, which in turn
 * calls this callback function, and disables flow control.
 */
void
ill_flow_enable(void *arg, ip_mac_tx_cookie_t cookie)
{
	ill_t *ill = (ill_t *)arg;
	ip_stack_t *ipst = ill->ill_ipst;
	idl_tx_list_t *idl_txl;

	idl_txl = &ipst->ips_idl_tx_list[IDLHASHINDEX(cookie)];
	mutex_enter(&idl_txl->txl_lock);
	/* add code to to set a flag to indicate idl_txl is enabled */
	conn_walk_drain(ipst, idl_txl);
	mutex_exit(&idl_txl->txl_lock);
}

/*
 * Flow control has been relieved and STREAMS has backenabled us; drain
 * all the conn lists on `tx_list'.
 */
static void
conn_walk_drain(ip_stack_t *ipst, idl_tx_list_t *tx_list)
{
	int i;
	idl_t *idl;

	IP_STAT(ipst, ip_conn_walk_drain);

	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
		idl = &tx_list->txl_drain_list[i];
		mutex_enter(&idl->idl_lock);
		conn_drain(idl->idl_conn, B_FALSE);
		mutex_exit(&idl->idl_lock);
	}
}

/*
 * Determine if the ill and multicast aspects of that packets
 * "matches" the conn.
 */
boolean_t
conn_wantpacket(conn_t *connp, ip_recv_attr_t *ira, ipha_t *ipha)
{
	ill_t		*ill = ira->ira_rill;
	zoneid_t	zoneid = ira->ira_zoneid;
	uint_t		in_ifindex;
	ipaddr_t	dst, src;

	dst = ipha->ipha_dst;
	src = ipha->ipha_src;

	/*
	 * conn_incoming_ifindex is set by IP_BOUND_IF which limits
	 * unicast, broadcast and multicast reception to
	 * conn_incoming_ifindex.
	 * conn_wantpacket is called for unicast, broadcast and
	 * multicast packets.
	 */
	in_ifindex = connp->conn_incoming_ifindex;

	/* mpathd can bind to the under IPMP interface, which we allow */
	if (in_ifindex != 0 && in_ifindex != ill->ill_phyint->phyint_ifindex) {
		if (!IS_UNDER_IPMP(ill))
			return (B_FALSE);

		if (in_ifindex != ipmp_ill_get_ipmp_ifindex(ill))
			return (B_FALSE);
	}

	if (!IPCL_ZONE_MATCH(connp, zoneid))
		return (B_FALSE);

	if (!(ira->ira_flags & IRAF_MULTICAST))
		return (B_TRUE);

	if (connp->conn_multi_router) {
		/* multicast packet and multicast router socket: send up */
		return (B_TRUE);
	}

	if (ipha->ipha_protocol == IPPROTO_PIM ||
	    ipha->ipha_protocol == IPPROTO_RSVP)
		return (B_TRUE);

	return (conn_hasmembers_ill_withsrc_v4(connp, dst, src, ira->ira_ill));
}

void
conn_setqfull(conn_t *connp, boolean_t *flow_stopped)
{
	if (IPCL_IS_NONSTR(connp)) {
		(*connp->conn_upcalls->su_txq_full)
		    (connp->conn_upper_handle, B_TRUE);
		if (flow_stopped != NULL)
			*flow_stopped = B_TRUE;
	} else {
		queue_t *q = connp->conn_wq;

		ASSERT(q != NULL);
		if (!(q->q_flag & QFULL)) {
			mutex_enter(QLOCK(q));
			if (!(q->q_flag & QFULL)) {
				/* still need to set QFULL */
				q->q_flag |= QFULL;
				/* set flow_stopped to true under QLOCK */
				if (flow_stopped != NULL)
					*flow_stopped = B_TRUE;
				mutex_exit(QLOCK(q));
			} else {
				/* flow_stopped is left unchanged */
				mutex_exit(QLOCK(q));
			}
		}
	}
}

void
conn_clrqfull(conn_t *connp, boolean_t *flow_stopped)
{
	if (IPCL_IS_NONSTR(connp)) {
		(*connp->conn_upcalls->su_txq_full)
		    (connp->conn_upper_handle, B_FALSE);
		if (flow_stopped != NULL)
			*flow_stopped = B_FALSE;
	} else {
		queue_t *q = connp->conn_wq;

		ASSERT(q != NULL);
		if (q->q_flag & QFULL) {
			mutex_enter(QLOCK(q));
			if (q->q_flag & QFULL) {
				q->q_flag &= ~QFULL;
				/* set flow_stopped to false under QLOCK */
				if (flow_stopped != NULL)
					*flow_stopped = B_FALSE;
				mutex_exit(QLOCK(q));
				if (q->q_flag & QWANTW)
					qbackenable(q, 0);
			} else {
				/* flow_stopped is left unchanged */
				mutex_exit(QLOCK(q));
			}
		}
	}

	mutex_enter(&connp->conn_lock);
	connp->conn_blocked = B_FALSE;
	mutex_exit(&connp->conn_lock);
}

/*
 * Return the length in bytes of the IPv4 headers (base header, label, and
 * other IP options) that will be needed based on the
 * ip_pkt_t structure passed by the caller.
 *
 * The returned length does not include the length of the upper level
 * protocol (ULP) header.
 * The caller needs to check that the length doesn't exceed the max for IPv4.
 */
int
ip_total_hdrs_len_v4(const ip_pkt_t *ipp)
{
	int len;

	len = IP_SIMPLE_HDR_LENGTH;
	if (ipp->ipp_fields & IPPF_LABEL_V4) {
		ASSERT(ipp->ipp_label_len_v4 != 0);
		/* We need to round up here */
		len += (ipp->ipp_label_len_v4 + 3) & ~3;
	}

	if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
		ASSERT(ipp->ipp_ipv4_options_len != 0);
		ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
		len += ipp->ipp_ipv4_options_len;
	}
	return (len);
}

/*
 * All-purpose routine to build an IPv4 header with options based
 * on the abstract ip_pkt_t.
 *
 * The caller has to set the source and destination address as well as
 * ipha_length. The caller has to massage any source route and compensate
 * for the ULP pseudo-header checksum due to the source route.
 */
void
ip_build_hdrs_v4(uchar_t *buf, uint_t buf_len, const ip_pkt_t *ipp,
    uint8_t protocol)
{
	ipha_t	*ipha = (ipha_t *)buf;
	uint8_t *cp;

	/* Initialize IPv4 header */
	ipha->ipha_type_of_service = ipp->ipp_type_of_service;
	ipha->ipha_length = 0;	/* Caller will set later */
	ipha->ipha_ident = 0;
	ipha->ipha_fragment_offset_and_flags = 0;
	ipha->ipha_ttl = ipp->ipp_unicast_hops;
	ipha->ipha_protocol = protocol;
	ipha->ipha_hdr_checksum = 0;

	if ((ipp->ipp_fields & IPPF_ADDR) &&
	    IN6_IS_ADDR_V4MAPPED(&ipp->ipp_addr))
		ipha->ipha_src = ipp->ipp_addr_v4;

	cp = (uint8_t *)&ipha[1];
	if (ipp->ipp_fields & IPPF_LABEL_V4) {
		ASSERT(ipp->ipp_label_len_v4 != 0);
		bcopy(ipp->ipp_label_v4, cp, ipp->ipp_label_len_v4);
		cp += ipp->ipp_label_len_v4;
		/* We need to round up here */
		while ((uintptr_t)cp & 0x3) {
			*cp++ = IPOPT_NOP;
		}
	}

	if (ipp->ipp_fields & IPPF_IPV4_OPTIONS) {
		ASSERT(ipp->ipp_ipv4_options_len != 0);
		ASSERT((ipp->ipp_ipv4_options_len & 3) == 0);
		bcopy(ipp->ipp_ipv4_options, cp, ipp->ipp_ipv4_options_len);
		cp += ipp->ipp_ipv4_options_len;
	}
	ipha->ipha_version_and_hdr_length =
	    (uint8_t)((IP_VERSION << 4) + buf_len / 4);

	ASSERT((int)(cp - buf) == buf_len);
}

/* Allocate the private structure */
static int
ip_priv_alloc(void **bufp)
{
	void	*buf;

	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
		return (ENOMEM);

	*bufp = buf;
	return (0);
}

/* Function to delete the private structure */
void
ip_priv_free(void *buf)
{
	ASSERT(buf != NULL);
	kmem_free(buf, sizeof (ip_priv_t));
}

/*
 * The entry point for IPPF processing.
 * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
 * routine just returns.
 *
 * When called, ip_process generates an ipp_packet_t structure
 * which holds the state information for this packet and invokes the
 * the classifier (via ipp_packet_process). The classification, depending on
 * configured filters, results in a list of actions for this packet. Invoking
 * an action may cause the packet to be dropped, in which case we return NULL.
 * proc indicates the callout position for
 * this packet and ill is the interface this packet arrived on or will leave
 * on (inbound and outbound resp.).
 *
 * We do the processing on the rill (mapped to the upper if ipmp), but MIB
 * on the ill corrsponding to the destination IP address.
 */
mblk_t *
ip_process(ip_proc_t proc, mblk_t *mp, ill_t *rill, ill_t *ill)
{
	ip_priv_t	*priv;
	ipp_action_id_t	aid;
	int		rc = 0;
	ipp_packet_t	*pp;

	/* If the classifier is not loaded, return  */
	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
		return (mp);
	}

	ASSERT(mp != NULL);

	/* Allocate the packet structure */
	rc = ipp_packet_alloc(&pp, "ip", aid);
	if (rc != 0)
		goto drop;

	/* Allocate the private structure */
	rc = ip_priv_alloc((void **)&priv);
	if (rc != 0) {
		ipp_packet_free(pp);
		goto drop;
	}
	priv->proc = proc;
	priv->ill_index = ill_get_upper_ifindex(rill);

	ipp_packet_set_private(pp, priv, ip_priv_free);
	ipp_packet_set_data(pp, mp);

	/* Invoke the classifier */
	rc = ipp_packet_process(&pp);
	if (pp != NULL) {
		mp = ipp_packet_get_data(pp);
		ipp_packet_free(pp);
		if (rc != 0)
			goto drop;
		return (mp);
	} else {
		/* No mp to trace in ip_drop_input/ip_drop_output  */
		mp = NULL;
	}
drop:
	if (proc == IPP_LOCAL_IN || proc == IPP_FWD_IN) {
		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
		ip_drop_input("ip_process", mp, ill);
	} else {
		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
		ip_drop_output("ip_process", mp, ill);
	}
	freemsg(mp);
	return (NULL);
}

/*
 * Propagate a multicast group membership operation (add/drop) on
 * all the interfaces crossed by the related multirt routes.
 * The call is considered successful if the operation succeeds
 * on at least one interface.
 *
 * This assumes that a set of IRE_HOST/RTF_MULTIRT has been created for the
 * multicast addresses with the ire argument being the first one.
 * We walk the bucket to find all the of those.
 *
 * Common to IPv4 and IPv6.
 */
static int
ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
    const in6_addr_t *, ipaddr_t, uint_t, mcast_record_t, const in6_addr_t *),
    ire_t *ire, conn_t *connp, boolean_t checkonly, const in6_addr_t *v6group,
    mcast_record_t fmode, const in6_addr_t *v6src)
{
	ire_t		*ire_gw;
	irb_t		*irb;
	int		ifindex;
	int		error = 0;
	int		result;
	ip_stack_t	*ipst = ire->ire_ipst;
	ipaddr_t	group;
	boolean_t	isv6;
	int		match_flags;

	if (IN6_IS_ADDR_V4MAPPED(v6group)) {
		IN6_V4MAPPED_TO_IPADDR(v6group, group);
		isv6 = B_FALSE;
	} else {
		isv6 = B_TRUE;
	}

	irb = ire->ire_bucket;
	ASSERT(irb != NULL);

	result = 0;
	irb_refhold(irb);
	for (; ire != NULL; ire = ire->ire_next) {
		if ((ire->ire_flags & RTF_MULTIRT) == 0)
			continue;

		/* We handle -ifp routes by matching on the ill if set */
		match_flags = MATCH_IRE_TYPE;
		if (ire->ire_ill != NULL)
			match_flags |= MATCH_IRE_ILL;

		if (isv6) {
			if (!IN6_ARE_ADDR_EQUAL(&ire->ire_addr_v6, v6group))
				continue;

			ire_gw = ire_ftable_lookup_v6(&ire->ire_gateway_addr_v6,
			    0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
			    match_flags, 0, ipst, NULL);
		} else {
			if (ire->ire_addr != group)
				continue;

			ire_gw = ire_ftable_lookup_v4(ire->ire_gateway_addr,
			    0, 0, IRE_INTERFACE, ire->ire_ill, ALL_ZONES, NULL,
			    match_flags, 0, ipst, NULL);
		}
		/* No interface route exists for the gateway; skip this ire. */
		if (ire_gw == NULL)
			continue;
		if (ire_gw->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
			ire_refrele(ire_gw);
			continue;
		}
		ASSERT(ire_gw->ire_ill != NULL);	/* IRE_INTERFACE */
		ifindex = ire_gw->ire_ill->ill_phyint->phyint_ifindex;

		/*
		 * The operation is considered a success if
		 * it succeeds at least once on any one interface.
		 */
		error = fn(connp, checkonly, v6group, INADDR_ANY, ifindex,
		    fmode, v6src);
		if (error == 0)
			result = CGTP_MCAST_SUCCESS;

		ire_refrele(ire_gw);
	}
	irb_refrele(irb);
	/*
	 * Consider the call as successful if we succeeded on at least
	 * one interface. Otherwise, return the last encountered error.
	 */
	return (result == CGTP_MCAST_SUCCESS ? 0 : error);
}

/*
 * Return the expected CGTP hooks version number.
 */
int
ip_cgtp_filter_supported(void)
{
	return (ip_cgtp_filter_rev);
}

/*
 * CGTP hooks can be registered by invoking this function.
 * Checks that the version number matches.
 */
int
ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
{
	netstack_t *ns;
	ip_stack_t *ipst;

	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
		return (ENOTSUP);

	ns = netstack_find_by_stackid(stackid);
	if (ns == NULL)
		return (EINVAL);
	ipst = ns->netstack_ip;
	ASSERT(ipst != NULL);

	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
		netstack_rele(ns);
		return (EALREADY);
	}

	ipst->ips_ip_cgtp_filter_ops = ops;

	ill_set_inputfn_all(ipst);

	netstack_rele(ns);
	return (0);
}

/*
 * CGTP hooks can be unregistered by invoking this function.
 * Returns ENXIO if there was no registration.
 * Returns EBUSY if the ndd variable has not been turned off.
 */
int
ip_cgtp_filter_unregister(netstackid_t stackid)
{
	netstack_t *ns;
	ip_stack_t *ipst;

	ns = netstack_find_by_stackid(stackid);
	if (ns == NULL)
		return (EINVAL);
	ipst = ns->netstack_ip;
	ASSERT(ipst != NULL);

	if (ipst->ips_ip_cgtp_filter) {
		netstack_rele(ns);
		return (EBUSY);
	}

	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
		netstack_rele(ns);
		return (ENXIO);
	}
	ipst->ips_ip_cgtp_filter_ops = NULL;

	ill_set_inputfn_all(ipst);

	netstack_rele(ns);
	return (0);
}

/*
 * Check whether there is a CGTP filter registration.
 * Returns non-zero if there is a registration, otherwise returns zero.
 * Note: returns zero if bad stackid.
 */
int
ip_cgtp_filter_is_registered(netstackid_t stackid)
{
	netstack_t *ns;
	ip_stack_t *ipst;
	int ret;

	ns = netstack_find_by_stackid(stackid);
	if (ns == NULL)
		return (0);
	ipst = ns->netstack_ip;
	ASSERT(ipst != NULL);

	if (ipst->ips_ip_cgtp_filter_ops != NULL)
		ret = 1;
	else
		ret = 0;

	netstack_rele(ns);
	return (ret);
}

static int
ip_squeue_switch(int val)
{
	int rval;

	switch (val) {
	case IP_SQUEUE_ENTER_NODRAIN:
		rval = SQ_NODRAIN;
		break;
	case IP_SQUEUE_ENTER:
		rval = SQ_PROCESS;
		break;
	case IP_SQUEUE_FILL:
	default:
		rval = SQ_FILL;
		break;
	}
	return (rval);
}

static void *
ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
{
	kstat_t *ksp;

	ip_stat_t template = {
		{ "ip_udp_fannorm",		KSTAT_DATA_UINT64 },
		{ "ip_udp_fanmb",		KSTAT_DATA_UINT64 },
		{ "ip_recv_pullup",		KSTAT_DATA_UINT64 },
		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
		{ "ip_notaligned",		KSTAT_DATA_UINT64 },
		{ "ip_multimblk",		KSTAT_DATA_UINT64 },
		{ "ip_opt",			KSTAT_DATA_UINT64 },
		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
		{ "ip_out_sw_cksum_bytes",	KSTAT_DATA_UINT64 },
		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
		{ "ip_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
		{ "ip_ire_reclaim_deleted",	KSTAT_DATA_UINT64 },
		{ "ip_nce_reclaim_calls",	KSTAT_DATA_UINT64 },
		{ "ip_nce_reclaim_deleted",	KSTAT_DATA_UINT64 },
		{ "ip_nce_mcast_reclaim_calls",	KSTAT_DATA_UINT64 },
		{ "ip_nce_mcast_reclaim_deleted",	KSTAT_DATA_UINT64 },
		{ "ip_nce_mcast_reclaim_tqfail",	KSTAT_DATA_UINT64 },
		{ "ip_dce_reclaim_calls",	KSTAT_DATA_UINT64 },
		{ "ip_dce_reclaim_deleted",	KSTAT_DATA_UINT64 },
		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
		{ "ip_udp_in_sw_cksum_err",	KSTAT_DATA_UINT64 },
		{ "conn_in_recvdstaddr",	KSTAT_DATA_UINT64 },
		{ "conn_in_recvopts",		KSTAT_DATA_UINT64 },
		{ "conn_in_recvif",		KSTAT_DATA_UINT64 },
		{ "conn_in_recvslla",		KSTAT_DATA_UINT64 },
		{ "conn_in_recvucred",		KSTAT_DATA_UINT64 },
		{ "conn_in_recvttl",		KSTAT_DATA_UINT64 },
		{ "conn_in_recvtos",		KSTAT_DATA_UINT64 },
		{ "conn_in_recvhopopts",	KSTAT_DATA_UINT64 },
		{ "conn_in_recvhoplimit",	KSTAT_DATA_UINT64 },
		{ "conn_in_recvdstopts",	KSTAT_DATA_UINT64 },
		{ "conn_in_recvrthdrdstopts",	KSTAT_DATA_UINT64 },
		{ "conn_in_recvrthdr",		KSTAT_DATA_UINT64 },
		{ "conn_in_recvpktinfo",	KSTAT_DATA_UINT64 },
		{ "conn_in_recvtclass",		KSTAT_DATA_UINT64 },
		{ "conn_in_timestamp",		KSTAT_DATA_UINT64 },
	};

	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
	    KSTAT_FLAG_VIRTUAL, stackid);

	if (ksp == NULL)
		return (NULL);

	bcopy(&template, ip_statisticsp, sizeof (template));
	ksp->ks_data = (void *)ip_statisticsp;
	ksp->ks_private = (void *)(uintptr_t)stackid;

	kstat_install(ksp);
	return (ksp);
}

static void
ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
{
	if (ksp != NULL) {
		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
		kstat_delete_netstack(ksp, stackid);
	}
}

static void *
ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
{
	kstat_t	*ksp;

	ip_named_kstat_t template = {
		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
	};

	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
	if (ksp == NULL || ksp->ks_data == NULL)
		return (NULL);

	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
	template.reasmTimeout.value.ui32 = ipst->ips_ip_reassembly_timeout;
	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);

	template.netToMediaEntrySize.value.i32 =
	    sizeof (mib2_ipNetToMediaEntry_t);

	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);

	bcopy(&template, ksp->ks_data, sizeof (template));
	ksp->ks_update = ip_kstat_update;
	ksp->ks_private = (void *)(uintptr_t)stackid;

	kstat_install(ksp);
	return (ksp);
}

static void
ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
{
	if (ksp != NULL) {
		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
		kstat_delete_netstack(ksp, stackid);
	}
}

static int
ip_kstat_update(kstat_t *kp, int rw)
{
	ip_named_kstat_t *ipkp;
	mib2_ipIfStatsEntry_t ipmib;
	ill_walk_context_t ctx;
	ill_t *ill;
	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
	netstack_t	*ns;
	ip_stack_t	*ipst;

	if (kp->ks_data == NULL)
		return (EIO);

	if (rw == KSTAT_WRITE)
		return (EACCES);

	ns = netstack_find_by_stackid(stackid);
	if (ns == NULL)
		return (-1);
	ipst = ns->netstack_ip;
	if (ipst == NULL) {
		netstack_rele(ns);
		return (-1);
	}
	ipkp = (ip_named_kstat_t *)kp->ks_data;

	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
	ill = ILL_START_WALK_V4(&ctx, ipst);
	for (; ill != NULL; ill = ill_next(&ctx, ill))
		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
	rw_exit(&ipst->ips_ill_g_lock);

	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_reassembly_timeout;
	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;

	ipkp->routingDiscards.value.ui32 =	0;
	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;

	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;

	netstack_rele(ns);

	return (0);
}

static void *
icmp_kstat_init(netstackid_t stackid)
{
	kstat_t	*ksp;

	icmp_named_kstat_t template = {
		{ "inMsgs",		KSTAT_DATA_UINT32 },
		{ "inErrors",		KSTAT_DATA_UINT32 },
		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
		{ "inParmProbs",	KSTAT_DATA_UINT32 },
		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
		{ "inRedirects",	KSTAT_DATA_UINT32 },
		{ "inEchos",		KSTAT_DATA_UINT32 },
		{ "inEchoReps",		KSTAT_DATA_UINT32 },
		{ "inTimestamps",	KSTAT_DATA_UINT32 },
		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
		{ "outMsgs",		KSTAT_DATA_UINT32 },
		{ "outErrors",		KSTAT_DATA_UINT32 },
		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
		{ "outParmProbs",	KSTAT_DATA_UINT32 },
		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
		{ "outRedirects",	KSTAT_DATA_UINT32 },
		{ "outEchos",		KSTAT_DATA_UINT32 },
		{ "outEchoReps",	KSTAT_DATA_UINT32 },
		{ "outTimestamps",	KSTAT_DATA_UINT32 },
		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
		{ "inUnknowns",		KSTAT_DATA_UINT32 },
		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
		{ "outDrops",		KSTAT_DATA_UINT32 },
		{ "inOverFlows",	KSTAT_DATA_UINT32 },
		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
	};

	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
	if (ksp == NULL || ksp->ks_data == NULL)
		return (NULL);

	bcopy(&template, ksp->ks_data, sizeof (template));

	ksp->ks_update = icmp_kstat_update;
	ksp->ks_private = (void *)(uintptr_t)stackid;

	kstat_install(ksp);
	return (ksp);
}

static void
icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
{
	if (ksp != NULL) {
		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
		kstat_delete_netstack(ksp, stackid);
	}
}

static int
icmp_kstat_update(kstat_t *kp, int rw)
{
	icmp_named_kstat_t *icmpkp;
	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
	netstack_t	*ns;
	ip_stack_t	*ipst;

	if (kp->ks_data == NULL)
		return (EIO);

	if (rw == KSTAT_WRITE)
		return (EACCES);

	ns = netstack_find_by_stackid(stackid);
	if (ns == NULL)
		return (-1);
	ipst = ns->netstack_ip;
	if (ipst == NULL) {
		netstack_rele(ns);
		return (-1);
	}
	icmpkp = (icmp_named_kstat_t *)kp->ks_data;

	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
	icmpkp->inDestUnreachs.value.ui32 =
	    ipst->ips_icmp_mib.icmpInDestUnreachs;
	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
	icmpkp->inTimestampReps.value.ui32 =
	    ipst->ips_icmp_mib.icmpInTimestampReps;
	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
	icmpkp->inAddrMaskReps.value.ui32 =
	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
	icmpkp->outDestUnreachs.value.ui32 =
	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
	icmpkp->outSrcQuenchs.value.ui32 =
	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
	icmpkp->outTimestamps.value.ui32 =
	    ipst->ips_icmp_mib.icmpOutTimestamps;
	icmpkp->outTimestampReps.value.ui32 =
	    ipst->ips_icmp_mib.icmpOutTimestampReps;
	icmpkp->outAddrMasks.value.ui32 =
	    ipst->ips_icmp_mib.icmpOutAddrMasks;
	icmpkp->outAddrMaskReps.value.ui32 =
	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
	icmpkp->outFragNeeded.value.ui32 =
	    ipst->ips_icmp_mib.icmpOutFragNeeded;
	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
	icmpkp->inBadRedirects.value.ui32 =
	    ipst->ips_icmp_mib.icmpInBadRedirects;

	netstack_rele(ns);
	return (0);
}

/*
 * This is the fanout function for raw socket opened for SCTP.  Note
 * that it is called after SCTP checks that there is no socket which
 * wants a packet.  Then before SCTP handles this out of the blue packet,
 * this function is called to see if there is any raw socket for SCTP.
 * If there is and it is bound to the correct address, the packet will
 * be sent to that socket.  Note that only one raw socket can be bound to
 * a port.  This is assured in ipcl_sctp_hash_insert();
 */
void
ip_fanout_sctp_raw(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, uint32_t ports,
    ip_recv_attr_t *ira)
{
	conn_t		*connp;
	queue_t		*rq;
	boolean_t	secure;
	ill_t		*ill = ira->ira_ill;
	ip_stack_t	*ipst = ill->ill_ipst;
	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
	iaflags_t	iraflags = ira->ira_flags;
	ill_t		*rill = ira->ira_rill;

	secure = iraflags & IRAF_IPSEC_SECURE;

	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, ports, ipha, ip6h,
	    ira, ipst);
	if (connp == NULL) {
		/*
		 * Although raw sctp is not summed, OOB chunks must be.
		 * Drop the packet here if the sctp checksum failed.
		 */
		if (iraflags & IRAF_SCTP_CSUM_ERR) {
			SCTPS_BUMP_MIB(sctps, sctpChecksumError);
			freemsg(mp);
			return;
		}
		ira->ira_ill = ira->ira_rill = NULL;
		sctp_ootb_input(mp, ira, ipst);
		ira->ira_ill = ill;
		ira->ira_rill = rill;
		return;
	}
	rq = connp->conn_rq;
	if (IPCL_IS_NONSTR(connp) ? connp->conn_flow_cntrld : !canputnext(rq)) {
		CONN_DEC_REF(connp);
		BUMP_MIB(ill->ill_ip_mib, rawipIfStatsInOverflows);
		freemsg(mp);
		return;
	}
	if (((iraflags & IRAF_IS_IPV4) ?
	    CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) ||
	    secure) {
		mp = ipsec_check_inbound_policy(mp, connp, ipha,
		    ip6h, ira);
		if (mp == NULL) {
			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
			/* Note that mp is NULL */
			ip_drop_input("ipIfStatsInDiscards", mp, ill);
			CONN_DEC_REF(connp);
			return;
		}
	}

	if (iraflags & IRAF_ICMP_ERROR) {
		(connp->conn_recvicmp)(connp, mp, NULL, ira);
	} else {
		ill_t *rill = ira->ira_rill;

		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
		/* This is the SOCK_RAW, IPPROTO_SCTP case. */
		ira->ira_ill = ira->ira_rill = NULL;
		(connp->conn_recv)(connp, mp, NULL, ira);
		ira->ira_ill = ill;
		ira->ira_rill = rill;
	}
	CONN_DEC_REF(connp);
}

/*
 * Free a packet that has the link-layer dl_unitdata_req_t or fast-path
 * header before the ip payload.
 */
static void
ip_xmit_flowctl_drop(ill_t *ill, mblk_t *mp, boolean_t is_fp_mp, int fp_mp_len)
{
	int len = (mp->b_wptr - mp->b_rptr);
	mblk_t *ip_mp;

	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
	if (is_fp_mp || len != fp_mp_len) {
		if (len > fp_mp_len) {
			/*
			 * fastpath header and ip header in the first mblk
			 */
			mp->b_rptr += fp_mp_len;
		} else {
			/*
			 * ip_xmit_attach_llhdr had to prepend an mblk to
			 * attach the fastpath header before ip header.
			 */
			ip_mp = mp->b_cont;
			freeb(mp);
			mp = ip_mp;
			mp->b_rptr += (fp_mp_len - len);
		}
	} else {
		ip_mp = mp->b_cont;
		freeb(mp);
		mp = ip_mp;
	}
	ip_drop_output("ipIfStatsOutDiscards - flow ctl", mp, ill);
	freemsg(mp);
}

/*
 * Normal post fragmentation function.
 *
 * Send a packet using the passed in nce. This handles both IPv4 and IPv6
 * using the same state machine.
 *
 * We return an error on failure. In particular we return EWOULDBLOCK
 * when the driver flow controls. In that case this ensures that ip_wsrv runs
 * (currently by canputnext failure resulting in backenabling from GLD.)
 * This allows the callers of conn_ip_output() to use EWOULDBLOCK as an
 * indication that they can flow control until ip_wsrv() tells then to restart.
 *
 * If the nce passed by caller is incomplete, this function
 * queues the packet and if necessary, sends ARP request and bails.
 * If the Neighbor Cache passed is fully resolved, we simply prepend
 * the link-layer header to the packet, do ipsec hw acceleration
 * work if necessary, and send the packet out on the wire.
 */
/* ARGSUSED6 */
int
ip_xmit(mblk_t *mp, nce_t *nce, iaflags_t ixaflags, uint_t pkt_len,
    uint32_t xmit_hint, zoneid_t szone, zoneid_t nolzid, uintptr_t *ixacookie)
{
	queue_t		*wq;
	ill_t		*ill = nce->nce_ill;
	ip_stack_t	*ipst = ill->ill_ipst;
	uint64_t	delta;
	boolean_t	isv6 = ill->ill_isv6;
	boolean_t	fp_mp;
	ncec_t		*ncec = nce->nce_common;
	int64_t		now = LBOLT_FASTPATH64;
	boolean_t	is_probe;

	DTRACE_PROBE1(ip__xmit, nce_t *, nce);

	ASSERT(mp != NULL);
	ASSERT(mp->b_datap->db_type == M_DATA);
	ASSERT(pkt_len == msgdsize(mp));

	/*
	 * If we have already been here and are coming back after ARP/ND.
	 * the IXAF_NO_TRACE flag is set. We skip FW_HOOKS, DTRACE and ipobs
	 * in that case since they have seen the packet when it came here
	 * the first time.
	 */
	if (ixaflags & IXAF_NO_TRACE)
		goto sendit;

	if (ixaflags & IXAF_IS_IPV4) {
		ipha_t *ipha = (ipha_t *)mp->b_rptr;

		ASSERT(!isv6);
		ASSERT(pkt_len == ntohs(((ipha_t *)mp->b_rptr)->ipha_length));
		if (HOOKS4_INTERESTED_PHYSICAL_OUT(ipst) &&
		    !(ixaflags & IXAF_NO_PFHOOK)) {
			int	error;

			FW_HOOKS(ipst->ips_ip4_physical_out_event,
			    ipst->ips_ipv4firewall_physical_out,
			    NULL, ill, ipha, mp, mp, 0, ipst, error);
			DTRACE_PROBE1(ip4__physical__out__end,
			    mblk_t *, mp);
			if (mp == NULL)
				return (error);

			/* The length could have changed */
			pkt_len = msgdsize(mp);
		}
		if (ipst->ips_ip4_observe.he_interested) {
			/*
			 * Note that for TX the zoneid is the sending
			 * zone, whether or not MLP is in play.
			 * Since the szone argument is the IP zoneid (i.e.,
			 * zero for exclusive-IP zones) and ipobs wants
			 * the system zoneid, we map it here.
			 */
			szone = IP_REAL_ZONEID(szone, ipst);

			/*
			 * On the outbound path the destination zone will be
			 * unknown as we're sending this packet out on the
			 * wire.
			 */
			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
			    ill, ipst);
		}
		DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
		    void_ip_t *, ipha,  __dtrace_ipsr_ill_t *, ill,
		    ipha_t *, ipha, ip6_t *, NULL, int, 0);
	} else {
		ip6_t *ip6h = (ip6_t *)mp->b_rptr;

		ASSERT(isv6);
		ASSERT(pkt_len ==
		    ntohs(((ip6_t *)mp->b_rptr)->ip6_plen) + IPV6_HDR_LEN);
		if (HOOKS6_INTERESTED_PHYSICAL_OUT(ipst) &&
		    !(ixaflags & IXAF_NO_PFHOOK)) {
			int	error;

			FW_HOOKS6(ipst->ips_ip6_physical_out_event,
			    ipst->ips_ipv6firewall_physical_out,
			    NULL, ill, ip6h, mp, mp, 0, ipst, error);
			DTRACE_PROBE1(ip6__physical__out__end,
			    mblk_t *, mp);
			if (mp == NULL)
				return (error);

			/* The length could have changed */
			pkt_len = msgdsize(mp);
		}
		if (ipst->ips_ip6_observe.he_interested) {
			/* See above */
			szone = IP_REAL_ZONEID(szone, ipst);

			ipobs_hook(mp, IPOBS_HOOK_OUTBOUND, szone, ALL_ZONES,
			    ill, ipst);
		}
		DTRACE_IP7(send, mblk_t *, mp,  conn_t *, NULL,
		    void_ip_t *, ip6h,  __dtrace_ipsr_ill_t *, ill,
		    ipha_t *, NULL, ip6_t *, ip6h, int, 0);
	}

sendit:
	/*
	 * We check the state without a lock because the state can never
	 * move "backwards" to initial or incomplete.
	 */
	switch (ncec->ncec_state) {
	case ND_REACHABLE:
	case ND_STALE:
	case ND_DELAY:
	case ND_PROBE:
		mp = ip_xmit_attach_llhdr(mp, nce);
		if (mp == NULL) {
			/*
			 * ip_xmit_attach_llhdr has increased
			 * ipIfStatsOutDiscards and called ip_drop_output()
			 */
			return (ENOBUFS);
		}
		/*
		 * check if nce_fastpath completed and we tagged on a
		 * copy of nce_fp_mp in ip_xmit_attach_llhdr().
		 */
		fp_mp = (mp->b_datap->db_type == M_DATA);

		if (fp_mp &&
		    (ill->ill_capabilities & ILL_CAPAB_DLD_DIRECT)) {
			ill_dld_direct_t *idd;

			idd = &ill->ill_dld_capab->idc_direct;
			/*
			 * Send the packet directly to DLD, where it
			 * may be queued depending on the availability
			 * of transmit resources at the media layer.
			 * Return value should be taken into
			 * account and flow control the TCP.
			 */
			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
			    pkt_len);

			if (ixaflags & IXAF_NO_DEV_FLOW_CTL) {
				(void) idd->idd_tx_df(idd->idd_tx_dh, mp,
				    (uintptr_t)xmit_hint, IP_DROP_ON_NO_DESC);
			} else {
				uintptr_t cookie;

				if ((cookie = idd->idd_tx_df(idd->idd_tx_dh,
				    mp, (uintptr_t)xmit_hint, 0)) != 0) {
					if (ixacookie != NULL)
						*ixacookie = cookie;
					return (EWOULDBLOCK);
				}
			}
		} else {
			wq = ill->ill_wq;

			if (!(ixaflags & IXAF_NO_DEV_FLOW_CTL) &&
			    !canputnext(wq)) {
				if (ixacookie != NULL)
					*ixacookie = 0;
				ip_xmit_flowctl_drop(ill, mp, fp_mp,
				    nce->nce_fp_mp != NULL ?
				    MBLKL(nce->nce_fp_mp) : 0);
				return (EWOULDBLOCK);
			}
			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits);
			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets,
			    pkt_len);
			putnext(wq, mp);
		}

		/*
		 * The rest of this function implements Neighbor Unreachability
		 * detection. Determine if the ncec is eligible for NUD.
		 */
		if (ncec->ncec_flags & NCE_F_NONUD)
			return (0);

		ASSERT(ncec->ncec_state != ND_INCOMPLETE);

		/*
		 * Check for upper layer advice
		 */
		if (ixaflags & IXAF_REACH_CONF) {
			timeout_id_t tid;

			/*
			 * It should be o.k. to check the state without
			 * a lock here, at most we lose an advice.
			 */
			ncec->ncec_last = TICK_TO_MSEC(now);
			if (ncec->ncec_state != ND_REACHABLE) {
				mutex_enter(&ncec->ncec_lock);
				ncec->ncec_state = ND_REACHABLE;
				tid = ncec->ncec_timeout_id;
				ncec->ncec_timeout_id = 0;
				mutex_exit(&ncec->ncec_lock);
				(void) untimeout(tid);
				if (ip_debug > 2) {
					/* ip1dbg */
					pr_addr_dbg("ip_xmit: state"
					    " for %s changed to"
					    " REACHABLE\n", AF_INET6,
					    &ncec->ncec_addr);
				}
			}
			return (0);
		}

		delta =  TICK_TO_MSEC(now) - ncec->ncec_last;
		ip1dbg(("ip_xmit: delta = %" PRId64
		    " ill_reachable_time = %d \n", delta,
		    ill->ill_reachable_time));
		if (delta > (uint64_t)ill->ill_reachable_time) {
			mutex_enter(&ncec->ncec_lock);
			switch (ncec->ncec_state) {
			case ND_REACHABLE:
				ASSERT((ncec->ncec_flags & NCE_F_NONUD) == 0);
				/* FALLTHROUGH */
			case ND_STALE:
				/*
				 * ND_REACHABLE is identical to
				 * ND_STALE in this specific case. If
				 * reachable time has expired for this
				 * neighbor (delta is greater than
				 * reachable time), conceptually, the
				 * neighbor cache is no longer in
				 * REACHABLE state, but already in
				 * STALE state.  So the correct
				 * transition here is to ND_DELAY.
				 */
				ncec->ncec_state = ND_DELAY;
				mutex_exit(&ncec->ncec_lock);
				nce_restart_timer(ncec,
				    ipst->ips_delay_first_probe_time);
				if (ip_debug > 3) {
					/* ip2dbg */
					pr_addr_dbg("ip_xmit: state"
					    " for %s changed to"
					    " DELAY\n", AF_INET6,
					    &ncec->ncec_addr);
				}
				break;
			case ND_DELAY:
			case ND_PROBE:
				mutex_exit(&ncec->ncec_lock);
				/* Timers have already started */
				break;
			case ND_UNREACHABLE:
				/*
				 * nce_timer has detected that this ncec
				 * is unreachable and initiated deleting
				 * this ncec.
				 * This is a harmless race where we found the
				 * ncec before it was deleted and have
				 * just sent out a packet using this
				 * unreachable ncec.
				 */
				mutex_exit(&ncec->ncec_lock);
				break;
			default:
				ASSERT(0);
				mutex_exit(&ncec->ncec_lock);
			}
		}
		return (0);

	case ND_INCOMPLETE:
		/*
		 * the state could have changed since we didn't hold the lock.
		 * Re-verify state under lock.
		 */
		is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
		mutex_enter(&ncec->ncec_lock);
		if (NCE_ISREACHABLE(ncec)) {
			mutex_exit(&ncec->ncec_lock);
			goto sendit;
		}
		/* queue the packet */
		nce_queue_mp(ncec, mp, is_probe);
		mutex_exit(&ncec->ncec_lock);
		DTRACE_PROBE2(ip__xmit__incomplete,
		    (ncec_t *), ncec, (mblk_t *), mp);
		return (0);

	case ND_INITIAL:
		/*
		 * State could have changed since we didn't hold the lock, so
		 * re-verify state.
		 */
		is_probe = ipmp_packet_is_probe(mp, nce->nce_ill);
		mutex_enter(&ncec->ncec_lock);
		if (NCE_ISREACHABLE(ncec))  {
			mutex_exit(&ncec->ncec_lock);
			goto sendit;
		}
		nce_queue_mp(ncec, mp, is_probe);
		if (ncec->ncec_state == ND_INITIAL) {
			ncec->ncec_state = ND_INCOMPLETE;
			mutex_exit(&ncec->ncec_lock);
			/*
			 * figure out the source we want to use
			 * and resolve it.
			 */
			ip_ndp_resolve(ncec);
		} else  {
			mutex_exit(&ncec->ncec_lock);
		}
		return (0);

	case ND_UNREACHABLE:
		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
		ip_drop_output("ipIfStatsOutDiscards - ND_UNREACHABLE",
		    mp, ill);
		freemsg(mp);
		return (0);

	default:
		ASSERT(0);
		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
		ip_drop_output("ipIfStatsOutDiscards - ND_other",
		    mp, ill);
		freemsg(mp);
		return (ENETUNREACH);
	}
}

/*
 * Return B_TRUE if the buffers differ in length or content.
 * This is used for comparing extension header buffers.
 * Note that an extension header would be declared different
 * even if all that changed was the next header value in that header i.e.
 * what really changed is the next extension header.
 */
boolean_t
ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
    uint_t blen)
{
	if (!b_valid)
		blen = 0;

	if (alen != blen)
		return (B_TRUE);
	if (alen == 0)
		return (B_FALSE);	/* Both zero length */
	return (bcmp(abuf, bbuf, alen));
}

/*
 * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
 * Return B_FALSE if memory allocation fails - don't change any state!
 */
boolean_t
ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
    const void *src, uint_t srclen)
{
	void *dst;

	if (!src_valid)
		srclen = 0;

	ASSERT(*dstlenp == 0);
	if (src != NULL && srclen != 0) {
		dst = mi_alloc(srclen, BPRI_MED);
		if (dst == NULL)
			return (B_FALSE);
	} else {
		dst = NULL;
	}
	if (*dstp != NULL)
		mi_free(*dstp);
	*dstp = dst;
	*dstlenp = dst == NULL ? 0 : srclen;
	return (B_TRUE);
}

/*
 * Replace what is in *dst, *dstlen with the source.
 * Assumes ip_allocbuf has already been called.
 */
void
ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
    const void *src, uint_t srclen)
{
	if (!src_valid)
		srclen = 0;

	ASSERT(*dstlenp == srclen);
	if (src != NULL && srclen != 0)
		bcopy(src, *dstp, srclen);
}

/*
 * Free the storage pointed to by the members of an ip_pkt_t.
 */
void
ip_pkt_free(ip_pkt_t *ipp)
{
	uint_t	fields = ipp->ipp_fields;

	if (fields & IPPF_HOPOPTS) {
		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
		ipp->ipp_hopopts = NULL;
		ipp->ipp_hopoptslen = 0;
	}
	if (fields & IPPF_RTHDRDSTOPTS) {
		kmem_free(ipp->ipp_rthdrdstopts, ipp->ipp_rthdrdstoptslen);
		ipp->ipp_rthdrdstopts = NULL;
		ipp->ipp_rthdrdstoptslen = 0;
	}
	if (fields & IPPF_DSTOPTS) {
		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
		ipp->ipp_dstopts = NULL;
		ipp->ipp_dstoptslen = 0;
	}
	if (fields & IPPF_RTHDR) {
		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
		ipp->ipp_rthdr = NULL;
		ipp->ipp_rthdrlen = 0;
	}
	if (fields & IPPF_IPV4_OPTIONS) {
		kmem_free(ipp->ipp_ipv4_options, ipp->ipp_ipv4_options_len);
		ipp->ipp_ipv4_options = NULL;
		ipp->ipp_ipv4_options_len = 0;
	}
	if (fields & IPPF_LABEL_V4) {
		kmem_free(ipp->ipp_label_v4, ipp->ipp_label_len_v4);
		ipp->ipp_label_v4 = NULL;
		ipp->ipp_label_len_v4 = 0;
	}
	if (fields & IPPF_LABEL_V6) {
		kmem_free(ipp->ipp_label_v6, ipp->ipp_label_len_v6);
		ipp->ipp_label_v6 = NULL;
		ipp->ipp_label_len_v6 = 0;
	}
	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);
}

/*
 * Copy from src to dst and allocate as needed.
 * Returns zero or ENOMEM.
 *
 * The caller must initialize dst to zero.
 */
int
ip_pkt_copy(ip_pkt_t *src, ip_pkt_t *dst, int kmflag)
{
	uint_t	fields = src->ipp_fields;

	/* Start with fields that don't require memory allocation */
	dst->ipp_fields = fields &
	    ~(IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6);

	dst->ipp_addr = src->ipp_addr;
	dst->ipp_unicast_hops = src->ipp_unicast_hops;
	dst->ipp_hoplimit = src->ipp_hoplimit;
	dst->ipp_tclass = src->ipp_tclass;
	dst->ipp_type_of_service = src->ipp_type_of_service;

	if (!(fields & (IPPF_HOPOPTS | IPPF_RTHDRDSTOPTS | IPPF_DSTOPTS |
	    IPPF_RTHDR | IPPF_IPV4_OPTIONS | IPPF_LABEL_V4 | IPPF_LABEL_V6)))
		return (0);

	if (fields & IPPF_HOPOPTS) {
		dst->ipp_hopopts = kmem_alloc(src->ipp_hopoptslen, kmflag);
		if (dst->ipp_hopopts == NULL) {
			ip_pkt_free(dst);
			return (ENOMEM);
		}
		dst->ipp_fields |= IPPF_HOPOPTS;
		bcopy(src->ipp_hopopts, dst->ipp_hopopts,
		    src->ipp_hopoptslen);
		dst->ipp_hopoptslen = src->ipp_hopoptslen;
	}
	if (fields & IPPF_RTHDRDSTOPTS) {
		dst->ipp_rthdrdstopts = kmem_alloc(src->ipp_rthdrdstoptslen,
		    kmflag);
		if (dst->ipp_rthdrdstopts == NULL) {
			ip_pkt_free(dst);
			return (ENOMEM);
		}
		dst->ipp_fields |= IPPF_RTHDRDSTOPTS;
		bcopy(src->ipp_rthdrdstopts, dst->ipp_rthdrdstopts,
		    src->ipp_rthdrdstoptslen);
		dst->ipp_rthdrdstoptslen = src->ipp_rthdrdstoptslen;
	}
	if (fields & IPPF_DSTOPTS) {
		dst->ipp_dstopts = kmem_alloc(src->ipp_dstoptslen, kmflag);
		if (dst->ipp_dstopts == NULL) {
			ip_pkt_free(dst);
			return (ENOMEM);
		}
		dst->ipp_fields |= IPPF_DSTOPTS;
		bcopy(src->ipp_dstopts, dst->ipp_dstopts,
		    src->ipp_dstoptslen);
		dst->ipp_dstoptslen = src->ipp_dstoptslen;
	}
	if (fields & IPPF_RTHDR) {
		dst->ipp_rthdr = kmem_alloc(src->ipp_rthdrlen, kmflag);
		if (dst->ipp_rthdr == NULL) {
			ip_pkt_free(dst);
			return (ENOMEM);
		}
		dst->ipp_fields |= IPPF_RTHDR;
		bcopy(src->ipp_rthdr, dst->ipp_rthdr,
		    src->ipp_rthdrlen);
		dst->ipp_rthdrlen = src->ipp_rthdrlen;
	}
	if (fields & IPPF_IPV4_OPTIONS) {
		dst->ipp_ipv4_options = kmem_alloc(src->ipp_ipv4_options_len,
		    kmflag);
		if (dst->ipp_ipv4_options == NULL) {
			ip_pkt_free(dst);
			return (ENOMEM);
		}
		dst->ipp_fields |= IPPF_IPV4_OPTIONS;
		bcopy(src->ipp_ipv4_options, dst->ipp_ipv4_options,
		    src->ipp_ipv4_options_len);
		dst->ipp_ipv4_options_len = src->ipp_ipv4_options_len;
	}
	if (fields & IPPF_LABEL_V4) {
		dst->ipp_label_v4 = kmem_alloc(src->ipp_label_len_v4, kmflag);
		if (dst->ipp_label_v4 == NULL) {
			ip_pkt_free(dst);
			return (ENOMEM);
		}
		dst->ipp_fields |= IPPF_LABEL_V4;
		bcopy(src->ipp_label_v4, dst->ipp_label_v4,
		    src->ipp_label_len_v4);
		dst->ipp_label_len_v4 = src->ipp_label_len_v4;
	}
	if (fields & IPPF_LABEL_V6) {
		dst->ipp_label_v6 = kmem_alloc(src->ipp_label_len_v6, kmflag);
		if (dst->ipp_label_v6 == NULL) {
			ip_pkt_free(dst);
			return (ENOMEM);
		}
		dst->ipp_fields |= IPPF_LABEL_V6;
		bcopy(src->ipp_label_v6, dst->ipp_label_v6,
		    src->ipp_label_len_v6);
		dst->ipp_label_len_v6 = src->ipp_label_len_v6;
	}
	if (fields & IPPF_FRAGHDR) {
		dst->ipp_fraghdr = kmem_alloc(src->ipp_fraghdrlen, kmflag);
		if (dst->ipp_fraghdr == NULL) {
			ip_pkt_free(dst);
			return (ENOMEM);
		}
		dst->ipp_fields |= IPPF_FRAGHDR;
		bcopy(src->ipp_fraghdr, dst->ipp_fraghdr,
		    src->ipp_fraghdrlen);
		dst->ipp_fraghdrlen = src->ipp_fraghdrlen;
	}
	return (0);
}

/*
 * Returns INADDR_ANY if no source route
 */
ipaddr_t
ip_pkt_source_route_v4(const ip_pkt_t *ipp)
{
	ipaddr_t	nexthop = INADDR_ANY;
	ipoptp_t	opts;
	uchar_t		*opt;
	uint8_t		optval;
	uint8_t		optlen;
	uint32_t	totallen;

	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
		return (INADDR_ANY);

	totallen = ipp->ipp_ipv4_options_len;
	if (totallen & 0x3)
		return (INADDR_ANY);

	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
	    optval != IPOPT_EOL;
	    optval = ipoptp_next(&opts)) {
		opt = opts.ipoptp_cur;
		switch (optval) {
			uint8_t off;
		case IPOPT_SSRR:
		case IPOPT_LSRR:
			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
				break;
			}
			optlen = opts.ipoptp_len;
			off = opt[IPOPT_OFFSET];
			off--;
			if (optlen < IP_ADDR_LEN ||
			    off > optlen - IP_ADDR_LEN) {
				/* End of source route */
				break;
			}
			bcopy((char *)opt + off, &nexthop, IP_ADDR_LEN);
			if (nexthop == htonl(INADDR_LOOPBACK)) {
				/* Ignore */
				nexthop = INADDR_ANY;
				break;
			}
			break;
		}
	}
	return (nexthop);
}

/*
 * Reverse a source route.
 */
void
ip_pkt_source_route_reverse_v4(ip_pkt_t *ipp)
{
	ipaddr_t	tmp;
	ipoptp_t	opts;
	uchar_t		*opt;
	uint8_t		optval;
	uint32_t	totallen;

	if (!(ipp->ipp_fields & IPPF_IPV4_OPTIONS))
		return;

	totallen = ipp->ipp_ipv4_options_len;
	if (totallen & 0x3)
		return;

	for (optval = ipoptp_first2(&opts, totallen, ipp->ipp_ipv4_options);
	    optval != IPOPT_EOL;
	    optval = ipoptp_next(&opts)) {
		uint8_t off1, off2;

		opt = opts.ipoptp_cur;
		switch (optval) {
		case IPOPT_SSRR:
		case IPOPT_LSRR:
			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
				break;
			}
			off1 = IPOPT_MINOFF_SR - 1;
			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
			while (off2 > off1) {
				bcopy(opt + off2, &tmp, IP_ADDR_LEN);
				bcopy(opt + off1, opt + off2, IP_ADDR_LEN);
				bcopy(&tmp, opt + off2, IP_ADDR_LEN);
				off2 -= IP_ADDR_LEN;
				off1 += IP_ADDR_LEN;
			}
			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
			break;
		}
	}
}

/*
 * Returns NULL if no routing header
 */
in6_addr_t *
ip_pkt_source_route_v6(const ip_pkt_t *ipp)
{
	in6_addr_t	*nexthop = NULL;
	ip6_rthdr0_t	*rthdr;

	if (!(ipp->ipp_fields & IPPF_RTHDR))
		return (NULL);

	rthdr = (ip6_rthdr0_t *)ipp->ipp_rthdr;
	if (rthdr->ip6r0_segleft == 0)
		return (NULL);

	nexthop = (in6_addr_t *)((char *)rthdr + sizeof (*rthdr));
	return (nexthop);
}

zoneid_t
ip_get_zoneid_v4(ipaddr_t addr, mblk_t *mp, ip_recv_attr_t *ira,
    zoneid_t lookup_zoneid)
{
	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
	ire_t		*ire;
	int		ire_flags = MATCH_IRE_TYPE;
	zoneid_t	zoneid = ALL_ZONES;

	if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
		return (ALL_ZONES);

	if (lookup_zoneid != ALL_ZONES)
		ire_flags |= MATCH_IRE_ZONEONLY;
	ire = ire_ftable_lookup_v4(addr, 0, 0, IRE_LOCAL | IRE_LOOPBACK,
	    NULL, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
	if (ire != NULL) {
		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
		ire_refrele(ire);
	}
	return (zoneid);
}

zoneid_t
ip_get_zoneid_v6(in6_addr_t *addr, mblk_t *mp, const ill_t *ill,
    ip_recv_attr_t *ira, zoneid_t lookup_zoneid)
{
	ip_stack_t	*ipst = ira->ira_ill->ill_ipst;
	ire_t		*ire;
	int		ire_flags = MATCH_IRE_TYPE;
	zoneid_t	zoneid = ALL_ZONES;

	if (is_system_labeled() && !tsol_can_accept_raw(mp, ira, B_FALSE))
		return (ALL_ZONES);

	if (IN6_IS_ADDR_LINKLOCAL(addr))
		ire_flags |= MATCH_IRE_ILL;

	if (lookup_zoneid != ALL_ZONES)
		ire_flags |= MATCH_IRE_ZONEONLY;
	ire = ire_ftable_lookup_v6(addr, NULL, NULL, IRE_LOCAL | IRE_LOOPBACK,
	    ill, lookup_zoneid, NULL, ire_flags, 0, ipst, NULL);
	if (ire != NULL) {
		zoneid = IP_REAL_ZONEID(ire->ire_zoneid, ipst);
		ire_refrele(ire);
	}
	return (zoneid);
}

/*
 * IP obserability hook support functions.
 */
static void
ipobs_init(ip_stack_t *ipst)
{
	netid_t id;

	id = net_getnetidbynetstackid(ipst->ips_netstack->netstack_stackid);

	ipst->ips_ip4_observe_pr = net_protocol_lookup(id, NHF_INET);
	VERIFY(ipst->ips_ip4_observe_pr != NULL);

	ipst->ips_ip6_observe_pr = net_protocol_lookup(id, NHF_INET6);
	VERIFY(ipst->ips_ip6_observe_pr != NULL);
}

static void
ipobs_fini(ip_stack_t *ipst)
{

	VERIFY(net_protocol_release(ipst->ips_ip4_observe_pr) == 0);
	VERIFY(net_protocol_release(ipst->ips_ip6_observe_pr) == 0);
}

/*
 * hook_pkt_observe_t is composed in network byte order so that the
 * entire mblk_t chain handed into hook_run can be used as-is.
 * The caveat is that use of the fields, such as the zone fields,
 * requires conversion into host byte order first.
 */
void
ipobs_hook(mblk_t *mp, int htype, zoneid_t zsrc, zoneid_t zdst,
    const ill_t *ill, ip_stack_t *ipst)
{
	hook_pkt_observe_t *hdr;
	uint64_t grifindex;
	mblk_t *imp;

	imp = allocb(sizeof (*hdr), BPRI_HI);
	if (imp == NULL)
		return;

	hdr = (hook_pkt_observe_t *)imp->b_rptr;
	/*
	 * b_wptr is set to make the apparent size of the data in the mblk_t
	 * to exclude the pointers at the end of hook_pkt_observer_t.
	 */
	imp->b_wptr = imp->b_rptr + sizeof (dl_ipnetinfo_t);
	imp->b_cont = mp;

	ASSERT(DB_TYPE(mp) == M_DATA);

	if (IS_UNDER_IPMP(ill))
		grifindex = ipmp_ill_get_ipmp_ifindex(ill);
	else
		grifindex = 0;

	hdr->hpo_version = 1;
	hdr->hpo_htype = htons(htype);
	hdr->hpo_pktlen = htonl((ulong_t)msgdsize(mp));
	hdr->hpo_ifindex = htonl(ill->ill_phyint->phyint_ifindex);
	hdr->hpo_grifindex = htonl(grifindex);
	hdr->hpo_zsrc = htonl(zsrc);
	hdr->hpo_zdst = htonl(zdst);
	hdr->hpo_pkt = imp;
	hdr->hpo_ctx = ipst->ips_netstack;

	if (ill->ill_isv6) {
		hdr->hpo_family = AF_INET6;
		(void) hook_run(ipst->ips_ipv6_net_data->netd_hooks,
		    ipst->ips_ipv6observing, (hook_data_t)hdr);
	} else {
		hdr->hpo_family = AF_INET;
		(void) hook_run(ipst->ips_ipv4_net_data->netd_hooks,
		    ipst->ips_ipv4observing, (hook_data_t)hdr);
	}

	imp->b_cont = NULL;
	freemsg(imp);
}

/*
 * Utility routine that checks if `v4srcp' is a valid address on underlying
 * interface `ill'.  If `ipifp' is non-NULL, it's set to a held ipif
 * associated with `v4srcp' on success.  NOTE: if this is not called from
 * inside the IPSQ (ill_g_lock is not held), `ill' may be removed from the
 * group during or after this lookup.
 */
boolean_t
ipif_lookup_testaddr_v4(ill_t *ill, const in_addr_t *v4srcp, ipif_t **ipifp)
{
	ipif_t *ipif;

	ipif = ipif_lookup_addr_exact(*v4srcp, ill, ill->ill_ipst);
	if (ipif != NULL) {
		if (ipifp != NULL)
			*ipifp = ipif;
		else
			ipif_refrele(ipif);
		return (B_TRUE);
	}

	ip1dbg(("ipif_lookup_testaddr_v4: cannot find ipif for src %x\n",
	    *v4srcp));
	return (B_FALSE);
}

/*
 * Transport protocol call back function for CPU state change.
 */
/* ARGSUSED */
static int
ip_tp_cpu_update(cpu_setup_t what, int id, void *arg)
{
	processorid_t cpu_seqid;
	netstack_handle_t nh;
	netstack_t *ns;

	ASSERT(MUTEX_HELD(&cpu_lock));

	switch (what) {
	case CPU_CONFIG:
	case CPU_ON:
	case CPU_INIT:
	case CPU_CPUPART_IN:
		cpu_seqid = cpu[id]->cpu_seqid;
		netstack_next_init(&nh);
		while ((ns = netstack_next(&nh)) != NULL) {
			tcp_stack_cpu_add(ns->netstack_tcp, cpu_seqid);
			sctp_stack_cpu_add(ns->netstack_sctp, cpu_seqid);
			udp_stack_cpu_add(ns->netstack_udp, cpu_seqid);
			netstack_rele(ns);
		}
		netstack_next_fini(&nh);
		break;
	case CPU_UNCONFIG:
	case CPU_OFF:
	case CPU_CPUPART_OUT:
		/*
		 * Nothing to do.  We don't remove the per CPU stats from
		 * the IP stack even when the CPU goes offline.
		 */
		break;
	default:
		break;
	}
	return (0);
}