aboutsummaryrefslogtreecommitdiff
path: root/sys/dev/ice/ice_lib.c
blob: 4212a0c76c88ec6d615a29efb9f0937c97787991 (plain) (blame)
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
/* SPDX-License-Identifier: BSD-3-Clause */
/*  Copyright (c) 2021, Intel Corporation
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *   1. Redistributions of source code must retain the above copyright notice,
 *      this list of conditions and the following disclaimer.
 *
 *   2. Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 *
 *   3. Neither the name of the Intel Corporation nor the names of its
 *      contributors may be used to endorse or promote products derived from
 *      this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 *  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 *  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 *  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 *  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 *  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 *  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 *  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 */
/*$FreeBSD$*/

/**
 * @file ice_lib.c
 * @brief Generic device setup and sysctl functions
 *
 * Library of generic device functions not specific to the networking stack.
 *
 * This includes hardware initialization functions, as well as handlers for
 * many of the device sysctls used to probe driver status or tune specific
 * behaviors.
 */

#include "ice_lib.h"
#include "ice_iflib.h"
#include <dev/pci/pcivar.h>
#include <dev/pci/pcireg.h>
#include <machine/resource.h>
#include <net/if_dl.h>
#include <sys/firmware.h>
#include <sys/priv.h>
#include <sys/limits.h>

/**
 * @var M_ICE
 * @brief main ice driver allocation type
 *
 * malloc(9) allocation type used by the majority of memory allocations in the
 * ice driver.
 */
MALLOC_DEFINE(M_ICE, "ice", "Intel(R) 100Gb Network Driver lib allocations");

/*
 * Helper function prototypes
 */
static int ice_get_next_vsi(struct ice_vsi **all_vsi, int size);
static void ice_set_default_vsi_ctx(struct ice_vsi_ctx *ctx);
static void ice_set_rss_vsi_ctx(struct ice_vsi_ctx *ctx, enum ice_vsi_type type);
static int ice_setup_vsi_qmap(struct ice_vsi *vsi, struct ice_vsi_ctx *ctx);
static int ice_setup_tx_ctx(struct ice_tx_queue *txq,
			    struct ice_tlan_ctx *tlan_ctx, u16 pf_q);
static int ice_setup_rx_ctx(struct ice_rx_queue *rxq);
static int ice_is_rxq_ready(struct ice_hw *hw, int pf_q, u32 *reg);
static void ice_free_fltr_list(struct ice_list_head *list);
static int ice_add_mac_to_list(struct ice_vsi *vsi, struct ice_list_head *list,
			       const u8 *addr, enum ice_sw_fwd_act_type action);
static void ice_check_ctrlq_errors(struct ice_softc *sc, const char *qname,
				   struct ice_ctl_q_info *cq);
static void ice_process_link_event(struct ice_softc *sc, struct ice_rq_event_info *e);
static void ice_process_ctrlq_event(struct ice_softc *sc, const char *qname,
				    struct ice_rq_event_info *event);
static void ice_nvm_version_str(struct ice_hw *hw, struct sbuf *buf);
static void ice_active_pkg_version_str(struct ice_hw *hw, struct sbuf *buf);
static void ice_os_pkg_version_str(struct ice_hw *hw, struct sbuf *buf);
static bool ice_filter_is_mcast(struct ice_vsi *vsi, struct ice_fltr_info *info);
static u_int ice_sync_one_mcast_filter(void *p, struct sockaddr_dl *sdl, u_int errors);
static void ice_add_debug_tunables(struct ice_softc *sc);
static void ice_add_debug_sysctls(struct ice_softc *sc);
static void ice_vsi_set_rss_params(struct ice_vsi *vsi);
static void ice_get_default_rss_key(u8 *seed);
static int  ice_set_rss_key(struct ice_vsi *vsi);
static int  ice_set_rss_lut(struct ice_vsi *vsi);
static void ice_set_rss_flow_flds(struct ice_vsi *vsi);
static void ice_clean_vsi_rss_cfg(struct ice_vsi *vsi);
static const char *ice_aq_speed_to_str(struct ice_port_info *pi);
static const char *ice_requested_fec_mode(struct ice_port_info *pi);
static const char *ice_negotiated_fec_mode(struct ice_port_info *pi);
static const char *ice_autoneg_mode(struct ice_port_info *pi);
static const char *ice_flowcontrol_mode(struct ice_port_info *pi);
static void ice_print_bus_link_data(device_t dev, struct ice_hw *hw);
static void ice_set_pci_link_status_data(struct ice_hw *hw, u16 link_status);
static uint8_t ice_pcie_bandwidth_check(struct ice_softc *sc);
static uint64_t ice_pcie_bus_speed_to_rate(enum ice_pcie_bus_speed speed);
static int ice_pcie_lnk_width_to_int(enum ice_pcie_link_width width);
static uint64_t ice_phy_types_to_max_rate(struct ice_port_info *pi);
static void ice_add_sysctls_sw_stats(struct ice_vsi *vsi,
				     struct sysctl_ctx_list *ctx,
				     struct sysctl_oid *parent);
static void
ice_add_sysctls_mac_pfc_one_stat(struct sysctl_ctx_list *ctx,
				 struct sysctl_oid_list *parent_list,
				 u64* pfc_stat_location,
				 const char *node_name,
				 const char *descr);
static void ice_add_sysctls_mac_pfc_stats(struct sysctl_ctx_list *ctx,
					  struct sysctl_oid *parent,
					  struct ice_hw_port_stats *stats);
static void ice_setup_vsi_common(struct ice_softc *sc, struct ice_vsi *vsi,
				 enum ice_vsi_type type, int idx,
				 bool dynamic);
static void ice_handle_mib_change_event(struct ice_softc *sc,
				 struct ice_rq_event_info *event);
static void
ice_handle_lan_overflow_event(struct ice_softc *sc,
			      struct ice_rq_event_info *event);
static int ice_add_ethertype_to_list(struct ice_vsi *vsi,
				     struct ice_list_head *list,
				     u16 ethertype, u16 direction,
				     enum ice_sw_fwd_act_type action);
static void ice_add_rx_lldp_filter(struct ice_softc *sc);
static void ice_del_rx_lldp_filter(struct ice_softc *sc);
static u16 ice_aq_phy_types_to_link_speeds(u64 phy_type_low,
					   u64 phy_type_high);
struct ice_phy_data;
static int
ice_intersect_phy_types_and_speeds(struct ice_softc *sc,
				   struct ice_phy_data *phy_data);
static int
ice_apply_saved_phy_req_to_cfg(struct ice_softc *sc,
			       struct ice_aqc_set_phy_cfg_data *cfg);
static int
ice_apply_saved_fec_req_to_cfg(struct ice_softc *sc,
			       struct ice_aqc_set_phy_cfg_data *cfg);
static void
ice_apply_saved_fc_req_to_cfg(struct ice_port_info *pi,
			      struct ice_aqc_set_phy_cfg_data *cfg);
static void
ice_print_ldo_tlv(struct ice_softc *sc,
		  struct ice_link_default_override_tlv *tlv);
static void
ice_sysctl_speeds_to_aq_phy_types(u16 sysctl_speeds, u64 *phy_type_low,
				  u64 *phy_type_high);
static u16 ice_apply_supported_speed_filter(u16 report_speeds, u8 mod_type);
static void
ice_handle_health_status_event(struct ice_softc *sc,
			       struct ice_rq_event_info *event);
static void
ice_print_health_status_string(device_t dev,
			       struct ice_aqc_health_status_elem *elem);
static void
ice_debug_print_mib_change_event(struct ice_softc *sc,
				 struct ice_rq_event_info *event);
static bool ice_check_ets_bw(u8 *table);
static bool
ice_dcb_needs_reconfig(struct ice_softc *sc, struct ice_dcbx_cfg *old_cfg,
		       struct ice_dcbx_cfg *new_cfg);
static void ice_dcb_recfg(struct ice_softc *sc);
static u8 ice_dcb_num_tc(u8 tc_map);
static int ice_ets_str_to_tbl(const char *str, u8 *table, u8 limit);
static int ice_pf_vsi_cfg_tc(struct ice_softc *sc, u8 tc_map);
static void ice_sbuf_print_ets_cfg(struct sbuf *sbuf, const char *name,
				   struct ice_dcb_ets_cfg *ets);
static void ice_stop_pf_vsi(struct ice_softc *sc);
static void ice_vsi_setup_q_map(struct ice_vsi *vsi, struct ice_vsi_ctx *ctxt);
static void ice_do_dcb_reconfig(struct ice_softc *sc);
static int ice_config_pfc(struct ice_softc *sc, u8 new_mode);
static u8 ice_dcb_get_tc_map(const struct ice_dcbx_cfg *dcbcfg);

static int ice_module_init(void);
static int ice_module_exit(void);

/*
 * package version comparison functions
 */
static bool pkg_ver_empty(struct ice_pkg_ver *pkg_ver, u8 *pkg_name);
static int pkg_ver_compatible(struct ice_pkg_ver *pkg_ver);

/*
 * dynamic sysctl handlers
 */
static int ice_sysctl_show_fw(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_pkg_version(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_os_pkg_version(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_dump_mac_filters(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_dump_vlan_filters(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_dump_ethertype_filters(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_dump_ethertype_mac_filters(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_current_speed(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_request_reset(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_dump_state_flags(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_fec_config(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_fc_config(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_negotiated_fc(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_negotiated_fec(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_phy_type_low(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_phy_type_high(SYSCTL_HANDLER_ARGS);
static int __ice_sysctl_phy_type_handler(SYSCTL_HANDLER_ARGS,
					 bool is_phy_type_high);
static int ice_sysctl_advertise_speed(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_rx_itr(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_tx_itr(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_fw_lldp_agent(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_fw_cur_lldp_persist_status(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_fw_dflt_lldp_persist_status(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_phy_caps(SYSCTL_HANDLER_ARGS, u8 report_mode);
static int ice_sysctl_phy_sw_caps(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_phy_nvm_caps(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_phy_topo_caps(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_phy_link_status(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_read_i2c_diag_data(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_tx_cso_stat(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_rx_cso_stat(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_pba_number(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_rx_errors_stat(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_dump_dcbx_cfg(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_dump_vsi_cfg(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_ets_min_rate(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_up2tc_map(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_pfc_config(SYSCTL_HANDLER_ARGS);
static int ice_sysctl_query_port_ets(SYSCTL_HANDLER_ARGS);

/**
 * ice_map_bar - Map PCIe BAR memory
 * @dev: the PCIe device
 * @bar: the BAR info structure
 * @bar_num: PCIe BAR number
 *
 * Maps the specified PCIe BAR. Stores the mapping data in struct
 * ice_bar_info.
 */
int
ice_map_bar(device_t dev, struct ice_bar_info *bar, int bar_num)
{
	if (bar->res != NULL) {
		device_printf(dev, "PCI BAR%d already mapped\n", bar_num);
		return (EDOOFUS);
	}

	bar->rid = PCIR_BAR(bar_num);
	bar->res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &bar->rid,
					  RF_ACTIVE);
	if (!bar->res) {
		device_printf(dev, "PCI BAR%d mapping failed\n", bar_num);
		return (ENXIO);
	}

	bar->tag = rman_get_bustag(bar->res);
	bar->handle = rman_get_bushandle(bar->res);
	bar->size = rman_get_size(bar->res);

	return (0);
}

/**
 * ice_free_bar - Free PCIe BAR memory
 * @dev: the PCIe device
 * @bar: the BAR info structure
 *
 * Frees the specified PCIe BAR, releasing its resources.
 */
void
ice_free_bar(device_t dev, struct ice_bar_info *bar)
{
	if (bar->res != NULL)
		bus_release_resource(dev, SYS_RES_MEMORY, bar->rid, bar->res);
	bar->res = NULL;
}

/**
 * ice_set_ctrlq_len - Configure ctrlq lengths for a device
 * @hw: the device hardware structure
 *
 * Configures the control queues for the given device, setting up the
 * specified lengths, prior to initializing hardware.
 */
void
ice_set_ctrlq_len(struct ice_hw *hw)
{
	hw->adminq.num_rq_entries = ICE_AQ_LEN;
	hw->adminq.num_sq_entries = ICE_AQ_LEN;
	hw->adminq.rq_buf_size = ICE_AQ_MAX_BUF_LEN;
	hw->adminq.sq_buf_size = ICE_AQ_MAX_BUF_LEN;

	hw->mailboxq.num_rq_entries = ICE_MBXQ_LEN;
	hw->mailboxq.num_sq_entries = ICE_MBXQ_LEN;
	hw->mailboxq.rq_buf_size = ICE_MBXQ_MAX_BUF_LEN;
	hw->mailboxq.sq_buf_size = ICE_MBXQ_MAX_BUF_LEN;

}

/**
 * ice_get_next_vsi - Get the next available VSI slot
 * @all_vsi: the VSI list
 * @size: the size of the VSI list
 *
 * Returns the index to the first available VSI slot. Will return size (one
 * past the last index) if there are no slots available.
 */
static int
ice_get_next_vsi(struct ice_vsi **all_vsi, int size)
{
	int i;

	for (i = 0; i < size; i++) {
		if (all_vsi[i] == NULL)
			return i;
	}

	return size;
}

/**
 * ice_setup_vsi_common - Common VSI setup for both dynamic and static VSIs
 * @sc: the device private softc structure
 * @vsi: the VSI to setup
 * @type: the VSI type of the new VSI
 * @idx: the index in the all_vsi array to use
 * @dynamic: whether this VSI memory was dynamically allocated
 *
 * Perform setup for a VSI that is common to both dynamically allocated VSIs
 * and the static PF VSI which is embedded in the softc structure.
 */
static void
ice_setup_vsi_common(struct ice_softc *sc, struct ice_vsi *vsi,
		     enum ice_vsi_type type, int idx, bool dynamic)
{
	/* Store important values in VSI struct */
	vsi->type = type;
	vsi->sc = sc;
	vsi->idx = idx;
	sc->all_vsi[idx] = vsi;
	vsi->dynamic = dynamic;

	/* Setup the VSI tunables now */
	ice_add_vsi_tunables(vsi, sc->vsi_sysctls);
}

/**
 * ice_alloc_vsi - Allocate a dynamic VSI
 * @sc: device softc structure
 * @type: VSI type
 *
 * Allocates a new dynamic VSI structure and inserts it into the VSI list.
 */
struct ice_vsi *
ice_alloc_vsi(struct ice_softc *sc, enum ice_vsi_type type)
{
	struct ice_vsi *vsi;
	int idx;

	/* Find an open index for a new VSI to be allocated. If the returned
	 * index is >= the num_available_vsi then it means no slot is
	 * available.
	 */
	idx = ice_get_next_vsi(sc->all_vsi, sc->num_available_vsi);
	if (idx >= sc->num_available_vsi) {
		device_printf(sc->dev, "No available VSI slots\n");
		return NULL;
	}

	vsi = (struct ice_vsi *)malloc(sizeof(*vsi), M_ICE, M_WAITOK|M_ZERO);
	if (!vsi) {
		device_printf(sc->dev, "Unable to allocate VSI memory\n");
		return NULL;
	}

	ice_setup_vsi_common(sc, vsi, type, idx, true);

	return vsi;
}

/**
 * ice_setup_pf_vsi - Setup the PF VSI
 * @sc: the device private softc
 *
 * Setup the PF VSI structure which is embedded as sc->pf_vsi in the device
 * private softc. Unlike other VSIs, the PF VSI memory is allocated as part of
 * the softc memory, instead of being dynamically allocated at creation.
 */
void
ice_setup_pf_vsi(struct ice_softc *sc)
{
	ice_setup_vsi_common(sc, &sc->pf_vsi, ICE_VSI_PF, 0, false);
}

/**
 * ice_alloc_vsi_qmap
 * @vsi: VSI structure
 * @max_tx_queues: Number of transmit queues to identify
 * @max_rx_queues: Number of receive queues to identify
 *
 * Allocates a max_[t|r]x_queues array of words for the VSI where each
 * word contains the index of the queue it represents.  In here, all
 * words are initialized to an index of ICE_INVALID_RES_IDX, indicating
 * all queues for this VSI are not yet assigned an index and thus,
 * not ready for use.
 *
 * Returns an error code on failure.
 */
int
ice_alloc_vsi_qmap(struct ice_vsi *vsi, const int max_tx_queues,
		   const int max_rx_queues)
{
	struct ice_softc *sc = vsi->sc;
	int i;

	MPASS(max_tx_queues > 0);
	MPASS(max_rx_queues > 0);

	/* Allocate Tx queue mapping memory */
	if (!(vsi->tx_qmap =
	      (u16 *) malloc(sizeof(u16) * max_tx_queues, M_ICE, M_WAITOK))) {
		device_printf(sc->dev, "Unable to allocate Tx qmap memory\n");
		return (ENOMEM);
	}

	/* Allocate Rx queue mapping memory */
	if (!(vsi->rx_qmap =
	      (u16 *) malloc(sizeof(u16) * max_rx_queues, M_ICE, M_WAITOK))) {
		device_printf(sc->dev, "Unable to allocate Rx qmap memory\n");
		goto free_tx_qmap;
	}

	/* Mark every queue map as invalid to start with */
	for (i = 0; i < max_tx_queues; i++) {
		vsi->tx_qmap[i] = ICE_INVALID_RES_IDX;
	}
	for (i = 0; i < max_rx_queues; i++) {
		vsi->rx_qmap[i] = ICE_INVALID_RES_IDX;
	}

	return 0;

free_tx_qmap:
	free(vsi->tx_qmap, M_ICE);
	vsi->tx_qmap = NULL;

	return (ENOMEM);
}

/**
 * ice_free_vsi_qmaps - Free the PF qmaps associated with a VSI
 * @vsi: the VSI private structure
 *
 * Frees the PF qmaps associated with the given VSI. Generally this will be
 * called by ice_release_vsi, but may need to be called during attach cleanup,
 * depending on when the qmaps were allocated.
 */
void
ice_free_vsi_qmaps(struct ice_vsi *vsi)
{
	struct ice_softc *sc = vsi->sc;

	if (vsi->tx_qmap) {
		ice_resmgr_release_map(&sc->tx_qmgr, vsi->tx_qmap,
					   vsi->num_tx_queues);
		free(vsi->tx_qmap, M_ICE);
		vsi->tx_qmap = NULL;
	}

	if (vsi->rx_qmap) {
		ice_resmgr_release_map(&sc->rx_qmgr, vsi->rx_qmap,
					   vsi->num_rx_queues);
		free(vsi->rx_qmap, M_ICE);
		vsi->rx_qmap = NULL;
	}
}

/**
 * ice_set_default_vsi_ctx - Setup default VSI context parameters
 * @ctx: the VSI context to initialize
 *
 * Initialize and prepare a default VSI context for configuring a new VSI.
 */
static void
ice_set_default_vsi_ctx(struct ice_vsi_ctx *ctx)
{
	u32 table = 0;

	memset(&ctx->info, 0, sizeof(ctx->info));
	/* VSI will be allocated from shared pool */
	ctx->alloc_from_pool = true;
	/* Enable source pruning by default */
	ctx->info.sw_flags = ICE_AQ_VSI_SW_FLAG_SRC_PRUNE;
	/* Traffic from VSI can be sent to LAN */
	ctx->info.sw_flags2 = ICE_AQ_VSI_SW_FLAG_LAN_ENA;
	/* Allow all packets untagged/tagged */
	ctx->info.inner_vlan_flags = ((ICE_AQ_VSI_INNER_VLAN_TX_MODE_ALL &
				       ICE_AQ_VSI_INNER_VLAN_TX_MODE_M) >>
				       ICE_AQ_VSI_INNER_VLAN_TX_MODE_S);
	/* Show VLAN/UP from packets in Rx descriptors */
	ctx->info.inner_vlan_flags |= ((ICE_AQ_VSI_INNER_VLAN_EMODE_STR_BOTH &
					ICE_AQ_VSI_INNER_VLAN_EMODE_M) >>
					ICE_AQ_VSI_INNER_VLAN_EMODE_S);
	/* Have 1:1 UP mapping for both ingress/egress tables */
	table |= ICE_UP_TABLE_TRANSLATE(0, 0);
	table |= ICE_UP_TABLE_TRANSLATE(1, 1);
	table |= ICE_UP_TABLE_TRANSLATE(2, 2);
	table |= ICE_UP_TABLE_TRANSLATE(3, 3);
	table |= ICE_UP_TABLE_TRANSLATE(4, 4);
	table |= ICE_UP_TABLE_TRANSLATE(5, 5);
	table |= ICE_UP_TABLE_TRANSLATE(6, 6);
	table |= ICE_UP_TABLE_TRANSLATE(7, 7);
	ctx->info.ingress_table = CPU_TO_LE32(table);
	ctx->info.egress_table = CPU_TO_LE32(table);
	/* Have 1:1 UP mapping for outer to inner UP table */
	ctx->info.outer_up_table = CPU_TO_LE32(table);
	/* No Outer tag support, so outer_vlan_flags remains zero */
}

/**
 * ice_set_rss_vsi_ctx - Setup VSI context parameters for RSS
 * @ctx: the VSI context to configure
 * @type: the VSI type
 *
 * Configures the VSI context for RSS, based on the VSI type.
 */
static void
ice_set_rss_vsi_ctx(struct ice_vsi_ctx *ctx, enum ice_vsi_type type)
{
	u8 lut_type, hash_type;

	switch (type) {
	case ICE_VSI_PF:
		lut_type = ICE_AQ_VSI_Q_OPT_RSS_LUT_PF;
		hash_type = ICE_AQ_VSI_Q_OPT_RSS_TPLZ;
		break;
	case ICE_VSI_VF:
		lut_type = ICE_AQ_VSI_Q_OPT_RSS_LUT_VSI;
		hash_type = ICE_AQ_VSI_Q_OPT_RSS_TPLZ;
		break;
	default:
		/* Other VSI types do not support RSS */
		return;
	}

	ctx->info.q_opt_rss = (((lut_type << ICE_AQ_VSI_Q_OPT_RSS_LUT_S) &
				 ICE_AQ_VSI_Q_OPT_RSS_LUT_M) |
				((hash_type << ICE_AQ_VSI_Q_OPT_RSS_HASH_S) &
				 ICE_AQ_VSI_Q_OPT_RSS_HASH_M));
}

/**
 * ice_setup_vsi_qmap - Setup the queue mapping for a VSI
 * @vsi: the VSI to configure
 * @ctx: the VSI context to configure
 *
 * Configures the context for the given VSI, setting up how the firmware
 * should map the queues for this VSI.
 */
static int
ice_setup_vsi_qmap(struct ice_vsi *vsi, struct ice_vsi_ctx *ctx)
{
	int pow = 0;
	u16 qmap;

	MPASS(vsi->rx_qmap != NULL);

	/* TODO:
	 * Handle multiple Traffic Classes
	 * Handle scattered queues (for VFs)
	 */
	if (vsi->qmap_type != ICE_RESMGR_ALLOC_CONTIGUOUS)
		return (EOPNOTSUPP);

	ctx->info.mapping_flags |= CPU_TO_LE16(ICE_AQ_VSI_Q_MAP_CONTIG);

	ctx->info.q_mapping[0] = CPU_TO_LE16(vsi->rx_qmap[0]);
	ctx->info.q_mapping[1] = CPU_TO_LE16(vsi->num_rx_queues);


	/* Calculate the next power-of-2 of number of queues */
	if (vsi->num_rx_queues)
		pow = flsl(vsi->num_rx_queues - 1);

	/* Assign all the queues to traffic class zero */
	qmap = (pow << ICE_AQ_VSI_TC_Q_NUM_S) & ICE_AQ_VSI_TC_Q_NUM_M;
	ctx->info.tc_mapping[0] = CPU_TO_LE16(qmap);

	return 0;
}

/**
 * ice_initialize_vsi - Initialize a VSI for use
 * @vsi: the vsi to initialize
 *
 * Initialize a VSI over the adminq and prepare it for operation.
 */
int
ice_initialize_vsi(struct ice_vsi *vsi)
{
	struct ice_vsi_ctx ctx = { 0 };
	struct ice_hw *hw = &vsi->sc->hw;
	u16 max_txqs[ICE_MAX_TRAFFIC_CLASS] = { 0 };
	enum ice_status status;
	int err;

	/* For now, we only have code supporting PF VSIs */
	switch (vsi->type) {
	case ICE_VSI_PF:
		ctx.flags = ICE_AQ_VSI_TYPE_PF;
		break;
	default:
		return (ENODEV);
	}

	ice_set_default_vsi_ctx(&ctx);
	ice_set_rss_vsi_ctx(&ctx, vsi->type);

	/* XXX: VSIs of other types may need different port info? */
	ctx.info.sw_id = hw->port_info->sw_id;

	/* Set some RSS parameters based on the VSI type */
	ice_vsi_set_rss_params(vsi);

	/* Initialize the Rx queue mapping for this VSI */
	err = ice_setup_vsi_qmap(vsi, &ctx);
	if (err) {
		return err;
	}

	/* (Re-)add VSI to HW VSI handle list */
	status = ice_add_vsi(hw, vsi->idx, &ctx, NULL);
	if (status != 0) {
		device_printf(vsi->sc->dev,
		    "Add VSI AQ call failed, err %s aq_err %s\n",
		    ice_status_str(status),
		    ice_aq_str(hw->adminq.sq_last_status));
		return (EIO);
	}
	vsi->info = ctx.info;

	/* Initialize VSI with just 1 TC to start */
	max_txqs[0] = vsi->num_tx_queues;

	status = ice_cfg_vsi_lan(hw->port_info, vsi->idx,
			      ICE_DFLT_TRAFFIC_CLASS, max_txqs);
	if (status) {
		device_printf(vsi->sc->dev,
		    "Failed VSI lan queue config, err %s aq_err %s\n",
		    ice_status_str(status),
		    ice_aq_str(hw->adminq.sq_last_status));
		ice_deinit_vsi(vsi);
		return (ENODEV);
	}

	/* Reset VSI stats */
	ice_reset_vsi_stats(vsi);

	return 0;
}

/**
 * ice_deinit_vsi - Tell firmware to release resources for a VSI
 * @vsi: the VSI to release
 *
 * Helper function which requests the firmware to release the hardware
 * resources associated with a given VSI.
 */
void
ice_deinit_vsi(struct ice_vsi *vsi)
{
	struct ice_vsi_ctx ctx = { 0 };
	struct ice_softc *sc = vsi->sc;
	struct ice_hw *hw = &sc->hw;
	enum ice_status status;

	/* Assert that the VSI pointer matches in the list */
	MPASS(vsi == sc->all_vsi[vsi->idx]);

	ctx.info = vsi->info;

	status = ice_rm_vsi_lan_cfg(hw->port_info, vsi->idx);
	if (status) {
		/*
		 * This should only fail if the VSI handle is invalid, or if
		 * any of the nodes have leaf nodes which are still in use.
		 */
		device_printf(sc->dev,
			      "Unable to remove scheduler nodes for VSI %d, err %s\n",
			      vsi->idx, ice_status_str(status));
	}

	/* Tell firmware to release the VSI resources */
	status = ice_free_vsi(hw, vsi->idx, &ctx, false, NULL);
	if (status != 0) {
		device_printf(sc->dev,
		    "Free VSI %u AQ call failed, err %s aq_err %s\n",
		    vsi->idx, ice_status_str(status),
		    ice_aq_str(hw->adminq.sq_last_status));
	}
}

/**
 * ice_release_vsi - Release resources associated with a VSI
 * @vsi: the VSI to release
 *
 * Release software and firmware resources associated with a VSI. Release the
 * queue managers associated with this VSI. Also free the VSI structure memory
 * if the VSI was allocated dynamically using ice_alloc_vsi().
 */
void
ice_release_vsi(struct ice_vsi *vsi)
{
	struct ice_softc *sc = vsi->sc;
	int idx = vsi->idx;

	/* Assert that the VSI pointer matches in the list */
	MPASS(vsi == sc->all_vsi[idx]);

	/* Cleanup RSS configuration */
	if (ice_is_bit_set(sc->feat_en, ICE_FEATURE_RSS))
		ice_clean_vsi_rss_cfg(vsi);

	ice_del_vsi_sysctl_ctx(vsi);

	/*
	 * If we unload the driver after a reset fails, we do not need to do
	 * this step.
	 */
	if (!ice_test_state(&sc->state, ICE_STATE_RESET_FAILED))
		ice_deinit_vsi(vsi);

	ice_free_vsi_qmaps(vsi);

	if (vsi->dynamic) {
		free(sc->all_vsi[idx], M_ICE);
	}

	sc->all_vsi[idx] = NULL;
}

/**
 * ice_aq_speed_to_rate - Convert AdminQ speed enum to baudrate
 * @pi: port info data
 *
 * Returns the baudrate value for the current link speed of a given port.
 */
uint64_t
ice_aq_speed_to_rate(struct ice_port_info *pi)
{
	switch (pi->phy.link_info.link_speed) {
	case ICE_AQ_LINK_SPEED_100GB:
		return IF_Gbps(100);
	case ICE_AQ_LINK_SPEED_50GB:
		return IF_Gbps(50);
	case ICE_AQ_LINK_SPEED_40GB:
		return IF_Gbps(40);
	case ICE_AQ_LINK_SPEED_25GB:
		return IF_Gbps(25);
	case ICE_AQ_LINK_SPEED_10GB:
		return IF_Gbps(10);
	case ICE_AQ_LINK_SPEED_5GB:
		return IF_Gbps(5);
	case ICE_AQ_LINK_SPEED_2500MB:
		return IF_Mbps(2500);
	case ICE_AQ_LINK_SPEED_1000MB:
		return IF_Mbps(1000);
	case ICE_AQ_LINK_SPEED_100MB:
		return IF_Mbps(100);
	case ICE_AQ_LINK_SPEED_10MB:
		return IF_Mbps(10);
	case ICE_AQ_LINK_SPEED_UNKNOWN:
	default:
		/* return 0 if we don't know the link speed */
		return 0;
	}
}

/**
 * ice_aq_speed_to_str - Convert AdminQ speed enum to string representation
 * @pi: port info data
 *
 * Returns the string representation of the current link speed for a given
 * port.
 */
static const char *
ice_aq_speed_to_str(struct ice_port_info *pi)
{
	switch (pi->phy.link_info.link_speed) {
	case ICE_AQ_LINK_SPEED_100GB:
		return "100 Gbps";
	case ICE_AQ_LINK_SPEED_50GB:
		return "50 Gbps";
	case ICE_AQ_LINK_SPEED_40GB:
		return "40 Gbps";
	case ICE_AQ_LINK_SPEED_25GB:
		return "25 Gbps";
	case ICE_AQ_LINK_SPEED_20GB:
		return "20 Gbps";
	case ICE_AQ_LINK_SPEED_10GB:
		return "10 Gbps";
	case ICE_AQ_LINK_SPEED_5GB:
		return "5 Gbps";
	case ICE_AQ_LINK_SPEED_2500MB:
		return "2.5 Gbps";
	case ICE_AQ_LINK_SPEED_1000MB:
		return "1 Gbps";
	case ICE_AQ_LINK_SPEED_100MB:
		return "100 Mbps";
	case ICE_AQ_LINK_SPEED_10MB:
		return "10 Mbps";
	case ICE_AQ_LINK_SPEED_UNKNOWN:
	default:
		return "Unknown speed";
	}
}

/**
 * ice_get_phy_type_low - Get media associated with phy_type_low
 * @phy_type_low: the low 64bits of phy_type from the AdminQ
 *
 * Given the lower 64bits of the phy_type from the hardware, return the
 * ifm_active bit associated. Return IFM_UNKNOWN when phy_type_low is unknown.
 * Note that only one of ice_get_phy_type_low or ice_get_phy_type_high should
 * be called. If phy_type_low is zero, call ice_phy_type_high.
 */
int
ice_get_phy_type_low(uint64_t phy_type_low)
{
	switch (phy_type_low) {
	case ICE_PHY_TYPE_LOW_100BASE_TX:
		return IFM_100_TX;
	case ICE_PHY_TYPE_LOW_100M_SGMII:
		return IFM_100_SGMII;
	case ICE_PHY_TYPE_LOW_1000BASE_T:
		return IFM_1000_T;
	case ICE_PHY_TYPE_LOW_1000BASE_SX:
		return IFM_1000_SX;
	case ICE_PHY_TYPE_LOW_1000BASE_LX:
		return IFM_1000_LX;
	case ICE_PHY_TYPE_LOW_1000BASE_KX:
		return IFM_1000_KX;
	case ICE_PHY_TYPE_LOW_1G_SGMII:
		return IFM_1000_SGMII;
	case ICE_PHY_TYPE_LOW_2500BASE_T:
		return IFM_2500_T;
	case ICE_PHY_TYPE_LOW_2500BASE_X:
		return IFM_2500_X;
	case ICE_PHY_TYPE_LOW_2500BASE_KX:
		return IFM_2500_KX;
	case ICE_PHY_TYPE_LOW_5GBASE_T:
		return IFM_5000_T;
	case ICE_PHY_TYPE_LOW_5GBASE_KR:
		return IFM_5000_KR;
	case ICE_PHY_TYPE_LOW_10GBASE_T:
		return IFM_10G_T;
	case ICE_PHY_TYPE_LOW_10G_SFI_DA:
		return IFM_10G_TWINAX;
	case ICE_PHY_TYPE_LOW_10GBASE_SR:
		return IFM_10G_SR;
	case ICE_PHY_TYPE_LOW_10GBASE_LR:
		return IFM_10G_LR;
	case ICE_PHY_TYPE_LOW_10GBASE_KR_CR1:
		return IFM_10G_KR;
	case ICE_PHY_TYPE_LOW_10G_SFI_AOC_ACC:
		return IFM_10G_AOC;
	case ICE_PHY_TYPE_LOW_10G_SFI_C2C:
		return IFM_10G_SFI;
	case ICE_PHY_TYPE_LOW_25GBASE_T:
		return IFM_25G_T;
	case ICE_PHY_TYPE_LOW_25GBASE_CR:
		return IFM_25G_CR;
	case ICE_PHY_TYPE_LOW_25GBASE_CR_S:
		return IFM_25G_CR_S;
	case ICE_PHY_TYPE_LOW_25GBASE_CR1:
		return IFM_25G_CR1;
	case ICE_PHY_TYPE_LOW_25GBASE_SR:
		return IFM_25G_SR;
	case ICE_PHY_TYPE_LOW_25GBASE_LR:
		return IFM_25G_LR;
	case ICE_PHY_TYPE_LOW_25GBASE_KR:
		return IFM_25G_KR;
	case ICE_PHY_TYPE_LOW_25GBASE_KR_S:
		return IFM_25G_KR_S;
	case ICE_PHY_TYPE_LOW_25GBASE_KR1:
		return IFM_25G_KR1;
	case ICE_PHY_TYPE_LOW_25G_AUI_AOC_ACC:
		return IFM_25G_AOC;
	case ICE_PHY_TYPE_LOW_25G_AUI_C2C:
		return IFM_25G_AUI;
	case ICE_PHY_TYPE_LOW_40GBASE_CR4:
		return IFM_40G_CR4;
	case ICE_PHY_TYPE_LOW_40GBASE_SR4:
		return IFM_40G_SR4;
	case ICE_PHY_TYPE_LOW_40GBASE_LR4:
		return IFM_40G_LR4;
	case ICE_PHY_TYPE_LOW_40GBASE_KR4:
		return IFM_40G_KR4;
	case ICE_PHY_TYPE_LOW_40G_XLAUI_AOC_ACC:
		return IFM_40G_XLAUI_AC;
	case ICE_PHY_TYPE_LOW_40G_XLAUI:
		return IFM_40G_XLAUI;
	case ICE_PHY_TYPE_LOW_50GBASE_CR2:
		return IFM_50G_CR2;
	case ICE_PHY_TYPE_LOW_50GBASE_SR2:
		return IFM_50G_SR2;
	case ICE_PHY_TYPE_LOW_50GBASE_LR2:
		return IFM_50G_LR2;
	case ICE_PHY_TYPE_LOW_50GBASE_KR2:
		return IFM_50G_KR2;
	case ICE_PHY_TYPE_LOW_50G_LAUI2_AOC_ACC:
		return IFM_50G_LAUI2_AC;
	case ICE_PHY_TYPE_LOW_50G_LAUI2:
		return IFM_50G_LAUI2;
	case ICE_PHY_TYPE_LOW_50G_AUI2_AOC_ACC:
		return IFM_50G_AUI2_AC;
	case ICE_PHY_TYPE_LOW_50G_AUI2:
		return IFM_50G_AUI2;
	case ICE_PHY_TYPE_LOW_50GBASE_CP:
		return IFM_50G_CP;
	case ICE_PHY_TYPE_LOW_50GBASE_SR:
		return IFM_50G_SR;
	case ICE_PHY_TYPE_LOW_50GBASE_FR:
		return IFM_50G_FR;
	case ICE_PHY_TYPE_LOW_50GBASE_LR:
		return IFM_50G_LR;
	case ICE_PHY_TYPE_LOW_50GBASE_KR_PAM4:
		return IFM_50G_KR_PAM4;
	case ICE_PHY_TYPE_LOW_50G_AUI1_AOC_ACC:
		return IFM_50G_AUI1_AC;
	case ICE_PHY_TYPE_LOW_50G_AUI1:
		return IFM_50G_AUI1;
	case ICE_PHY_TYPE_LOW_100GBASE_CR4:
		return IFM_100G_CR4;
	case ICE_PHY_TYPE_LOW_100GBASE_SR4:
		return IFM_100G_SR4;
	case ICE_PHY_TYPE_LOW_100GBASE_LR4:
		return IFM_100G_LR4;
	case ICE_PHY_TYPE_LOW_100GBASE_KR4:
		return IFM_100G_KR4;
	case ICE_PHY_TYPE_LOW_100G_CAUI4_AOC_ACC:
		return IFM_100G_CAUI4_AC;
	case ICE_PHY_TYPE_LOW_100G_CAUI4:
		return IFM_100G_CAUI4;
	case ICE_PHY_TYPE_LOW_100G_AUI4_AOC_ACC:
		return IFM_100G_AUI4_AC;
	case ICE_PHY_TYPE_LOW_100G_AUI4:
		return IFM_100G_AUI4;
	case ICE_PHY_TYPE_LOW_100GBASE_CR_PAM4:
		return IFM_100G_CR_PAM4;
	case ICE_PHY_TYPE_LOW_100GBASE_KR_PAM4:
		return IFM_100G_KR_PAM4;
	case ICE_PHY_TYPE_LOW_100GBASE_CP2:
		return IFM_100G_CP2;
	case ICE_PHY_TYPE_LOW_100GBASE_SR2:
		return IFM_100G_SR2;
	case ICE_PHY_TYPE_LOW_100GBASE_DR:
		return IFM_100G_DR;
	default:
		return IFM_UNKNOWN;
	}
}

/**
 * ice_get_phy_type_high - Get media associated with phy_type_high
 * @phy_type_high: the upper 64bits of phy_type from the AdminQ
 *
 * Given the upper 64bits of the phy_type from the hardware, return the
 * ifm_active bit associated. Return IFM_UNKNOWN on an unknown value. Note
 * that only one of ice_get_phy_type_low or ice_get_phy_type_high should be
 * called. If phy_type_high is zero, call ice_get_phy_type_low.
 */
int
ice_get_phy_type_high(uint64_t phy_type_high)
{
	switch (phy_type_high) {
	case ICE_PHY_TYPE_HIGH_100GBASE_KR2_PAM4:
		return IFM_100G_KR2_PAM4;
	case ICE_PHY_TYPE_HIGH_100G_CAUI2_AOC_ACC:
		return IFM_100G_CAUI2_AC;
	case ICE_PHY_TYPE_HIGH_100G_CAUI2:
		return IFM_100G_CAUI2;
	case ICE_PHY_TYPE_HIGH_100G_AUI2_AOC_ACC:
		return IFM_100G_AUI2_AC;
	case ICE_PHY_TYPE_HIGH_100G_AUI2:
		return IFM_100G_AUI2;
	default:
		return IFM_UNKNOWN;
	}
}

/**
 * ice_phy_types_to_max_rate - Returns port's max supported baudrate
 * @pi: port info struct
 *
 * ice_aq_get_phy_caps() w/ ICE_AQC_REPORT_TOPO_CAP_MEDIA parameter needs
 * to have been called before this function for it to work.
 */
static uint64_t
ice_phy_types_to_max_rate(struct ice_port_info *pi)
{
	uint64_t phy_low = pi->phy.phy_type_low;
	uint64_t phy_high = pi->phy.phy_type_high;
	uint64_t max_rate = 0;
	int bit;

	/*
	 * These are based on the indices used in the BIT() macros for
	 * ICE_PHY_TYPE_LOW_*
	 */
	static const uint64_t phy_rates[] = {
	    IF_Mbps(100),
	    IF_Mbps(100),
	    IF_Gbps(1ULL),
	    IF_Gbps(1ULL),
	    IF_Gbps(1ULL),
	    IF_Gbps(1ULL),
	    IF_Gbps(1ULL),
	    IF_Mbps(2500ULL),
	    IF_Mbps(2500ULL),
	    IF_Mbps(2500ULL),
	    IF_Gbps(5ULL),
	    IF_Gbps(5ULL),
	    IF_Gbps(10ULL),
	    IF_Gbps(10ULL),
	    IF_Gbps(10ULL),
	    IF_Gbps(10ULL),
	    IF_Gbps(10ULL),
	    IF_Gbps(10ULL),
	    IF_Gbps(10ULL),
	    IF_Gbps(25ULL),
	    IF_Gbps(25ULL),
	    IF_Gbps(25ULL),
	    IF_Gbps(25ULL),
	    IF_Gbps(25ULL),
	    IF_Gbps(25ULL),
	    IF_Gbps(25ULL),
	    IF_Gbps(25ULL),
	    IF_Gbps(25ULL),
	    IF_Gbps(25ULL),
	    IF_Gbps(25ULL),
	    IF_Gbps(40ULL),
	    IF_Gbps(40ULL),
	    IF_Gbps(40ULL),
	    IF_Gbps(40ULL),
	    IF_Gbps(40ULL),
	    IF_Gbps(40ULL),
	    IF_Gbps(50ULL),
	    IF_Gbps(50ULL),
	    IF_Gbps(50ULL),
	    IF_Gbps(50ULL),
	    IF_Gbps(50ULL),
	    IF_Gbps(50ULL),
	    IF_Gbps(50ULL),
	    IF_Gbps(50ULL),
	    IF_Gbps(50ULL),
	    IF_Gbps(50ULL),
	    IF_Gbps(50ULL),
	    IF_Gbps(50ULL),
	    IF_Gbps(50ULL),
	    IF_Gbps(50ULL),
	    IF_Gbps(50ULL),
	    IF_Gbps(100ULL),
	    IF_Gbps(100ULL),
	    IF_Gbps(100ULL),
	    IF_Gbps(100ULL),
	    IF_Gbps(100ULL),
	    IF_Gbps(100ULL),
	    IF_Gbps(100ULL),
	    IF_Gbps(100ULL),
	    IF_Gbps(100ULL),
	    IF_Gbps(100ULL),
	    IF_Gbps(100ULL),
	    IF_Gbps(100ULL),
	    IF_Gbps(100ULL),
	    /* These rates are for ICE_PHY_TYPE_HIGH_* */
	    IF_Gbps(100ULL),
	    IF_Gbps(100ULL),
	    IF_Gbps(100ULL),
	    IF_Gbps(100ULL),
	    IF_Gbps(100ULL)
	};

	/* coverity[address_of] */
	for_each_set_bit(bit, &phy_high, 64)
		if ((bit + 64) < (int)ARRAY_SIZE(phy_rates))
			max_rate = uqmax(max_rate, phy_rates[(bit + 64)]);

	/* coverity[address_of] */
	for_each_set_bit(bit, &phy_low, 64)
		max_rate = uqmax(max_rate, phy_rates[bit]);

	return (max_rate);
}

/* The if_media type is split over the original 5 bit media variant field,
 * along with extended types using up extra bits in the options section.
 * We want to convert this split number into a bitmap index, so we reverse the
 * calculation of IFM_X here.
 */
#define IFM_IDX(x) (((x) & IFM_TMASK) | \
		    (((x) & IFM_ETH_XTYPE) >> IFM_ETH_XSHIFT))

/**
 * ice_add_media_types - Add supported media types to the media structure
 * @sc: ice private softc structure
 * @media: ifmedia structure to setup
 *
 * Looks up the supported phy types, and initializes the various media types
 * available.
 *
 * @pre this function must be protected from being called while another thread
 * is accessing the ifmedia types.
 */
enum ice_status
ice_add_media_types(struct ice_softc *sc, struct ifmedia *media)
{
	struct ice_aqc_get_phy_caps_data pcaps = { 0 };
	struct ice_port_info *pi = sc->hw.port_info;
	enum ice_status status;
	uint64_t phy_low, phy_high;
	int bit;

	ASSERT_CFG_LOCKED(sc);

	/* the maximum possible media type index is 511. We probably don't
	 * need most of this space, but this ensures future compatibility when
	 * additional media types are used.
	 */
	ice_declare_bitmap(already_added, 511);

	/* Remove all previous media types */
	ifmedia_removeall(media);

	status = ice_aq_get_phy_caps(pi, false, ICE_AQC_REPORT_ACTIVE_CFG,
				     &pcaps, NULL);
	if (status != ICE_SUCCESS) {
		device_printf(sc->dev,
		    "%s: ice_aq_get_phy_caps (ACTIVE) failed; status %s, aq_err %s\n",
		    __func__, ice_status_str(status),
		    ice_aq_str(sc->hw.adminq.sq_last_status));
		return (status);
	}
	phy_low = le64toh(pcaps.phy_type_low);
	phy_high = le64toh(pcaps.phy_type_high);

	/* make sure the added bitmap is zero'd */
	memset(already_added, 0, sizeof(already_added));

	/* coverity[address_of] */
	for_each_set_bit(bit, &phy_low, 64) {
		uint64_t type = BIT_ULL(bit);
		int ostype;

		/* get the OS media type */
		ostype = ice_get_phy_type_low(type);

		/* don't bother adding the unknown type */
		if (ostype == IFM_UNKNOWN)
			continue;

		/* only add each media type to the list once */
		if (ice_is_bit_set(already_added, IFM_IDX(ostype)))
			continue;

		ifmedia_add(media, IFM_ETHER | ostype, 0, NULL);
		ice_set_bit(IFM_IDX(ostype), already_added);
	}

	/* coverity[address_of] */
	for_each_set_bit(bit, &phy_high, 64) {
		uint64_t type = BIT_ULL(bit);
		int ostype;

		/* get the OS media type */
		ostype = ice_get_phy_type_high(type);

		/* don't bother adding the unknown type */
		if (ostype == IFM_UNKNOWN)
			continue;

		/* only add each media type to the list once */
		if (ice_is_bit_set(already_added, IFM_IDX(ostype)))
			continue;

		ifmedia_add(media, IFM_ETHER | ostype, 0, NULL);
		ice_set_bit(IFM_IDX(ostype), already_added);
	}

	/* Use autoselect media by default */
	ifmedia_add(media, IFM_ETHER | IFM_AUTO, 0, NULL);
	ifmedia_set(media, IFM_ETHER | IFM_AUTO);

	return (ICE_SUCCESS);
}

/**
 * ice_configure_rxq_interrupts - Configure HW Rx queues for MSI-X interrupts
 * @vsi: the VSI to configure
 *
 * Called when setting up MSI-X interrupts to configure the Rx hardware queues.
 */
void
ice_configure_rxq_interrupts(struct ice_vsi *vsi)
{
	struct ice_hw *hw = &vsi->sc->hw;
	int i;

	for (i = 0; i < vsi->num_rx_queues; i++) {
		struct ice_rx_queue *rxq = &vsi->rx_queues[i];
		u32 val;

		val = (QINT_RQCTL_CAUSE_ENA_M |
		       (ICE_RX_ITR << QINT_RQCTL_ITR_INDX_S) |
		       (rxq->irqv->me << QINT_RQCTL_MSIX_INDX_S));
		wr32(hw, QINT_RQCTL(vsi->rx_qmap[rxq->me]), val);
	}

	ice_flush(hw);
}

/**
 * ice_configure_txq_interrupts - Configure HW Tx queues for MSI-X interrupts
 * @vsi: the VSI to configure
 *
 * Called when setting up MSI-X interrupts to configure the Tx hardware queues.
 */
void
ice_configure_txq_interrupts(struct ice_vsi *vsi)
{
	struct ice_hw *hw = &vsi->sc->hw;
	int i;

	for (i = 0; i < vsi->num_tx_queues; i++) {
		struct ice_tx_queue *txq = &vsi->tx_queues[i];
		u32 val;

		val = (QINT_TQCTL_CAUSE_ENA_M |
		       (ICE_TX_ITR << QINT_TQCTL_ITR_INDX_S) |
		       (txq->irqv->me << QINT_TQCTL_MSIX_INDX_S));
		wr32(hw, QINT_TQCTL(vsi->tx_qmap[txq->me]), val);
	}

	ice_flush(hw);
}

/**
 * ice_flush_rxq_interrupts - Unconfigure Hw Rx queues MSI-X interrupt cause
 * @vsi: the VSI to configure
 *
 * Unset the CAUSE_ENA flag of the TQCTL register for each queue, then trigger
 * a software interrupt on that cause. This is required as part of the Rx
 * queue disable logic to dissociate the Rx queue from the interrupt.
 *
 * Note: this function must be called prior to disabling Rx queues with
 * ice_control_rx_queues, otherwise the Rx queue may not be disabled properly.
 */
void
ice_flush_rxq_interrupts(struct ice_vsi *vsi)
{
	struct ice_hw *hw = &vsi->sc->hw;
	int i;

	for (i = 0; i < vsi->num_rx_queues; i++) {
		struct ice_rx_queue *rxq = &vsi->rx_queues[i];
		u32 reg, val;

		/* Clear the CAUSE_ENA flag */
		reg = vsi->rx_qmap[rxq->me];
		val = rd32(hw, QINT_RQCTL(reg));
		val &= ~QINT_RQCTL_CAUSE_ENA_M;
		wr32(hw, QINT_RQCTL(reg), val);

		ice_flush(hw);

		/* Trigger a software interrupt to complete interrupt
		 * dissociation.
		 */
		wr32(hw, GLINT_DYN_CTL(rxq->irqv->me),
		     GLINT_DYN_CTL_SWINT_TRIG_M | GLINT_DYN_CTL_INTENA_MSK_M);
	}
}

/**
 * ice_flush_txq_interrupts - Unconfigure Hw Tx queues MSI-X interrupt cause
 * @vsi: the VSI to configure
 *
 * Unset the CAUSE_ENA flag of the TQCTL register for each queue, then trigger
 * a software interrupt on that cause. This is required as part of the Tx
 * queue disable logic to dissociate the Tx queue from the interrupt.
 *
 * Note: this function must be called prior to ice_vsi_disable_tx, otherwise
 * the Tx queue disable may not complete properly.
 */
void
ice_flush_txq_interrupts(struct ice_vsi *vsi)
{
	struct ice_hw *hw = &vsi->sc->hw;
	int i;

	for (i = 0; i < vsi->num_tx_queues; i++) {
		struct ice_tx_queue *txq = &vsi->tx_queues[i];
		u32 reg, val;

		/* Clear the CAUSE_ENA flag */
		reg = vsi->tx_qmap[txq->me];
		val = rd32(hw, QINT_TQCTL(reg));
		val &= ~QINT_TQCTL_CAUSE_ENA_M;
		wr32(hw, QINT_TQCTL(reg), val);

		ice_flush(hw);

		/* Trigger a software interrupt to complete interrupt
		 * dissociation.
		 */
		wr32(hw, GLINT_DYN_CTL(txq->irqv->me),
		     GLINT_DYN_CTL_SWINT_TRIG_M | GLINT_DYN_CTL_INTENA_MSK_M);
	}
}

/**
 * ice_configure_rx_itr - Configure the Rx ITR settings for this VSI
 * @vsi: the VSI to configure
 *
 * Program the hardware ITR registers with the settings for this VSI.
 */
void
ice_configure_rx_itr(struct ice_vsi *vsi)
{
	struct ice_hw *hw = &vsi->sc->hw;
	int i;

	/* TODO: Handle per-queue/per-vector ITR? */

	for (i = 0; i < vsi->num_rx_queues; i++) {
		struct ice_rx_queue *rxq = &vsi->rx_queues[i];

		wr32(hw, GLINT_ITR(ICE_RX_ITR, rxq->irqv->me),
		     ice_itr_to_reg(hw, vsi->rx_itr));
	}

	ice_flush(hw);
}

/**
 * ice_configure_tx_itr - Configure the Tx ITR settings for this VSI
 * @vsi: the VSI to configure
 *
 * Program the hardware ITR registers with the settings for this VSI.
 */
void
ice_configure_tx_itr(struct ice_vsi *vsi)
{
	struct ice_hw *hw = &vsi->sc->hw;
	int i;

	/* TODO: Handle per-queue/per-vector ITR? */

	for (i = 0; i < vsi->num_tx_queues; i++) {
		struct ice_tx_queue *txq = &vsi->tx_queues[i];

		wr32(hw, GLINT_ITR(ICE_TX_ITR, txq->irqv->me),
		     ice_itr_to_reg(hw, vsi->tx_itr));
	}

	ice_flush(hw);
}

/**
 * ice_setup_tx_ctx - Setup an ice_tlan_ctx structure for a queue
 * @txq: the Tx queue to configure
 * @tlan_ctx: the Tx LAN queue context structure to initialize
 * @pf_q: real queue number
 */
static int
ice_setup_tx_ctx(struct ice_tx_queue *txq, struct ice_tlan_ctx *tlan_ctx, u16 pf_q)
{
	struct ice_vsi *vsi = txq->vsi;
	struct ice_softc *sc = vsi->sc;
	struct ice_hw *hw = &sc->hw;

	tlan_ctx->port_num = hw->port_info->lport;

	/* number of descriptors in the queue */
	tlan_ctx->qlen = txq->desc_count;

	/* set the transmit queue base address, defined in 128 byte units */
	tlan_ctx->base = txq->tx_paddr >> 7;

	tlan_ctx->pf_num = hw->pf_id;

	/* For now, we only have code supporting PF VSIs */
	switch (vsi->type) {
	case ICE_VSI_PF:
		tlan_ctx->vmvf_type = ICE_TLAN_CTX_VMVF_TYPE_PF;
		break;
	default:
		return (ENODEV);
	}

	tlan_ctx->src_vsi = ice_get_hw_vsi_num(hw, vsi->idx);

	/* Enable TSO */
	tlan_ctx->tso_ena = 1;
	tlan_ctx->internal_usage_flag = 1;

	tlan_ctx->tso_qnum = pf_q;

	/*
	 * Stick with the older legacy Tx queue interface, instead of the new
	 * advanced queue interface.
	 */
	tlan_ctx->legacy_int = 1;

	/* Descriptor WB mode */
	tlan_ctx->wb_mode = 0;

	return (0);
}

/**
 * ice_cfg_vsi_for_tx - Configure the hardware for Tx
 * @vsi: the VSI to configure
 *
 * Configure the device Tx queues through firmware AdminQ commands. After
 * this, Tx queues will be ready for transmit.
 */
int
ice_cfg_vsi_for_tx(struct ice_vsi *vsi)
{
	struct ice_aqc_add_tx_qgrp *qg;
	struct ice_hw *hw = &vsi->sc->hw;
	device_t dev = vsi->sc->dev;
	enum ice_status status;
	int i;
	int err = 0;
	u16 qg_size, pf_q;

	qg_size = ice_struct_size(qg, txqs, 1);
	qg = (struct ice_aqc_add_tx_qgrp *)malloc(qg_size, M_ICE, M_NOWAIT|M_ZERO);
	if (!qg)
		return (ENOMEM);

	qg->num_txqs = 1;

	for (i = 0; i < vsi->num_tx_queues; i++) {
		struct ice_tlan_ctx tlan_ctx = { 0 };
		struct ice_tx_queue *txq = &vsi->tx_queues[i];

		pf_q = vsi->tx_qmap[txq->me];
		qg->txqs[0].txq_id = htole16(pf_q);

		err = ice_setup_tx_ctx(txq, &tlan_ctx, pf_q);
		if (err)
			goto free_txqg;

		ice_set_ctx(hw, (u8 *)&tlan_ctx, qg->txqs[0].txq_ctx,
			    ice_tlan_ctx_info);

		status = ice_ena_vsi_txq(hw->port_info, vsi->idx, txq->tc,
					 txq->q_handle, 1, qg, qg_size, NULL);
		if (status) {
			device_printf(dev,
				      "Failed to set LAN Tx queue %d (TC %d, handle %d) context, err %s aq_err %s\n",
				      i, txq->tc, txq->q_handle,
				      ice_status_str(status),
				      ice_aq_str(hw->adminq.sq_last_status));
			err = ENODEV;
			goto free_txqg;
		}

		/* Keep track of the Tx queue TEID */
		if (pf_q == le16toh(qg->txqs[0].txq_id))
			txq->q_teid = le32toh(qg->txqs[0].q_teid);
	}

free_txqg:
	free(qg, M_ICE);

	return (err);
}

/**
 * ice_setup_rx_ctx - Setup an Rx context structure for a receive queue
 * @rxq: the receive queue to program
 *
 * Setup an Rx queue context structure and program it into the hardware
 * registers. This is a necessary step for enabling the Rx queue.
 *
 * @pre the VSI associated with this queue must have initialized mbuf_sz
 */
static int
ice_setup_rx_ctx(struct ice_rx_queue *rxq)
{
	struct ice_rlan_ctx rlan_ctx = {0};
	struct ice_vsi *vsi = rxq->vsi;
	struct ice_softc *sc = vsi->sc;
	struct ice_hw *hw = &sc->hw;
	enum ice_status status;
	u32 rxdid = ICE_RXDID_FLEX_NIC;
	u32 regval;
	u16 pf_q;

	pf_q = vsi->rx_qmap[rxq->me];

	/* set the receive queue base address, defined in 128 byte units */
	rlan_ctx.base = rxq->rx_paddr >> 7;

	rlan_ctx.qlen = rxq->desc_count;

	rlan_ctx.dbuf = vsi->mbuf_sz >> ICE_RLAN_CTX_DBUF_S;

	/* use 32 byte descriptors */
	rlan_ctx.dsize = 1;

	/* Strip the Ethernet CRC bytes before the packet is posted to the
	 * host memory.
	 */
	rlan_ctx.crcstrip = 1;

	rlan_ctx.l2tsel = 1;

	/* don't do header splitting */
	rlan_ctx.dtype = ICE_RX_DTYPE_NO_SPLIT;
	rlan_ctx.hsplit_0 = ICE_RLAN_RX_HSPLIT_0_NO_SPLIT;
	rlan_ctx.hsplit_1 = ICE_RLAN_RX_HSPLIT_1_NO_SPLIT;

	/* strip VLAN from inner headers */
	rlan_ctx.showiv = 1;

	rlan_ctx.rxmax = min(vsi->max_frame_size,
			     ICE_MAX_RX_SEGS * vsi->mbuf_sz);

	rlan_ctx.lrxqthresh = 1;

	if (vsi->type != ICE_VSI_VF) {
		regval = rd32(hw, QRXFLXP_CNTXT(pf_q));
		regval &= ~QRXFLXP_CNTXT_RXDID_IDX_M;
		regval |= (rxdid << QRXFLXP_CNTXT_RXDID_IDX_S) &
			QRXFLXP_CNTXT_RXDID_IDX_M;

		regval &= ~QRXFLXP_CNTXT_RXDID_PRIO_M;
		regval |= (0x03 << QRXFLXP_CNTXT_RXDID_PRIO_S) &
			QRXFLXP_CNTXT_RXDID_PRIO_M;

		wr32(hw, QRXFLXP_CNTXT(pf_q), regval);
	}

	status = ice_write_rxq_ctx(hw, &rlan_ctx, pf_q);
	if (status) {
		device_printf(sc->dev,
			      "Failed to set LAN Rx queue context, err %s aq_err %s\n",
			      ice_status_str(status), ice_aq_str(hw->adminq.sq_last_status));
		return (EIO);
	}

	wr32(hw, rxq->tail, 0);

	return 0;
}

/**
 * ice_cfg_vsi_for_rx - Configure the hardware for Rx
 * @vsi: the VSI to configure
 *
 * Prepare an Rx context descriptor and configure the device to receive
 * traffic.
 *
 * @pre the VSI must have initialized mbuf_sz
 */
int
ice_cfg_vsi_for_rx(struct ice_vsi *vsi)
{
	int i, err;

	for (i = 0; i < vsi->num_rx_queues; i++) {
		MPASS(vsi->mbuf_sz > 0);
		err = ice_setup_rx_ctx(&vsi->rx_queues[i]);
		if (err)
			return err;
	}

	return (0);
}

/**
 * ice_is_rxq_ready - Check if an Rx queue is ready
 * @hw: ice hw structure
 * @pf_q: absolute PF queue index to check
 * @reg: on successful return, contains qrx_ctrl contents
 *
 * Reads the QRX_CTRL register and verifies if the queue is in a consistent
 * state. That is, QENA_REQ matches QENA_STAT. Used to check before making
 * a request to change the queue, as well as to verify the request has
 * finished. The queue should change status within a few microseconds, so we
 * use a small delay while polling the register.
 *
 * Returns an error code if the queue does not update after a few retries.
 */
static int
ice_is_rxq_ready(struct ice_hw *hw, int pf_q, u32 *reg)
{
	u32 qrx_ctrl, qena_req, qena_stat;
	int i;

	for (i = 0; i < ICE_Q_WAIT_RETRY_LIMIT; i++) {
		qrx_ctrl = rd32(hw, QRX_CTRL(pf_q));
		qena_req = (qrx_ctrl >> QRX_CTRL_QENA_REQ_S) & 1;
		qena_stat = (qrx_ctrl >> QRX_CTRL_QENA_STAT_S) & 1;

		/* if the request and status bits equal, then the queue is
		 * fully disabled or enabled.
		 */
		if (qena_req == qena_stat) {
			*reg = qrx_ctrl;
			return (0);
		}

		/* wait a few microseconds before we check again */
		DELAY(10);
	}

	return (ETIMEDOUT);
}

/**
 * ice_control_rx_queues - Configure hardware to start or stop the Rx queues
 * @vsi: VSI to enable/disable queues
 * @enable: true to enable queues, false to disable
 *
 * Control the Rx queues through the QRX_CTRL register, enabling or disabling
 * them. Wait for the appropriate time to ensure that the queues have actually
 * reached the expected state.
 */
int
ice_control_rx_queues(struct ice_vsi *vsi, bool enable)
{
	struct ice_hw *hw = &vsi->sc->hw;
	device_t dev = vsi->sc->dev;
	u32 qrx_ctrl = 0;
	int i, err;

	/* TODO: amortize waits by changing all queues up front and then
	 * checking their status afterwards. This will become more necessary
	 * when we have a large number of queues.
	 */
	for (i = 0; i < vsi->num_rx_queues; i++) {
		struct ice_rx_queue *rxq = &vsi->rx_queues[i];
		int pf_q = vsi->rx_qmap[rxq->me];

		err = ice_is_rxq_ready(hw, pf_q, &qrx_ctrl);
		if (err) {
			device_printf(dev,
				      "Rx queue %d is not ready\n",
				      pf_q);
			return err;
		}

		/* Skip if the queue is already in correct state */
		if (enable == !!(qrx_ctrl & QRX_CTRL_QENA_STAT_M))
			continue;

		if (enable)
			qrx_ctrl |= QRX_CTRL_QENA_REQ_M;
		else
			qrx_ctrl &= ~QRX_CTRL_QENA_REQ_M;
		wr32(hw, QRX_CTRL(pf_q), qrx_ctrl);

		/* wait for the queue to finalize the request */
		err = ice_is_rxq_ready(hw, pf_q, &qrx_ctrl);
		if (err) {
			device_printf(dev,
				      "Rx queue %d %sable timeout\n",
				      pf_q, (enable ? "en" : "dis"));
			return err;
		}

		/* this should never happen */
		if (enable != !!(qrx_ctrl & QRX_CTRL_QENA_STAT_M)) {
			device_printf(dev,
				      "Rx queue %d invalid state\n",
				      pf_q);
			return (EDOOFUS);
		}
	}

	return (0);
}

/**
 * ice_add_mac_to_list - Add MAC filter to a MAC filter list
 * @vsi: the VSI to forward to
 * @list: list which contains MAC filter entries
 * @addr: the MAC address to be added
 * @action: filter action to perform on match
 *
 * Adds a MAC address filter to the list which will be forwarded to firmware
 * to add a series of MAC address filters.
 *
 * Returns 0 on success, and an error code on failure.
 *
 */
static int
ice_add_mac_to_list(struct ice_vsi *vsi, struct ice_list_head *list,
		    const u8 *addr, enum ice_sw_fwd_act_type action)
{
	struct ice_fltr_list_entry *entry;

	entry = (__typeof(entry))malloc(sizeof(*entry), M_ICE, M_NOWAIT|M_ZERO);
	if (!entry)
		return (ENOMEM);

	entry->fltr_info.flag = ICE_FLTR_TX;
	entry->fltr_info.src_id = ICE_SRC_ID_VSI;
	entry->fltr_info.lkup_type = ICE_SW_LKUP_MAC;
	entry->fltr_info.fltr_act = action;
	entry->fltr_info.vsi_handle = vsi->idx;
	bcopy(addr, entry->fltr_info.l_data.mac.mac_addr, ETHER_ADDR_LEN);

	LIST_ADD(&entry->list_entry, list);

	return 0;
}

/**
 * ice_free_fltr_list - Free memory associated with a MAC address list
 * @list: the list to free
 *
 * Free the memory of each entry associated with the list.
 */
static void
ice_free_fltr_list(struct ice_list_head *list)
{
	struct ice_fltr_list_entry *e, *tmp;

	LIST_FOR_EACH_ENTRY_SAFE(e, tmp, list, ice_fltr_list_entry, list_entry) {
		LIST_DEL(&e->list_entry);
		free(e, M_ICE);
	}
}

/**
 * ice_add_vsi_mac_filter - Add a MAC address filter for a VSI
 * @vsi: the VSI to add the filter for
 * @addr: MAC address to add a filter for
 *
 * Add a MAC address filter for a given VSI. This is a wrapper around
 * ice_add_mac to simplify the interface. First, it only accepts a single
 * address, so we don't have to mess around with the list setup in other
 * functions. Second, it ignores the ICE_ERR_ALREADY_EXIST error, so that
 * callers don't need to worry about attempting to add the same filter twice.
 */
int
ice_add_vsi_mac_filter(struct ice_vsi *vsi, const u8 *addr)
{
	struct ice_list_head mac_addr_list;
	struct ice_hw *hw = &vsi->sc->hw;
	device_t dev = vsi->sc->dev;
	enum ice_status status;
	int err = 0;

	INIT_LIST_HEAD(&mac_addr_list);

	err = ice_add_mac_to_list(vsi, &mac_addr_list, addr, ICE_FWD_TO_VSI);
	if (err)
		goto free_mac_list;

	status = ice_add_mac(hw, &mac_addr_list);
	if (status == ICE_ERR_ALREADY_EXISTS) {
		; /* Don't complain if we try to add a filter that already exists */
	} else if (status) {
		device_printf(dev,
			      "Failed to add a filter for MAC %6D, err %s aq_err %s\n",
			      addr, ":",
			      ice_status_str(status),
			      ice_aq_str(hw->adminq.sq_last_status));
		err = (EIO);
	}

free_mac_list:
	ice_free_fltr_list(&mac_addr_list);
	return err;
}

/**
 * ice_cfg_pf_default_mac_filters - Setup default unicast and broadcast addrs
 * @sc: device softc structure
 *
 * Program the default unicast and broadcast filters for the PF VSI.
 */
int
ice_cfg_pf_default_mac_filters(struct ice_softc *sc)
{
	struct ice_vsi *vsi = &sc->pf_vsi;
	struct ice_hw *hw = &sc->hw;
	int err;

	/* Add the LAN MAC address */
	err = ice_add_vsi_mac_filter(vsi, hw->port_info->mac.lan_addr);
	if (err)
		return err;

	/* Add the broadcast address */
	err = ice_add_vsi_mac_filter(vsi, broadcastaddr);
	if (err)
		return err;

	return (0);
}

/**
 * ice_remove_vsi_mac_filter - Remove a MAC address filter for a VSI
 * @vsi: the VSI to add the filter for
 * @addr: MAC address to remove a filter for
 *
 * Remove a MAC address filter from a given VSI. This is a wrapper around
 * ice_remove_mac to simplify the interface. First, it only accepts a single
 * address, so we don't have to mess around with the list setup in other
 * functions. Second, it ignores the ICE_ERR_DOES_NOT_EXIST error, so that
 * callers don't need to worry about attempting to remove filters which
 * haven't yet been added.
 */
int
ice_remove_vsi_mac_filter(struct ice_vsi *vsi, const u8 *addr)
{
	struct ice_list_head mac_addr_list;
	struct ice_hw *hw = &vsi->sc->hw;
	device_t dev = vsi->sc->dev;
	enum ice_status status;
	int err = 0;

	INIT_LIST_HEAD(&mac_addr_list);

	err = ice_add_mac_to_list(vsi, &mac_addr_list, addr, ICE_FWD_TO_VSI);
	if (err)
		goto free_mac_list;

	status = ice_remove_mac(hw, &mac_addr_list);
	if (status == ICE_ERR_DOES_NOT_EXIST) {
		; /* Don't complain if we try to remove a filter that doesn't exist */
	} else if (status) {
		device_printf(dev,
			      "Failed to remove a filter for MAC %6D, err %s aq_err %s\n",
			      addr, ":",
			      ice_status_str(status),
			      ice_aq_str(hw->adminq.sq_last_status));
		err = (EIO);
	}

free_mac_list:
	ice_free_fltr_list(&mac_addr_list);
	return err;
}

/**
 * ice_rm_pf_default_mac_filters - Remove default unicast and broadcast addrs
 * @sc: device softc structure
 *
 * Remove the default unicast and broadcast filters from the PF VSI.
 */
int
ice_rm_pf_default_mac_filters(struct ice_softc *sc)
{
	struct ice_vsi *vsi = &sc->pf_vsi;
	struct ice_hw *hw = &sc->hw;
	int err;

	/* Remove the LAN MAC address */
	err = ice_remove_vsi_mac_filter(vsi, hw->port_info->mac.lan_addr);
	if (err)
		return err;

	/* Remove the broadcast address */
	err = ice_remove_vsi_mac_filter(vsi, broadcastaddr);
	if (err)
		return (EIO);

	return (0);
}

/**
 * ice_check_ctrlq_errors - Check for and report controlq errors
 * @sc: device private structure
 * @qname: name of the controlq
 * @cq: the controlq to check
 *
 * Check and report controlq errors. Currently all we do is report them to the
 * kernel message log, but we might want to improve this in the future, such
 * as to keep track of statistics.
 */
static void
ice_check_ctrlq_errors(struct ice_softc *sc, const char *qname,
		       struct ice_ctl_q_info *cq)
{
	struct ice_hw *hw = &sc->hw;
	u32 val;

	/* Check for error indications. Note that all the controlqs use the
	 * same register layout, so we use the PF_FW_AxQLEN defines only.
	 */
	val = rd32(hw, cq->rq.len);
	if (val & (PF_FW_ARQLEN_ARQVFE_M | PF_FW_ARQLEN_ARQOVFL_M |
		   PF_FW_ARQLEN_ARQCRIT_M)) {
		if (val & PF_FW_ARQLEN_ARQVFE_M)
			device_printf(sc->dev,
				"%s Receive Queue VF Error detected\n", qname);
		if (val & PF_FW_ARQLEN_ARQOVFL_M)
			device_printf(sc->dev,
				"%s Receive Queue Overflow Error detected\n",
				qname);
		if (val & PF_FW_ARQLEN_ARQCRIT_M)
			device_printf(sc->dev,
				"%s Receive Queue Critical Error detected\n",
				qname);
		val &= ~(PF_FW_ARQLEN_ARQVFE_M | PF_FW_ARQLEN_ARQOVFL_M |
			 PF_FW_ARQLEN_ARQCRIT_M);
		wr32(hw, cq->rq.len, val);
	}

	val = rd32(hw, cq->sq.len);
	if (val & (PF_FW_ATQLEN_ATQVFE_M | PF_FW_ATQLEN_ATQOVFL_M |
		   PF_FW_ATQLEN_ATQCRIT_M)) {
		if (val & PF_FW_ATQLEN_ATQVFE_M)
			device_printf(sc->dev,
				"%s Send Queue VF Error detected\n", qname);
		if (val & PF_FW_ATQLEN_ATQOVFL_M)
			device_printf(sc->dev,
				"%s Send Queue Overflow Error detected\n",
				qname);
		if (val & PF_FW_ATQLEN_ATQCRIT_M)
			device_printf(sc->dev,
				"%s Send Queue Critical Error detected\n",
				qname);
		val &= ~(PF_FW_ATQLEN_ATQVFE_M | PF_FW_ATQLEN_ATQOVFL_M |
			 PF_FW_ATQLEN_ATQCRIT_M);
		wr32(hw, cq->sq.len, val);
	}
}

/**
 * ice_process_link_event - Process a link event indication from firmware
 * @sc: device softc structure
 * @e: the received event data
 *
 * Gets the current link status from hardware, and may print a message if an
 * unqualified is detected.
 */
static void
ice_process_link_event(struct ice_softc *sc,
		       struct ice_rq_event_info __invariant_only *e)
{
	struct ice_port_info *pi = sc->hw.port_info;
	struct ice_hw *hw = &sc->hw;
	device_t dev = sc->dev;
	enum ice_status status;

	/* Sanity check that the data length matches */
	MPASS(le16toh(e->desc.datalen) == sizeof(struct ice_aqc_get_link_status_data));

	/*
	 * Even though the adapter gets link status information inside the
	 * event, it needs to send a Get Link Status AQ command in order
	 * to re-enable link events.
	 */
	pi->phy.get_link_info = true;
	ice_get_link_status(pi, &sc->link_up);

	if (pi->phy.link_info.topo_media_conflict &
	   (ICE_AQ_LINK_TOPO_CONFLICT | ICE_AQ_LINK_MEDIA_CONFLICT |
	    ICE_AQ_LINK_TOPO_CORRUPT))
		device_printf(dev,
		    "Possible mis-configuration of the Ethernet port detected; please use the Intel (R) Ethernet Port Configuration Tool utility to address the issue.\n");

	if ((pi->phy.link_info.link_info & ICE_AQ_MEDIA_AVAILABLE) &&
	    !(pi->phy.link_info.link_info & ICE_AQ_LINK_UP)) {
		if (!(pi->phy.link_info.an_info & ICE_AQ_QUALIFIED_MODULE))
			device_printf(dev,
			    "Link is disabled on this device because an unsupported module type was detected! Refer to the Intel (R) Ethernet Adapters and Devices User Guide for a list of supported modules.\n");
		if (pi->phy.link_info.link_cfg_err & ICE_AQ_LINK_MODULE_POWER_UNSUPPORTED)
			device_printf(dev,
			    "The module's power requirements exceed the device's power supply. Cannot start link.\n");
		if (pi->phy.link_info.link_cfg_err & ICE_AQ_LINK_INVAL_MAX_POWER_LIMIT)
			device_printf(dev,
			    "The installed module is incompatible with the device's NVM image. Cannot start link.\n");
	}

	if (!(pi->phy.link_info.link_info & ICE_AQ_MEDIA_AVAILABLE)) {
		if (!ice_testandset_state(&sc->state, ICE_STATE_NO_MEDIA)) {
			status = ice_aq_set_link_restart_an(pi, false, NULL);
			if (status != ICE_SUCCESS)
				device_printf(dev,
				    "%s: ice_aq_set_link_restart_an: status %s, aq_err %s\n",
				    __func__, ice_status_str(status),
				    ice_aq_str(hw->adminq.sq_last_status));
		}
	}
	/* ICE_STATE_NO_MEDIA is cleared when polling task detects media */

	/* Indicate that link status must be reported again */
	ice_clear_state(&sc->state, ICE_STATE_LINK_STATUS_REPORTED);

	/* OS link info is updated elsewhere */
}

/**
 * ice_process_ctrlq_event - Respond to a controlq event
 * @sc: device private structure
 * @qname: the name for this controlq
 * @event: the event to process
 *
 * Perform actions in response to various controlq event notifications.
 */
static void
ice_process_ctrlq_event(struct ice_softc *sc, const char *qname,
			struct ice_rq_event_info *event)
{
	u16 opcode;

	opcode = le16toh(event->desc.opcode);

	switch (opcode) {
	case ice_aqc_opc_get_link_status:
		ice_process_link_event(sc, event);
		break;
	case ice_mbx_opc_send_msg_to_pf:
		/* TODO: handle IOV event */
		break;
	case ice_aqc_opc_fw_logs_event:
		ice_handle_fw_log_event(sc, &event->desc, event->msg_buf);
		break;
	case ice_aqc_opc_lldp_set_mib_change:
		ice_handle_mib_change_event(sc, event);
		break;
	case ice_aqc_opc_event_lan_overflow:
		ice_handle_lan_overflow_event(sc, event);
		break;
	case ice_aqc_opc_get_health_status:
		ice_handle_health_status_event(sc, event);
		break;
	default:
		device_printf(sc->dev,
			      "%s Receive Queue unhandled event 0x%04x ignored\n",
			      qname, opcode);
	}
}

/**
 * ice_process_ctrlq - helper function to process controlq rings
 * @sc: device private structure
 * @q_type: specific control queue type
 * @pending: return parameter to track remaining events
 *
 * Process controlq events for a given control queue type. Returns zero on
 * success, and an error code on failure. If successful, pending is the number
 * of remaining events left in the queue.
 */
int
ice_process_ctrlq(struct ice_softc *sc, enum ice_ctl_q q_type, u16 *pending)
{
	struct ice_rq_event_info event = { { 0 } };
	struct ice_hw *hw = &sc->hw;
	struct ice_ctl_q_info *cq;
	enum ice_status status;
	const char *qname;
	int loop = 0;

	switch (q_type) {
	case ICE_CTL_Q_ADMIN:
		cq = &hw->adminq;
		qname = "Admin";
		break;
	case ICE_CTL_Q_MAILBOX:
		cq = &hw->mailboxq;
		qname = "Mailbox";
		break;
	default:
		device_printf(sc->dev,
			      "Unknown control queue type 0x%x\n",
			      q_type);
		return 0;
	}

	ice_check_ctrlq_errors(sc, qname, cq);

	/*
	 * Control queue processing happens during the admin task which may be
	 * holding a non-sleepable lock, so we *must* use M_NOWAIT here.
	 */
	event.buf_len = cq->rq_buf_size;
	event.msg_buf = (u8 *)malloc(event.buf_len, M_ICE, M_ZERO | M_NOWAIT);
	if (!event.msg_buf) {
		device_printf(sc->dev,
			      "Unable to allocate memory for %s Receive Queue event\n",
			      qname);
		return (ENOMEM);
	}

	do {
		status = ice_clean_rq_elem(hw, cq, &event, pending);
		if (status == ICE_ERR_AQ_NO_WORK)
			break;
		if (status) {
			if (q_type == ICE_CTL_Q_ADMIN)
				device_printf(sc->dev,
					      "%s Receive Queue event error %s\n",
					      qname, ice_status_str(status));
			else
				device_printf(sc->dev,
					      "%s Receive Queue event error %s\n",
					      qname, ice_status_str(status));
			free(event.msg_buf, M_ICE);
			return (EIO);
		}
		/* XXX should we separate this handler by controlq type? */
		ice_process_ctrlq_event(sc, qname, &event);
	} while (*pending && (++loop < ICE_CTRLQ_WORK_LIMIT));

	free(event.msg_buf, M_ICE);

	return 0;
}

/**
 * pkg_ver_empty - Check if a package version is empty
 * @pkg_ver: the package version to check
 * @pkg_name: the package name to check
 *
 * Checks if the package version structure is empty. We consider a package
 * version as empty if none of the versions are non-zero and the name string
 * is null as well.
 *
 * This is used to check if the package version was initialized by the driver,
 * as we do not expect an actual DDP package file to have a zero'd version and
 * name.
 *
 * @returns true if the package version is valid, or false otherwise.
 */
static bool
pkg_ver_empty(struct ice_pkg_ver *pkg_ver, u8 *pkg_name)
{
	return (pkg_name[0] == '\0' &&
		pkg_ver->major == 0 &&
		pkg_ver->minor == 0 &&
		pkg_ver->update == 0 &&
		pkg_ver->draft == 0);
}

/**
 * pkg_ver_compatible - Check if the package version is compatible
 * @pkg_ver: the package version to check
 *
 * Compares the package version number to the driver's expected major/minor
 * version. Returns an integer indicating whether the version is older, newer,
 * or compatible with the driver.
 *
 * @returns 0 if the package version is compatible, -1 if the package version
 * is older, and 1 if the package version is newer than the driver version.
 */
static int
pkg_ver_compatible(struct ice_pkg_ver *pkg_ver)
{
	if (pkg_ver->major > ICE_PKG_SUPP_VER_MAJ)
		return (1); /* newer */
	else if ((pkg_ver->major == ICE_PKG_SUPP_VER_MAJ) &&
		 (pkg_ver->minor > ICE_PKG_SUPP_VER_MNR))
		return (1); /* newer */
	else if ((pkg_ver->major == ICE_PKG_SUPP_VER_MAJ) &&
		 (pkg_ver->minor == ICE_PKG_SUPP_VER_MNR))
		return (0); /* compatible */
	else
		return (-1); /* older */
}

/**
 * ice_os_pkg_version_str - Format OS package version info into a sbuf
 * @hw: device hw structure
 * @buf: string buffer to store name/version string
 *
 * Formats the name and version of the OS DDP package as found in the ice_ddp
 * module into a string.
 *
 * @remark This will almost always be the same as the active package, but
 * could be different in some cases. Use ice_active_pkg_version_str to get the
 * version of the active DDP package.
 */
static void
ice_os_pkg_version_str(struct ice_hw *hw, struct sbuf *buf)
{
	char name_buf[ICE_PKG_NAME_SIZE];

	/* If the OS DDP package info is empty, use "None" */
	if (pkg_ver_empty(&hw->pkg_ver, hw->pkg_name)) {
		sbuf_printf(buf, "None");
		return;
	}

	/*
	 * This should already be null-terminated, but since this is a raw
	 * value from an external source, strlcpy() into a new buffer to
	 * make sure.
	 */
	bzero(name_buf, sizeof(name_buf));
	strlcpy(name_buf, (char *)hw->pkg_name, ICE_PKG_NAME_SIZE);

	sbuf_printf(buf, "%s version %u.%u.%u.%u",
	    name_buf,
	    hw->pkg_ver.major,
	    hw->pkg_ver.minor,
	    hw->pkg_ver.update,
	    hw->pkg_ver.draft);
}

/**
 * ice_active_pkg_version_str - Format active package version info into a sbuf
 * @hw: device hw structure
 * @buf: string buffer to store name/version string
 *
 * Formats the name and version of the active DDP package info into a string
 * buffer for use.
 */
static void
ice_active_pkg_version_str(struct ice_hw *hw, struct sbuf *buf)
{
	char name_buf[ICE_PKG_NAME_SIZE];

	/* If the active DDP package info is empty, use "None" */
	if (pkg_ver_empty(&hw->active_pkg_ver, hw->active_pkg_name)) {
		sbuf_printf(buf, "None");
		return;
	}

	/*
	 * This should already be null-terminated, but since this is a raw
	 * value from an external source, strlcpy() into a new buffer to
	 * make sure.
	 */
	bzero(name_buf, sizeof(name_buf));
	strlcpy(name_buf, (char *)hw->active_pkg_name, ICE_PKG_NAME_SIZE);

	sbuf_printf(buf, "%s version %u.%u.%u.%u",
	    name_buf,
	    hw->active_pkg_ver.major,
	    hw->active_pkg_ver.minor,
	    hw->active_pkg_ver.update,
	    hw->active_pkg_ver.draft);

	if (hw->active_track_id != 0)
		sbuf_printf(buf, ", track id 0x%08x", hw->active_track_id);
}

/**
 * ice_nvm_version_str - Format the NVM version information into a sbuf
 * @hw: device hw structure
 * @buf: string buffer to store version string
 *
 * Formats the NVM information including firmware version, API version, NVM
 * version, the EETRACK id, and OEM specific version information into a string
 * buffer.
 */
static void
ice_nvm_version_str(struct ice_hw *hw, struct sbuf *buf)
{
	struct ice_nvm_info *nvm = &hw->flash.nvm;
	struct ice_orom_info *orom = &hw->flash.orom;
	struct ice_netlist_info *netlist = &hw->flash.netlist;

	/* Note that the netlist versions are stored in packed Binary Coded
	 * Decimal format. The use of '%x' will correctly display these as
	 * decimal numbers. This works because every 4 bits will be displayed
	 * as a hexadecimal digit, and the BCD format will only use the values
	 * 0-9.
	 */
	sbuf_printf(buf,
		    "fw %u.%u.%u api %u.%u nvm %x.%02x etid %08x netlist %x.%x.%x-%x.%x.%x.%04x oem %u.%u.%u",
		    hw->fw_maj_ver, hw->fw_min_ver, hw->fw_patch,
		    hw->api_maj_ver, hw->api_min_ver,
		    nvm->major, nvm->minor, nvm->eetrack,
		    netlist->major, netlist->minor,
		    netlist->type >> 16, netlist->type & 0xFFFF,
		    netlist->rev, netlist->cust_ver, netlist->hash,
		    orom->major, orom->build, orom->patch);
}

/**
 * ice_print_nvm_version - Print the NVM info to the kernel message log
 * @sc: the device softc structure
 *
 * Format and print an NVM version string using ice_nvm_version_str().
 */
void
ice_print_nvm_version(struct ice_softc *sc)
{
	struct ice_hw *hw = &sc->hw;
	device_t dev = sc->dev;
	struct sbuf *sbuf;

	sbuf = sbuf_new_auto();
	ice_nvm_version_str(hw, sbuf);
	sbuf_finish(sbuf);
	device_printf(dev, "%s\n", sbuf_data(sbuf));
	sbuf_delete(sbuf);
}

/**
 * ice_update_vsi_hw_stats - Update VSI-specific ethernet statistics counters
 * @vsi: the VSI to be updated
 *
 * Reads hardware stats and updates the ice_vsi_hw_stats tracking structure with
 * the updated values.
 */
void
ice_update_vsi_hw_stats(struct ice_vsi *vsi)
{
	struct ice_eth_stats *prev_es, *cur_es;
	struct ice_hw *hw = &vsi->sc->hw;
	u16 vsi_num;

	if (!ice_is_vsi_valid(hw, vsi->idx))
		return;

	vsi_num = ice_get_hw_vsi_num(hw, vsi->idx); /* HW absolute index of a VSI */
	prev_es = &vsi->hw_stats.prev;
	cur_es = &vsi->hw_stats.cur;

#define ICE_VSI_STAT40(name, location) \
	ice_stat_update40(hw, name ## L(vsi_num), \
			  vsi->hw_stats.offsets_loaded, \
			  &prev_es->location, &cur_es->location)

#define ICE_VSI_STAT32(name, location) \
	ice_stat_update32(hw, name(vsi_num), \
			  vsi->hw_stats.offsets_loaded, \
			  &prev_es->location, &cur_es->location)

	ICE_VSI_STAT40(GLV_GORC, rx_bytes);
	ICE_VSI_STAT40(GLV_UPRC, rx_unicast);
	ICE_VSI_STAT40(GLV_MPRC, rx_multicast);
	ICE_VSI_STAT40(GLV_BPRC, rx_broadcast);
	ICE_VSI_STAT32(GLV_RDPC, rx_discards);
	ICE_VSI_STAT40(GLV_GOTC, tx_bytes);
	ICE_VSI_STAT40(GLV_UPTC, tx_unicast);
	ICE_VSI_STAT40(GLV_MPTC, tx_multicast);
	ICE_VSI_STAT40(GLV_BPTC, tx_broadcast);
	ICE_VSI_STAT32(GLV_TEPC, tx_errors);

	ice_stat_update_repc(hw, vsi->idx, vsi->hw_stats.offsets_loaded,
			     cur_es);

#undef ICE_VSI_STAT40
#undef ICE_VSI_STAT32

	vsi->hw_stats.offsets_loaded = true;
}

/**
 * ice_reset_vsi_stats - Reset VSI statistics counters
 * @vsi: VSI structure
 *
 * Resets the software tracking counters for the VSI statistics, and indicate
 * that the offsets haven't been loaded. This is intended to be called
 * post-reset so that VSI statistics count from zero again.
 */
void
ice_reset_vsi_stats(struct ice_vsi *vsi)
{
	/* Reset HW stats */
	memset(&vsi->hw_stats.prev, 0, sizeof(vsi->hw_stats.prev));
	memset(&vsi->hw_stats.cur, 0, sizeof(vsi->hw_stats.cur));
	vsi->hw_stats.offsets_loaded = false;
}

/**
 * ice_update_pf_stats - Update port stats counters
 * @sc: device private softc structure
 *
 * Reads hardware statistics registers and updates the software tracking
 * structure with new values.
 */
void
ice_update_pf_stats(struct ice_softc *sc)
{
	struct ice_hw_port_stats *prev_ps, *cur_ps;
	struct ice_hw *hw = &sc->hw;
	u8 lport;

	MPASS(hw->port_info);

	prev_ps = &sc->stats.prev;
	cur_ps = &sc->stats.cur;
	lport = hw->port_info->lport;

#define ICE_PF_STAT_PFC(name, location, index) \
	ice_stat_update40(hw, name(lport, index), \
			  sc->stats.offsets_loaded, \
			  &prev_ps->location[index], &cur_ps->location[index])

#define ICE_PF_STAT40(name, location) \
	ice_stat_update40(hw, name ## L(lport), \
			  sc->stats.offsets_loaded, \
			  &prev_ps->location, &cur_ps->location)

#define ICE_PF_STAT32(name, location) \
	ice_stat_update32(hw, name(lport), \
			  sc->stats.offsets_loaded, \
			  &prev_ps->location, &cur_ps->location)

	ICE_PF_STAT40(GLPRT_GORC, eth.rx_bytes);
	ICE_PF_STAT40(GLPRT_UPRC, eth.rx_unicast);
	ICE_PF_STAT40(GLPRT_MPRC, eth.rx_multicast);
	ICE_PF_STAT40(GLPRT_BPRC, eth.rx_broadcast);
	ICE_PF_STAT40(GLPRT_GOTC, eth.tx_bytes);
	ICE_PF_STAT40(GLPRT_UPTC, eth.tx_unicast);
	ICE_PF_STAT40(GLPRT_MPTC, eth.tx_multicast);
	ICE_PF_STAT40(GLPRT_BPTC, eth.tx_broadcast);
	/* This stat register doesn't have an lport */
	ice_stat_update32(hw, PRTRPB_RDPC,
			  sc->stats.offsets_loaded,
			  &prev_ps->eth.rx_discards, &cur_ps->eth.rx_discards);

	ICE_PF_STAT32(GLPRT_TDOLD, tx_dropped_link_down);
	ICE_PF_STAT40(GLPRT_PRC64, rx_size_64);
	ICE_PF_STAT40(GLPRT_PRC127, rx_size_127);
	ICE_PF_STAT40(GLPRT_PRC255, rx_size_255);
	ICE_PF_STAT40(GLPRT_PRC511, rx_size_511);
	ICE_PF_STAT40(GLPRT_PRC1023, rx_size_1023);
	ICE_PF_STAT40(GLPRT_PRC1522, rx_size_1522);
	ICE_PF_STAT40(GLPRT_PRC9522, rx_size_big);
	ICE_PF_STAT40(GLPRT_PTC64, tx_size_64);
	ICE_PF_STAT40(GLPRT_PTC127, tx_size_127);
	ICE_PF_STAT40(GLPRT_PTC255, tx_size_255);
	ICE_PF_STAT40(GLPRT_PTC511, tx_size_511);
	ICE_PF_STAT40(GLPRT_PTC1023, tx_size_1023);
	ICE_PF_STAT40(GLPRT_PTC1522, tx_size_1522);
	ICE_PF_STAT40(GLPRT_PTC9522, tx_size_big);

	/* Update Priority Flow Control Stats */
	for (int i = 0; i <= GLPRT_PXOFFRXC_MAX_INDEX; i++) {
		ICE_PF_STAT_PFC(GLPRT_PXONRXC, priority_xon_rx, i);
		ICE_PF_STAT_PFC(GLPRT_PXOFFRXC, priority_xoff_rx, i);
		ICE_PF_STAT_PFC(GLPRT_PXONTXC, priority_xon_tx, i);
		ICE_PF_STAT_PFC(GLPRT_PXOFFTXC, priority_xoff_tx, i);
		ICE_PF_STAT_PFC(GLPRT_RXON2OFFCNT, priority_xon_2_xoff, i);
	}

	ICE_PF_STAT32(GLPRT_LXONRXC, link_xon_rx);
	ICE_PF_STAT32(GLPRT_LXOFFRXC, link_xoff_rx);
	ICE_PF_STAT32(GLPRT_LXONTXC, link_xon_tx);
	ICE_PF_STAT32(GLPRT_LXOFFTXC, link_xoff_tx);
	ICE_PF_STAT32(GLPRT_CRCERRS, crc_errors);
	ICE_PF_STAT32(GLPRT_ILLERRC, illegal_bytes);
	ICE_PF_STAT32(GLPRT_MLFC, mac_local_faults);
	ICE_PF_STAT32(GLPRT_MRFC, mac_remote_faults);
	ICE_PF_STAT32(GLPRT_RLEC, rx_len_errors);
	ICE_PF_STAT32(GLPRT_RUC, rx_undersize);
	ICE_PF_STAT32(GLPRT_RFC, rx_fragments);
	ICE_PF_STAT32(GLPRT_ROC, rx_oversize);
	ICE_PF_STAT32(GLPRT_RJC, rx_jabber);

#undef ICE_PF_STAT40
#undef ICE_PF_STAT32
#undef ICE_PF_STAT_PFC

	sc->stats.offsets_loaded = true;
}

/**
 * ice_reset_pf_stats - Reset port stats counters
 * @sc: Device private softc structure
 *
 * Reset software tracking values for statistics to zero, and indicate that
 * offsets haven't been loaded. Intended to be called after a device reset so
 * that statistics count from zero again.
 */
void
ice_reset_pf_stats(struct ice_softc *sc)
{
	memset(&sc->stats.prev, 0, sizeof(sc->stats.prev));
	memset(&sc->stats.cur, 0, sizeof(sc->stats.cur));
	sc->stats.offsets_loaded = false;
}

/**
 * ice_sysctl_show_fw - sysctl callback to show firmware information
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: unused
 * @req: sysctl request pointer
 *
 * Callback for the fw_version sysctl, to display the current firmware
 * information found at hardware init time.
 */
static int
ice_sysctl_show_fw(SYSCTL_HANDLER_ARGS)
{
	struct ice_softc *sc = (struct ice_softc *)arg1;
	struct ice_hw *hw = &sc->hw;
	struct sbuf *sbuf;

	UNREFERENCED_PARAMETER(oidp);
	UNREFERENCED_PARAMETER(arg2);

	if (ice_driver_is_detaching(sc))
		return (ESHUTDOWN);

	sbuf = sbuf_new_for_sysctl(NULL, NULL, 128, req);
	ice_nvm_version_str(hw, sbuf);
	sbuf_finish(sbuf);
	sbuf_delete(sbuf);

	return (0);
}

/**
 * ice_sysctl_pba_number - sysctl callback to show PBA number
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: unused
 * @req: sysctl request pointer
 *
 * Callback for the pba_number sysctl, used to read the Product Board Assembly
 * number for this device.
 */
static int
ice_sysctl_pba_number(SYSCTL_HANDLER_ARGS)
{
	struct ice_softc *sc = (struct ice_softc *)arg1;
	struct ice_hw *hw = &sc->hw;
	device_t dev = sc->dev;
	u8 pba_string[32] = "";
	enum ice_status status;

	UNREFERENCED_PARAMETER(arg2);

	if (ice_driver_is_detaching(sc))
		return (ESHUTDOWN);

	status = ice_read_pba_string(hw, pba_string, sizeof(pba_string));
	if (status) {
		device_printf(dev,
		    "%s: failed to read PBA string from NVM; status %s, aq_err %s\n",
		    __func__, ice_status_str(status),
		    ice_aq_str(hw->adminq.sq_last_status));
		return (EIO);
	}

	return sysctl_handle_string(oidp, pba_string, sizeof(pba_string), req);
}

/**
 * ice_sysctl_pkg_version - sysctl to show the active package version info
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: unused
 * @req: sysctl request pointer
 *
 * Callback for the pkg_version sysctl, to display the active DDP package name
 * and version information.
 */
static int
ice_sysctl_pkg_version(SYSCTL_HANDLER_ARGS)
{
	struct ice_softc *sc = (struct ice_softc *)arg1;
	struct ice_hw *hw = &sc->hw;
	struct sbuf *sbuf;

	UNREFERENCED_PARAMETER(oidp);
	UNREFERENCED_PARAMETER(arg2);

	if (ice_driver_is_detaching(sc))
		return (ESHUTDOWN);

	sbuf = sbuf_new_for_sysctl(NULL, NULL, 128, req);
	ice_active_pkg_version_str(hw, sbuf);
	sbuf_finish(sbuf);
	sbuf_delete(sbuf);

	return (0);
}

/**
 * ice_sysctl_os_pkg_version - sysctl to show the OS package version info
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: unused
 * @req: sysctl request pointer
 *
 * Callback for the pkg_version sysctl, to display the OS DDP package name and
 * version info found in the ice_ddp module.
 */
static int
ice_sysctl_os_pkg_version(SYSCTL_HANDLER_ARGS)
{
	struct ice_softc *sc = (struct ice_softc *)arg1;
	struct ice_hw *hw = &sc->hw;
	struct sbuf *sbuf;

	UNREFERENCED_PARAMETER(oidp);
	UNREFERENCED_PARAMETER(arg2);

	if (ice_driver_is_detaching(sc))
		return (ESHUTDOWN);

	sbuf = sbuf_new_for_sysctl(NULL, NULL, 128, req);
	ice_os_pkg_version_str(hw, sbuf);
	sbuf_finish(sbuf);
	sbuf_delete(sbuf);

	return (0);
}

/**
 * ice_sysctl_current_speed - sysctl callback to show current link speed
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: unused
 * @req: sysctl request pointer
 *
 * Callback for the current_speed sysctl, to display the string representing
 * the current link speed.
 */
static int
ice_sysctl_current_speed(SYSCTL_HANDLER_ARGS)
{
	struct ice_softc *sc = (struct ice_softc *)arg1;
	struct ice_hw *hw = &sc->hw;
	struct sbuf *sbuf;

	UNREFERENCED_PARAMETER(oidp);
	UNREFERENCED_PARAMETER(arg2);

	if (ice_driver_is_detaching(sc))
		return (ESHUTDOWN);

	sbuf = sbuf_new_for_sysctl(NULL, NULL, 10, req);
	sbuf_printf(sbuf, "%s", ice_aq_speed_to_str(hw->port_info));
	sbuf_finish(sbuf);
	sbuf_delete(sbuf);

	return (0);
}

/**
 * @var phy_link_speeds
 * @brief PHY link speed conversion array
 *
 * Array of link speeds to convert ICE_PHY_TYPE_LOW and ICE_PHY_TYPE_HIGH into
 * link speeds used by the link speed sysctls.
 *
 * @remark these are based on the indices used in the BIT() macros for the
 * ICE_PHY_TYPE_LOW_* and ICE_PHY_TYPE_HIGH_* definitions.
 */
static const uint16_t phy_link_speeds[] = {
    ICE_AQ_LINK_SPEED_100MB,
    ICE_AQ_LINK_SPEED_100MB,
    ICE_AQ_LINK_SPEED_1000MB,
    ICE_AQ_LINK_SPEED_1000MB,
    ICE_AQ_LINK_SPEED_1000MB,
    ICE_AQ_LINK_SPEED_1000MB,
    ICE_AQ_LINK_SPEED_1000MB,
    ICE_AQ_LINK_SPEED_2500MB,
    ICE_AQ_LINK_SPEED_2500MB,
    ICE_AQ_LINK_SPEED_2500MB,
    ICE_AQ_LINK_SPEED_5GB,
    ICE_AQ_LINK_SPEED_5GB,
    ICE_AQ_LINK_SPEED_10GB,
    ICE_AQ_LINK_SPEED_10GB,
    ICE_AQ_LINK_SPEED_10GB,
    ICE_AQ_LINK_SPEED_10GB,
    ICE_AQ_LINK_SPEED_10GB,
    ICE_AQ_LINK_SPEED_10GB,
    ICE_AQ_LINK_SPEED_10GB,
    ICE_AQ_LINK_SPEED_25GB,
    ICE_AQ_LINK_SPEED_25GB,
    ICE_AQ_LINK_SPEED_25GB,
    ICE_AQ_LINK_SPEED_25GB,
    ICE_AQ_LINK_SPEED_25GB,
    ICE_AQ_LINK_SPEED_25GB,
    ICE_AQ_LINK_SPEED_25GB,
    ICE_AQ_LINK_SPEED_25GB,
    ICE_AQ_LINK_SPEED_25GB,
    ICE_AQ_LINK_SPEED_25GB,
    ICE_AQ_LINK_SPEED_25GB,
    ICE_AQ_LINK_SPEED_40GB,
    ICE_AQ_LINK_SPEED_40GB,
    ICE_AQ_LINK_SPEED_40GB,
    ICE_AQ_LINK_SPEED_40GB,
    ICE_AQ_LINK_SPEED_40GB,
    ICE_AQ_LINK_SPEED_40GB,
    ICE_AQ_LINK_SPEED_50GB,
    ICE_AQ_LINK_SPEED_50GB,
    ICE_AQ_LINK_SPEED_50GB,
    ICE_AQ_LINK_SPEED_50GB,
    ICE_AQ_LINK_SPEED_50GB,
    ICE_AQ_LINK_SPEED_50GB,
    ICE_AQ_LINK_SPEED_50GB,
    ICE_AQ_LINK_SPEED_50GB,
    ICE_AQ_LINK_SPEED_50GB,
    ICE_AQ_LINK_SPEED_50GB,
    ICE_AQ_LINK_SPEED_50GB,
    ICE_AQ_LINK_SPEED_50GB,
    ICE_AQ_LINK_SPEED_50GB,
    ICE_AQ_LINK_SPEED_50GB,
    ICE_AQ_LINK_SPEED_50GB,
    ICE_AQ_LINK_SPEED_100GB,
    ICE_AQ_LINK_SPEED_100GB,
    ICE_AQ_LINK_SPEED_100GB,
    ICE_AQ_LINK_SPEED_100GB,
    ICE_AQ_LINK_SPEED_100GB,
    ICE_AQ_LINK_SPEED_100GB,
    ICE_AQ_LINK_SPEED_100GB,
    ICE_AQ_LINK_SPEED_100GB,
    ICE_AQ_LINK_SPEED_100GB,
    ICE_AQ_LINK_SPEED_100GB,
    ICE_AQ_LINK_SPEED_100GB,
    ICE_AQ_LINK_SPEED_100GB,
    ICE_AQ_LINK_SPEED_100GB,
    /* These rates are for ICE_PHY_TYPE_HIGH_* */
    ICE_AQ_LINK_SPEED_100GB,
    ICE_AQ_LINK_SPEED_100GB,
    ICE_AQ_LINK_SPEED_100GB,
    ICE_AQ_LINK_SPEED_100GB,
    ICE_AQ_LINK_SPEED_100GB
};

#define ICE_SYSCTL_HELP_ADVERTISE_SPEED		\
"\nControl advertised link speed."		\
"\nFlags:"					\
"\n\t   0x0 - Auto"				\
"\n\t   0x1 - 10 Mb"				\
"\n\t   0x2 - 100 Mb"				\
"\n\t   0x4 - 1G"				\
"\n\t   0x8 - 2.5G"				\
"\n\t  0x10 - 5G"				\
"\n\t  0x20 - 10G"				\
"\n\t  0x40 - 20G"				\
"\n\t  0x80 - 25G"				\
"\n\t 0x100 - 40G"				\
"\n\t 0x200 - 50G"				\
"\n\t 0x400 - 100G"				\
"\n\t0x8000 - Unknown"				\
"\n\t"						\
"\nUse \"sysctl -x\" to view flags properly."

#define ICE_PHYS_100MB			\
    (ICE_PHY_TYPE_LOW_100BASE_TX |	\
     ICE_PHY_TYPE_LOW_100M_SGMII)
#define ICE_PHYS_1000MB			\
    (ICE_PHY_TYPE_LOW_1000BASE_T |	\
     ICE_PHY_TYPE_LOW_1000BASE_SX |	\
     ICE_PHY_TYPE_LOW_1000BASE_LX |	\
     ICE_PHY_TYPE_LOW_1000BASE_KX |	\
     ICE_PHY_TYPE_LOW_1G_SGMII)
#define ICE_PHYS_2500MB			\
    (ICE_PHY_TYPE_LOW_2500BASE_T |	\
     ICE_PHY_TYPE_LOW_2500BASE_X |	\
     ICE_PHY_TYPE_LOW_2500BASE_KX)
#define ICE_PHYS_5GB			\
    (ICE_PHY_TYPE_LOW_5GBASE_T |	\
     ICE_PHY_TYPE_LOW_5GBASE_KR)
#define ICE_PHYS_10GB			\
    (ICE_PHY_TYPE_LOW_10GBASE_T |	\
     ICE_PHY_TYPE_LOW_10G_SFI_DA |	\
     ICE_PHY_TYPE_LOW_10GBASE_SR |	\
     ICE_PHY_TYPE_LOW_10GBASE_LR |	\
     ICE_PHY_TYPE_LOW_10GBASE_KR_CR1 |	\
     ICE_PHY_TYPE_LOW_10G_SFI_AOC_ACC |	\
     ICE_PHY_TYPE_LOW_10G_SFI_C2C)
#define ICE_PHYS_25GB			\
    (ICE_PHY_TYPE_LOW_25GBASE_T |	\
     ICE_PHY_TYPE_LOW_25GBASE_CR |	\
     ICE_PHY_TYPE_LOW_25GBASE_CR_S |	\
     ICE_PHY_TYPE_LOW_25GBASE_CR1 |	\
     ICE_PHY_TYPE_LOW_25GBASE_SR |	\
     ICE_PHY_TYPE_LOW_25GBASE_LR |	\
     ICE_PHY_TYPE_LOW_25GBASE_KR |	\
     ICE_PHY_TYPE_LOW_25GBASE_KR_S |	\
     ICE_PHY_TYPE_LOW_25GBASE_KR1 |	\
     ICE_PHY_TYPE_LOW_25G_AUI_AOC_ACC |	\
     ICE_PHY_TYPE_LOW_25G_AUI_C2C)
#define ICE_PHYS_40GB			\
    (ICE_PHY_TYPE_LOW_40GBASE_CR4 |	\
     ICE_PHY_TYPE_LOW_40GBASE_SR4 |	\
     ICE_PHY_TYPE_LOW_40GBASE_LR4 |	\
     ICE_PHY_TYPE_LOW_40GBASE_KR4 |	\
     ICE_PHY_TYPE_LOW_40G_XLAUI_AOC_ACC | \
     ICE_PHY_TYPE_LOW_40G_XLAUI)
#define ICE_PHYS_50GB			\
    (ICE_PHY_TYPE_LOW_50GBASE_CR2 |	\
     ICE_PHY_TYPE_LOW_50GBASE_SR2 |	\
     ICE_PHY_TYPE_LOW_50GBASE_LR2 |	\
     ICE_PHY_TYPE_LOW_50GBASE_KR2 |	\
     ICE_PHY_TYPE_LOW_50G_LAUI2_AOC_ACC | \
     ICE_PHY_TYPE_LOW_50G_LAUI2 |	\
     ICE_PHY_TYPE_LOW_50G_AUI2_AOC_ACC | \
     ICE_PHY_TYPE_LOW_50G_AUI2 |	\
     ICE_PHY_TYPE_LOW_50GBASE_CP |	\
     ICE_PHY_TYPE_LOW_50GBASE_SR |	\
     ICE_PHY_TYPE_LOW_50GBASE_FR |	\
     ICE_PHY_TYPE_LOW_50GBASE_LR |	\
     ICE_PHY_TYPE_LOW_50GBASE_KR_PAM4 |	\
     ICE_PHY_TYPE_LOW_50G_AUI1_AOC_ACC | \
     ICE_PHY_TYPE_LOW_50G_AUI1)
#define ICE_PHYS_100GB_LOW		\
    (ICE_PHY_TYPE_LOW_100GBASE_CR4 |	\
     ICE_PHY_TYPE_LOW_100GBASE_SR4 |	\
     ICE_PHY_TYPE_LOW_100GBASE_LR4 |	\
     ICE_PHY_TYPE_LOW_100GBASE_KR4 |	\
     ICE_PHY_TYPE_LOW_100G_CAUI4_AOC_ACC | \
     ICE_PHY_TYPE_LOW_100G_CAUI4 |	\
     ICE_PHY_TYPE_LOW_100G_AUI4_AOC_ACC | \
     ICE_PHY_TYPE_LOW_100G_AUI4 |	\
     ICE_PHY_TYPE_LOW_100GBASE_CR_PAM4 | \
     ICE_PHY_TYPE_LOW_100GBASE_KR_PAM4 | \
     ICE_PHY_TYPE_LOW_100GBASE_CP2 |	\
     ICE_PHY_TYPE_LOW_100GBASE_SR2 |	\
     ICE_PHY_TYPE_LOW_100GBASE_DR)
#define ICE_PHYS_100GB_HIGH		\
    (ICE_PHY_TYPE_HIGH_100GBASE_KR2_PAM4 | \
     ICE_PHY_TYPE_HIGH_100G_CAUI2_AOC_ACC | \
     ICE_PHY_TYPE_HIGH_100G_CAUI2 |	\
     ICE_PHY_TYPE_HIGH_100G_AUI2_AOC_ACC | \
     ICE_PHY_TYPE_HIGH_100G_AUI2)

/**
 * ice_aq_phy_types_to_link_speeds - Convert the PHY Types to speeds
 * @phy_type_low: lower 64-bit PHY Type bitmask
 * @phy_type_high: upper 64-bit PHY Type bitmask
 *
 * Convert the PHY Type fields from Get PHY Abilities and Set PHY Config into
 * link speed flags. If phy_type_high has an unknown PHY type, then the return
 * value will include the "ICE_AQ_LINK_SPEED_UNKNOWN" flag as well.
 */
static u16
ice_aq_phy_types_to_link_speeds(u64 phy_type_low, u64 phy_type_high)
{
	u16 sysctl_speeds = 0;
	int bit;

	/* coverity[address_of] */
	for_each_set_bit(bit, &phy_type_low, 64)
		sysctl_speeds |= phy_link_speeds[bit];

	/* coverity[address_of] */
	for_each_set_bit(bit, &phy_type_high, 64) {
		if ((bit + 64) < (int)ARRAY_SIZE(phy_link_speeds))
			sysctl_speeds |= phy_link_speeds[bit + 64];
		else
			sysctl_speeds |= ICE_AQ_LINK_SPEED_UNKNOWN;
	}

	return (sysctl_speeds);
}

/**
 * ice_sysctl_speeds_to_aq_phy_types - Convert sysctl speed flags to AQ PHY flags
 * @sysctl_speeds: 16-bit sysctl speeds or AQ_LINK_SPEED flags
 * @phy_type_low: output parameter for lower AQ PHY flags
 * @phy_type_high: output parameter for higher AQ PHY flags
 *
 * Converts the given link speed flags into AQ PHY type flag sets appropriate
 * for use in a Set PHY Config command.
 */
static void
ice_sysctl_speeds_to_aq_phy_types(u16 sysctl_speeds, u64 *phy_type_low,
				  u64 *phy_type_high)
{
	*phy_type_low = 0, *phy_type_high = 0;

	if (sysctl_speeds & ICE_AQ_LINK_SPEED_100MB)
		*phy_type_low |= ICE_PHYS_100MB;
	if (sysctl_speeds & ICE_AQ_LINK_SPEED_1000MB)
		*phy_type_low |= ICE_PHYS_1000MB;
	if (sysctl_speeds & ICE_AQ_LINK_SPEED_2500MB)
		*phy_type_low |= ICE_PHYS_2500MB;
	if (sysctl_speeds & ICE_AQ_LINK_SPEED_5GB)
		*phy_type_low |= ICE_PHYS_5GB;
	if (sysctl_speeds & ICE_AQ_LINK_SPEED_10GB)
		*phy_type_low |= ICE_PHYS_10GB;
	if (sysctl_speeds & ICE_AQ_LINK_SPEED_25GB)
		*phy_type_low |= ICE_PHYS_25GB;
	if (sysctl_speeds & ICE_AQ_LINK_SPEED_40GB)
		*phy_type_low |= ICE_PHYS_40GB;
	if (sysctl_speeds & ICE_AQ_LINK_SPEED_50GB)
		*phy_type_low |= ICE_PHYS_50GB;
	if (sysctl_speeds & ICE_AQ_LINK_SPEED_100GB) {
		*phy_type_low |= ICE_PHYS_100GB_LOW;
		*phy_type_high |= ICE_PHYS_100GB_HIGH;
	}
}

/**
 * @struct ice_phy_data
 * @brief PHY caps and link speeds
 *
 * Buffer providing report mode and user speeds;
 * returning intersection of PHY types and speeds.
 */
struct ice_phy_data {
	u64 phy_low_orig;     /* PHY low quad from report */
	u64 phy_high_orig;    /* PHY high quad from report */
	u64 phy_low_intr;     /* PHY low quad intersection with user speeds */
	u64 phy_high_intr;    /* PHY high quad intersection with user speeds */
	u16 user_speeds_orig; /* Input from caller - See ICE_AQ_LINK_SPEED_* */
	u16 user_speeds_intr; /* Intersect with report speeds */
	u8 report_mode;       /* See ICE_AQC_REPORT_* */
};

/**
 * ice_intersect_phy_types_and_speeds - Return intersection of link speeds
 * @sc: device private structure
 * @phy_data: device PHY data
 *
 * On read: Displays the currently supported speeds
 * On write: Sets the device's supported speeds
 * Valid input flags: see ICE_SYSCTL_HELP_ADVERTISE_SPEED
 */
static int
ice_intersect_phy_types_and_speeds(struct ice_softc *sc,
				   struct ice_phy_data *phy_data)
{
	struct ice_aqc_get_phy_caps_data pcaps = { 0 };
	const char *report_types[5] = { "w/o MEDIA",
					"w/MEDIA",
					"ACTIVE",
					"EDOOFUS", /* Not used */
					"DFLT" };
	struct ice_hw *hw = &sc->hw;
	struct ice_port_info *pi = hw->port_info;
	enum ice_status status;
	u16 report_speeds, temp_speeds;
	u8 report_type;
	bool apply_speed_filter = false;

	switch (phy_data->report_mode) {
	case ICE_AQC_REPORT_TOPO_CAP_NO_MEDIA:
	case ICE_AQC_REPORT_TOPO_CAP_MEDIA:
	case ICE_AQC_REPORT_ACTIVE_CFG:
	case ICE_AQC_REPORT_DFLT_CFG:
		report_type = phy_data->report_mode >> 1;
		break;
	default:
		device_printf(sc->dev,
		    "%s: phy_data.report_mode \"%u\" doesn't exist\n",
		    __func__, phy_data->report_mode);
		return (EINVAL);
	}

	/* 0 is treated as "Auto"; the driver will handle selecting the
	 * correct speeds. Including, in some cases, applying an override
	 * if provided.
	 */
	if (phy_data->user_speeds_orig == 0)
		phy_data->user_speeds_orig = USHRT_MAX;
	else if (ice_is_bit_set(sc->feat_en, ICE_FEATURE_LENIENT_LINK_MODE))
		apply_speed_filter = true;

	status = ice_aq_get_phy_caps(pi, false, phy_data->report_mode, &pcaps, NULL);
	if (status != ICE_SUCCESS) {
		device_printf(sc->dev,
		    "%s: ice_aq_get_phy_caps (%s) failed; status %s, aq_err %s\n",
		    __func__, report_types[report_type],
		    ice_status_str(status),
		    ice_aq_str(sc->hw.adminq.sq_last_status));
		return (EIO);
	}

	phy_data->phy_low_orig = le64toh(pcaps.phy_type_low);
	phy_data->phy_high_orig = le64toh(pcaps.phy_type_high);
	report_speeds = ice_aq_phy_types_to_link_speeds(phy_data->phy_low_orig,
	    phy_data->phy_high_orig);
	if (apply_speed_filter) {
		temp_speeds = ice_apply_supported_speed_filter(report_speeds,
		    pcaps.module_type[0]);
		if ((phy_data->user_speeds_orig & temp_speeds) == 0) {
			device_printf(sc->dev,
			    "User-specified speeds (\"0x%04X\") not supported\n",
			    phy_data->user_speeds_orig);
			return (EINVAL);
		}
		report_speeds = temp_speeds;
	}
	ice_sysctl_speeds_to_aq_phy_types(phy_data->user_speeds_orig,
	    &phy_data->phy_low_intr, &phy_data->phy_high_intr);
	phy_data->user_speeds_intr = phy_data->user_speeds_orig & report_speeds;
	phy_data->phy_low_intr &= phy_data->phy_low_orig;
	phy_data->phy_high_intr &= phy_data->phy_high_orig;

	return (0);
 }

/**
 * ice_sysctl_advertise_speed - Display/change link speeds supported by port
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: unused
 * @req: sysctl request pointer
 *
 * On read: Displays the currently supported speeds
 * On write: Sets the device's supported speeds
 * Valid input flags: see ICE_SYSCTL_HELP_ADVERTISE_SPEED
 */
static int
ice_sysctl_advertise_speed(SYSCTL_HANDLER_ARGS)
{
	struct ice_softc *sc = (struct ice_softc *)arg1;
	struct ice_port_info *pi = sc->hw.port_info;
	struct ice_phy_data phy_data = { 0 };
	device_t dev = sc->dev;
	u16 sysctl_speeds;
	int ret;

	UNREFERENCED_PARAMETER(arg2);

	if (ice_driver_is_detaching(sc))
		return (ESHUTDOWN);

	/* Get the current speeds from the adapter's "active" configuration. */
	phy_data.report_mode = ICE_AQC_REPORT_ACTIVE_CFG;
	ret = ice_intersect_phy_types_and_speeds(sc, &phy_data);
	if (ret) {
		/* Error message already printed within function */
		return (ret);
	}

	sysctl_speeds = phy_data.user_speeds_intr;

	ret = sysctl_handle_16(oidp, &sysctl_speeds, 0, req);
	if ((ret) || (req->newptr == NULL))
		return (ret);

	if (sysctl_speeds > 0x7FF) {
		device_printf(dev,
			      "%s: \"%u\" is outside of the range of acceptable values.\n",
			      __func__, sysctl_speeds);
		return (EINVAL);
	}

	pi->phy.curr_user_speed_req = sysctl_speeds;

	/* Apply settings requested by user */
	return ice_apply_saved_phy_cfg(sc, ICE_APPLY_LS);
}

#define ICE_SYSCTL_HELP_FEC_CONFIG			\
"\nDisplay or set the port's requested FEC mode."	\
"\n\tauto - " ICE_FEC_STRING_AUTO			\
"\n\tfc - " ICE_FEC_STRING_BASER			\
"\n\trs - " ICE_FEC_STRING_RS				\
"\n\tnone - " ICE_FEC_STRING_NONE			\
"\nEither of the left or right strings above can be used to set the requested mode."

/**
 * ice_sysctl_fec_config - Display/change the configured FEC mode
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: unused
 * @req: sysctl request pointer
 *
 * On read: Displays the configured FEC mode
 * On write: Sets the device's FEC mode to the input string, if it's valid.
 * Valid input strings: see ICE_SYSCTL_HELP_FEC_CONFIG
 */
static int
ice_sysctl_fec_config(SYSCTL_HANDLER_ARGS)
{
	struct ice_softc *sc = (struct ice_softc *)arg1;
	struct ice_port_info *pi = sc->hw.port_info;
	enum ice_fec_mode new_mode;
	device_t dev = sc->dev;
	char req_fec[32];
	int ret;

	UNREFERENCED_PARAMETER(arg2);

	if (ice_driver_is_detaching(sc))
		return (ESHUTDOWN);

	bzero(req_fec, sizeof(req_fec));
	strlcpy(req_fec, ice_requested_fec_mode(pi), sizeof(req_fec));

	ret = sysctl_handle_string(oidp, req_fec, sizeof(req_fec), req);
	if ((ret) || (req->newptr == NULL))
		return (ret);

	if (strcmp(req_fec, "auto") == 0 ||
	    strcmp(req_fec, ice_fec_str(ICE_FEC_AUTO)) == 0) {
		new_mode = ICE_FEC_AUTO;
	} else if (strcmp(req_fec, "fc") == 0 ||
	    strcmp(req_fec, ice_fec_str(ICE_FEC_BASER)) == 0) {
		new_mode = ICE_FEC_BASER;
	} else if (strcmp(req_fec, "rs") == 0 ||
	    strcmp(req_fec, ice_fec_str(ICE_FEC_RS)) == 0) {
		new_mode = ICE_FEC_RS;
	} else if (strcmp(req_fec, "none") == 0 ||
	    strcmp(req_fec, ice_fec_str(ICE_FEC_NONE)) == 0) {
		new_mode = ICE_FEC_NONE;
	} else {
		device_printf(dev,
		    "%s: \"%s\" is not a valid FEC mode\n",
		    __func__, req_fec);
		return (EINVAL);
	}

	/* Cache user FEC mode for later link ups */
	pi->phy.curr_user_fec_req = new_mode;

	/* Apply settings requested by user */
	return ice_apply_saved_phy_cfg(sc, ICE_APPLY_FEC);
}

/**
 * ice_sysctl_negotiated_fec - Display the negotiated FEC mode on the link
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: unused
 * @req: sysctl request pointer
 *
 * On read: Displays the negotiated FEC mode, in a string
 */
static int
ice_sysctl_negotiated_fec(SYSCTL_HANDLER_ARGS)
{
	struct ice_softc *sc = (struct ice_softc *)arg1;
	struct ice_hw *hw = &sc->hw;
	char neg_fec[32];
	int ret;

	UNREFERENCED_PARAMETER(arg2);

	if (ice_driver_is_detaching(sc))
		return (ESHUTDOWN);

	/* Copy const string into a buffer to drop const qualifier */
	bzero(neg_fec, sizeof(neg_fec));
	strlcpy(neg_fec, ice_negotiated_fec_mode(hw->port_info), sizeof(neg_fec));

	ret = sysctl_handle_string(oidp, neg_fec, 0, req);
	if (req->newptr != NULL)
		return (EPERM);

	return (ret);
}

#define ICE_SYSCTL_HELP_FC_CONFIG				\
"\nDisplay or set the port's advertised flow control mode.\n"	\
"\t0 - " ICE_FC_STRING_NONE					\
"\n\t1 - " ICE_FC_STRING_RX					\
"\n\t2 - " ICE_FC_STRING_TX					\
"\n\t3 - " ICE_FC_STRING_FULL					\
"\nEither the numbers or the strings above can be used to set the advertised mode."

/**
 * ice_sysctl_fc_config - Display/change the advertised flow control mode
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: unused
 * @req: sysctl request pointer
 *
 * On read: Displays the configured flow control mode
 * On write: Sets the device's flow control mode to the input, if it's valid.
 * Valid input strings: see ICE_SYSCTL_HELP_FC_CONFIG
 */
static int
ice_sysctl_fc_config(SYSCTL_HANDLER_ARGS)
{
	struct ice_softc *sc = (struct ice_softc *)arg1;
	struct ice_port_info *pi = sc->hw.port_info;
	struct ice_aqc_get_phy_caps_data pcaps = { 0 };
	enum ice_fc_mode old_mode, new_mode;
	struct ice_hw *hw = &sc->hw;
	device_t dev = sc->dev;
	enum ice_status status;
	int ret, fc_num;
	bool mode_set = false;
	struct sbuf buf;
	char *fc_str_end;
	char fc_str[32];

	UNREFERENCED_PARAMETER(arg2);

	if (ice_driver_is_detaching(sc))
		return (ESHUTDOWN);

	status = ice_aq_get_phy_caps(pi, false, ICE_AQC_REPORT_ACTIVE_CFG,
				     &pcaps, NULL);
	if (status != ICE_SUCCESS) {
		device_printf(dev,
		    "%s: ice_aq_get_phy_caps failed; status %s, aq_err %s\n",
		    __func__, ice_status_str(status),
		    ice_aq_str(hw->adminq.sq_last_status));
		return (EIO);
	}

	/* Convert HW response format to SW enum value */
	if ((pcaps.caps & ICE_AQC_PHY_EN_TX_LINK_PAUSE) &&
	    (pcaps.caps & ICE_AQC_PHY_EN_RX_LINK_PAUSE))
		old_mode = ICE_FC_FULL;
	else if (pcaps.caps & ICE_AQC_PHY_EN_TX_LINK_PAUSE)
		old_mode = ICE_FC_TX_PAUSE;
	else if (pcaps.caps & ICE_AQC_PHY_EN_RX_LINK_PAUSE)
		old_mode = ICE_FC_RX_PAUSE;
	else
		old_mode = ICE_FC_NONE;

	/* Create "old" string for output */
	bzero(fc_str, sizeof(fc_str));
	sbuf_new_for_sysctl(&buf, fc_str, sizeof(fc_str), req);
	sbuf_printf(&buf, "%d<%s>", old_mode, ice_fc_str(old_mode));
	sbuf_finish(&buf);
	sbuf_delete(&buf);

	ret = sysctl_handle_string(oidp, fc_str, sizeof(fc_str), req);
	if ((ret) || (req->newptr == NULL))
		return (ret);

	/* Try to parse input as a string, first */
	if (strcasecmp(ice_fc_str(ICE_FC_FULL), fc_str) == 0) {
		new_mode = ICE_FC_FULL;
		mode_set = true;
	}
	else if (strcasecmp(ice_fc_str(ICE_FC_TX_PAUSE), fc_str) == 0) {
		new_mode = ICE_FC_TX_PAUSE;
		mode_set = true;
	}
	else if (strcasecmp(ice_fc_str(ICE_FC_RX_PAUSE), fc_str) == 0) {
		new_mode = ICE_FC_RX_PAUSE;
		mode_set = true;
	}
	else if (strcasecmp(ice_fc_str(ICE_FC_NONE), fc_str) == 0) {
		new_mode = ICE_FC_NONE;
		mode_set = true;
	}

	/*
	 * Then check if it's an integer, for compatibility with the method
	 * used in older drivers.
	 */
	if (!mode_set) {
		fc_num = strtol(fc_str, &fc_str_end, 0);
		if (fc_str_end == fc_str)
			fc_num = -1;
		switch (fc_num) {
		case 3:
			new_mode = ICE_FC_FULL;
			break;
		case 2:
			new_mode = ICE_FC_TX_PAUSE;
			break;
		case 1:
			new_mode = ICE_FC_RX_PAUSE;
			break;
		case 0:
			new_mode = ICE_FC_NONE;
			break;
		default:
			device_printf(dev,
			    "%s: \"%s\" is not a valid flow control mode\n",
			    __func__, fc_str);
			return (EINVAL);
		}
	}

	/* Save flow control mode from user */
	pi->phy.curr_user_fc_req = new_mode;

	/* Turn off Priority Flow Control when Link Flow Control is enabled */
	if ((hw->port_info->qos_cfg.is_sw_lldp) &&
	    (hw->port_info->qos_cfg.local_dcbx_cfg.pfc.pfcena != 0) &&
	    (new_mode != ICE_FC_NONE)) {
		ret = ice_config_pfc(sc, 0x0);
		if (ret)
			return (ret);
	}

	/* Apply settings requested by user */
	return ice_apply_saved_phy_cfg(sc, ICE_APPLY_FC);
}

/**
 * ice_sysctl_negotiated_fc - Display currently negotiated FC mode
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: unused
 * @req: sysctl request pointer
 *
 * On read: Displays the currently negotiated flow control settings.
 *
 * If link is not established, this will report ICE_FC_NONE, as no flow
 * control is negotiated while link is down.
 */
static int
ice_sysctl_negotiated_fc(SYSCTL_HANDLER_ARGS)
{
	struct ice_softc *sc = (struct ice_softc *)arg1;
	struct ice_port_info *pi = sc->hw.port_info;
	const char *negotiated_fc;

	UNREFERENCED_PARAMETER(arg2);

	if (ice_driver_is_detaching(sc))
		return (ESHUTDOWN);

	negotiated_fc = ice_flowcontrol_mode(pi);

	return sysctl_handle_string(oidp, __DECONST(char *, negotiated_fc), 0, req);
}

/**
 * __ice_sysctl_phy_type_handler - Display/change supported PHY types/speeds
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: unused
 * @req: sysctl request pointer
 * @is_phy_type_high: if true, handle the high PHY type instead of the low PHY type
 *
 * Private handler for phy_type_high and phy_type_low sysctls.
 */
static int
__ice_sysctl_phy_type_handler(SYSCTL_HANDLER_ARGS, bool is_phy_type_high)
{
	struct ice_softc *sc = (struct ice_softc *)arg1;
	struct ice_aqc_get_phy_caps_data pcaps = { 0 };
	struct ice_aqc_set_phy_cfg_data cfg = { 0 };
	struct ice_hw *hw = &sc->hw;
	device_t dev = sc->dev;
	enum ice_status status;
	uint64_t types;
	int ret;

	UNREFERENCED_PARAMETER(arg2);

	if (ice_driver_is_detaching(sc))
		return (ESHUTDOWN);

	status = ice_aq_get_phy_caps(hw->port_info, false, ICE_AQC_REPORT_ACTIVE_CFG,
				     &pcaps, NULL);
	if (status != ICE_SUCCESS) {
		device_printf(dev,
		    "%s: ice_aq_get_phy_caps failed; status %s, aq_err %s\n",
		    __func__, ice_status_str(status),
		    ice_aq_str(hw->adminq.sq_last_status));
		return (EIO);
	}

	if (is_phy_type_high)
		types = pcaps.phy_type_high;
	else
		types = pcaps.phy_type_low;

	ret = sysctl_handle_64(oidp, &types, sizeof(types), req);
	if ((ret) || (req->newptr == NULL))
		return (ret);

	ice_copy_phy_caps_to_cfg(hw->port_info, &pcaps, &cfg);

	if (is_phy_type_high)
		cfg.phy_type_high = types & hw->port_info->phy.phy_type_high;
	else
		cfg.phy_type_low = types & hw->port_info->phy.phy_type_low;
	cfg.caps |= ICE_AQ_PHY_ENA_AUTO_LINK_UPDT;

	status = ice_aq_set_phy_cfg(hw, hw->port_info, &cfg, NULL);
	if (status != ICE_SUCCESS) {
		device_printf(dev,
		    "%s: ice_aq_set_phy_cfg failed; status %s, aq_err %s\n",
		    __func__, ice_status_str(status),
		    ice_aq_str(hw->adminq.sq_last_status));
		return (EIO);
	}

	return (0);

}

/**
 * ice_sysctl_phy_type_low - Display/change supported lower PHY types/speeds
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: unused
 * @req: sysctl request pointer
 *
 * On read: Displays the currently supported lower PHY types
 * On write: Sets the device's supported low PHY types
 */
static int
ice_sysctl_phy_type_low(SYSCTL_HANDLER_ARGS)
{
	return __ice_sysctl_phy_type_handler(oidp, arg1, arg2, req, false);
}

/**
 * ice_sysctl_phy_type_high - Display/change supported higher PHY types/speeds
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: unused
 * @req: sysctl request pointer
 *
 * On read: Displays the currently supported higher PHY types
 * On write: Sets the device's supported high PHY types
 */
static int
ice_sysctl_phy_type_high(SYSCTL_HANDLER_ARGS)
{
	return __ice_sysctl_phy_type_handler(oidp, arg1, arg2, req, true);
}

/**
 * ice_sysctl_phy_caps - Display response from Get PHY abililties
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: unused
 * @req: sysctl request pointer
 * @report_mode: the mode to report
 *
 * On read: Display the response from Get PHY abillities with the given report
 * mode.
 */
static int
ice_sysctl_phy_caps(SYSCTL_HANDLER_ARGS, u8 report_mode)
{
	struct ice_softc *sc = (struct ice_softc *)arg1;
	struct ice_aqc_get_phy_caps_data pcaps = { 0 };
	struct ice_hw *hw = &sc->hw;
	struct ice_port_info *pi = hw->port_info;
	device_t dev = sc->dev;
	enum ice_status status;
	int ret;

	UNREFERENCED_PARAMETER(arg2);

	ret = priv_check(curthread, PRIV_DRIVER);
	if (ret)
		return (ret);

	if (ice_driver_is_detaching(sc))
		return (ESHUTDOWN);

	status = ice_aq_get_phy_caps(pi, true, report_mode, &pcaps, NULL);
	if (status != ICE_SUCCESS) {
		device_printf(dev,
		    "%s: ice_aq_get_phy_caps failed; status %s, aq_err %s\n",
		    __func__, ice_status_str(status),
		    ice_aq_str(hw->adminq.sq_last_status));
		return (EIO);
	}

	ret = sysctl_handle_opaque(oidp, &pcaps, sizeof(pcaps), req);
	if (req->newptr != NULL)
		return (EPERM);

	return (ret);
}

/**
 * ice_sysctl_phy_sw_caps - Display response from Get PHY abililties
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: unused
 * @req: sysctl request pointer
 *
 * On read: Display the response from Get PHY abillities reporting the last
 * software configuration.
 */
static int
ice_sysctl_phy_sw_caps(SYSCTL_HANDLER_ARGS)
{
	return ice_sysctl_phy_caps(oidp, arg1, arg2, req,
				   ICE_AQC_REPORT_ACTIVE_CFG);
}

/**
 * ice_sysctl_phy_nvm_caps - Display response from Get PHY abililties
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: unused
 * @req: sysctl request pointer
 *
 * On read: Display the response from Get PHY abillities reporting the NVM
 * configuration.
 */
static int
ice_sysctl_phy_nvm_caps(SYSCTL_HANDLER_ARGS)
{
	return ice_sysctl_phy_caps(oidp, arg1, arg2, req,
				   ICE_AQC_REPORT_TOPO_CAP_NO_MEDIA);
}

/**
 * ice_sysctl_phy_topo_caps - Display response from Get PHY abililties
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: unused
 * @req: sysctl request pointer
 *
 * On read: Display the response from Get PHY abillities reporting the
 * topology configuration.
 */
static int
ice_sysctl_phy_topo_caps(SYSCTL_HANDLER_ARGS)
{
	return ice_sysctl_phy_caps(oidp, arg1, arg2, req,
				   ICE_AQC_REPORT_TOPO_CAP_MEDIA);
}

/**
 * ice_sysctl_phy_link_status - Display response from Get Link Status
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: unused
 * @req: sysctl request pointer
 *
 * On read: Display the response from firmware for the Get Link Status
 * request.
 */
static int
ice_sysctl_phy_link_status(SYSCTL_HANDLER_ARGS)
{
	struct ice_aqc_get_link_status_data link_data = { 0 };
	struct ice_softc *sc = (struct ice_softc *)arg1;
	struct ice_hw *hw = &sc->hw;
	struct ice_port_info *pi = hw->port_info;
	struct ice_aqc_get_link_status *resp;
	struct ice_aq_desc desc;
	device_t dev = sc->dev;
	enum ice_status status;
	int ret;

	UNREFERENCED_PARAMETER(arg2);

	/*
	 * Ensure that only contexts with driver privilege are allowed to
	 * access this information
	 */
	ret = priv_check(curthread, PRIV_DRIVER);
	if (ret)
		return (ret);

	if (ice_driver_is_detaching(sc))
		return (ESHUTDOWN);

	ice_fill_dflt_direct_cmd_desc(&desc, ice_aqc_opc_get_link_status);
	resp = &desc.params.get_link_status;
	resp->lport_num = pi->lport;

	status = ice_aq_send_cmd(hw, &desc, &link_data, sizeof(link_data), NULL);
	if (status != ICE_SUCCESS) {
		device_printf(dev,
		    "%s: ice_aq_send_cmd failed; status %s, aq_err %s\n",
		    __func__, ice_status_str(status),
		    ice_aq_str(hw->adminq.sq_last_status));
		return (EIO);
	}

	ret = sysctl_handle_opaque(oidp, &link_data, sizeof(link_data), req);
	if (req->newptr != NULL)
		return (EPERM);

	return (ret);
}

/**
 * ice_sysctl_fw_cur_lldp_persist_status - Display current FW LLDP status
 * @oidp: sysctl oid structure
 * @arg1: pointer to private softc structure
 * @arg2: unused
 * @req: sysctl request pointer
 *
 * On read: Displays current persistent LLDP status.
 */
static int
ice_sysctl_fw_cur_lldp_persist_status(SYSCTL_HANDLER_ARGS)
{
	struct ice_softc *sc = (struct ice_softc *)arg1;
	struct ice_hw *hw = &sc->hw;
	device_t dev = sc->dev;
	enum ice_status status;
	struct sbuf *sbuf;
	u32 lldp_state;

	UNREFERENCED_PARAMETER(arg2);
	UNREFERENCED_PARAMETER(oidp);

	if (ice_driver_is_detaching(sc))
		return (ESHUTDOWN);

	status = ice_get_cur_lldp_persist_status(hw, &lldp_state);
	if (status) {
		device_printf(dev,
		    "Could not acquire current LLDP persistence status, err %s aq_err %s\n",
		    ice_status_str(status), ice_aq_str(hw->adminq.sq_last_status));
		return (EIO);
	}

	sbuf = sbuf_new_for_sysctl(NULL, NULL, 128, req);
	sbuf_printf(sbuf, "%s", ice_fw_lldp_status(lldp_state));
	sbuf_finish(sbuf);
	sbuf_delete(sbuf);

	return (0);
}

/**
 * ice_sysctl_fw_dflt_lldp_persist_status - Display default FW LLDP status
 * @oidp: sysctl oid structure
 * @arg1: pointer to private softc structure
 * @arg2: unused
 * @req: sysctl request pointer
 *
 * On read: Displays default persistent LLDP status.
 */
static int
ice_sysctl_fw_dflt_lldp_persist_status(SYSCTL_HANDLER_ARGS)
{
	struct ice_softc *sc = (struct ice_softc *)arg1;
	struct ice_hw *hw = &sc->hw;
	device_t dev = sc->dev;
	enum ice_status status;
	struct sbuf *sbuf;
	u32 lldp_state;

	UNREFERENCED_PARAMETER(arg2);
	UNREFERENCED_PARAMETER(oidp);

	if (ice_driver_is_detaching(sc))
		return (ESHUTDOWN);

	status = ice_get_dflt_lldp_persist_status(hw, &lldp_state);
	if (status) {
		device_printf(dev,
		    "Could not acquire default LLDP persistence status, err %s aq_err %s\n",
		    ice_status_str(status), ice_aq_str(hw->adminq.sq_last_status));
		return (EIO);
	}

	sbuf = sbuf_new_for_sysctl(NULL, NULL, 128, req);
	sbuf_printf(sbuf, "%s", ice_fw_lldp_status(lldp_state));
	sbuf_finish(sbuf);
	sbuf_delete(sbuf);

	return (0);
}

#define ICE_SYSCTL_HELP_FW_LLDP_AGENT	\
"\nDisplay or change FW LLDP agent state:" \
"\n\t0 - disabled"			\
"\n\t1 - enabled"

/**
 * ice_sysctl_fw_lldp_agent - Display or change the FW LLDP agent status
 * @oidp: sysctl oid structure
 * @arg1: pointer to private softc structure
 * @arg2: unused
 * @req: sysctl request pointer
 *
 * On read: Displays whether the FW LLDP agent is running
 * On write: Persistently enables or disables the FW LLDP agent
 */
static int
ice_sysctl_fw_lldp_agent(SYSCTL_HANDLER_ARGS)
{
	struct ice_softc *sc = (struct ice_softc *)arg1;
	struct ice_hw *hw = &sc->hw;
	device_t dev = sc->dev;
	enum ice_status status;
	int ret;
	u32 old_state;
	u8 fw_lldp_enabled;
	bool retried_start_lldp = false;

	UNREFERENCED_PARAMETER(arg2);

	if (ice_driver_is_detaching(sc))
		return (ESHUTDOWN);

	status = ice_get_cur_lldp_persist_status(hw, &old_state);
	if (status) {
		device_printf(dev,
		    "Could not acquire current LLDP persistence status, err %s aq_err %s\n",
		    ice_status_str(status), ice_aq_str(hw->adminq.sq_last_status));
		return (EIO);
	}

	if (old_state > ICE_LLDP_ADMINSTATUS_ENA_RXTX) {
		status = ice_get_dflt_lldp_persist_status(hw, &old_state);
		if (status) {
			device_printf(dev,
			    "Could not acquire default LLDP persistence status, err %s aq_err %s\n",
			    ice_status_str(status),
			    ice_aq_str(hw->adminq.sq_last_status));
			return (EIO);
		}
	}
	if (old_state == 0)
		fw_lldp_enabled = false;
	else
		fw_lldp_enabled = true;

	ret = sysctl_handle_bool(oidp, &fw_lldp_enabled, 0, req);
	if ((ret) || (req->newptr == NULL))
		return (ret);

	if (old_state == 0 && fw_lldp_enabled == false)
		return (0);

	if (old_state != 0 && fw_lldp_enabled == true)
		return (0);

	if (fw_lldp_enabled == false) {
		status = ice_aq_stop_lldp(hw, true, true, NULL);
		/* EPERM is returned if the LLDP agent is already shutdown */
		if (status && hw->adminq.sq_last_status != ICE_AQ_RC_EPERM) {
			device_printf(dev,
			    "%s: ice_aq_stop_lldp failed; status %s, aq_err %s\n",
			    __func__, ice_status_str(status),
			    ice_aq_str(hw->adminq.sq_last_status));
			return (EIO);
		}
		ice_aq_set_dcb_parameters(hw, true, NULL);
		hw->port_info->qos_cfg.is_sw_lldp = true;
		ice_add_rx_lldp_filter(sc);
	} else {
		ice_del_rx_lldp_filter(sc);
retry_start_lldp:
		status = ice_aq_start_lldp(hw, true, NULL);
		if (status) {
			switch (hw->adminq.sq_last_status) {
			/* EEXIST is returned if the LLDP agent is already started */
			case ICE_AQ_RC_EEXIST:
				break;
			case ICE_AQ_RC_EAGAIN:
				/* Retry command after a 2 second wait */
				if (retried_start_lldp == false) {
					retried_start_lldp = true;
					pause("slldp", ICE_START_LLDP_RETRY_WAIT);
					goto retry_start_lldp;
				}
				/* Fallthrough */
			default:
				device_printf(dev,
				    "%s: ice_aq_start_lldp failed; status %s, aq_err %s\n",
				    __func__, ice_status_str(status),
				    ice_aq_str(hw->adminq.sq_last_status));
				return (EIO);
			}
		}
		hw->port_info->qos_cfg.is_sw_lldp = false;
	}

	return (ret);
}

#define ICE_SYSCTL_HELP_ETS_MIN_RATE \
"\nIn FW DCB mode (fw_lldp_agent=1), displays the current ETS bandwidth table." \
"\nIn SW DCB mode, displays and allows setting the table." \
"\nInput must be in the format e.g. 30,10,10,10,10,10,10,10" \
"\nWhere the bandwidth total must add up to 100"

/**
 * ice_sysctl_ets_min_rate - Report/configure ETS bandwidth
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: unused
 * @req: sysctl request pointer
 *
 * Returns the current ETS TC bandwidth table
 * cached by the driver.
 *
 * In SW DCB mode this sysctl also accepts a value that will
 * be sent to the firmware for configuration.
 */
static int
ice_sysctl_ets_min_rate(SYSCTL_HANDLER_ARGS)
{
	struct ice_softc *sc = (struct ice_softc *)arg1;
	struct ice_dcbx_cfg *local_dcbx_cfg;
	struct ice_port_info *pi;
	struct ice_hw *hw = &sc->hw;
	device_t dev = sc->dev;
	enum ice_status status;
	struct sbuf *sbuf;
	int ret;

	/* Store input rates from user */
	char ets_user_buf[128] = "";
	u8 new_ets_table[ICE_MAX_TRAFFIC_CLASS] = {};

	UNREFERENCED_PARAMETER(arg2);

	if (ice_driver_is_detaching(sc))
		return (ESHUTDOWN);

	if (req->oldptr == NULL && req->newptr == NULL) {
		ret = SYSCTL_OUT(req, 0, 128);
		return (ret);
	}

	pi = hw->port_info;
	local_dcbx_cfg = &pi->qos_cfg.local_dcbx_cfg;

	sbuf = sbuf_new(NULL, ets_user_buf, 128, SBUF_FIXEDLEN | SBUF_INCLUDENUL);

	/* Format ETS BW data for output */
	for (int i = 0; i < ICE_MAX_TRAFFIC_CLASS; i++) {
		sbuf_printf(sbuf, "%d", local_dcbx_cfg->etscfg.tcbwtable[i]);
		if (i != ICE_MAX_TRAFFIC_CLASS - 1)
			sbuf_printf(sbuf, ",");
	}

	sbuf_finish(sbuf);
	sbuf_delete(sbuf);

	/* Read in the new ETS values */
	ret = sysctl_handle_string(oidp, ets_user_buf, sizeof(ets_user_buf), req);
	if ((ret) || (req->newptr == NULL))
		return (ret);

	/* Don't allow setting changes in FW DCB mode */
	if (!hw->port_info->qos_cfg.is_sw_lldp)
		return (EPERM);

	ret = ice_ets_str_to_tbl(ets_user_buf, new_ets_table, 100);
	if (ret) {
		device_printf(dev, "%s: Could not parse input BW table: %s\n",
		    __func__, ets_user_buf);
		return (ret);
	}

	if (!ice_check_ets_bw(new_ets_table)) {
		device_printf(dev, "%s: Bandwidth sum does not equal 100: %s\n",
		    __func__, ets_user_buf);
		return (EINVAL);
	}

	memcpy(local_dcbx_cfg->etscfg.tcbwtable, new_ets_table,
	    sizeof(new_ets_table));

	/* If BW > 0, then set TSA entry to 2 */
	for (int i = 0; i < ICE_MAX_TRAFFIC_CLASS; i++) {
		if (new_ets_table[i] > 0)
			local_dcbx_cfg->etscfg.tsatable[i] = 2;
		else
			local_dcbx_cfg->etscfg.tsatable[i] = 0;
	}
	local_dcbx_cfg->etscfg.willing = 0;
	local_dcbx_cfg->etsrec = local_dcbx_cfg->etscfg;
	local_dcbx_cfg->app_mode = ICE_DCBX_APPS_NON_WILLING;

	status = ice_set_dcb_cfg(pi);
	if (status) {
		device_printf(dev,
		    "%s: Failed to set DCB config; status %s, aq_err %s\n",
		    __func__, ice_status_str(status),
		    ice_aq_str(hw->adminq.sq_last_status));
		return (EIO);
	}

	ice_do_dcb_reconfig(sc);

	return (0);
}

#define ICE_SYSCTL_HELP_UP2TC_MAP \
"\nIn FW DCB mode (fw_lldp_agent=1), displays the current ETS priority assignment table." \
"\nIn SW DCB mode, displays and allows setting the table." \
"\nInput must be in this format: 0,1,2,3,4,5,6,7" \
"\nWhere the 1st number is the TC for UP0, 2nd number is the TC for UP1, etc"

/**
 * ice_sysctl_up2tc_map - Report or configure UP2TC mapping
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: unused
 * @req: sysctl request pointer
 *
 * In FW DCB mode, returns the current ETS prio table /
 * UP2TC mapping from the local MIB.
 *
 * In SW DCB mode this sysctl also accepts a value that will
 * be sent to the firmware for configuration.
 */
static int
ice_sysctl_up2tc_map(SYSCTL_HANDLER_ARGS)
{
	struct ice_softc *sc = (struct ice_softc *)arg1;
	struct ice_dcbx_cfg *local_dcbx_cfg;
	struct ice_port_info *pi;
	struct ice_hw *hw = &sc->hw;
	device_t dev = sc->dev;
	enum ice_status status;
	struct sbuf *sbuf;
	int ret;

	/* Store input rates from user */
	char up2tc_user_buf[128] = "";
	/* This array is indexed by UP, not TC */
	u8 new_up2tc[ICE_MAX_TRAFFIC_CLASS] = {};

	UNREFERENCED_PARAMETER(arg2);

	if (ice_driver_is_detaching(sc))
		return (ESHUTDOWN);

	if (req->oldptr == NULL && req->newptr == NULL) {
		ret = SYSCTL_OUT(req, 0, 128);
		return (ret);
	}

	pi = hw->port_info;
	local_dcbx_cfg = &pi->qos_cfg.local_dcbx_cfg;

	sbuf = sbuf_new(NULL, up2tc_user_buf, 128, SBUF_FIXEDLEN | SBUF_INCLUDENUL);

	/* Format ETS Priority Mapping Table for output */
	for (int i = 0; i < ICE_MAX_TRAFFIC_CLASS; i++) {
		sbuf_printf(sbuf, "%d", local_dcbx_cfg->etscfg.prio_table[i]);
		if (i != ICE_MAX_TRAFFIC_CLASS - 1)
			sbuf_printf(sbuf, ",");
	}

	sbuf_finish(sbuf);
	sbuf_delete(sbuf);

	/* Read in the new ETS priority mapping */
	ret = sysctl_handle_string(oidp, up2tc_user_buf, sizeof(up2tc_user_buf), req);
	if ((ret) || (req->newptr == NULL))
		return (ret);

	/* Don't allow setting changes in FW DCB mode */
	if (!hw->port_info->qos_cfg.is_sw_lldp)
		return (EPERM);

	ret = ice_ets_str_to_tbl(up2tc_user_buf, new_up2tc, 7);
	if (ret) {
		device_printf(dev, "%s: Could not parse input priority assignment table: %s\n",
		    __func__, up2tc_user_buf);
		return (ret);
	}

	/* Prepare updated ETS TLV */
	memcpy(local_dcbx_cfg->etscfg.prio_table, new_up2tc,
	    sizeof(new_up2tc));

	status = ice_set_dcb_cfg(pi);
	if (status) {
		device_printf(dev,
		    "%s: Failed to set DCB config; status %s, aq_err %s\n",
		    __func__, ice_status_str(status),
		    ice_aq_str(hw->adminq.sq_last_status));
		return (EIO);
	}

	ice_do_dcb_reconfig(sc);

	return (0);
}

/**
 * ice_config_pfc - helper function to set PFC config in FW
 * @sc: device private structure
 * @new_mode: bit flags indicating PFC status for TCs
 *
 * @pre must be in SW DCB mode
 *
 * Configures the driver's local PFC TLV and sends it to the
 * FW for configuration, then reconfigures the driver/VSI
 * for DCB if needed.
 */
static int
ice_config_pfc(struct ice_softc *sc, u8 new_mode)
{
	struct ice_dcbx_cfg *local_dcbx_cfg;
	struct ice_hw *hw = &sc->hw;
	struct ice_port_info *pi;
	device_t dev = sc->dev;
	enum ice_status status;

	pi = hw->port_info;
	local_dcbx_cfg = &pi->qos_cfg.local_dcbx_cfg;

	/* Prepare updated PFC TLV */
	local_dcbx_cfg->pfc.pfcena = new_mode;
	local_dcbx_cfg->pfc.pfccap = ICE_MAX_TRAFFIC_CLASS;
	local_dcbx_cfg->pfc.willing = 0;
	local_dcbx_cfg->pfc.mbc = 0;

	status = ice_set_dcb_cfg(pi);
	if (status) {
		device_printf(dev,
		    "%s: Failed to set DCB config; status %s, aq_err %s\n",
		    __func__, ice_status_str(status),
		    ice_aq_str(hw->adminq.sq_last_status));
		return (EIO);
	}

	ice_do_dcb_reconfig(sc);

	return (0);
}

#define ICE_SYSCTL_HELP_PFC_CONFIG \
"\nIn FW DCB mode (fw_lldp_agent=1), displays the current Priority Flow Control configuration" \
"\nIn SW DCB mode, displays and allows setting the configuration" \
"\nInput/Output is in this format: 0xff" \
"\nWhere bit position # enables/disables PFC for that Traffic Class #"

/**
 * ice_sysctl_pfc_config - Report or configure enabled PFC TCs
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: unused
 * @req: sysctl request pointer
 *
 * In FW DCB mode, returns a bitmap containing the current TCs
 * that have PFC enabled on them.
 *
 * In SW DCB mode this sysctl also accepts a value that will
 * be sent to the firmware for configuration.
 */
static int
ice_sysctl_pfc_config(SYSCTL_HANDLER_ARGS)
{
	struct ice_softc *sc = (struct ice_softc *)arg1;
	struct ice_dcbx_cfg *local_dcbx_cfg;
	struct ice_port_info *pi;
	struct ice_hw *hw = &sc->hw;
	int ret;

	/* Store input flags from user */
	u8 user_pfc;

	UNREFERENCED_PARAMETER(arg2);

	if (ice_driver_is_detaching(sc))
		return (ESHUTDOWN);

	if (req->oldptr == NULL && req->newptr == NULL) {
		ret = SYSCTL_OUT(req, 0, sizeof(u8));
		return (ret);
	}

	pi = hw->port_info;
	local_dcbx_cfg = &pi->qos_cfg.local_dcbx_cfg;

	/* Format current PFC enable setting for output */
	user_pfc = local_dcbx_cfg->pfc.pfcena;

	/* Read in the new PFC config */
	ret = sysctl_handle_8(oidp, &user_pfc, 0, req);
	if ((ret) || (req->newptr == NULL))
		return (ret);

	/* Don't allow setting changes in FW DCB mode */
	if (!hw->port_info->qos_cfg.is_sw_lldp)
		return (EPERM);

	/* If LFC is active and PFC is going to be turned on, turn LFC off */
	if (user_pfc != 0 && pi->phy.curr_user_fc_req != ICE_FC_NONE) {
		pi->phy.curr_user_fc_req = ICE_FC_NONE;
		ret = ice_apply_saved_phy_cfg(sc, ICE_APPLY_FC);
		if (ret)
			return (ret);
	}

	return ice_config_pfc(sc, user_pfc);
}

/**
 * ice_add_device_sysctls - add device specific dynamic sysctls
 * @sc: device private structure
 *
 * Add per-device dynamic sysctls which show device configuration or enable
 * configuring device functionality. For tunable values which can be set prior
 * to load, see ice_add_device_tunables.
 *
 * This function depends on the sysctl layout setup by ice_add_device_tunables,
 * and likely should be called near the end of the attach process.
 */
void
ice_add_device_sysctls(struct ice_softc *sc)
{
	struct sysctl_oid *hw_node;
	device_t dev = sc->dev;

	struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(dev);
	struct sysctl_oid_list *ctx_list =
	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev));

	SYSCTL_ADD_PROC(ctx, ctx_list,
	    OID_AUTO, "fw_version", CTLTYPE_STRING | CTLFLAG_RD,
	    sc, 0, ice_sysctl_show_fw, "A", "Firmware version");

	if (ice_is_bit_set(sc->feat_en, ICE_FEATURE_HAS_PBA)) {
		SYSCTL_ADD_PROC(ctx, ctx_list,
		    OID_AUTO, "pba_number", CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
		    ice_sysctl_pba_number, "A", "Product Board Assembly Number");
	}

	SYSCTL_ADD_PROC(ctx, ctx_list,
	    OID_AUTO, "ddp_version", CTLTYPE_STRING | CTLFLAG_RD,
	    sc, 0, ice_sysctl_pkg_version, "A", "Active DDP package name and version");

	SYSCTL_ADD_PROC(ctx, ctx_list,
	    OID_AUTO, "current_speed", CTLTYPE_STRING | CTLFLAG_RD,
	    sc, 0, ice_sysctl_current_speed, "A", "Current Port Link Speed");

	SYSCTL_ADD_PROC(ctx, ctx_list,
	    OID_AUTO, "requested_fec", CTLTYPE_STRING | CTLFLAG_RW,
	    sc, 0, ice_sysctl_fec_config, "A", ICE_SYSCTL_HELP_FEC_CONFIG);

	SYSCTL_ADD_PROC(ctx, ctx_list,
	    OID_AUTO, "negotiated_fec", CTLTYPE_STRING | CTLFLAG_RD,
	    sc, 0, ice_sysctl_negotiated_fec, "A", "Current Negotiated FEC mode");

	SYSCTL_ADD_PROC(ctx, ctx_list,
	    OID_AUTO, "fc", CTLTYPE_STRING | CTLFLAG_RW,
	    sc, 0, ice_sysctl_fc_config, "A", ICE_SYSCTL_HELP_FC_CONFIG);

	SYSCTL_ADD_PROC(ctx, ctx_list,
	    OID_AUTO, "advertise_speed", CTLTYPE_U16 | CTLFLAG_RW,
	    sc, 0, ice_sysctl_advertise_speed, "SU", ICE_SYSCTL_HELP_ADVERTISE_SPEED);

	SYSCTL_ADD_PROC(ctx, ctx_list,
	    OID_AUTO, "fw_lldp_agent", CTLTYPE_U8 | CTLFLAG_RWTUN,
	    sc, 0, ice_sysctl_fw_lldp_agent, "CU", ICE_SYSCTL_HELP_FW_LLDP_AGENT);

	SYSCTL_ADD_PROC(ctx, ctx_list,
	    OID_AUTO, "ets_min_rate", CTLTYPE_STRING | CTLFLAG_RW,
	    sc, 0, ice_sysctl_ets_min_rate, "A", ICE_SYSCTL_HELP_ETS_MIN_RATE);

	SYSCTL_ADD_PROC(ctx, ctx_list,
	    OID_AUTO, "up2tc_map", CTLTYPE_STRING | CTLFLAG_RW,
	    sc, 0, ice_sysctl_up2tc_map, "A", ICE_SYSCTL_HELP_UP2TC_MAP);

	SYSCTL_ADD_PROC(ctx, ctx_list,
	    OID_AUTO, "pfc", CTLTYPE_U8 | CTLFLAG_RW,
	    sc, 0, ice_sysctl_pfc_config, "CU", ICE_SYSCTL_HELP_PFC_CONFIG);

	/* Differentiate software and hardware statistics, by keeping hw stats
	 * in their own node. This isn't in ice_add_device_tunables, because
	 * we won't have any CTLFLAG_TUN sysctls under this node.
	 */
	hw_node = SYSCTL_ADD_NODE(ctx, ctx_list, OID_AUTO, "hw", CTLFLAG_RD,
				  NULL, "Port Hardware Statistics");

	ice_add_sysctls_mac_stats(ctx, hw_node, &sc->stats.cur);

	/* Add the main PF VSI stats now. Other VSIs will add their own stats
	 * during creation
	 */
	ice_add_vsi_sysctls(&sc->pf_vsi);

	/* Add sysctls related to debugging the device driver. This includes
	 * sysctls which display additional internal driver state for use in
	 * understanding what is happening within the driver.
	 */
	ice_add_debug_sysctls(sc);
}

/**
 * @enum hmc_error_type
 * @brief enumeration of HMC errors
 *
 * Enumeration defining the possible HMC errors that might occur.
 */
enum hmc_error_type {
	HMC_ERR_PMF_INVALID = 0,
	HMC_ERR_VF_IDX_INVALID = 1,
	HMC_ERR_VF_PARENT_PF_INVALID = 2,
	/* 3 is reserved */
	HMC_ERR_INDEX_TOO_BIG = 4,
	HMC_ERR_ADDRESS_TOO_LARGE = 5,
	HMC_ERR_SEGMENT_DESC_INVALID = 6,
	HMC_ERR_SEGMENT_DESC_TOO_SMALL = 7,
	HMC_ERR_PAGE_DESC_INVALID = 8,
	HMC_ERR_UNSUPPORTED_REQUEST_COMPLETION = 9,
	/* 10 is reserved */
	HMC_ERR_INVALID_OBJECT_TYPE = 11,
	/* 12 is reserved */
};

/**
 * ice_log_hmc_error - Log an HMC error message
 * @hw: device hw structure
 * @dev: the device to pass to device_printf()
 *
 * Log a message when an HMC error interrupt is triggered.
 */
void
ice_log_hmc_error(struct ice_hw *hw, device_t dev)
{
	u32 info, data;
	u8 index, errtype, objtype;
	bool isvf;

	info = rd32(hw, PFHMC_ERRORINFO);
	data = rd32(hw, PFHMC_ERRORDATA);

	index = (u8)(info & PFHMC_ERRORINFO_PMF_INDEX_M);
	errtype = (u8)((info & PFHMC_ERRORINFO_HMC_ERROR_TYPE_M) >>
		       PFHMC_ERRORINFO_HMC_ERROR_TYPE_S);
	objtype = (u8)((info & PFHMC_ERRORINFO_HMC_OBJECT_TYPE_M) >>
		       PFHMC_ERRORINFO_HMC_OBJECT_TYPE_S);

	isvf = info & PFHMC_ERRORINFO_PMF_ISVF_M;

	device_printf(dev, "%s HMC Error detected on PMF index %d:\n",
		      isvf ? "VF" : "PF", index);

	device_printf(dev, "error type %d, object type %d, data 0x%08x\n",
		      errtype, objtype, data);

	switch (errtype) {
	case HMC_ERR_PMF_INVALID:
		device_printf(dev, "Private Memory Function is not valid\n");
		break;
	case HMC_ERR_VF_IDX_INVALID:
		device_printf(dev, "Invalid Private Memory Function index for PE enabled VF\n");
		break;
	case HMC_ERR_VF_PARENT_PF_INVALID:
		device_printf(dev, "Invalid parent PF for PE enabled VF\n");
		break;
	case HMC_ERR_INDEX_TOO_BIG:
		device_printf(dev, "Object index too big\n");
		break;
	case HMC_ERR_ADDRESS_TOO_LARGE:
		device_printf(dev, "Address extends beyond segment descriptor limit\n");
		break;
	case HMC_ERR_SEGMENT_DESC_INVALID:
		device_printf(dev, "Segment descriptor is invalid\n");
		break;
	case HMC_ERR_SEGMENT_DESC_TOO_SMALL:
		device_printf(dev, "Segment descriptor is too small\n");
		break;
	case HMC_ERR_PAGE_DESC_INVALID:
		device_printf(dev, "Page descriptor is invalid\n");
		break;
	case HMC_ERR_UNSUPPORTED_REQUEST_COMPLETION:
		device_printf(dev, "Unsupported Request completion received from PCIe\n");
		break;
	case HMC_ERR_INVALID_OBJECT_TYPE:
		device_printf(dev, "Invalid object type\n");
		break;
	default:
		device_printf(dev, "Unknown HMC error\n");
	}

	/* Clear the error indication */
	wr32(hw, PFHMC_ERRORINFO, 0);
}

/**
 * @struct ice_sysctl_info
 * @brief sysctl information
 *
 * Structure used to simplify the process of defining the many similar
 * statistics sysctls.
 */
struct ice_sysctl_info {
	u64		*stat;
	const char	*name;
	const char	*description;
};

/**
 * ice_add_sysctls_eth_stats - Add sysctls for ethernet statistics
 * @ctx: sysctl ctx to use
 * @parent: the parent node to add sysctls under
 * @stats: the ethernet stats structure to source values from
 *
 * Adds statistics sysctls for the ethernet statistics of the MAC or a VSI.
 * Will add them under the parent node specified.
 *
 * Note that tx_errors is only meaningful for VSIs and not the global MAC/PF
 * statistics, so it is not included here. Similarly, rx_discards has different
 * descriptions for VSIs and MAC/PF stats, so it is also not included here.
 */
void
ice_add_sysctls_eth_stats(struct sysctl_ctx_list *ctx,
			  struct sysctl_oid *parent,
			  struct ice_eth_stats *stats)
{
	const struct ice_sysctl_info ctls[] = {
		/* Rx Stats */
		{ &stats->rx_bytes, "good_octets_rcvd", "Good Octets Received" },
		{ &stats->rx_unicast, "ucast_pkts_rcvd", "Unicast Packets Received" },
		{ &stats->rx_multicast, "mcast_pkts_rcvd", "Multicast Packets Received" },
		{ &stats->rx_broadcast, "bcast_pkts_rcvd", "Broadcast Packets Received" },
		/* Tx Stats */
		{ &stats->tx_bytes, "good_octets_txd", "Good Octets Transmitted" },
		{ &stats->tx_unicast, "ucast_pkts_txd", "Unicast Packets Transmitted" },
		{ &stats->tx_multicast, "mcast_pkts_txd", "Multicast Packets Transmitted" },
		{ &stats->tx_broadcast, "bcast_pkts_txd", "Broadcast Packets Transmitted" },
		/* End */
		{ 0, 0, 0 }
	};

	struct sysctl_oid_list *parent_list = SYSCTL_CHILDREN(parent);

	const struct ice_sysctl_info *entry = ctls;
	while (entry->stat != 0) {
		SYSCTL_ADD_U64(ctx, parent_list, OID_AUTO, entry->name,
			       CTLFLAG_RD | CTLFLAG_STATS, entry->stat, 0,
			       entry->description);
		entry++;
	}
}

/**
 * ice_sysctl_tx_cso_stat - Display Tx checksum offload statistic
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: Tx CSO stat to read
 * @req: sysctl request pointer
 *
 * On read: Sums the per-queue Tx CSO stat and displays it.
 */
static int
ice_sysctl_tx_cso_stat(SYSCTL_HANDLER_ARGS)
{
	struct ice_vsi *vsi = (struct ice_vsi *)arg1;
	enum ice_tx_cso_stat type = (enum ice_tx_cso_stat)arg2;
	u64 stat = 0;
	int i;

	if (ice_driver_is_detaching(vsi->sc))
		return (ESHUTDOWN);

	/* Check that the type is valid */
	if (type >= ICE_CSO_STAT_TX_COUNT)
		return (EDOOFUS);

	/* Sum the stat for each of the Tx queues */
	for (i = 0; i < vsi->num_tx_queues; i++)
		stat += vsi->tx_queues[i].stats.cso[type];

	return sysctl_handle_64(oidp, NULL, stat, req);
}

/**
 * ice_sysctl_rx_cso_stat - Display Rx checksum offload statistic
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: Rx CSO stat to read
 * @req: sysctl request pointer
 *
 * On read: Sums the per-queue Rx CSO stat and displays it.
 */
static int
ice_sysctl_rx_cso_stat(SYSCTL_HANDLER_ARGS)
{
	struct ice_vsi *vsi = (struct ice_vsi *)arg1;
	enum ice_rx_cso_stat type = (enum ice_rx_cso_stat)arg2;
	u64 stat = 0;
	int i;

	if (ice_driver_is_detaching(vsi->sc))
		return (ESHUTDOWN);

	/* Check that the type is valid */
	if (type >= ICE_CSO_STAT_RX_COUNT)
		return (EDOOFUS);

	/* Sum the stat for each of the Rx queues */
	for (i = 0; i < vsi->num_rx_queues; i++)
		stat += vsi->rx_queues[i].stats.cso[type];

	return sysctl_handle_64(oidp, NULL, stat, req);
}

/**
 * ice_sysctl_rx_errors_stat - Display aggregate of Rx errors
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: unused
 * @req: sysctl request pointer
 *
 * On read: Sums current values of Rx error statistics and
 * displays it.
 */
static int
ice_sysctl_rx_errors_stat(SYSCTL_HANDLER_ARGS)
{
	struct ice_vsi *vsi = (struct ice_vsi *)arg1;
	struct ice_hw_port_stats *hs = &vsi->sc->stats.cur;
	u64 stat = 0;
	int i, type;

	UNREFERENCED_PARAMETER(arg2);

	if (ice_driver_is_detaching(vsi->sc))
		return (ESHUTDOWN);

	stat += hs->rx_undersize;
	stat += hs->rx_fragments;
	stat += hs->rx_oversize;
	stat += hs->rx_jabber;
	stat += hs->rx_len_errors;
	stat += hs->crc_errors;
	stat += hs->illegal_bytes;

	/* Checksum error stats */
	for (i = 0; i < vsi->num_rx_queues; i++)
		for (type = ICE_CSO_STAT_RX_IP4_ERR;
		     type < ICE_CSO_STAT_RX_COUNT;
		     type++)
			stat += vsi->rx_queues[i].stats.cso[type];

	return sysctl_handle_64(oidp, NULL, stat, req);
}

/**
 * @struct ice_rx_cso_stat_info
 * @brief sysctl information for an Rx checksum offload statistic
 *
 * Structure used to simplify the process of defining the checksum offload
 * statistics.
 */
struct ice_rx_cso_stat_info {
	enum ice_rx_cso_stat	type;
	const char		*name;
	const char		*description;
};

/**
 * @struct ice_tx_cso_stat_info
 * @brief sysctl information for a Tx checksum offload statistic
 *
 * Structure used to simplify the process of defining the checksum offload
 * statistics.
 */
struct ice_tx_cso_stat_info {
	enum ice_tx_cso_stat	type;
	const char		*name;
	const char		*description;
};

/**
 * ice_add_sysctls_sw_stats - Add sysctls for software statistics
 * @vsi: pointer to the VSI to add sysctls for
 * @ctx: sysctl ctx to use
 * @parent: the parent node to add sysctls under
 *
 * Add statistics sysctls for software tracked statistics of a VSI.
 *
 * Currently this only adds checksum offload statistics, but more counters may
 * be added in the future.
 */
static void
ice_add_sysctls_sw_stats(struct ice_vsi *vsi,
			 struct sysctl_ctx_list *ctx,
			 struct sysctl_oid *parent)
{
	struct sysctl_oid *cso_node;
	struct sysctl_oid_list *cso_list;

	/* Tx CSO Stats */
	const struct ice_tx_cso_stat_info tx_ctls[] = {
		{ ICE_CSO_STAT_TX_TCP, "tx_tcp", "Transmit TCP Packets marked for HW checksum" },
		{ ICE_CSO_STAT_TX_UDP, "tx_udp", "Transmit UDP Packets marked for HW checksum" },
		{ ICE_CSO_STAT_TX_SCTP, "tx_sctp", "Transmit SCTP Packets marked for HW checksum" },
		{ ICE_CSO_STAT_TX_IP4, "tx_ip4", "Transmit IPv4 Packets marked for HW checksum" },
		{ ICE_CSO_STAT_TX_IP6, "tx_ip6", "Transmit IPv6 Packets marked for HW checksum" },
		{ ICE_CSO_STAT_TX_L3_ERR, "tx_l3_err", "Transmit packets that driver failed to set L3 HW CSO bits for" },
		{ ICE_CSO_STAT_TX_L4_ERR, "tx_l4_err", "Transmit packets that driver failed to set L4 HW CSO bits for" },
		/* End */
		{ ICE_CSO_STAT_TX_COUNT, 0, 0 }
	};

	/* Rx CSO Stats */
	const struct ice_rx_cso_stat_info rx_ctls[] = {
		{ ICE_CSO_STAT_RX_IP4_ERR, "rx_ip4_err", "Received packets with invalid IPv4 checksum indicated by HW" },
		{ ICE_CSO_STAT_RX_IP6_ERR, "rx_ip6_err", "Received IPv6 packets with extension headers" },
		{ ICE_CSO_STAT_RX_L3_ERR, "rx_l3_err", "Received packets with an unexpected invalid L3 checksum indicated by HW" },
		{ ICE_CSO_STAT_RX_TCP_ERR, "rx_tcp_err", "Received packets with invalid TCP checksum indicated by HW" },
		{ ICE_CSO_STAT_RX_UDP_ERR, "rx_udp_err", "Received packets with invalid UDP checksum indicated by HW" },
		{ ICE_CSO_STAT_RX_SCTP_ERR, "rx_sctp_err", "Received packets with invalid SCTP checksum indicated by HW" },
		{ ICE_CSO_STAT_RX_L4_ERR, "rx_l4_err", "Received packets with an unexpected invalid L4 checksum indicated by HW" },
		/* End */
		{ ICE_CSO_STAT_RX_COUNT, 0, 0 }
	};

	struct sysctl_oid_list *parent_list = SYSCTL_CHILDREN(parent);

	/* Add a node for statistics tracked by software. */
	cso_node = SYSCTL_ADD_NODE(ctx, parent_list, OID_AUTO, "cso", CTLFLAG_RD,
				  NULL, "Checksum offload Statistics");
	cso_list = SYSCTL_CHILDREN(cso_node);

	const struct ice_tx_cso_stat_info *tx_entry = tx_ctls;
	while (tx_entry->name && tx_entry->description) {
		SYSCTL_ADD_PROC(ctx, cso_list, OID_AUTO, tx_entry->name,
				CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_STATS,
				vsi, tx_entry->type, ice_sysctl_tx_cso_stat, "QU",
				tx_entry->description);
		tx_entry++;
	}

	const struct ice_rx_cso_stat_info *rx_entry = rx_ctls;
	while (rx_entry->name && rx_entry->description) {
		SYSCTL_ADD_PROC(ctx, cso_list, OID_AUTO, rx_entry->name,
				CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_STATS,
				vsi, rx_entry->type, ice_sysctl_rx_cso_stat, "QU",
				rx_entry->description);
		rx_entry++;
	}
}

/**
 * ice_add_vsi_sysctls - Add sysctls for a VSI
 * @vsi: pointer to VSI structure
 *
 * Add various sysctls for a given VSI.
 */
void
ice_add_vsi_sysctls(struct ice_vsi *vsi)
{
	struct sysctl_ctx_list *ctx = &vsi->ctx;
	struct sysctl_oid *hw_node, *sw_node;
	struct sysctl_oid_list *vsi_list, *hw_list;

	vsi_list = SYSCTL_CHILDREN(vsi->vsi_node);

	/* Keep hw stats in their own node. */
	hw_node = SYSCTL_ADD_NODE(ctx, vsi_list, OID_AUTO, "hw", CTLFLAG_RD,
				  NULL, "VSI Hardware Statistics");
	hw_list = SYSCTL_CHILDREN(hw_node);

	/* Add the ethernet statistics for this VSI */
	ice_add_sysctls_eth_stats(ctx, hw_node, &vsi->hw_stats.cur);

	SYSCTL_ADD_U64(ctx, hw_list, OID_AUTO, "rx_discards",
			CTLFLAG_RD | CTLFLAG_STATS, &vsi->hw_stats.cur.rx_discards,
			0, "Discarded Rx Packets (see rx_errors or rx_no_desc)");

	SYSCTL_ADD_PROC(ctx, hw_list, OID_AUTO, "rx_errors",
			CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_STATS,
			vsi, 0, ice_sysctl_rx_errors_stat, "QU",
			"Aggregate of all Rx errors");

	SYSCTL_ADD_U64(ctx, hw_list, OID_AUTO, "rx_no_desc",
		       CTLFLAG_RD | CTLFLAG_STATS, &vsi->hw_stats.cur.rx_no_desc,
		       0, "Rx Packets Discarded Due To Lack Of Descriptors");

	SYSCTL_ADD_U64(ctx, hw_list, OID_AUTO, "tx_errors",
			CTLFLAG_RD | CTLFLAG_STATS, &vsi->hw_stats.cur.tx_errors,
			0, "Tx Packets Discarded Due To Error");

	/* Add a node for statistics tracked by software. */
	sw_node = SYSCTL_ADD_NODE(ctx, vsi_list, OID_AUTO, "sw", CTLFLAG_RD,
				  NULL, "VSI Software Statistics");

	ice_add_sysctls_sw_stats(vsi, ctx, sw_node);
}

/**
 * ice_add_sysctls_mac_pfc_one_stat - Add sysctl node for a PFC statistic
 * @ctx: sysctl ctx to use
 * @parent_list: parent sysctl list to add sysctls under
 * @pfc_stat_location: address of statistic for sysctl to display
 * @node_name: Name for statistic node
 * @descr: Description used for nodes added in this function
 *
 * A helper function for ice_add_sysctls_mac_pfc_stats that adds a node
 * for a stat and leaves for each traffic class for that stat.
 */
static void
ice_add_sysctls_mac_pfc_one_stat(struct sysctl_ctx_list *ctx,
				 struct sysctl_oid_list *parent_list,
				 u64* pfc_stat_location,
				 const char *node_name,
				 const char *descr)
{
	struct sysctl_oid_list *node_list;
	struct sysctl_oid *node;
	struct sbuf *namebuf, *descbuf;

	node = SYSCTL_ADD_NODE(ctx, parent_list, OID_AUTO, node_name, CTLFLAG_RD,
				   NULL, descr);
	node_list = SYSCTL_CHILDREN(node);

	namebuf = sbuf_new_auto();
	descbuf = sbuf_new_auto();
	for (int i = 0; i < ICE_MAX_DCB_TCS; i++) {
		sbuf_clear(namebuf);
		sbuf_clear(descbuf);

		sbuf_printf(namebuf, "%d", i);
		sbuf_printf(descbuf, "%s for TC %d", descr, i);

		sbuf_finish(namebuf);
		sbuf_finish(descbuf);

		SYSCTL_ADD_U64(ctx, node_list, OID_AUTO, sbuf_data(namebuf),
			CTLFLAG_RD | CTLFLAG_STATS, &pfc_stat_location[i], 0,
			sbuf_data(descbuf));
	}

	sbuf_delete(namebuf);
	sbuf_delete(descbuf);
}

/**
 * ice_add_sysctls_mac_pfc_stats - Add sysctls for MAC PFC statistics
 * @ctx: the sysctl ctx to use
 * @parent: parent node to add the sysctls under
 * @stats: the hw ports stat structure to pull values from
 *
 * Add global Priority Flow Control MAC statistics sysctls. These are
 * structured as a node with the PFC statistic, where there are eight
 * nodes for each traffic class.
 */
static void
ice_add_sysctls_mac_pfc_stats(struct sysctl_ctx_list *ctx,
			      struct sysctl_oid *parent,
			      struct ice_hw_port_stats *stats)
{
	struct sysctl_oid_list *parent_list;

	parent_list = SYSCTL_CHILDREN(parent);

	ice_add_sysctls_mac_pfc_one_stat(ctx, parent_list, stats->priority_xon_rx,
	    "p_xon_recvd", "PFC XON received");
	ice_add_sysctls_mac_pfc_one_stat(ctx, parent_list, stats->priority_xoff_rx,
	    "p_xoff_recvd", "PFC XOFF received");
	ice_add_sysctls_mac_pfc_one_stat(ctx, parent_list, stats->priority_xon_tx,
	    "p_xon_txd", "PFC XON transmitted");
	ice_add_sysctls_mac_pfc_one_stat(ctx, parent_list, stats->priority_xoff_tx,
	    "p_xoff_txd", "PFC XOFF transmitted");
	ice_add_sysctls_mac_pfc_one_stat(ctx, parent_list, stats->priority_xon_2_xoff,
	    "p_xon2xoff", "PFC XON to XOFF transitions");
}

/**
 * ice_add_sysctls_mac_stats - Add sysctls for global MAC statistics
 * @ctx: the sysctl ctx to use
 * @parent: parent node to add the sysctls under
 * @stats: the hw ports stat structure to pull values from
 *
 * Add global MAC statistics sysctls.
 */
void
ice_add_sysctls_mac_stats(struct sysctl_ctx_list *ctx,
			  struct sysctl_oid *parent,
			  struct ice_hw_port_stats *stats)
{
	struct sysctl_oid *mac_node;
	struct sysctl_oid_list *parent_list, *mac_list;

	parent_list = SYSCTL_CHILDREN(parent);

	mac_node = SYSCTL_ADD_NODE(ctx, parent_list, OID_AUTO, "mac", CTLFLAG_RD,
				   NULL, "Mac Hardware Statistics");
	mac_list = SYSCTL_CHILDREN(mac_node);

	/* Add the ethernet statistics common to VSI and MAC */
	ice_add_sysctls_eth_stats(ctx, mac_node, &stats->eth);

	/* Add PFC stats that add per-TC counters */
	ice_add_sysctls_mac_pfc_stats(ctx, mac_node, stats);

	const struct ice_sysctl_info ctls[] = {
		/* Packet Reception Stats */
		{&stats->rx_size_64, "rx_frames_64", "64 byte frames received"},
		{&stats->rx_size_127, "rx_frames_65_127", "65-127 byte frames received"},
		{&stats->rx_size_255, "rx_frames_128_255", "128-255 byte frames received"},
		{&stats->rx_size_511, "rx_frames_256_511", "256-511 byte frames received"},
		{&stats->rx_size_1023, "rx_frames_512_1023", "512-1023 byte frames received"},
		{&stats->rx_size_1522, "rx_frames_1024_1522", "1024-1522 byte frames received"},
		{&stats->rx_size_big, "rx_frames_big", "1523-9522 byte frames received"},
		{&stats->rx_undersize, "rx_undersize", "Undersized packets received"},
		{&stats->rx_fragments, "rx_fragmented", "Fragmented packets received"},
		{&stats->rx_oversize, "rx_oversized", "Oversized packets received"},
		{&stats->rx_jabber, "rx_jabber", "Received Jabber"},
		{&stats->rx_len_errors, "rx_length_errors", "Receive Length Errors"},
		{&stats->eth.rx_discards, "rx_discards",
		    "Discarded Rx Packets by Port (shortage of storage space)"},
		/* Packet Transmission Stats */
		{&stats->tx_size_64, "tx_frames_64", "64 byte frames transmitted"},
		{&stats->tx_size_127, "tx_frames_65_127", "65-127 byte frames transmitted"},
		{&stats->tx_size_255, "tx_frames_128_255", "128-255 byte frames transmitted"},
		{&stats->tx_size_511, "tx_frames_256_511", "256-511 byte frames transmitted"},
		{&stats->tx_size_1023, "tx_frames_512_1023", "512-1023 byte frames transmitted"},
		{&stats->tx_size_1522, "tx_frames_1024_1522", "1024-1522 byte frames transmitted"},
		{&stats->tx_size_big, "tx_frames_big", "1523-9522 byte frames transmitted"},
		{&stats->tx_dropped_link_down, "tx_dropped", "Tx Dropped Due To Link Down"},
		/* Flow control */
		{&stats->link_xon_tx, "xon_txd", "Link XON transmitted"},
		{&stats->link_xon_rx, "xon_recvd", "Link XON received"},
		{&stats->link_xoff_tx, "xoff_txd", "Link XOFF transmitted"},
		{&stats->link_xoff_rx, "xoff_recvd", "Link XOFF received"},
		/* Other */
		{&stats->crc_errors, "crc_errors", "CRC Errors"},
		{&stats->illegal_bytes, "illegal_bytes", "Illegal Byte Errors"},
		{&stats->mac_local_faults, "local_faults", "MAC Local Faults"},
		{&stats->mac_remote_faults, "remote_faults", "MAC Remote Faults"},
		/* End */
		{ 0, 0, 0 }
	};

	const struct ice_sysctl_info *entry = ctls;
	while (entry->stat != 0) {
		SYSCTL_ADD_U64(ctx, mac_list, OID_AUTO, entry->name,
			CTLFLAG_RD | CTLFLAG_STATS, entry->stat, 0,
			entry->description);
		entry++;
	}
}

/**
 * ice_configure_misc_interrupts - enable 'other' interrupt causes
 * @sc: pointer to device private softc
 *
 * Enable various "other" interrupt causes, and associate them to interrupt 0,
 * which is our administrative interrupt.
 */
void
ice_configure_misc_interrupts(struct ice_softc *sc)
{
	struct ice_hw *hw = &sc->hw;
	u32 val;

	/* Read the OICR register to clear it */
	rd32(hw, PFINT_OICR);

	/* Enable useful "other" interrupt causes */
	val = (PFINT_OICR_ECC_ERR_M |
	       PFINT_OICR_MAL_DETECT_M |
	       PFINT_OICR_GRST_M |
	       PFINT_OICR_PCI_EXCEPTION_M |
	       PFINT_OICR_VFLR_M |
	       PFINT_OICR_HMC_ERR_M |
	       PFINT_OICR_PE_CRITERR_M);

	wr32(hw, PFINT_OICR_ENA, val);

	/* Note that since we're using MSI-X index 0, and ITR index 0, we do
	 * not explicitly program them when writing to the PFINT_*_CTL
	 * registers. Nevertheless, these writes are associating the
	 * interrupts with the ITR 0 vector
	 */

	/* Associate the OICR interrupt with ITR 0, and enable it */
	wr32(hw, PFINT_OICR_CTL, PFINT_OICR_CTL_CAUSE_ENA_M);

	/* Associate the Mailbox interrupt with ITR 0, and enable it */
	wr32(hw, PFINT_MBX_CTL, PFINT_MBX_CTL_CAUSE_ENA_M);

	/* Associate the AdminQ interrupt with ITR 0, and enable it */
	wr32(hw, PFINT_FW_CTL, PFINT_FW_CTL_CAUSE_ENA_M);
}

/**
 * ice_filter_is_mcast - Check if info is a multicast filter
 * @vsi: vsi structure addresses are targeted towards
 * @info: filter info
 *
 * @returns true if the provided info is a multicast filter, and false
 * otherwise.
 */
static bool
ice_filter_is_mcast(struct ice_vsi *vsi, struct ice_fltr_info *info)
{
	const u8 *addr = info->l_data.mac.mac_addr;

	/*
	 * Check if this info matches a multicast filter added by
	 * ice_add_mac_to_list
	 */
	if ((info->flag == ICE_FLTR_TX) &&
	    (info->src_id == ICE_SRC_ID_VSI) &&
	    (info->lkup_type == ICE_SW_LKUP_MAC) &&
	    (info->vsi_handle == vsi->idx) &&
	    ETHER_IS_MULTICAST(addr) && !ETHER_IS_BROADCAST(addr))
		return true;

	return false;
}

/**
 * @struct ice_mcast_sync_data
 * @brief data used by ice_sync_one_mcast_filter function
 *
 * Structure used to store data needed for processing by the
 * ice_sync_one_mcast_filter. This structure contains a linked list of filters
 * to be added, an error indication, and a pointer to the device softc.
 */
struct ice_mcast_sync_data {
	struct ice_list_head add_list;
	struct ice_softc *sc;
	int err;
};

/**
 * ice_sync_one_mcast_filter - Check if we need to program the filter
 * @p: void pointer to algorithm data
 * @sdl: link level socket address
 * @count: unused count value
 *
 * Called by if_foreach_llmaddr to operate on each filter in the ifp filter
 * list. For the given address, search our internal list to see if we have
 * found the filter. If not, add it to our list of filters that need to be
 * programmed.
 *
 * @returns (1) if we've actually setup the filter to be added
 */
static u_int
ice_sync_one_mcast_filter(void *p, struct sockaddr_dl *sdl,
			  u_int __unused count)
{
	struct ice_mcast_sync_data *data = (struct ice_mcast_sync_data *)p;
	struct ice_softc *sc = data->sc;
	struct ice_hw *hw = &sc->hw;
	struct ice_switch_info *sw = hw->switch_info;
	const u8 *sdl_addr = (const u8 *)LLADDR(sdl);
	struct ice_fltr_mgmt_list_entry *itr;
	struct ice_list_head *rules;
	int err;

	rules = &sw->recp_list[ICE_SW_LKUP_MAC].filt_rules;

	/*
	 * If a previous filter already indicated an error, there is no need
	 * for us to finish processing the rest of the filters.
	 */
	if (data->err)
		return (0);

	/* See if this filter has already been programmed */
	LIST_FOR_EACH_ENTRY(itr, rules, ice_fltr_mgmt_list_entry, list_entry) {
		struct ice_fltr_info *info = &itr->fltr_info;
		const u8 *addr = info->l_data.mac.mac_addr;

		/* Only check multicast filters */
		if (!ice_filter_is_mcast(&sc->pf_vsi, info))
			continue;

		/*
		 * If this filter matches, mark the internal filter as
		 * "found", and exit.
		 */
		if (bcmp(addr, sdl_addr, ETHER_ADDR_LEN) == 0) {
			itr->marker = ICE_FLTR_FOUND;
			return (1);
		}
	}

	/*
	 * If we failed to locate the filter in our internal list, we need to
	 * place it into our add list.
	 */
	err = ice_add_mac_to_list(&sc->pf_vsi, &data->add_list, sdl_addr,
				  ICE_FWD_TO_VSI);
	if (err) {
		device_printf(sc->dev,
			      "Failed to place MAC %6D onto add list, err %s\n",
			      sdl_addr, ":", ice_err_str(err));
		data->err = err;

		return (0);
	}

	return (1);
}

/**
 * ice_sync_multicast_filters - Synchronize OS and internal filter list
 * @sc: device private structure
 *
 * Called in response to SIOCDELMULTI to synchronize the operating system
 * multicast address list with the internal list of filters programmed to
 * firmware.
 *
 * Works in one phase to find added and deleted filters using a marker bit on
 * the internal list.
 *
 * First, a loop over the internal list clears the marker bit. Second, for
 * each filter in the ifp list is checked. If we find it in the internal list,
 * the marker bit is set. Otherwise, the filter is added to the add list.
 * Third, a loop over the internal list determines if any filters have not
 * been found. Each of these is added to the delete list. Finally, the add and
 * delete lists are programmed to firmware to update the filters.
 *
 * @returns zero on success or an integer error code on failure.
 */
int
ice_sync_multicast_filters(struct ice_softc *sc)
{
	struct ice_hw *hw = &sc->hw;
	struct ice_switch_info *sw = hw->switch_info;
	struct ice_fltr_mgmt_list_entry *itr;
	struct ice_mcast_sync_data data = {};
	struct ice_list_head *rules, remove_list;
	enum ice_status status;
	int err = 0;

	INIT_LIST_HEAD(&data.add_list);
	INIT_LIST_HEAD(&remove_list);
	data.sc = sc;
	data.err = 0;

	rules = &sw->recp_list[ICE_SW_LKUP_MAC].filt_rules;

	/* Acquire the lock for the entire duration */
	ice_acquire_lock(&sw->recp_list[ICE_SW_LKUP_MAC].filt_rule_lock);

	/* (1) Reset the marker state for all filters */
	LIST_FOR_EACH_ENTRY(itr, rules, ice_fltr_mgmt_list_entry, list_entry)
		itr->marker = ICE_FLTR_NOT_FOUND;

	/* (2) determine which filters need to be added and removed */
	if_foreach_llmaddr(sc->ifp, ice_sync_one_mcast_filter, (void *)&data);
	if (data.err) {
		/* ice_sync_one_mcast_filter already prints an error */
		err = data.err;
		ice_release_lock(&sw->recp_list[ICE_SW_LKUP_MAC].filt_rule_lock);
		goto free_filter_lists;
	}

	LIST_FOR_EACH_ENTRY(itr, rules, ice_fltr_mgmt_list_entry, list_entry) {
		struct ice_fltr_info *info = &itr->fltr_info;
		const u8 *addr = info->l_data.mac.mac_addr;

		/* Only check multicast filters */
		if (!ice_filter_is_mcast(&sc->pf_vsi, info))
			continue;

		/*
		 * If the filter is not marked as found, then it must no
		 * longer be in the ifp address list, so we need to remove it.
		 */
		if (itr->marker == ICE_FLTR_NOT_FOUND) {
			err = ice_add_mac_to_list(&sc->pf_vsi, &remove_list,
						  addr, ICE_FWD_TO_VSI);
			if (err) {
				device_printf(sc->dev,
					      "Failed to place MAC %6D onto remove list, err %s\n",
					      addr, ":", ice_err_str(err));
				ice_release_lock(&sw->recp_list[ICE_SW_LKUP_MAC].filt_rule_lock);
				goto free_filter_lists;
			}
		}
	}

	ice_release_lock(&sw->recp_list[ICE_SW_LKUP_MAC].filt_rule_lock);

	status = ice_add_mac(hw, &data.add_list);
	if (status) {
		device_printf(sc->dev,
			      "Could not add new MAC filters, err %s aq_err %s\n",
			      ice_status_str(status), ice_aq_str(hw->adminq.sq_last_status));
		err = (EIO);
		goto free_filter_lists;
	}

	status = ice_remove_mac(hw, &remove_list);
	if (status) {
		device_printf(sc->dev,
			      "Could not remove old MAC filters, err %s aq_err %s\n",
			      ice_status_str(status), ice_aq_str(hw->adminq.sq_last_status));
		err = (EIO);
		goto free_filter_lists;
	}

free_filter_lists:
	ice_free_fltr_list(&data.add_list);
	ice_free_fltr_list(&remove_list);

	return (err);
}

/**
 * ice_add_vlan_hw_filter - Add a VLAN filter for a given VSI
 * @vsi: The VSI to add the filter for
 * @vid: VLAN to add
 *
 * Programs a HW filter so that the given VSI will receive the specified VLAN.
 */
enum ice_status
ice_add_vlan_hw_filter(struct ice_vsi *vsi, u16 vid)
{
	struct ice_hw *hw = &vsi->sc->hw;
	struct ice_list_head vlan_list;
	struct ice_fltr_list_entry vlan_entry;

	INIT_LIST_HEAD(&vlan_list);
	memset(&vlan_entry, 0, sizeof(vlan_entry));

	vlan_entry.fltr_info.lkup_type = ICE_SW_LKUP_VLAN;
	vlan_entry.fltr_info.fltr_act = ICE_FWD_TO_VSI;
	vlan_entry.fltr_info.flag = ICE_FLTR_TX;
	vlan_entry.fltr_info.src_id = ICE_SRC_ID_VSI;
	vlan_entry.fltr_info.vsi_handle = vsi->idx;
	vlan_entry.fltr_info.l_data.vlan.vlan_id = vid;

	LIST_ADD(&vlan_entry.list_entry, &vlan_list);

	return ice_add_vlan(hw, &vlan_list);
}

/**
 * ice_remove_vlan_hw_filter - Remove a VLAN filter for a given VSI
 * @vsi: The VSI to add the filter for
 * @vid: VLAN to remove
 *
 * Removes a previously programmed HW filter for the specified VSI.
 */
enum ice_status
ice_remove_vlan_hw_filter(struct ice_vsi *vsi, u16 vid)
{
	struct ice_hw *hw = &vsi->sc->hw;
	struct ice_list_head vlan_list;
	struct ice_fltr_list_entry vlan_entry;

	INIT_LIST_HEAD(&vlan_list);
	memset(&vlan_entry, 0, sizeof(vlan_entry));

	vlan_entry.fltr_info.lkup_type = ICE_SW_LKUP_VLAN;
	vlan_entry.fltr_info.fltr_act = ICE_FWD_TO_VSI;
	vlan_entry.fltr_info.flag = ICE_FLTR_TX;
	vlan_entry.fltr_info.src_id = ICE_SRC_ID_VSI;
	vlan_entry.fltr_info.vsi_handle = vsi->idx;
	vlan_entry.fltr_info.l_data.vlan.vlan_id = vid;

	LIST_ADD(&vlan_entry.list_entry, &vlan_list);

	return ice_remove_vlan(hw, &vlan_list);
}

#define ICE_SYSCTL_HELP_RX_ITR			\
"\nControl Rx interrupt throttle rate."		\
"\n\t0-8160 - sets interrupt rate in usecs"	\
"\n\t    -1 - reset the Rx itr to default"

/**
 * ice_sysctl_rx_itr - Display or change the Rx ITR for a VSI
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: unused
 * @req: sysctl request pointer
 *
 * On read: Displays the current Rx ITR value
 * on write: Sets the Rx ITR value, reconfiguring device if it is up
 */
static int
ice_sysctl_rx_itr(SYSCTL_HANDLER_ARGS)
{
	struct ice_vsi *vsi = (struct ice_vsi *)arg1;
	struct ice_softc *sc = vsi->sc;
	int increment, ret;

	UNREFERENCED_PARAMETER(arg2);

	if (ice_driver_is_detaching(sc))
		return (ESHUTDOWN);

	ret = sysctl_handle_16(oidp, &vsi->rx_itr, 0, req);
	if ((ret) || (req->newptr == NULL))
		return (ret);

	if (vsi->rx_itr < 0)
		vsi->rx_itr = ICE_DFLT_RX_ITR;
	if (vsi->rx_itr > ICE_ITR_MAX)
		vsi->rx_itr = ICE_ITR_MAX;

	/* Assume 2usec increment if it hasn't been loaded yet */
	increment = sc->hw.itr_gran ? : 2;

	/* We need to round the value to the hardware's ITR granularity */
	vsi->rx_itr = (vsi->rx_itr / increment ) * increment;

	/* If the driver has finished initializing, then we need to reprogram
	 * the ITR registers now. Otherwise, they will be programmed during
	 * driver initialization.
	 */
	if (ice_test_state(&sc->state, ICE_STATE_DRIVER_INITIALIZED))
		ice_configure_rx_itr(vsi);

	return (0);
}

#define ICE_SYSCTL_HELP_TX_ITR			\
"\nControl Tx interrupt throttle rate."		\
"\n\t0-8160 - sets interrupt rate in usecs"	\
"\n\t    -1 - reset the Tx itr to default"

/**
 * ice_sysctl_tx_itr - Display or change the Tx ITR for a VSI
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: unused
 * @req: sysctl request pointer
 *
 * On read: Displays the current Tx ITR value
 * on write: Sets the Tx ITR value, reconfiguring device if it is up
 */
static int
ice_sysctl_tx_itr(SYSCTL_HANDLER_ARGS)
{
	struct ice_vsi *vsi = (struct ice_vsi *)arg1;
	struct ice_softc *sc = vsi->sc;
	int increment, ret;

	UNREFERENCED_PARAMETER(arg2);

	if (ice_driver_is_detaching(sc))
		return (ESHUTDOWN);

	ret = sysctl_handle_16(oidp, &vsi->tx_itr, 0, req);
	if ((ret) || (req->newptr == NULL))
		return (ret);

	/* Allow configuring a negative value to reset to the default */
	if (vsi->tx_itr < 0)
		vsi->tx_itr = ICE_DFLT_TX_ITR;
	if (vsi->tx_itr > ICE_ITR_MAX)
		vsi->tx_itr = ICE_ITR_MAX;

	/* Assume 2usec increment if it hasn't been loaded yet */
	increment = sc->hw.itr_gran ? : 2;

	/* We need to round the value to the hardware's ITR granularity */
	vsi->tx_itr = (vsi->tx_itr / increment ) * increment;

	/* If the driver has finished initializing, then we need to reprogram
	 * the ITR registers now. Otherwise, they will be programmed during
	 * driver initialization.
	 */
	if (ice_test_state(&sc->state, ICE_STATE_DRIVER_INITIALIZED))
		ice_configure_tx_itr(vsi);

	return (0);
}

/**
 * ice_add_vsi_tunables - Add tunables and nodes for a VSI
 * @vsi: pointer to VSI structure
 * @parent: parent node to add the tunables under
 *
 * Create a sysctl context for the VSI, so that sysctls for the VSI can be
 * dynamically removed upon VSI removal.
 *
 * Add various tunables and set up the basic node structure for the VSI. Must
 * be called *prior* to ice_add_vsi_sysctls. It should be called as soon as
 * possible after the VSI memory is initialized.
 *
 * VSI specific sysctls with CTLFLAG_TUN should be initialized here so that
 * their values can be read from loader.conf prior to their first use in the
 * driver.
 */
void
ice_add_vsi_tunables(struct ice_vsi *vsi, struct sysctl_oid *parent)
{
	struct sysctl_oid_list *vsi_list;
	char vsi_name[32], vsi_desc[32];

	struct sysctl_oid_list *parent_list = SYSCTL_CHILDREN(parent);

	/* Initialize the sysctl context for this VSI */
	sysctl_ctx_init(&vsi->ctx);

	/* Add a node to collect this VSI's statistics together */
	snprintf(vsi_name, sizeof(vsi_name), "%u", vsi->idx);
	snprintf(vsi_desc, sizeof(vsi_desc), "VSI %u", vsi->idx);
	vsi->vsi_node = SYSCTL_ADD_NODE(&vsi->ctx, parent_list, OID_AUTO, vsi_name,
					CTLFLAG_RD, NULL, vsi_desc);
	vsi_list = SYSCTL_CHILDREN(vsi->vsi_node);

	vsi->rx_itr = ICE_DFLT_TX_ITR;
	SYSCTL_ADD_PROC(&vsi->ctx, vsi_list, OID_AUTO, "rx_itr",
			CTLTYPE_S16 | CTLFLAG_RWTUN,
			vsi, 0, ice_sysctl_rx_itr, "S",
			ICE_SYSCTL_HELP_RX_ITR);

	vsi->tx_itr = ICE_DFLT_TX_ITR;
	SYSCTL_ADD_PROC(&vsi->ctx, vsi_list, OID_AUTO, "tx_itr",
			CTLTYPE_S16 | CTLFLAG_RWTUN,
			vsi, 0, ice_sysctl_tx_itr, "S",
			ICE_SYSCTL_HELP_TX_ITR);
}

/**
 * ice_del_vsi_sysctl_ctx - Delete the sysctl context(s) of a VSI
 * @vsi: the VSI to remove contexts for
 *
 * Free the context for the VSI sysctls. This includes the main context, as
 * well as the per-queue sysctls.
 */
void
ice_del_vsi_sysctl_ctx(struct ice_vsi *vsi)
{
	device_t dev = vsi->sc->dev;
	int err;

	if (vsi->vsi_node) {
		err = sysctl_ctx_free(&vsi->ctx);
		if (err)
			device_printf(dev, "failed to free VSI %d sysctl context, err %s\n",
				      vsi->idx, ice_err_str(err));
		vsi->vsi_node = NULL;
	}
}

/**
 * ice_add_device_tunables - Add early tunable sysctls and sysctl nodes
 * @sc: device private structure
 *
 * Add per-device dynamic tunable sysctls, and setup the general sysctl trees
 * for re-use by ice_add_device_sysctls.
 *
 * In order for the sysctl fields to be initialized before use, this function
 * should be called as early as possible during attach activities.
 *
 * Any non-global sysctl marked as CTLFLAG_TUN should likely be initialized
 * here in this function, rather than later in ice_add_device_sysctls.
 *
 * To make things easier, this function is also expected to setup the various
 * sysctl nodes in addition to tunables so that other sysctls which can't be
 * initialized early can hook into the same nodes.
 */
void
ice_add_device_tunables(struct ice_softc *sc)
{
	device_t dev = sc->dev;

	struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(dev);
	struct sysctl_oid_list *ctx_list =
		SYSCTL_CHILDREN(device_get_sysctl_tree(dev));

	sc->enable_health_events = ice_enable_health_events;

	SYSCTL_ADD_BOOL(ctx, ctx_list, OID_AUTO, "enable_health_events",
			CTLFLAG_RDTUN, &sc->enable_health_events, 0,
			"Enable FW health event reporting for this PF");

	/* Add a node to track VSI sysctls. Keep track of the node in the
	 * softc so that we can hook other sysctls into it later. This
	 * includes both the VSI statistics, as well as potentially dynamic
	 * VSIs in the future.
	 */

	sc->vsi_sysctls = SYSCTL_ADD_NODE(ctx, ctx_list, OID_AUTO, "vsi",
					  CTLFLAG_RD, NULL, "VSI Configuration and Statistics");

	/* Add debug tunables */
	ice_add_debug_tunables(sc);
}

/**
 * ice_sysctl_dump_mac_filters - Dump a list of all HW MAC Filters
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: unused
 * @req: sysctl request pointer
 *
 * Callback for "mac_filters" sysctl to dump the programmed MAC filters.
 */
static int
ice_sysctl_dump_mac_filters(SYSCTL_HANDLER_ARGS)
{
	struct ice_softc *sc = (struct ice_softc *)arg1;
	struct ice_hw *hw = &sc->hw;
	struct ice_switch_info *sw = hw->switch_info;
	struct ice_fltr_mgmt_list_entry *fm_entry;
	struct ice_list_head *rule_head;
	struct ice_lock *rule_lock;
	struct ice_fltr_info *fi;
	struct sbuf *sbuf;
	int ret;

	UNREFERENCED_PARAMETER(oidp);
	UNREFERENCED_PARAMETER(arg2);

	if (ice_driver_is_detaching(sc))
		return (ESHUTDOWN);

	/* Wire the old buffer so we can take a non-sleepable lock */
	ret = sysctl_wire_old_buffer(req, 0);
	if (ret)
		return (ret);

	sbuf = sbuf_new_for_sysctl(NULL, NULL, 128, req);

	rule_lock = &sw->recp_list[ICE_SW_LKUP_MAC].filt_rule_lock;
	rule_head = &sw->recp_list[ICE_SW_LKUP_MAC].filt_rules;

	sbuf_printf(sbuf, "MAC Filter List");

	ice_acquire_lock(rule_lock);

	LIST_FOR_EACH_ENTRY(fm_entry, rule_head, ice_fltr_mgmt_list_entry, list_entry) {
		fi = &fm_entry->fltr_info;

		sbuf_printf(sbuf,
			    "\nmac = %6D, vsi_handle = %3d, fw_act_flag = %5s, lb_en = %1d, lan_en = %1d, fltr_act = %15s, fltr_rule_id = %d",
			    fi->l_data.mac.mac_addr, ":", fi->vsi_handle,
			    ice_fltr_flag_str(fi->flag), fi->lb_en, fi->lan_en,
			    ice_fwd_act_str(fi->fltr_act), fi->fltr_rule_id);

		/* if we have a vsi_list_info, print some information about that */
		if (fm_entry->vsi_list_info) {
			sbuf_printf(sbuf,
				    ", vsi_count = %3d, vsi_list_id = %3d, ref_cnt = %3d",
				    fm_entry->vsi_count,
				    fm_entry->vsi_list_info->vsi_list_id,
				    fm_entry->vsi_list_info->ref_cnt);
		}
	}

	ice_release_lock(rule_lock);

	sbuf_finish(sbuf);
	sbuf_delete(sbuf);

	return (0);
}

/**
 * ice_sysctl_dump_vlan_filters - Dump a list of all HW VLAN Filters
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: unused
 * @req: sysctl request pointer
 *
 * Callback for "vlan_filters" sysctl to dump the programmed VLAN filters.
 */
static int
ice_sysctl_dump_vlan_filters(SYSCTL_HANDLER_ARGS)
{
	struct ice_softc *sc = (struct ice_softc *)arg1;
	struct ice_hw *hw = &sc->hw;
	struct ice_switch_info *sw = hw->switch_info;
	struct ice_fltr_mgmt_list_entry *fm_entry;
	struct ice_list_head *rule_head;
	struct ice_lock *rule_lock;
	struct ice_fltr_info *fi;
	struct sbuf *sbuf;
	int ret;

	UNREFERENCED_PARAMETER(oidp);
	UNREFERENCED_PARAMETER(arg2);

	if (ice_driver_is_detaching(sc))
		return (ESHUTDOWN);

	/* Wire the old buffer so we can take a non-sleepable lock */
	ret = sysctl_wire_old_buffer(req, 0);
	if (ret)
		return (ret);

	sbuf = sbuf_new_for_sysctl(NULL, NULL, 128, req);

	rule_lock = &sw->recp_list[ICE_SW_LKUP_VLAN].filt_rule_lock;
	rule_head = &sw->recp_list[ICE_SW_LKUP_VLAN].filt_rules;

	sbuf_printf(sbuf, "VLAN Filter List");

	ice_acquire_lock(rule_lock);

	LIST_FOR_EACH_ENTRY(fm_entry, rule_head, ice_fltr_mgmt_list_entry, list_entry) {
		fi = &fm_entry->fltr_info;

		sbuf_printf(sbuf,
			    "\nvlan_id = %4d, vsi_handle = %3d, fw_act_flag = %5s, lb_en = %1d, lan_en = %1d, fltr_act = %15s, fltr_rule_id = %4d",
			    fi->l_data.vlan.vlan_id, fi->vsi_handle,
			    ice_fltr_flag_str(fi->flag), fi->lb_en, fi->lan_en,
			    ice_fwd_act_str(fi->fltr_act), fi->fltr_rule_id);

		/* if we have a vsi_list_info, print some information about that */
		if (fm_entry->vsi_list_info) {
			sbuf_printf(sbuf,
				    ", vsi_count = %3d, vsi_list_id = %3d, ref_cnt = %3d",
				    fm_entry->vsi_count,
				    fm_entry->vsi_list_info->vsi_list_id,
				    fm_entry->vsi_list_info->ref_cnt);
		}
	}

	ice_release_lock(rule_lock);

	sbuf_finish(sbuf);
	sbuf_delete(sbuf);

	return (0);
}

/**
 * ice_sysctl_dump_ethertype_filters - Dump a list of all HW Ethertype filters
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: unused
 * @req: sysctl request pointer
 *
 * Callback for "ethertype_filters" sysctl to dump the programmed Ethertype
 * filters.
 */
static int
ice_sysctl_dump_ethertype_filters(SYSCTL_HANDLER_ARGS)
{
	struct ice_softc *sc = (struct ice_softc *)arg1;
	struct ice_hw *hw = &sc->hw;
	struct ice_switch_info *sw = hw->switch_info;
	struct ice_fltr_mgmt_list_entry *fm_entry;
	struct ice_list_head *rule_head;
	struct ice_lock *rule_lock;
	struct ice_fltr_info *fi;
	struct sbuf *sbuf;
	int ret;

	UNREFERENCED_PARAMETER(oidp);
	UNREFERENCED_PARAMETER(arg2);

	if (ice_driver_is_detaching(sc))
		return (ESHUTDOWN);

	/* Wire the old buffer so we can take a non-sleepable lock */
	ret = sysctl_wire_old_buffer(req, 0);
	if (ret)
		return (ret);

	sbuf = sbuf_new_for_sysctl(NULL, NULL, 128, req);

	rule_lock = &sw->recp_list[ICE_SW_LKUP_ETHERTYPE].filt_rule_lock;
	rule_head = &sw->recp_list[ICE_SW_LKUP_ETHERTYPE].filt_rules;

	sbuf_printf(sbuf, "Ethertype Filter List");

	ice_acquire_lock(rule_lock);

	LIST_FOR_EACH_ENTRY(fm_entry, rule_head, ice_fltr_mgmt_list_entry, list_entry) {
		fi = &fm_entry->fltr_info;

		sbuf_printf(sbuf,
			    "\nethertype = 0x%04x, vsi_handle = %3d, fw_act_flag = %5s, lb_en = %1d, lan_en = %1d, fltr_act = %15s, fltr_rule_id = %4d",
			fi->l_data.ethertype_mac.ethertype,
			fi->vsi_handle, ice_fltr_flag_str(fi->flag),
			fi->lb_en, fi->lan_en, ice_fwd_act_str(fi->fltr_act),
			fi->fltr_rule_id);

		/* if we have a vsi_list_info, print some information about that */
		if (fm_entry->vsi_list_info) {
			sbuf_printf(sbuf,
				    ", vsi_count = %3d, vsi_list_id = %3d, ref_cnt = %3d",
				    fm_entry->vsi_count,
				    fm_entry->vsi_list_info->vsi_list_id,
				    fm_entry->vsi_list_info->ref_cnt);
		}
	}

	ice_release_lock(rule_lock);

	sbuf_finish(sbuf);
	sbuf_delete(sbuf);

	return (0);
}

/**
 * ice_sysctl_dump_ethertype_mac_filters - Dump a list of all HW Ethertype/MAC filters
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: unused
 * @req: sysctl request pointer
 *
 * Callback for "ethertype_mac_filters" sysctl to dump the programmed
 * Ethertype/MAC filters.
 */
static int
ice_sysctl_dump_ethertype_mac_filters(SYSCTL_HANDLER_ARGS)
{
	struct ice_softc *sc = (struct ice_softc *)arg1;
	struct ice_hw *hw = &sc->hw;
	struct ice_switch_info *sw = hw->switch_info;
	struct ice_fltr_mgmt_list_entry *fm_entry;
	struct ice_list_head *rule_head;
	struct ice_lock *rule_lock;
	struct ice_fltr_info *fi;
	struct sbuf *sbuf;
	int ret;

	UNREFERENCED_PARAMETER(oidp);
	UNREFERENCED_PARAMETER(arg2);

	if (ice_driver_is_detaching(sc))
		return (ESHUTDOWN);

	/* Wire the old buffer so we can take a non-sleepable lock */
	ret = sysctl_wire_old_buffer(req, 0);
	if (ret)
		return (ret);

	sbuf = sbuf_new_for_sysctl(NULL, NULL, 128, req);

	rule_lock = &sw->recp_list[ICE_SW_LKUP_ETHERTYPE_MAC].filt_rule_lock;
	rule_head = &sw->recp_list[ICE_SW_LKUP_ETHERTYPE_MAC].filt_rules;

	sbuf_printf(sbuf, "Ethertype/MAC Filter List");

	ice_acquire_lock(rule_lock);

	LIST_FOR_EACH_ENTRY(fm_entry, rule_head, ice_fltr_mgmt_list_entry, list_entry) {
		fi = &fm_entry->fltr_info;

		sbuf_printf(sbuf,
			    "\nethertype = 0x%04x, mac = %6D, vsi_handle = %3d, fw_act_flag = %5s, lb_en = %1d, lan_en = %1d, fltr_act = %15s, fltr_rule_id = %4d",
			    fi->l_data.ethertype_mac.ethertype,
			    fi->l_data.ethertype_mac.mac_addr, ":",
			    fi->vsi_handle, ice_fltr_flag_str(fi->flag),
			    fi->lb_en, fi->lan_en, ice_fwd_act_str(fi->fltr_act),
			    fi->fltr_rule_id);

		/* if we have a vsi_list_info, print some information about that */
		if (fm_entry->vsi_list_info) {
			sbuf_printf(sbuf,
				    ", vsi_count = %3d, vsi_list_id = %3d, ref_cnt = %3d",
				    fm_entry->vsi_count,
				    fm_entry->vsi_list_info->vsi_list_id,
				    fm_entry->vsi_list_info->ref_cnt);
		}
	}

	ice_release_lock(rule_lock);

	sbuf_finish(sbuf);
	sbuf_delete(sbuf);

	return (0);
}

/**
 * ice_sysctl_dump_state_flags - Dump device driver state flags
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: unused
 * @req: sysctl request pointer
 *
 * Callback for "state" sysctl to display currently set driver state flags.
 */
static int
ice_sysctl_dump_state_flags(SYSCTL_HANDLER_ARGS)
{
	struct ice_softc *sc = (struct ice_softc *)arg1;
	struct sbuf *sbuf;
	u32 copied_state;
	unsigned int i;
	bool at_least_one = false;

	UNREFERENCED_PARAMETER(oidp);
	UNREFERENCED_PARAMETER(arg2);

	if (ice_driver_is_detaching(sc))
		return (ESHUTDOWN);

	/* Make a copy of the state to ensure we display coherent values */
	copied_state = atomic_load_acq_32(&sc->state);

	sbuf = sbuf_new_for_sysctl(NULL, NULL, 128, req);

	/* Add the string for each set state to the sbuf */
	for (i = 0; i < 32; i++) {
		if (copied_state & BIT(i)) {
			const char *str = ice_state_to_str((enum ice_state)i);

			at_least_one = true;

			if (str)
				sbuf_printf(sbuf, "\n%s", str);
			else
				sbuf_printf(sbuf, "\nBIT(%u)", i);
		}
	}

	if (!at_least_one)
		sbuf_printf(sbuf, "Nothing set");

	sbuf_finish(sbuf);
	sbuf_delete(sbuf);

	return (0);
}

/**
 * ice_add_debug_tunables - Add tunables helpful for debugging the device driver
 * @sc: device private structure
 *
 * Add sysctl tunable values related to debugging the device driver. For now,
 * this means a tunable to set the debug mask early during driver load.
 *
 * The debug node will be marked CTLFLAG_SKIP unless INVARIANTS is defined, so
 * that in normal kernel builds, these will all be hidden, but on a debug
 * kernel they will be more easily visible.
 */
static void
ice_add_debug_tunables(struct ice_softc *sc)
{
	struct sysctl_oid_list *debug_list;
	device_t dev = sc->dev;

	struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(dev);
	struct sysctl_oid_list *ctx_list =
	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev));

	sc->debug_sysctls = SYSCTL_ADD_NODE(ctx, ctx_list, OID_AUTO, "debug",
					    ICE_CTLFLAG_DEBUG | CTLFLAG_RD,
					    NULL, "Debug Sysctls");
	debug_list = SYSCTL_CHILDREN(sc->debug_sysctls);

	SYSCTL_ADD_U64(ctx, debug_list, OID_AUTO, "debug_mask",
		       ICE_CTLFLAG_DEBUG | CTLFLAG_RW | CTLFLAG_TUN,
		       &sc->hw.debug_mask, 0,
		       "Debug message enable/disable mask");

	/* Load the default value from the global sysctl first */
	sc->enable_tx_fc_filter = ice_enable_tx_fc_filter;

	SYSCTL_ADD_BOOL(ctx, debug_list, OID_AUTO, "enable_tx_fc_filter",
			ICE_CTLFLAG_DEBUG | CTLFLAG_RDTUN,
			&sc->enable_tx_fc_filter, 0,
			"Drop Ethertype 0x8808 control frames originating from software on this PF");

	/* Load the default value from the global sysctl first */
	sc->enable_tx_lldp_filter = ice_enable_tx_lldp_filter;

	SYSCTL_ADD_BOOL(ctx, debug_list, OID_AUTO, "enable_tx_lldp_filter",
			ICE_CTLFLAG_DEBUG | CTLFLAG_RDTUN,
			&sc->enable_tx_lldp_filter, 0,
			"Drop Ethertype 0x88cc LLDP frames originating from software on this PF");

	ice_add_fw_logging_tunables(sc, sc->debug_sysctls);
}

#define ICE_SYSCTL_HELP_REQUEST_RESET		\
"\nRequest the driver to initiate a reset."	\
"\n\tpfr - Initiate a PF reset"			\
"\n\tcorer - Initiate a CORE reset"		\
"\n\tglobr - Initiate a GLOBAL reset"

/**
 * @var rl_sysctl_ticks
 * @brief timestamp for latest reset request sysctl call
 *
 * Helps rate-limit the call to the sysctl which resets the device
 */
int rl_sysctl_ticks = 0;

/**
 * ice_sysctl_request_reset - Request that the driver initiate a reset
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: unused
 * @req: sysctl request pointer
 *
 * Callback for "request_reset" sysctl to request that the driver initiate
 * a reset. Expects to be passed one of the following strings
 *
 * "pfr" - Initiate a PF reset
 * "corer" - Initiate a CORE reset
 * "globr" - Initiate a Global reset
 */
static int
ice_sysctl_request_reset(SYSCTL_HANDLER_ARGS)
{
	struct ice_softc *sc = (struct ice_softc *)arg1;
	struct ice_hw *hw = &sc->hw;
	enum ice_status status;
	enum ice_reset_req reset_type = ICE_RESET_INVAL;
	const char *reset_message;
	int ret;

	/* Buffer to store the requested reset string. Must contain enough
	 * space to store the largest expected reset string, which currently
	 * means 6 bytes of space.
	 */
	char reset[6] = "";

	UNREFERENCED_PARAMETER(arg2);

	ret = priv_check(curthread, PRIV_DRIVER);
	if (ret)
		return (ret);

	if (ice_driver_is_detaching(sc))
		return (ESHUTDOWN);

	/* Read in the requested reset type. */
	ret = sysctl_handle_string(oidp, reset, sizeof(reset), req);
	if ((ret) || (req->newptr == NULL))
		return (ret);

	if (strcmp(reset, "pfr") == 0) {
		reset_message = "Requesting a PF reset";
		reset_type = ICE_RESET_PFR;
	} else if (strcmp(reset, "corer") == 0) {
		reset_message = "Initiating a CORE reset";
		reset_type = ICE_RESET_CORER;
	} else if (strcmp(reset, "globr") == 0) {
		reset_message = "Initiating a GLOBAL reset";
		reset_type = ICE_RESET_GLOBR;
	} else if (strcmp(reset, "empr") == 0) {
		device_printf(sc->dev, "Triggering an EMP reset via software is not currently supported\n");
		return (EOPNOTSUPP);
	}

	if (reset_type == ICE_RESET_INVAL) {
		device_printf(sc->dev, "%s is not a valid reset request\n", reset);
		return (EINVAL);
	}

	/*
	 * Rate-limit the frequency at which this function is called.
	 * Assuming this is called successfully once, typically,
	 * everything should be handled within the allotted time frame.
	 * However, in the odd setup situations, we've also put in
	 * guards for when the reset has finished, but we're in the
	 * process of rebuilding. And instead of queueing an intent,
	 * simply error out and let the caller retry, if so desired.
	 */
	if (TICKS_2_MSEC(ticks - rl_sysctl_ticks) < 500) {
		device_printf(sc->dev,
		    "Call frequency too high. Operation aborted.\n");
		return (EBUSY);
	}
	rl_sysctl_ticks = ticks;

	if (TICKS_2_MSEC(ticks - sc->rebuild_ticks) < 100) {
		device_printf(sc->dev, "Device rebuilding. Operation aborted.\n");
		return (EBUSY);
	}

	if (rd32(hw, GLGEN_RSTAT) & GLGEN_RSTAT_DEVSTATE_M) {
		device_printf(sc->dev, "Device in reset. Operation aborted.\n");
		return (EBUSY);
	}

	device_printf(sc->dev, "%s\n", reset_message);

	/* Initiate the PF reset during the admin status task */
	if (reset_type == ICE_RESET_PFR) {
		ice_set_state(&sc->state, ICE_STATE_RESET_PFR_REQ);
		return (0);
	}

	/*
	 * Other types of resets including CORE and GLOBAL resets trigger an
	 * interrupt on all PFs. Initiate the reset now. Preparation and
	 * rebuild logic will be handled by the admin status task.
	 */
	status = ice_reset(hw, reset_type);

	/*
	 * Resets can take a long time and we still don't want another call
	 * to this function before we settle down.
	 */
	rl_sysctl_ticks = ticks;

	if (status) {
		device_printf(sc->dev, "failed to initiate device reset, err %s\n",
			      ice_status_str(status));
		ice_set_state(&sc->state, ICE_STATE_RESET_FAILED);
		return (EFAULT);
	}

	return (0);
}

/**
 * ice_add_debug_sysctls - Add sysctls helpful for debugging the device driver
 * @sc: device private structure
 *
 * Add sysctls related to debugging the device driver. Generally these should
 * simply be sysctls which dump internal driver state, to aid in understanding
 * what the driver is doing.
 */
static void
ice_add_debug_sysctls(struct ice_softc *sc)
{
	struct sysctl_oid *sw_node;
	struct sysctl_oid_list *debug_list, *sw_list;
	device_t dev = sc->dev;

	struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(dev);

	debug_list = SYSCTL_CHILDREN(sc->debug_sysctls);

	SYSCTL_ADD_PROC(ctx, debug_list, OID_AUTO, "request_reset",
			ICE_CTLFLAG_DEBUG | CTLTYPE_STRING | CTLFLAG_WR, sc, 0,
			ice_sysctl_request_reset, "A",
			ICE_SYSCTL_HELP_REQUEST_RESET);

	SYSCTL_ADD_U32(ctx, debug_list, OID_AUTO, "pfr_count",
		       ICE_CTLFLAG_DEBUG | CTLFLAG_RD,
		       &sc->soft_stats.pfr_count, 0,
		       "# of PF resets handled");

	SYSCTL_ADD_U32(ctx, debug_list, OID_AUTO, "corer_count",
		       ICE_CTLFLAG_DEBUG | CTLFLAG_RD,
		       &sc->soft_stats.corer_count, 0,
		       "# of CORE resets handled");

	SYSCTL_ADD_U32(ctx, debug_list, OID_AUTO, "globr_count",
		       ICE_CTLFLAG_DEBUG | CTLFLAG_RD,
		       &sc->soft_stats.globr_count, 0,
		       "# of Global resets handled");

	SYSCTL_ADD_U32(ctx, debug_list, OID_AUTO, "empr_count",
		       ICE_CTLFLAG_DEBUG | CTLFLAG_RD,
		       &sc->soft_stats.empr_count, 0,
		       "# of EMP resets handled");

	SYSCTL_ADD_U32(ctx, debug_list, OID_AUTO, "tx_mdd_count",
		       ICE_CTLFLAG_DEBUG | CTLFLAG_RD,
		       &sc->soft_stats.tx_mdd_count, 0,
		       "# of Tx MDD events detected");

	SYSCTL_ADD_U32(ctx, debug_list, OID_AUTO, "rx_mdd_count",
		       ICE_CTLFLAG_DEBUG | CTLFLAG_RD,
		       &sc->soft_stats.rx_mdd_count, 0,
		       "# of Rx MDD events detected");

	SYSCTL_ADD_PROC(ctx, debug_list, OID_AUTO, "state",
			ICE_CTLFLAG_DEBUG | CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
			ice_sysctl_dump_state_flags, "A",
			"Driver State Flags");

	SYSCTL_ADD_PROC(ctx, debug_list, OID_AUTO, "phy_type_low",
			ICE_CTLFLAG_DEBUG | CTLTYPE_U64 | CTLFLAG_RW, sc, 0,
			ice_sysctl_phy_type_low, "QU",
			"PHY type Low from Get PHY Caps/Set PHY Cfg");

	SYSCTL_ADD_PROC(ctx, debug_list, OID_AUTO, "phy_type_high",
			ICE_CTLFLAG_DEBUG | CTLTYPE_U64 | CTLFLAG_RW, sc, 0,
			ice_sysctl_phy_type_high, "QU",
			"PHY type High from Get PHY Caps/Set PHY Cfg");

	SYSCTL_ADD_PROC(ctx, debug_list, OID_AUTO, "phy_sw_caps",
			ICE_CTLFLAG_DEBUG | CTLTYPE_STRUCT | CTLFLAG_RD, sc, 0,
			ice_sysctl_phy_sw_caps, "",
			"Get PHY Capabilities (Software configuration)");

	SYSCTL_ADD_PROC(ctx, debug_list, OID_AUTO, "phy_nvm_caps",
			ICE_CTLFLAG_DEBUG | CTLTYPE_STRUCT | CTLFLAG_RD, sc, 0,
			ice_sysctl_phy_nvm_caps, "",
			"Get PHY Capabilities (NVM configuration)");

	SYSCTL_ADD_PROC(ctx, debug_list, OID_AUTO, "phy_topo_caps",
			ICE_CTLFLAG_DEBUG | CTLTYPE_STRUCT | CTLFLAG_RD, sc, 0,
			ice_sysctl_phy_topo_caps, "",
			"Get PHY Capabilities (Topology configuration)");

	SYSCTL_ADD_PROC(ctx, debug_list, OID_AUTO, "phy_link_status",
			ICE_CTLFLAG_DEBUG | CTLTYPE_STRUCT | CTLFLAG_RD, sc, 0,
			ice_sysctl_phy_link_status, "",
			"Get PHY Link Status");

	SYSCTL_ADD_PROC(ctx, debug_list, OID_AUTO, "read_i2c_diag_data",
			ICE_CTLFLAG_DEBUG | CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
			ice_sysctl_read_i2c_diag_data, "A",
			"Dump selected diagnostic data from FW");

	SYSCTL_ADD_U32(ctx, debug_list, OID_AUTO, "fw_build",
		       ICE_CTLFLAG_DEBUG | CTLFLAG_RD, &sc->hw.fw_build, 0,
		       "FW Build ID");

	SYSCTL_ADD_PROC(ctx, debug_list, OID_AUTO, "os_ddp_version",
			ICE_CTLFLAG_DEBUG | CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
			ice_sysctl_os_pkg_version, "A",
			"DDP package name and version found in ice_ddp");

	SYSCTL_ADD_PROC(ctx, debug_list, OID_AUTO, "cur_lldp_persist_status",
			ICE_CTLFLAG_DEBUG | CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
			ice_sysctl_fw_cur_lldp_persist_status, "A",
			"Current LLDP persistent status");

	SYSCTL_ADD_PROC(ctx, debug_list, OID_AUTO, "dflt_lldp_persist_status",
			ICE_CTLFLAG_DEBUG | CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
			ice_sysctl_fw_dflt_lldp_persist_status, "A",
			"Default LLDP persistent status");

	SYSCTL_ADD_PROC(ctx, debug_list, OID_AUTO, "negotiated_fc",
			ICE_CTLFLAG_DEBUG | CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
			ice_sysctl_negotiated_fc, "A",
			"Current Negotiated Flow Control mode");

	SYSCTL_ADD_PROC(ctx, debug_list, OID_AUTO, "local_dcbx_cfg",
			CTLTYPE_STRING | CTLFLAG_RD, sc, ICE_AQ_LLDP_MIB_LOCAL,
			ice_sysctl_dump_dcbx_cfg, "A",
			"Dumps Local MIB information from firmware");

	SYSCTL_ADD_PROC(ctx, debug_list, OID_AUTO, "remote_dcbx_cfg",
			CTLTYPE_STRING | CTLFLAG_RD, sc, ICE_AQ_LLDP_MIB_REMOTE,
			ice_sysctl_dump_dcbx_cfg, "A",
			"Dumps Remote MIB information from firmware");

	SYSCTL_ADD_PROC(ctx, debug_list, OID_AUTO, "pf_vsi_cfg", CTLTYPE_STRING | CTLFLAG_RD,
			sc, 0, ice_sysctl_dump_vsi_cfg, "A",
			"Dumps Selected PF VSI parameters from firmware");

	SYSCTL_ADD_PROC(ctx, debug_list, OID_AUTO, "query_port_ets", CTLTYPE_STRING | CTLFLAG_RD,
			sc, 0, ice_sysctl_query_port_ets, "A",
			"Prints selected output from Query Port ETS AQ command");

	sw_node = SYSCTL_ADD_NODE(ctx, debug_list, OID_AUTO, "switch",
				  ICE_CTLFLAG_DEBUG | CTLFLAG_RD, NULL,
				  "Switch Configuration");
	sw_list = SYSCTL_CHILDREN(sw_node);

	SYSCTL_ADD_PROC(ctx, sw_list, OID_AUTO, "mac_filters",
			ICE_CTLFLAG_DEBUG | CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
			ice_sysctl_dump_mac_filters, "A",
			"MAC Filters");

	SYSCTL_ADD_PROC(ctx, sw_list, OID_AUTO, "vlan_filters",
			ICE_CTLFLAG_DEBUG | CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
			ice_sysctl_dump_vlan_filters, "A",
			"VLAN Filters");

	SYSCTL_ADD_PROC(ctx, sw_list, OID_AUTO, "ethertype_filters",
			ICE_CTLFLAG_DEBUG | CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
			ice_sysctl_dump_ethertype_filters, "A",
			"Ethertype Filters");

	SYSCTL_ADD_PROC(ctx, sw_list, OID_AUTO, "ethertype_mac_filters",
			ICE_CTLFLAG_DEBUG | CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
			ice_sysctl_dump_ethertype_mac_filters, "A",
			"Ethertype/MAC Filters");

}

/**
 * ice_vsi_disable_tx - Disable (unconfigure) Tx queues for a VSI
 * @vsi: the VSI to disable
 *
 * Disables the Tx queues associated with this VSI. Essentially the opposite
 * of ice_cfg_vsi_for_tx.
 */
int
ice_vsi_disable_tx(struct ice_vsi *vsi)
{
	struct ice_softc *sc = vsi->sc;
	struct ice_hw *hw = &sc->hw;
	enum ice_status status;
	u32 *q_teids;
	u16 *q_ids, *q_handles;
	size_t q_teids_size, q_ids_size, q_handles_size;
	int tc, j, buf_idx, err = 0;

	if (vsi->num_tx_queues > 255)
		return (ENOSYS);

	q_teids_size = sizeof(*q_teids) * vsi->num_tx_queues;
	q_teids = (u32 *)malloc(q_teids_size, M_ICE, M_NOWAIT|M_ZERO);
	if (!q_teids)
		return (ENOMEM);

	q_ids_size = sizeof(*q_ids) * vsi->num_tx_queues;
	q_ids = (u16 *)malloc(q_ids_size, M_ICE, M_NOWAIT|M_ZERO);
	if (!q_ids) {
		err = (ENOMEM);
		goto free_q_teids;
	}

	q_handles_size = sizeof(*q_handles) * vsi->num_tx_queues;
	q_handles = (u16 *)malloc(q_handles_size, M_ICE, M_NOWAIT|M_ZERO);
	if (!q_handles) {
		err = (ENOMEM);
		goto free_q_ids;
	}

	ice_for_each_traffic_class(tc) {
		buf_idx = 0;
		for (j = 0; j < vsi->num_tx_queues; j++) {
			struct ice_tx_queue *txq = &vsi->tx_queues[j];

			if (txq->tc != tc)
				continue;

			q_ids[buf_idx] = vsi->tx_qmap[j];
			q_handles[buf_idx] = txq->q_handle;
			q_teids[buf_idx] = txq->q_teid;
			buf_idx++;
		}
		/* Skip TC if no queues belong to it */
		if (buf_idx == 0)
			continue;

		status = ice_dis_vsi_txq(hw->port_info, vsi->idx, tc, buf_idx,
					 q_handles, q_ids, q_teids, ICE_NO_RESET, 0, NULL);
		if (status == ICE_ERR_DOES_NOT_EXIST) {
			; /* Queues have already been disabled, no need to report this as an error */
		} else if (status == ICE_ERR_RESET_ONGOING) {
			device_printf(sc->dev,
				      "Reset in progress. LAN Tx queues already disabled\n");
			break;
		} else if (status) {
			device_printf(sc->dev,
				      "Failed to disable LAN Tx queues: err %s aq_err %s\n",
				      ice_status_str(status), ice_aq_str(hw->adminq.sq_last_status));
			err = (ENODEV);
			break;
		}

		/* Clear buffers */
		memset(q_teids, 0, q_teids_size); 
		memset(q_ids, 0, q_ids_size); 
		memset(q_handles, 0, q_handles_size); 
	}

/* free_q_handles: */
	free(q_handles, M_ICE);
free_q_ids:
	free(q_ids, M_ICE);
free_q_teids:
	free(q_teids, M_ICE);

	return err;
}

/**
 * ice_vsi_set_rss_params - Set the RSS parameters for the VSI
 * @vsi: the VSI to configure
 *
 * Sets the RSS table size and lookup table type for the VSI based on its
 * VSI type.
 */
static void
ice_vsi_set_rss_params(struct ice_vsi *vsi)
{
	struct ice_softc *sc = vsi->sc;
	struct ice_hw_common_caps *cap;

	cap = &sc->hw.func_caps.common_cap;

	switch (vsi->type) {
	case ICE_VSI_PF:
		/* The PF VSI inherits RSS instance of the PF */
		vsi->rss_table_size = cap->rss_table_size;
		vsi->rss_lut_type = ICE_AQC_GSET_RSS_LUT_TABLE_TYPE_PF;
		break;
	case ICE_VSI_VF:
		vsi->rss_table_size = ICE_VSIQF_HLUT_ARRAY_SIZE;
		vsi->rss_lut_type = ICE_AQC_GSET_RSS_LUT_TABLE_TYPE_VSI;
		break;
	default:
		device_printf(sc->dev,
			      "VSI %d: RSS not supported for VSI type %d\n",
			      vsi->idx, vsi->type);
		break;
	}
}

/**
 * ice_vsi_add_txqs_ctx - Create a sysctl context and node to store txq sysctls
 * @vsi: The VSI to add the context for
 *
 * Creates a sysctl context for storing txq sysctls. Additionally creates
 * a node rooted at the given VSI's main sysctl node. This context will be
 * used to store per-txq sysctls which may need to be released during the
 * driver's lifetime.
 */
void
ice_vsi_add_txqs_ctx(struct ice_vsi *vsi)
{
	struct sysctl_oid_list *vsi_list;

	sysctl_ctx_init(&vsi->txqs_ctx);

	vsi_list = SYSCTL_CHILDREN(vsi->vsi_node);

	vsi->txqs_node = SYSCTL_ADD_NODE(&vsi->txqs_ctx, vsi_list, OID_AUTO, "txqs",
					 CTLFLAG_RD, NULL, "Tx Queues");
}

/**
 * ice_vsi_add_rxqs_ctx - Create a sysctl context and node to store rxq sysctls
 * @vsi: The VSI to add the context for
 *
 * Creates a sysctl context for storing rxq sysctls. Additionally creates
 * a node rooted at the given VSI's main sysctl node. This context will be
 * used to store per-rxq sysctls which may need to be released during the
 * driver's lifetime.
 */
void
ice_vsi_add_rxqs_ctx(struct ice_vsi *vsi)
{
	struct sysctl_oid_list *vsi_list;

	sysctl_ctx_init(&vsi->rxqs_ctx);

	vsi_list = SYSCTL_CHILDREN(vsi->vsi_node);

	vsi->rxqs_node = SYSCTL_ADD_NODE(&vsi->rxqs_ctx, vsi_list, OID_AUTO, "rxqs",
					 CTLFLAG_RD, NULL, "Rx Queues");
}

/**
 * ice_vsi_del_txqs_ctx - Delete the Tx queue sysctl context for this VSI
 * @vsi: The VSI to delete from
 *
 * Frees the txq sysctl context created for storing the per-queue Tx sysctls.
 * Must be called prior to freeing the Tx queue memory, in order to avoid
 * having sysctls point at stale memory.
 */
void
ice_vsi_del_txqs_ctx(struct ice_vsi *vsi)
{
	device_t dev = vsi->sc->dev;
	int err;

	if (vsi->txqs_node) {
		err = sysctl_ctx_free(&vsi->txqs_ctx);
		if (err)
			device_printf(dev, "failed to free VSI %d txqs_ctx, err %s\n",
				      vsi->idx, ice_err_str(err));
		vsi->txqs_node = NULL;
	}
}

/**
 * ice_vsi_del_rxqs_ctx - Delete the Rx queue sysctl context for this VSI
 * @vsi: The VSI to delete from
 *
 * Frees the rxq sysctl context created for storing the per-queue Rx sysctls.
 * Must be called prior to freeing the Rx queue memory, in order to avoid
 * having sysctls point at stale memory.
 */
void
ice_vsi_del_rxqs_ctx(struct ice_vsi *vsi)
{
	device_t dev = vsi->sc->dev;
	int err;

	if (vsi->rxqs_node) {
		err = sysctl_ctx_free(&vsi->rxqs_ctx);
		if (err)
			device_printf(dev, "failed to free VSI %d rxqs_ctx, err %s\n",
				      vsi->idx, ice_err_str(err));
		vsi->rxqs_node = NULL;
	}
}

/**
 * ice_add_txq_sysctls - Add per-queue sysctls for a Tx queue
 * @txq: pointer to the Tx queue
 *
* Add per-queue sysctls for a given Tx queue. Can't be called during
* ice_add_vsi_sysctls, since the queue memory has not yet been setup.
 */
void
ice_add_txq_sysctls(struct ice_tx_queue *txq)
{
	struct ice_vsi *vsi = txq->vsi;
	struct sysctl_ctx_list *ctx = &vsi->txqs_ctx;
	struct sysctl_oid_list *txqs_list, *this_txq_list;
	struct sysctl_oid *txq_node;
	char txq_name[32], txq_desc[32];

	const struct ice_sysctl_info ctls[] = {
		{ &txq->stats.tx_packets, "tx_packets", "Queue Packets Transmitted" },
		{ &txq->stats.tx_bytes, "tx_bytes", "Queue Bytes Transmitted" },
		{ &txq->stats.mss_too_small, "mss_too_small", "TSO sends with an MSS less than 64" },
		{ 0, 0, 0 }
	};

	const struct ice_sysctl_info *entry = ctls;

	txqs_list = SYSCTL_CHILDREN(vsi->txqs_node);

	snprintf(txq_name, sizeof(txq_name), "%u", txq->me);
	snprintf(txq_desc, sizeof(txq_desc), "Tx Queue %u", txq->me);
	txq_node = SYSCTL_ADD_NODE(ctx, txqs_list, OID_AUTO, txq_name,
				   CTLFLAG_RD, NULL, txq_desc);
	this_txq_list = SYSCTL_CHILDREN(txq_node);

	/* Add the Tx queue statistics */
	while (entry->stat != 0) {
		SYSCTL_ADD_U64(ctx, this_txq_list, OID_AUTO, entry->name,
			       CTLFLAG_RD | CTLFLAG_STATS, entry->stat, 0,
			       entry->description);
		entry++;
	}

	SYSCTL_ADD_U8(ctx, this_txq_list, OID_AUTO, "tc",
		       CTLFLAG_RD, &txq->tc, 0,
		       "Traffic Class that Queue belongs to");
}

/**
 * ice_add_rxq_sysctls - Add per-queue sysctls for an Rx queue
 * @rxq: pointer to the Rx queue
 *
 * Add per-queue sysctls for a given Rx queue. Can't be called during
 * ice_add_vsi_sysctls, since the queue memory has not yet been setup.
 */
void
ice_add_rxq_sysctls(struct ice_rx_queue *rxq)
{
	struct ice_vsi *vsi = rxq->vsi;
	struct sysctl_ctx_list *ctx = &vsi->rxqs_ctx;
	struct sysctl_oid_list *rxqs_list, *this_rxq_list;
	struct sysctl_oid *rxq_node;
	char rxq_name[32], rxq_desc[32];

	const struct ice_sysctl_info ctls[] = {
		{ &rxq->stats.rx_packets, "rx_packets", "Queue Packets Received" },
		{ &rxq->stats.rx_bytes, "rx_bytes", "Queue Bytes Received" },
		{ &rxq->stats.desc_errs, "rx_desc_errs", "Queue Rx Descriptor Errors" },
		{ 0, 0, 0 }
	};

	const struct ice_sysctl_info *entry = ctls;

	rxqs_list = SYSCTL_CHILDREN(vsi->rxqs_node);

	snprintf(rxq_name, sizeof(rxq_name), "%u", rxq->me);
	snprintf(rxq_desc, sizeof(rxq_desc), "Rx Queue %u", rxq->me);
	rxq_node = SYSCTL_ADD_NODE(ctx, rxqs_list, OID_AUTO, rxq_name,
				   CTLFLAG_RD, NULL, rxq_desc);
	this_rxq_list = SYSCTL_CHILDREN(rxq_node);

	/* Add the Rx queue statistics */
	while (entry->stat != 0) {
		SYSCTL_ADD_U64(ctx, this_rxq_list, OID_AUTO, entry->name,
			       CTLFLAG_RD | CTLFLAG_STATS, entry->stat, 0,
			       entry->description);
		entry++;
	}

	SYSCTL_ADD_U8(ctx, this_rxq_list, OID_AUTO, "tc",
		       CTLFLAG_RD, &rxq->tc, 0,
		       "Traffic Class that Queue belongs to");
}

/**
 * ice_get_default_rss_key - Obtain a default RSS key
 * @seed: storage for the RSS key data
 *
 * Copies a pre-generated RSS key into the seed memory. The seed pointer must
 * point to a block of memory that is at least 40 bytes in size.
 *
 * The key isn't randomly generated each time this function is called because
 * that makes the RSS key change every time we reconfigure RSS. This does mean
 * that we're hard coding a possibly 'well known' key. We might want to
 * investigate randomly generating this key once during the first call.
 */
static void
ice_get_default_rss_key(u8 *seed)
{
	const u8 default_seed[ICE_AQC_GET_SET_RSS_KEY_DATA_RSS_KEY_SIZE] = {
		0x39, 0xed, 0xff, 0x4d, 0x43, 0x58, 0x42, 0xc3, 0x5f, 0xb8,
		0xa5, 0x32, 0x95, 0x65, 0x81, 0xcd, 0x36, 0x79, 0x71, 0x97,
		0xde, 0xa4, 0x41, 0x40, 0x6f, 0x27, 0xe9, 0x81, 0x13, 0xa0,
		0x95, 0x93, 0x5b, 0x1e, 0x9d, 0x27, 0x9d, 0x24, 0x84, 0xb5,
	};

	bcopy(default_seed, seed, ICE_AQC_GET_SET_RSS_KEY_DATA_RSS_KEY_SIZE);
}

/**
 * ice_set_rss_key - Configure a given VSI with the default RSS key
 * @vsi: the VSI to configure
 *
 * Program the hardware RSS key. We use rss_getkey to grab the kernel RSS key.
 * If the kernel RSS interface is not available, this will fall back to our
 * pre-generated hash seed from ice_get_default_rss_key().
 */
static int
ice_set_rss_key(struct ice_vsi *vsi)
{
	struct ice_aqc_get_set_rss_keys keydata = { .standard_rss_key = {0} };
	struct ice_softc *sc = vsi->sc;
	struct ice_hw *hw = &sc->hw;
	enum ice_status status;

	/*
	 * If the RSS kernel interface is disabled, this will return the
	 * default RSS key above.
	 */
	rss_getkey(keydata.standard_rss_key);

	status = ice_aq_set_rss_key(hw, vsi->idx, &keydata);
	if (status) {
		device_printf(sc->dev,
			      "ice_aq_set_rss_key status %s, error %s\n",
			      ice_status_str(status), ice_aq_str(hw->adminq.sq_last_status));
		return (EIO);
	}

	return (0);
}

/**
 * ice_set_rss_flow_flds - Program the RSS hash flows after package init
 * @vsi: the VSI to configure
 *
 * If the package file is initialized, the default RSS flows are reset. We
 * need to reprogram the expected hash configuration. We'll use
 * rss_gethashconfig() to determine which flows to enable. If RSS kernel
 * support is not enabled, this macro will fall back to suitable defaults.
 */
static void
ice_set_rss_flow_flds(struct ice_vsi *vsi)
{
	struct ice_softc *sc = vsi->sc;
	struct ice_hw *hw = &sc->hw;
	struct ice_rss_hash_cfg rss_cfg = { 0, 0, ICE_RSS_ANY_HEADERS, false };
	device_t dev = sc->dev;
	enum ice_status status;
	u_int rss_hash_config;

	rss_hash_config = rss_gethashconfig();

	if (rss_hash_config & RSS_HASHTYPE_RSS_IPV4) {
		rss_cfg.addl_hdrs = ICE_FLOW_SEG_HDR_IPV4;
		rss_cfg.hash_flds = ICE_FLOW_HASH_IPV4;
		status = ice_add_rss_cfg(hw, vsi->idx, &rss_cfg);
		if (status)
			device_printf(dev,
				      "ice_add_rss_cfg on VSI %d failed for ipv4 flow, err %s aq_err %s\n",
				      vsi->idx, ice_status_str(status), ice_aq_str(hw->adminq.sq_last_status));
	}
	if (rss_hash_config & RSS_HASHTYPE_RSS_TCP_IPV4) {
		rss_cfg.addl_hdrs = ICE_FLOW_SEG_HDR_IPV4 | ICE_FLOW_SEG_HDR_TCP;
		rss_cfg.hash_flds = ICE_HASH_TCP_IPV4;
		status = ice_add_rss_cfg(hw, vsi->idx, &rss_cfg);
		if (status)
			device_printf(dev,
				      "ice_add_rss_cfg on VSI %d failed for tcp4 flow, err %s aq_err %s\n",
				      vsi->idx, ice_status_str(status), ice_aq_str(hw->adminq.sq_last_status));
	}
	if (rss_hash_config & RSS_HASHTYPE_RSS_UDP_IPV4) {
		rss_cfg.addl_hdrs = ICE_FLOW_SEG_HDR_IPV4 | ICE_FLOW_SEG_HDR_UDP;
		rss_cfg.hash_flds = ICE_HASH_UDP_IPV4;
		status = ice_add_rss_cfg(hw, vsi->idx, &rss_cfg);
		if (status)
			device_printf(dev,
				      "ice_add_rss_cfg on VSI %d failed for udp4 flow, err %s aq_err %s\n",
				      vsi->idx, ice_status_str(status), ice_aq_str(hw->adminq.sq_last_status));
	}
	if (rss_hash_config & (RSS_HASHTYPE_RSS_IPV6 | RSS_HASHTYPE_RSS_IPV6_EX)) {
		rss_cfg.addl_hdrs = ICE_FLOW_SEG_HDR_IPV6;
		rss_cfg.hash_flds = ICE_FLOW_HASH_IPV6;
		status = ice_add_rss_cfg(hw, vsi->idx, &rss_cfg);
		if (status)
			device_printf(dev,
				      "ice_add_rss_cfg on VSI %d failed for ipv6 flow, err %s aq_err %s\n",
				      vsi->idx, ice_status_str(status), ice_aq_str(hw->adminq.sq_last_status));
	}
	if (rss_hash_config & RSS_HASHTYPE_RSS_TCP_IPV6) {
		rss_cfg.addl_hdrs = ICE_FLOW_SEG_HDR_IPV6 | ICE_FLOW_SEG_HDR_TCP;
		rss_cfg.hash_flds = ICE_HASH_TCP_IPV6;
		status = ice_add_rss_cfg(hw, vsi->idx, &rss_cfg);
		if (status)
			device_printf(dev,
				      "ice_add_rss_cfg on VSI %d failed for tcp6 flow, err %s aq_err %s\n",
				      vsi->idx, ice_status_str(status), ice_aq_str(hw->adminq.sq_last_status));
	}
	if (rss_hash_config & RSS_HASHTYPE_RSS_UDP_IPV6) {
		rss_cfg.addl_hdrs = ICE_FLOW_SEG_HDR_IPV6 | ICE_FLOW_SEG_HDR_UDP;
		rss_cfg.hash_flds = ICE_HASH_UDP_IPV6;
		status = ice_add_rss_cfg(hw, vsi->idx, &rss_cfg);
		if (status)
			device_printf(dev,
				      "ice_add_rss_cfg on VSI %d failed for udp6 flow, err %s aq_err %s\n",
				      vsi->idx, ice_status_str(status), ice_aq_str(hw->adminq.sq_last_status));
	}

	/* Warn about RSS hash types which are not supported */
	/* coverity[dead_error_condition] */
	if (rss_hash_config & ~ICE_DEFAULT_RSS_HASH_CONFIG) {
		device_printf(dev,
			      "ice_add_rss_cfg on VSI %d could not configure every requested hash type\n",
			      vsi->idx);
	}
}

/**
 * ice_set_rss_lut - Program the RSS lookup table for a VSI
 * @vsi: the VSI to configure
 *
 * Programs the RSS lookup table for a given VSI. We use
 * rss_get_indirection_to_bucket which will use the indirection table provided
 * by the kernel RSS interface when available. If the kernel RSS interface is
 * not available, we will fall back to a simple round-robin fashion queue
 * assignment.
 */
static int
ice_set_rss_lut(struct ice_vsi *vsi)
{
	struct ice_softc *sc = vsi->sc;
	struct ice_hw *hw = &sc->hw;
	device_t dev = sc->dev;
	struct ice_aq_get_set_rss_lut_params lut_params;
	enum ice_status status;
	int i, err = 0;
	u8 *lut;

	lut = (u8 *)malloc(vsi->rss_table_size, M_ICE, M_NOWAIT|M_ZERO);
	if (!lut) {
		device_printf(dev, "Failed to allocate RSS lut memory\n");
		return (ENOMEM);
	}

	/* Populate the LUT with max no. of queues. If the RSS kernel
	 * interface is disabled, this will assign the lookup table in
	 * a simple round robin fashion
	 */
	for (i = 0; i < vsi->rss_table_size; i++) {
		/* XXX: this needs to be changed if num_rx_queues ever counts
		 * more than just the RSS queues */
		lut[i] = rss_get_indirection_to_bucket(i) % vsi->num_rx_queues;
	}

	lut_params.vsi_handle = vsi->idx;
	lut_params.lut_size = vsi->rss_table_size;
	lut_params.lut_type = vsi->rss_lut_type;
	lut_params.lut = lut;
	lut_params.global_lut_id = 0;
	status = ice_aq_set_rss_lut(hw, &lut_params);
	if (status) {
		device_printf(dev,
			      "Cannot set RSS lut, err %s aq_err %s\n",
			      ice_status_str(status), ice_aq_str(hw->adminq.sq_last_status));
		err = (EIO);
	}

	free(lut, M_ICE);
	return err;
}

/**
 * ice_config_rss - Configure RSS for a VSI
 * @vsi: the VSI to configure
 *
 * If FEATURE_RSS is enabled, configures the RSS lookup table and hash key for
 * a given VSI.
 */
int
ice_config_rss(struct ice_vsi *vsi)
{
	int err;

	/* Nothing to do, if RSS is not enabled */
	if (!ice_is_bit_set(vsi->sc->feat_en, ICE_FEATURE_RSS))
		return 0;

	err = ice_set_rss_key(vsi);
	if (err)
		return err;

	ice_set_rss_flow_flds(vsi);

	return ice_set_rss_lut(vsi);
}

/**
 * ice_log_pkg_init - Log a message about status of DDP initialization
 * @sc: the device softc pointer
 * @pkg_status: the status result of ice_copy_and_init_pkg
 *
 * Called by ice_load_pkg after an attempt to download the DDP package
 * contents to the device. Determines whether the download was successful or
 * not and logs an appropriate message for the system administrator.
 *
 * @post if a DDP package was previously downloaded on another port and it
 * is not compatible with this driver, pkg_status will be updated to reflect
 * this, and the driver will transition to safe mode.
 */
void
ice_log_pkg_init(struct ice_softc *sc, enum ice_status *pkg_status)
{
	struct ice_hw *hw = &sc->hw;
	device_t dev = sc->dev;
	struct sbuf *active_pkg, *os_pkg;

	active_pkg = sbuf_new_auto();
	ice_active_pkg_version_str(hw, active_pkg);
	sbuf_finish(active_pkg);

	os_pkg = sbuf_new_auto();
	ice_os_pkg_version_str(hw, os_pkg);
	sbuf_finish(os_pkg);

	switch (*pkg_status) {
	case ICE_SUCCESS:
		/* The package download AdminQ command returned success because
		 * this download succeeded or ICE_ERR_AQ_NO_WORK since there is
		 * already a package loaded on the device.
		 */
		if (hw->pkg_ver.major == hw->active_pkg_ver.major &&
		    hw->pkg_ver.minor == hw->active_pkg_ver.minor &&
		    hw->pkg_ver.update == hw->active_pkg_ver.update &&
		    hw->pkg_ver.draft == hw->active_pkg_ver.draft &&
		    !memcmp(hw->pkg_name, hw->active_pkg_name,
			    sizeof(hw->pkg_name))) {
			switch (hw->pkg_dwnld_status) {
			case ICE_AQ_RC_OK:
				device_printf(dev,
					      "The DDP package was successfully loaded: %s.\n",
					      sbuf_data(active_pkg));
				break;
			case ICE_AQ_RC_EEXIST:
				device_printf(dev,
					      "DDP package already present on device: %s.\n",
					      sbuf_data(active_pkg));
				break;
			default:
				/* We do not expect this to occur, but the
				 * extra messaging is here in case something
				 * changes in the ice_init_pkg flow.
				 */
				device_printf(dev,
					      "DDP package already present on device: %s.  An unexpected error occurred, pkg_dwnld_status %s.\n",
					      sbuf_data(active_pkg),
					      ice_aq_str(hw->pkg_dwnld_status));
				break;
			}
		} else if (pkg_ver_compatible(&hw->active_pkg_ver) == 0) {
			device_printf(dev,
				      "The driver could not load the DDP package file because a compatible DDP package is already present on the device.  The device has package %s.  The ice_ddp module has package: %s.\n",
				      sbuf_data(active_pkg),
				      sbuf_data(os_pkg));
		} else if (pkg_ver_compatible(&hw->active_pkg_ver) > 0) {
			device_printf(dev,
				      "The device has a DDP package that is higher than the driver supports.  The device has package %s.  The driver requires version %d.%d.x.x.  Entering Safe Mode.\n",
				      sbuf_data(active_pkg),
				      ICE_PKG_SUPP_VER_MAJ, ICE_PKG_SUPP_VER_MNR);
			*pkg_status = ICE_ERR_NOT_SUPPORTED;
		} else {
			device_printf(dev,
				      "The device has a DDP package that is lower than the driver supports.  The device has package %s.  The driver requires version %d.%d.x.x.  Entering Safe Mode.\n",
				      sbuf_data(active_pkg),
				      ICE_PKG_SUPP_VER_MAJ, ICE_PKG_SUPP_VER_MNR);
			*pkg_status = ICE_ERR_NOT_SUPPORTED;
		}
		break;
	case ICE_ERR_NOT_SUPPORTED:
		/*
		 * This assumes that the active_pkg_ver will not be
		 * initialized if the ice_ddp package version is not
		 * supported.
		 */
		if (pkg_ver_empty(&hw->active_pkg_ver, hw->active_pkg_name)) {
			/* The ice_ddp version is not supported */
			if (pkg_ver_compatible(&hw->pkg_ver) > 0) {
				device_printf(dev,
					      "The DDP package in the ice_ddp module is higher than the driver supports.  The ice_ddp module has package %s.  The driver requires version %d.%d.x.x.  Please use an updated driver.  Entering Safe Mode.\n",
					      sbuf_data(os_pkg),
					      ICE_PKG_SUPP_VER_MAJ, ICE_PKG_SUPP_VER_MNR);
			} else if (pkg_ver_compatible(&hw->pkg_ver) < 0) {
				device_printf(dev,
					      "The DDP package in the ice_ddp module is lower than the driver supports.  The ice_ddp module has package %s.  The driver requires version %d.%d.x.x.  Please use an updated ice_ddp module.  Entering Safe Mode.\n",
					      sbuf_data(os_pkg),
					      ICE_PKG_SUPP_VER_MAJ, ICE_PKG_SUPP_VER_MNR);
			} else {
				device_printf(dev,
					      "An unknown error (%s aq_err %s) occurred when loading the DDP package.  The ice_ddp module has package %s.  The device has package %s.  The driver requires version %d.%d.x.x.  Entering Safe Mode.\n",
					      ice_status_str(*pkg_status),
					      ice_aq_str(hw->pkg_dwnld_status),
					      sbuf_data(os_pkg),
					      sbuf_data(active_pkg),
					      ICE_PKG_SUPP_VER_MAJ, ICE_PKG_SUPP_VER_MNR);
			}
		} else {
			if (pkg_ver_compatible(&hw->active_pkg_ver) > 0) {
				device_printf(dev,
					      "The device has a DDP package that is higher than the driver supports.  The device has package %s.  The driver requires version %d.%d.x.x.  Entering Safe Mode.\n",
					      sbuf_data(active_pkg),
					      ICE_PKG_SUPP_VER_MAJ, ICE_PKG_SUPP_VER_MNR);
			} else if (pkg_ver_compatible(&hw->active_pkg_ver) < 0) {
				device_printf(dev,
					      "The device has a DDP package that is lower than the driver supports.  The device has package %s.  The driver requires version %d.%d.x.x.  Entering Safe Mode.\n",
					      sbuf_data(active_pkg),
					      ICE_PKG_SUPP_VER_MAJ, ICE_PKG_SUPP_VER_MNR);
			} else {
				device_printf(dev,
					      "An unknown error (%s aq_err %s) occurred when loading the DDP package.  The ice_ddp module has package %s.  The device has package %s.  The driver requires version %d.%d.x.x.  Entering Safe Mode.\n",
					      ice_status_str(*pkg_status),
					      ice_aq_str(hw->pkg_dwnld_status),
					      sbuf_data(os_pkg),
					      sbuf_data(active_pkg),
					      ICE_PKG_SUPP_VER_MAJ, ICE_PKG_SUPP_VER_MNR);
			}
		}
		break;
	case ICE_ERR_CFG:
	case ICE_ERR_BUF_TOO_SHORT:
	case ICE_ERR_PARAM:
		device_printf(dev,
			      "The DDP package in the ice_ddp module is invalid.  Entering Safe Mode\n");
		break;
	case ICE_ERR_FW_DDP_MISMATCH:
		device_printf(dev,
			      "The firmware loaded on the device is not compatible with the DDP package.  Please update the device's NVM.  Entering safe mode.\n");
		break;
	case ICE_ERR_AQ_ERROR:
		switch (hw->pkg_dwnld_status) {
		case ICE_AQ_RC_ENOSEC:
		case ICE_AQ_RC_EBADSIG:
			device_printf(dev,
				 "The DDP package in the ice_ddp module cannot be loaded because its signature is not valid.  Please use a valid ice_ddp module.  Entering Safe Mode.\n");
			goto free_sbufs;
		case ICE_AQ_RC_ESVN:
			device_printf(dev,
				 "The DDP package in the ice_ddp module could not be loaded because its security revision is too low.  Please use an updated ice_ddp module.  Entering Safe Mode.\n");
			goto free_sbufs;
		case ICE_AQ_RC_EBADMAN:
		case ICE_AQ_RC_EBADBUF:
			device_printf(dev,
				 "An error occurred on the device while loading the DDP package.  Entering Safe Mode.\n");
			goto free_sbufs;
		default:
			break;
		}
		/* fall-through */
	default:
		device_printf(dev,
			 "An unknown error (%s aq_err %s) occurred when loading the DDP package.  Entering Safe Mode.\n",
			 ice_status_str(*pkg_status),
			 ice_aq_str(hw->pkg_dwnld_status));
		break;
	}

free_sbufs:
	sbuf_delete(active_pkg);
	sbuf_delete(os_pkg);
}

/**
 * ice_load_pkg_file - Load the DDP package file using firmware_get
 * @sc: device private softc
 *
 * Use firmware_get to load the DDP package memory and then request that
 * firmware download the package contents and program the relevant hardware
 * bits.
 *
 * This function makes a copy of the DDP package memory which is tracked in
 * the ice_hw structure. The copy will be managed and released by
 * ice_deinit_hw(). This allows the firmware reference to be immediately
 * released using firmware_put.
 */
void
ice_load_pkg_file(struct ice_softc *sc)
{
	struct ice_hw *hw = &sc->hw;
	device_t dev = sc->dev;
	enum ice_status status;
	const struct firmware *pkg;

	pkg = firmware_get("ice_ddp");
	if (!pkg) {
		device_printf(dev, "The DDP package module (ice_ddp) failed to load or could not be found. Entering Safe Mode.\n");
		if (cold)
			device_printf(dev,
				      "The DDP package module cannot be automatically loaded while booting. You may want to specify ice_ddp_load=\"YES\" in your loader.conf\n");
		ice_set_bit(ICE_FEATURE_SAFE_MODE, sc->feat_cap);
		ice_set_bit(ICE_FEATURE_SAFE_MODE, sc->feat_en);
		return;
	}

	/* Copy and download the pkg contents */
	status = ice_copy_and_init_pkg(hw, (const u8 *)pkg->data, pkg->datasize);

	/* Release the firmware reference */
	firmware_put(pkg, FIRMWARE_UNLOAD);

	/* Check the active DDP package version and log a message */
	ice_log_pkg_init(sc, &status);

	/* Place the driver into safe mode */
	if (status != ICE_SUCCESS) {
		ice_set_bit(ICE_FEATURE_SAFE_MODE, sc->feat_cap);
		ice_set_bit(ICE_FEATURE_SAFE_MODE, sc->feat_en);
	}
}

/**
 * ice_get_ifnet_counter - Retrieve counter value for a given ifnet counter
 * @vsi: the vsi to retrieve the value for
 * @counter: the counter type to retrieve
 *
 * Returns the value for a given ifnet counter. To do so, we calculate the
 * value based on the matching hardware statistics.
 */
uint64_t
ice_get_ifnet_counter(struct ice_vsi *vsi, ift_counter counter)
{
	struct ice_hw_port_stats *hs = &vsi->sc->stats.cur;
	struct ice_eth_stats *es = &vsi->hw_stats.cur;

	/* For some statistics, especially those related to error flows, we do
	 * not have per-VSI counters. In this case, we just report the global
	 * counters.
	 */

	switch (counter) {
	case IFCOUNTER_IPACKETS:
		return (es->rx_unicast + es->rx_multicast + es->rx_broadcast);
	case IFCOUNTER_IERRORS:
		return (hs->crc_errors + hs->illegal_bytes +
			hs->mac_local_faults + hs->mac_remote_faults +
			hs->rx_len_errors + hs->rx_undersize +
			hs->rx_oversize + hs->rx_fragments + hs->rx_jabber);
	case IFCOUNTER_OPACKETS:
		return (es->tx_unicast + es->tx_multicast + es->tx_broadcast);
	case IFCOUNTER_OERRORS:
		return (es->tx_errors);
	case IFCOUNTER_COLLISIONS:
		return (0);
	case IFCOUNTER_IBYTES:
		return (es->rx_bytes);
	case IFCOUNTER_OBYTES:
		return (es->tx_bytes);
	case IFCOUNTER_IMCASTS:
		return (es->rx_multicast);
	case IFCOUNTER_OMCASTS:
		return (es->tx_multicast);
	case IFCOUNTER_IQDROPS:
		return (es->rx_discards);
	case IFCOUNTER_OQDROPS:
		return (hs->tx_dropped_link_down);
	case IFCOUNTER_NOPROTO:
		return (es->rx_unknown_protocol);
	default:
		return if_get_counter_default(vsi->sc->ifp, counter);
	}
}

/**
 * ice_save_pci_info - Save PCI configuration fields in HW struct
 * @hw: the ice_hw struct to save the PCI information in
 * @dev: the device to get the PCI information from
 *
 * This should only be called once, early in the device attach
 * process.
 */
void
ice_save_pci_info(struct ice_hw *hw, device_t dev)
{
	hw->vendor_id = pci_get_vendor(dev);
	hw->device_id = pci_get_device(dev);
	hw->subsystem_vendor_id = pci_get_subvendor(dev);
	hw->subsystem_device_id = pci_get_subdevice(dev);
	hw->revision_id = pci_get_revid(dev);
	hw->bus.device = pci_get_slot(dev);
	hw->bus.func = pci_get_function(dev);
}

/**
 * ice_replay_all_vsi_cfg - Replace configuration for all VSIs after reset
 * @sc: the device softc
 *
 * Replace the configuration for each VSI, and then cleanup replay
 * information. Called after a hardware reset in order to reconfigure the
 * active VSIs.
 */
int
ice_replay_all_vsi_cfg(struct ice_softc *sc)
{
	struct ice_hw *hw = &sc->hw;
	enum ice_status status;
	int i;

	for (i = 0 ; i < sc->num_available_vsi; i++) {
		struct ice_vsi *vsi = sc->all_vsi[i];

		if (!vsi)
			continue;

		status = ice_replay_vsi(hw, vsi->idx);
		if (status) {
			device_printf(sc->dev, "Failed to replay VSI %d, err %s aq_err %s\n",
				      vsi->idx, ice_status_str(status),
				      ice_aq_str(hw->adminq.sq_last_status));
			return (EIO);
		}
	}

	/* Cleanup replay filters after successful reconfiguration */
	ice_replay_post(hw);
	return (0);
}

/**
 * ice_clean_vsi_rss_cfg - Cleanup RSS configuration for a given VSI
 * @vsi: pointer to the VSI structure
 *
 * Cleanup the advanced RSS configuration for a given VSI. This is necessary
 * during driver removal to ensure that all RSS resources are properly
 * released.
 *
 * @remark this function doesn't report an error as it is expected to be
 * called during driver reset and unload, and there isn't much the driver can
 * do if freeing RSS resources fails.
 */
static void
ice_clean_vsi_rss_cfg(struct ice_vsi *vsi)
{
	struct ice_softc *sc = vsi->sc;
	struct ice_hw *hw = &sc->hw;
	device_t dev = sc->dev;
	enum ice_status status;

	status = ice_rem_vsi_rss_cfg(hw, vsi->idx);
	if (status)
		device_printf(dev,
			      "Failed to remove RSS configuration for VSI %d, err %s\n",
			      vsi->idx, ice_status_str(status));

	/* Remove this VSI from the RSS list */
	ice_rem_vsi_rss_list(hw, vsi->idx);
}

/**
 * ice_clean_all_vsi_rss_cfg - Cleanup RSS configuration for all VSIs
 * @sc: the device softc pointer
 *
 * Cleanup the advanced RSS configuration for all VSIs on a given PF
 * interface.
 *
 * @remark This should be called while preparing for a reset, to cleanup stale
 * RSS configuration for all VSIs.
 */
void
ice_clean_all_vsi_rss_cfg(struct ice_softc *sc)
{
	int i;

	/* No need to cleanup if RSS is not enabled */
	if (!ice_is_bit_set(sc->feat_en, ICE_FEATURE_RSS))
		return;

	for (i = 0; i < sc->num_available_vsi; i++) {
		struct ice_vsi *vsi = sc->all_vsi[i];

		if (vsi)
			ice_clean_vsi_rss_cfg(vsi);
	}
}

/**
 * ice_requested_fec_mode - Return the requested FEC mode as a string
 * @pi: The port info structure
 *
 * Return a string representing the requested FEC mode.
 */
static const char *
ice_requested_fec_mode(struct ice_port_info *pi)
{
	struct ice_aqc_get_phy_caps_data pcaps = { 0 };
	enum ice_status status;

	status = ice_aq_get_phy_caps(pi, false, ICE_AQC_REPORT_ACTIVE_CFG,
				     &pcaps, NULL);
	if (status)
		/* Just report unknown if we can't get capabilities */
		return "Unknown";

	/* Check if RS-FEC has been requested first */
	if (pcaps.link_fec_options & (ICE_AQC_PHY_FEC_25G_RS_528_REQ |
				      ICE_AQC_PHY_FEC_25G_RS_544_REQ))
		return ice_fec_str(ICE_FEC_RS);

	/* If RS FEC has not been requested, then check BASE-R */
	if (pcaps.link_fec_options & (ICE_AQC_PHY_FEC_10G_KR_40G_KR4_REQ |
				      ICE_AQC_PHY_FEC_25G_KR_REQ))
		return ice_fec_str(ICE_FEC_BASER);

	return ice_fec_str(ICE_FEC_NONE);
}

/**
 * ice_negotiated_fec_mode - Return the negotiated FEC mode as a string
 * @pi: The port info structure
 *
 * Return a string representing the current FEC mode.
 */
static const char *
ice_negotiated_fec_mode(struct ice_port_info *pi)
{
	/* First, check if RS has been requested first */
	if (pi->phy.link_info.fec_info & (ICE_AQ_LINK_25G_RS_528_FEC_EN |
					  ICE_AQ_LINK_25G_RS_544_FEC_EN))
		return ice_fec_str(ICE_FEC_RS);

	/* If RS FEC has not been requested, then check BASE-R */
	if (pi->phy.link_info.fec_info & ICE_AQ_LINK_25G_KR_FEC_EN)
		return ice_fec_str(ICE_FEC_BASER);

	return ice_fec_str(ICE_FEC_NONE);
}

/**
 * ice_autoneg_mode - Return string indicating of autoneg completed
 * @pi: The port info structure
 *
 * Return "True" if autonegotiation is completed, "False" otherwise.
 */
static const char *
ice_autoneg_mode(struct ice_port_info *pi)
{
	if (pi->phy.link_info.an_info & ICE_AQ_AN_COMPLETED)
		return "True";
	else
		return "False";
}

/**
 * ice_flowcontrol_mode - Return string indicating the Flow Control mode
 * @pi: The port info structure
 *
 * Returns the current Flow Control mode as a string.
 */
static const char *
ice_flowcontrol_mode(struct ice_port_info *pi)
{
	return ice_fc_str(pi->fc.current_mode);
}

/**
 * ice_link_up_msg - Log a link up message with associated info
 * @sc: the device private softc
 *
 * Log a link up message with LOG_NOTICE message level. Include information
 * about the duplex, FEC mode, autonegotiation and flow control.
 */
void
ice_link_up_msg(struct ice_softc *sc)
{
	struct ice_hw *hw = &sc->hw;
	struct ifnet *ifp = sc->ifp;
	const char *speed, *req_fec, *neg_fec, *autoneg, *flowcontrol;

	speed = ice_aq_speed_to_str(hw->port_info);
	req_fec = ice_requested_fec_mode(hw->port_info);
	neg_fec = ice_negotiated_fec_mode(hw->port_info);
	autoneg = ice_autoneg_mode(hw->port_info);
	flowcontrol = ice_flowcontrol_mode(hw->port_info);

	log(LOG_NOTICE, "%s: Link is up, %s Full Duplex, Requested FEC: %s, Negotiated FEC: %s, Autoneg: %s, Flow Control: %s\n",
	    ifp->if_xname, speed, req_fec, neg_fec, autoneg, flowcontrol);
}

/**
 * ice_update_laa_mac - Update MAC address if Locally Administered
 * @sc: the device softc
 *
 * Update the device MAC address when a Locally Administered Address is
 * assigned.
 *
 * This function does *not* update the MAC filter list itself. Instead, it
 * should be called after ice_rm_pf_default_mac_filters, so that the previous
 * address filter will be removed, and before ice_cfg_pf_default_mac_filters,
 * so that the new address filter will be assigned.
 */
int
ice_update_laa_mac(struct ice_softc *sc)
{
	const u8 *lladdr = (const u8 *)IF_LLADDR(sc->ifp);
	struct ice_hw *hw = &sc->hw;
	enum ice_status status;

	/* If the address is the same, then there is nothing to update */
	if (!memcmp(lladdr, hw->port_info->mac.lan_addr, ETHER_ADDR_LEN))
		return (0);

	/* Reject Multicast addresses */
	if (ETHER_IS_MULTICAST(lladdr))
		return (EINVAL);

	status = ice_aq_manage_mac_write(hw, lladdr, ICE_AQC_MAN_MAC_UPDATE_LAA_WOL, NULL);
	if (status) {
		device_printf(sc->dev, "Failed to write mac %6D to firmware, err %s aq_err %s\n",
			      lladdr, ":", ice_status_str(status),
			      ice_aq_str(hw->adminq.sq_last_status));
		return (EFAULT);
	}

	/* Copy the address into place of the LAN address. */
	bcopy(lladdr, hw->port_info->mac.lan_addr, ETHER_ADDR_LEN);

	return (0);
}

/**
 * ice_get_and_print_bus_info - Save (PCI) bus info and print messages
 * @sc: device softc
 *
 * This will potentially print out a warning message if bus bandwidth
 * is insufficient for full-speed operation.
 *
 * This should only be called once, during the attach process, after
 * hw->port_info has been filled out with port link topology information
 * (from the Get PHY Capabilities Admin Queue command).
 */
void
ice_get_and_print_bus_info(struct ice_softc *sc)
{
	struct ice_hw *hw = &sc->hw;
	device_t dev = sc->dev;
	u16 pci_link_status;
	int offset;

	pci_find_cap(dev, PCIY_EXPRESS, &offset);
	pci_link_status = pci_read_config(dev, offset + PCIER_LINK_STA, 2);

	/* Fill out hw struct with PCIE link status info */
	ice_set_pci_link_status_data(hw, pci_link_status);

	/* Use info to print out bandwidth messages */
	ice_print_bus_link_data(dev, hw);

	if (ice_pcie_bandwidth_check(sc)) {
		device_printf(dev,
		    "PCI-Express bandwidth available for this device may be insufficient for optimal performance.\n");
		device_printf(dev,
		    "Please move the device to a different PCI-e link with more lanes and/or higher transfer rate.\n");
	}
}

/**
 * ice_pcie_bus_speed_to_rate - Convert driver bus speed enum value to
 * a 64-bit baudrate.
 * @speed: enum value to convert
 *
 * This only goes up to PCIE Gen 4.
 */
static uint64_t
ice_pcie_bus_speed_to_rate(enum ice_pcie_bus_speed speed)
{
	/* If the PCI-E speed is Gen1 or Gen2, then report
	 * only 80% of bus speed to account for encoding overhead.
	 */
	switch (speed) {
	case ice_pcie_speed_2_5GT:
		return IF_Gbps(2);
	case ice_pcie_speed_5_0GT:
		return IF_Gbps(4);
	case ice_pcie_speed_8_0GT:
		return IF_Gbps(8);
	case ice_pcie_speed_16_0GT:
		return IF_Gbps(16);
	case ice_pcie_speed_unknown:
	default:
		return 0;
	}
}

/**
 * ice_pcie_lnk_width_to_int - Convert driver pci-e width enum value to
 * a 32-bit number.
 * @width: enum value to convert
 */
static int
ice_pcie_lnk_width_to_int(enum ice_pcie_link_width width)
{
	switch (width) {
	case ice_pcie_lnk_x1:
		return (1);
	case ice_pcie_lnk_x2:
		return (2);
	case ice_pcie_lnk_x4:
		return (4);
	case ice_pcie_lnk_x8:
		return (8);
	case ice_pcie_lnk_x12:
		return (12);
	case ice_pcie_lnk_x16:
		return (16);
	case ice_pcie_lnk_x32:
		return (32);
	case ice_pcie_lnk_width_resrv:
	case ice_pcie_lnk_width_unknown:
	default:
		return (0);
	}
}

/**
 * ice_pcie_bandwidth_check - Check if PCI-E bandwidth is sufficient for
 * full-speed device operation.
 * @sc: adapter softc
 *
 * Returns 0 if sufficient; 1 if not.
 */
static uint8_t
ice_pcie_bandwidth_check(struct ice_softc *sc)
{
	struct ice_hw *hw = &sc->hw;
	int num_ports, pcie_width;
	u64 pcie_speed, port_speed;

	MPASS(hw->port_info);

	num_ports = bitcount32(hw->func_caps.common_cap.valid_functions);
	port_speed = ice_phy_types_to_max_rate(hw->port_info);
	pcie_speed = ice_pcie_bus_speed_to_rate(hw->bus.speed);
	pcie_width = ice_pcie_lnk_width_to_int(hw->bus.width);

	/*
	 * If 2x100, clamp ports to 1 -- 2nd port is intended for
	 * failover.
	 */
	if (port_speed == IF_Gbps(100))
		num_ports = 1;

	return !!((num_ports * port_speed) > pcie_speed * pcie_width);
}

/**
 * ice_print_bus_link_data - Print PCI-E bandwidth information
 * @dev: device to print string for
 * @hw: hw struct with PCI-e link information
 */
static void
ice_print_bus_link_data(device_t dev, struct ice_hw *hw)
{
        device_printf(dev, "PCI Express Bus: Speed %s %s\n",
            ((hw->bus.speed == ice_pcie_speed_16_0GT) ? "16.0GT/s" :
            (hw->bus.speed == ice_pcie_speed_8_0GT) ? "8.0GT/s" :
            (hw->bus.speed == ice_pcie_speed_5_0GT) ? "5.0GT/s" :
            (hw->bus.speed == ice_pcie_speed_2_5GT) ? "2.5GT/s" : "Unknown"),
            (hw->bus.width == ice_pcie_lnk_x32) ? "Width x32" :
            (hw->bus.width == ice_pcie_lnk_x16) ? "Width x16" :
            (hw->bus.width == ice_pcie_lnk_x12) ? "Width x12" :
            (hw->bus.width == ice_pcie_lnk_x8) ? "Width x8" :
            (hw->bus.width == ice_pcie_lnk_x4) ? "Width x4" :
            (hw->bus.width == ice_pcie_lnk_x2) ? "Width x2" :
            (hw->bus.width == ice_pcie_lnk_x1) ? "Width x1" : "Width Unknown");
}

/**
 * ice_set_pci_link_status_data - store PCI bus info
 * @hw: pointer to hardware structure
 * @link_status: the link status word from PCI config space
 *
 * Stores the PCI bus info (speed, width, type) within the ice_hw structure
 **/
static void
ice_set_pci_link_status_data(struct ice_hw *hw, u16 link_status)
{
	u16 reg;

	hw->bus.type = ice_bus_pci_express;

	reg = (link_status & PCIEM_LINK_STA_WIDTH) >> 4;

	switch (reg) {
	case ice_pcie_lnk_x1:
	case ice_pcie_lnk_x2:
	case ice_pcie_lnk_x4:
	case ice_pcie_lnk_x8:
	case ice_pcie_lnk_x12:
	case ice_pcie_lnk_x16:
	case ice_pcie_lnk_x32:
		hw->bus.width = (enum ice_pcie_link_width)reg;
		break;
	default:
		hw->bus.width = ice_pcie_lnk_width_unknown;
		break;
	}

	reg = (link_status & PCIEM_LINK_STA_SPEED) + 0x13;

	switch (reg) {
	case ice_pcie_speed_2_5GT:
	case ice_pcie_speed_5_0GT:
	case ice_pcie_speed_8_0GT:
	case ice_pcie_speed_16_0GT:
		hw->bus.speed = (enum ice_pcie_bus_speed)reg;
		break;
	default:
		hw->bus.speed = ice_pcie_speed_unknown;
		break;
	}
}

/**
 * ice_init_link_events - Initialize Link Status Events mask
 * @sc: the device softc
 *
 * Initialize the Link Status Events mask to disable notification of link
 * events we don't care about in software. Also request that link status
 * events be enabled.
 */
int
ice_init_link_events(struct ice_softc *sc)
{
	struct ice_hw *hw = &sc->hw;
	enum ice_status status;
	u16 wanted_events;

	/* Set the bits for the events that we want to be notified by */
	wanted_events = (ICE_AQ_LINK_EVENT_UPDOWN |
			 ICE_AQ_LINK_EVENT_MEDIA_NA |
			 ICE_AQ_LINK_EVENT_MODULE_QUAL_FAIL);

	/* request that every event except the wanted events be masked */
	status = ice_aq_set_event_mask(hw, hw->port_info->lport, ~wanted_events, NULL);
	if (status) {
		device_printf(sc->dev,
			      "Failed to set link status event mask, err %s aq_err %s\n",
			      ice_status_str(status), ice_aq_str(hw->adminq.sq_last_status));
		return (EIO);
	}

	/* Request link info with the LSE bit set to enable link status events */
	status = ice_aq_get_link_info(hw->port_info, true, NULL, NULL);
	if (status) {
		device_printf(sc->dev,
			      "Failed to enable link status events, err %s aq_err %s\n",
			      ice_status_str(status), ice_aq_str(hw->adminq.sq_last_status));
		return (EIO);
	}

	return (0);
}

/**
 * ice_handle_mdd_event - Handle possibly malicious events
 * @sc: the device softc
 *
 * Called by the admin task if an MDD detection interrupt is triggered.
 * Identifies possibly malicious events coming from VFs. Also triggers for
 * similar incorrect behavior from the PF as well.
 */
void
ice_handle_mdd_event(struct ice_softc *sc)
{
	struct ice_hw *hw = &sc->hw;
	bool mdd_detected = false, request_reinit = false;
	device_t dev = sc->dev;
	u32 reg;

	if (!ice_testandclear_state(&sc->state, ICE_STATE_MDD_PENDING))
		return;

	reg = rd32(hw, GL_MDET_TX_TCLAN);
	if (reg & GL_MDET_TX_TCLAN_VALID_M) {
		u8 pf_num  = (reg & GL_MDET_TX_TCLAN_PF_NUM_M) >> GL_MDET_TX_TCLAN_PF_NUM_S;
		u16 vf_num = (reg & GL_MDET_TX_TCLAN_VF_NUM_M) >> GL_MDET_TX_TCLAN_VF_NUM_S;
		u8 event   = (reg & GL_MDET_TX_TCLAN_MAL_TYPE_M) >> GL_MDET_TX_TCLAN_MAL_TYPE_S;
		u16 queue  = (reg & GL_MDET_TX_TCLAN_QNUM_M) >> GL_MDET_TX_TCLAN_QNUM_S;

		device_printf(dev, "Malicious Driver Detection Tx Descriptor check event '%s' on Tx queue %u PF# %u VF# %u\n",
			      ice_mdd_tx_tclan_str(event), queue, pf_num, vf_num);

		/* Only clear this event if it matches this PF, that way other
		 * PFs can read the event and determine VF and queue number.
		 */
		if (pf_num == hw->pf_id)
			wr32(hw, GL_MDET_TX_TCLAN, 0xffffffff);

		mdd_detected = true;
	}

	/* Determine what triggered the MDD event */
	reg = rd32(hw, GL_MDET_TX_PQM);
	if (reg & GL_MDET_TX_PQM_VALID_M) {
		u8 pf_num  = (reg & GL_MDET_TX_PQM_PF_NUM_M) >> GL_MDET_TX_PQM_PF_NUM_S;
		u16 vf_num = (reg & GL_MDET_TX_PQM_VF_NUM_M) >> GL_MDET_TX_PQM_VF_NUM_S;
		u8 event   = (reg & GL_MDET_TX_PQM_MAL_TYPE_M) >> GL_MDET_TX_PQM_MAL_TYPE_S;
		u16 queue  = (reg & GL_MDET_TX_PQM_QNUM_M) >> GL_MDET_TX_PQM_QNUM_S;

		device_printf(dev, "Malicious Driver Detection Tx Quanta check event '%s' on Tx queue %u PF# %u VF# %u\n",
			      ice_mdd_tx_pqm_str(event), queue, pf_num, vf_num);

		/* Only clear this event if it matches this PF, that way other
		 * PFs can read the event and determine VF and queue number.
		 */
		if (pf_num == hw->pf_id)
			wr32(hw, GL_MDET_TX_PQM, 0xffffffff);

		mdd_detected = true;
	}

	reg = rd32(hw, GL_MDET_RX);
	if (reg & GL_MDET_RX_VALID_M) {
		u8 pf_num  = (reg & GL_MDET_RX_PF_NUM_M) >> GL_MDET_RX_PF_NUM_S;
		u16 vf_num = (reg & GL_MDET_RX_VF_NUM_M) >> GL_MDET_RX_VF_NUM_S;
		u8 event   = (reg & GL_MDET_RX_MAL_TYPE_M) >> GL_MDET_RX_MAL_TYPE_S;
		u16 queue  = (reg & GL_MDET_RX_QNUM_M) >> GL_MDET_RX_QNUM_S;

		device_printf(dev, "Malicious Driver Detection Rx event '%s' on Rx queue %u PF# %u VF# %u\n",
			      ice_mdd_rx_str(event), queue, pf_num, vf_num);

		/* Only clear this event if it matches this PF, that way other
		 * PFs can read the event and determine VF and queue number.
		 */
		if (pf_num == hw->pf_id)
			wr32(hw, GL_MDET_RX, 0xffffffff);

		mdd_detected = true;
	}

	/* Now, confirm that this event actually affects this PF, by checking
	 * the PF registers.
	 */
	if (mdd_detected) {
		reg = rd32(hw, PF_MDET_TX_TCLAN);
		if (reg & PF_MDET_TX_TCLAN_VALID_M) {
			wr32(hw, PF_MDET_TX_TCLAN, 0xffff);
			sc->soft_stats.tx_mdd_count++;
			request_reinit = true;
		}

		reg = rd32(hw, PF_MDET_TX_PQM);
		if (reg & PF_MDET_TX_PQM_VALID_M) {
			wr32(hw, PF_MDET_TX_PQM, 0xffff);
			sc->soft_stats.tx_mdd_count++;
			request_reinit = true;
		}

		reg = rd32(hw, PF_MDET_RX);
		if (reg & PF_MDET_RX_VALID_M) {
			wr32(hw, PF_MDET_RX, 0xffff);
			sc->soft_stats.rx_mdd_count++;
			request_reinit = true;
		}
	}

	/* TODO: Implement logic to detect and handle events caused by VFs. */

	/* request that the upper stack re-initialize the Tx/Rx queues */
	if (request_reinit)
		ice_request_stack_reinit(sc);

	ice_flush(hw);
}

/**
 * ice_init_dcb_setup - Initialize DCB settings for HW
 * @sc: the device softc
 *
 * This needs to be called after the fw_lldp_agent sysctl is added, since that
 * can update the device's LLDP agent status if a tunable value is set.
 *
 * Get and store the initial state of DCB settings on driver load. Print out
 * informational messages as well.
 */
void
ice_init_dcb_setup(struct ice_softc *sc)
{
	struct ice_hw *hw = &sc->hw;
	device_t dev = sc->dev;
	bool dcbx_agent_status;
	enum ice_status status;

	/* Don't do anything if DCB isn't supported */
	if (!hw->func_caps.common_cap.dcb) {
		device_printf(dev, "%s: No DCB support\n",
		    __func__);
		return;
	}

	hw->port_info->qos_cfg.dcbx_status = ice_get_dcbx_status(hw);
	if (hw->port_info->qos_cfg.dcbx_status != ICE_DCBX_STATUS_DONE &&
	    hw->port_info->qos_cfg.dcbx_status != ICE_DCBX_STATUS_IN_PROGRESS) {
		/*
		 * Start DCBX agent, but not LLDP. The return value isn't
		 * checked here because a more detailed dcbx agent status is
		 * retrieved and checked in ice_init_dcb() and below.
		 */
		status = ice_aq_start_stop_dcbx(hw, true, &dcbx_agent_status, NULL);
		if (status && hw->adminq.sq_last_status != ICE_AQ_RC_EPERM)
			device_printf(dev,
			    "start_stop_dcbx failed, err %s aq_err %s\n",
			    ice_status_str(status),
			    ice_aq_str(hw->adminq.sq_last_status));
	}

	/* This sets hw->port_info->qos_cfg.is_sw_lldp */
	status = ice_init_dcb(hw, true);

	/* If there is an error, then FW LLDP is not in a usable state */
	if (status != 0 && status != ICE_ERR_NOT_READY) {
		/* Don't print an error message if the return code from the AQ
		 * cmd performed in ice_init_dcb() is EPERM; that means the
		 * FW LLDP engine is disabled, and that is a valid state.
		 */
		if (!(status == ICE_ERR_AQ_ERROR &&
		      hw->adminq.sq_last_status == ICE_AQ_RC_EPERM)) {
			device_printf(dev, "DCB init failed, err %s aq_err %s\n",
				      ice_status_str(status),
				      ice_aq_str(hw->adminq.sq_last_status));
		}
		hw->port_info->qos_cfg.dcbx_status = ICE_DCBX_STATUS_NOT_STARTED;
	}

	switch (hw->port_info->qos_cfg.dcbx_status) {
	case ICE_DCBX_STATUS_DIS:
		ice_debug(hw, ICE_DBG_DCB, "DCBX disabled\n");
		break;
	case ICE_DCBX_STATUS_NOT_STARTED:
		ice_debug(hw, ICE_DBG_DCB, "DCBX not started\n");
		break;
	case ICE_DCBX_STATUS_MULTIPLE_PEERS:
		ice_debug(hw, ICE_DBG_DCB, "DCBX detected multiple peers\n");
		break;
	default:
		break;
	}

	/* LLDP disabled in FW */
	if (hw->port_info->qos_cfg.is_sw_lldp) {
		ice_add_rx_lldp_filter(sc);
		device_printf(dev, "Firmware LLDP agent disabled\n");
	}
}

/**
 * ice_dcb_get_tc_map - Scans config to get bitmap of enabled TCs
 * @dcbcfg: DCB configuration to examine
 *
 * Scans a TC mapping table inside dcbcfg to find traffic classes
 * enabled and @returns a bitmask of enabled TCs
 */
static u8
ice_dcb_get_tc_map(const struct ice_dcbx_cfg *dcbcfg)
{
	u8 tc_map = 0;
	int i = 0;

	switch (dcbcfg->pfc_mode) {
	case ICE_QOS_MODE_VLAN:
		/* XXX: "i" is actually "User Priority" here, not
		 * Traffic Class, but the max for both is 8, so it works
		 * out here.
		 */
		for (i = 0; i < ICE_MAX_TRAFFIC_CLASS; i++)
			tc_map |= BIT(dcbcfg->etscfg.prio_table[i]);
		break;
	default:
		/* Invalid Mode */
		tc_map = ICE_DFLT_TRAFFIC_CLASS;
		break;
	}

	return (tc_map);
}

/**
 * ice_dcb_num_tc - Count the number of TCs in a bitmap
 * @tc_map: bitmap of enabled traffic classes
 *
 * @return the number of traffic classes in
 * an 8-bit TC bitmap, or 0 if they are noncontiguous
 */
static u8
ice_dcb_num_tc(u8 tc_map)
{
	bool tc_unused = false;
	u8 ret = 0;
	int i = 0;

	ice_for_each_traffic_class(i) {
		if (tc_map & BIT(i)) {
			if (!tc_unused) {
				ret++;
			} else {
				/* Non-contiguous TCs detected */
				return (0);
			}
		} else
			tc_unused = true;
	}

	return (ret);
}

/**
 * ice_debug_print_mib_change_event - helper function to log LLDP MIB change events
 * @sc: the device private softc
 * @event: event received on a control queue
 *
 * Prints out the type and contents of an LLDP MIB change event in a DCB debug message.
 */
static void
ice_debug_print_mib_change_event(struct ice_softc *sc, struct ice_rq_event_info *event)
{
	struct ice_aqc_lldp_get_mib *params =
	    (struct ice_aqc_lldp_get_mib *)&event->desc.params.lldp_get_mib;
	u8 mib_type, bridge_type, tx_status;

	static const char* mib_type_strings[] = {
	    "Local MIB",
	    "Remote MIB",
	    "Reserved",
	    "Reserved"
	};
	static const char* bridge_type_strings[] = {
	    "Nearest Bridge",
	    "Non-TPMR Bridge",
	    "Reserved",
	    "Reserved"
	};
	static const char* tx_status_strings[] = {
	    "Port's TX active",
	    "Port's TX suspended and drained",
	    "Reserved",
	    "Port's TX suspended and drained; blocked TC pipe flushed"
	};

	mib_type = (params->type & ICE_AQ_LLDP_MIB_TYPE_M) >>
	    ICE_AQ_LLDP_MIB_TYPE_S;
	bridge_type = (params->type & ICE_AQ_LLDP_BRID_TYPE_M) >>
	    ICE_AQ_LLDP_BRID_TYPE_S;
	tx_status = (params->type & ICE_AQ_LLDP_TX_M) >>
	    ICE_AQ_LLDP_TX_S;

	ice_debug(&sc->hw, ICE_DBG_DCB, "LLDP MIB Change Event (%s, %s, %s)\n",
	    mib_type_strings[mib_type], bridge_type_strings[bridge_type],
	    tx_status_strings[tx_status]);

	/* Nothing else to report */
	if (!event->msg_buf)
		return;

	ice_debug(&sc->hw, ICE_DBG_DCB, "- %s contents:\n", mib_type_strings[mib_type]);
	ice_debug_array(&sc->hw, ICE_DBG_DCB, 16, 1, event->msg_buf,
			event->msg_len);
}

/**
 * ice_dcb_needs_reconfig - Returns true if driver needs to reconfigure
 * @sc: the device private softc
 * @old_cfg: Old DCBX configuration to compare against
 * @new_cfg: New DCBX configuration to check
 *
 * @return true if something changed in new_cfg that requires the driver
 * to do some reconfiguration.
 */
static bool
ice_dcb_needs_reconfig(struct ice_softc *sc, struct ice_dcbx_cfg *old_cfg,
    struct ice_dcbx_cfg *new_cfg)
{
	struct ice_hw *hw = &sc->hw;
	bool needs_reconfig = false;

	/* Check if ETS config has changed */
	if (memcmp(&new_cfg->etscfg, &old_cfg->etscfg,
		   sizeof(new_cfg->etscfg))) {
		/* If Priority Table has changed, then driver reconfig is needed */
		if (memcmp(&new_cfg->etscfg.prio_table,
			   &old_cfg->etscfg.prio_table,
			   sizeof(new_cfg->etscfg.prio_table))) {
			ice_debug(hw, ICE_DBG_DCB, "ETS UP2TC changed\n");
			needs_reconfig = true;
		}

		/* These are just informational */
		if (memcmp(&new_cfg->etscfg.tcbwtable,
			   &old_cfg->etscfg.tcbwtable,
			   sizeof(new_cfg->etscfg.tcbwtable)))
			ice_debug(hw, ICE_DBG_DCB, "ETS TCBW table changed\n");

		if (memcmp(&new_cfg->etscfg.tsatable,
			   &old_cfg->etscfg.tsatable,
			   sizeof(new_cfg->etscfg.tsatable)))
			ice_debug(hw, ICE_DBG_DCB, "ETS TSA table changed\n");
	}

	/* Check if PFC config has changed */
	if (memcmp(&new_cfg->pfc, &old_cfg->pfc, sizeof(new_cfg->pfc))) {
		needs_reconfig = true;
		ice_debug(hw, ICE_DBG_DCB, "PFC config changed\n");
	}

	ice_debug(hw, ICE_DBG_DCB, "%s result: %d\n", __func__, needs_reconfig);

	return (needs_reconfig);
}

/**
 * ice_stop_pf_vsi - Stop queues for PF LAN VSI
 * @sc: the device private softc
 *
 * Flushes interrupts and stops the queues associated with the PF LAN VSI.
 */
static void
ice_stop_pf_vsi(struct ice_softc *sc)
{
	/* Dissociate the Tx and Rx queues from the interrupts */
	ice_flush_txq_interrupts(&sc->pf_vsi);
	ice_flush_rxq_interrupts(&sc->pf_vsi);

	if (!ice_testandclear_state(&sc->state, ICE_STATE_DRIVER_INITIALIZED))
		return;

	/* Disable the Tx and Rx queues */
	ice_vsi_disable_tx(&sc->pf_vsi);
	ice_control_rx_queues(&sc->pf_vsi, false);
}

/**
 * ice_vsi_setup_q_map - Setup a VSI queue map
 * @vsi: the VSI being configured
 * @ctxt: VSI context structure
 */
static void
ice_vsi_setup_q_map(struct ice_vsi *vsi, struct ice_vsi_ctx *ctxt)
{
	u16 offset = 0, qmap = 0, pow = 0;
	u16 num_txq_per_tc, num_rxq_per_tc, qcount_rx;
	int i, j, k;

	if (vsi->num_tcs == 0) {
		/* at least TC0 should be enabled by default */
		vsi->num_tcs = 1;
		vsi->tc_map = 0x1;
	}

	qcount_rx = vsi->num_rx_queues;
	num_rxq_per_tc = min(qcount_rx / vsi->num_tcs, ICE_MAX_RXQS_PER_TC);
	if (!num_rxq_per_tc)
		num_rxq_per_tc = 1;

	/* Have TX queue count match RX queue count */
	num_txq_per_tc = num_rxq_per_tc;

	/* find the (rounded up) power-of-2 of qcount */
	pow = flsl(num_rxq_per_tc - 1);

	/* TC mapping is a function of the number of Rx queues assigned to the
	 * VSI for each traffic class and the offset of these queues.
	 * The first 10 bits are for queue offset for TC0, next 4 bits for no:of
	 * queues allocated to TC0. No:of queues is a power-of-2.
	 *
	 * If TC is not enabled, the queue offset is set to 0, and allocate one
	 * queue, this way, traffic for the given TC will be sent to the default
	 * queue.
	 *
	 * Setup number and offset of Rx queues for all TCs for the VSI
	 */
	ice_for_each_traffic_class(i) {
		if (!(vsi->tc_map & BIT(i))) {
			/* TC is not enabled */
			vsi->tc_info[i].qoffset = 0;
			vsi->tc_info[i].qcount_rx = 1;
			vsi->tc_info[i].qcount_tx = 1;

			ctxt->info.tc_mapping[i] = 0;
			continue;
		}

		/* TC is enabled */
		vsi->tc_info[i].qoffset = offset;
		vsi->tc_info[i].qcount_rx = num_rxq_per_tc;
		vsi->tc_info[i].qcount_tx = num_txq_per_tc;

		qmap = ((offset << ICE_AQ_VSI_TC_Q_OFFSET_S) &
			ICE_AQ_VSI_TC_Q_OFFSET_M) |
			((pow << ICE_AQ_VSI_TC_Q_NUM_S) &
			 ICE_AQ_VSI_TC_Q_NUM_M);
		ctxt->info.tc_mapping[i] = CPU_TO_LE16(qmap);

		/* Store traffic class and handle data in queue structures */
		for (j = offset, k = 0; j < offset + num_txq_per_tc; j++, k++) {
			vsi->tx_queues[j].q_handle = k;
			vsi->tx_queues[j].tc = i;
		}
		for (j = offset; j < offset + num_rxq_per_tc; j++)
			vsi->rx_queues[j].tc = i;
		
		offset += num_rxq_per_tc;
	}

	/* Rx queue mapping */
	ctxt->info.mapping_flags |= CPU_TO_LE16(ICE_AQ_VSI_Q_MAP_CONTIG);
	ctxt->info.q_mapping[0] = CPU_TO_LE16(vsi->rx_qmap[0]);
	ctxt->info.q_mapping[1] = CPU_TO_LE16(vsi->num_rx_queues);
}

/**
 * ice_pf_vsi_cfg_tc - Configure PF VSI for a given TC map
 * @sc: the device private softc
 * @tc_map: traffic class bitmap
 *
 * @pre VSI queues are stopped
 *
 * @return 0 if configuration is successful
 * @return EIO if Update VSI AQ cmd fails
 * @return ENODEV if updating Tx Scheduler fails
 */
static int
ice_pf_vsi_cfg_tc(struct ice_softc *sc, u8 tc_map)
{
	u16 max_txqs[ICE_MAX_TRAFFIC_CLASS] = { 0 };
	struct ice_vsi *vsi = &sc->pf_vsi;
	struct ice_hw *hw = &sc->hw;
	struct ice_vsi_ctx ctx = { 0 };
	device_t dev = sc->dev;
	enum ice_status status;
	u8 num_tcs = 0;
	int i = 0;

	/* Count the number of enabled Traffic Classes */
	ice_for_each_traffic_class(i)
		if (tc_map & BIT(i))
			num_tcs++;

	vsi->tc_map = tc_map;
	vsi->num_tcs = num_tcs;

	/* Set default parameters for context */
	ctx.vf_num = 0;
	ctx.info = vsi->info;

	/* Setup queue map */
	ice_vsi_setup_q_map(vsi, &ctx);

	/* Update VSI configuration in firmware (RX queues) */
	ctx.info.valid_sections = CPU_TO_LE16(ICE_AQ_VSI_PROP_RXQ_MAP_VALID);
	status = ice_update_vsi(hw, vsi->idx, &ctx, NULL);
	if (status) {
		device_printf(dev,
		    "%s: Update VSI AQ call failed, err %s aq_err %s\n",
		    __func__, ice_status_str(status),
		    ice_aq_str(hw->adminq.sq_last_status));
		return (EIO);
	}
	vsi->info = ctx.info;

	/* Use values derived in ice_vsi_setup_q_map() */
	for (i = 0; i < num_tcs; i++)
		max_txqs[i] = vsi->tc_info[i].qcount_tx;

	/* Update LAN Tx queue info in firmware */
	status = ice_cfg_vsi_lan(hw->port_info, vsi->idx, vsi->tc_map,
				 max_txqs);
	if (status) {
		device_printf(dev,
		    "%s: Failed VSI lan queue config, err %s aq_err %s\n",
		    __func__, ice_status_str(status),
		    ice_aq_str(hw->adminq.sq_last_status));
		return (ENODEV);
	}

	vsi->info.valid_sections = 0;

	return (0);
}

/**
 * ice_dcb_recfg - Reconfigure VSI with new DCB settings
 * @sc: the device private softc
 *
 * @pre All VSIs have been disabled/stopped
 * 
 * Reconfigures VSI settings based on local_dcbx_cfg.
 */
static void
ice_dcb_recfg(struct ice_softc *sc)
{
	struct ice_dcbx_cfg *dcbcfg =
	    &sc->hw.port_info->qos_cfg.local_dcbx_cfg;
	device_t dev = sc->dev;
	u8 tc_map = 0;
	int ret;

	tc_map = ice_dcb_get_tc_map(dcbcfg);

	/* If non-contiguous TCs are used, then configure
	 * the default TC instead. There's no support for
	 * non-contiguous TCs being used.
	 */
	if (ice_dcb_num_tc(tc_map) == 0) {
		tc_map = ICE_DFLT_TRAFFIC_CLASS;
		ice_set_default_local_lldp_mib(sc);
	}

	/* Reconfigure VSI queues to add/remove traffic classes */
	ret = ice_pf_vsi_cfg_tc(sc, tc_map);
	if (ret)
		device_printf(dev,
		    "Failed to configure TCs for PF VSI, err %s\n",
		    ice_err_str(ret));

}

/**
 * ice_do_dcb_reconfig - notify RDMA and reconfigure PF LAN VSI
 * @sc: the device private softc
 * 
 * @pre Determined that the DCB configuration requires a change
 *
 * Reconfigures the PF LAN VSI based on updated DCB configuration
 * found in the hw struct's/port_info's/ local dcbx configuration.
 */
static void
ice_do_dcb_reconfig(struct ice_softc *sc)
{
	struct ice_aqc_port_ets_elem port_ets = { 0 };
	struct ice_dcbx_cfg *local_dcbx_cfg;
	struct ice_hw *hw = &sc->hw;
	struct ice_port_info *pi;
	device_t dev = sc->dev;
	enum ice_status status;
	u8 tc_map;

	pi = sc->hw.port_info;
	local_dcbx_cfg = &pi->qos_cfg.local_dcbx_cfg;

	/* Set state when there's more than one TC */
	tc_map = ice_dcb_get_tc_map(local_dcbx_cfg);
	if (ice_dcb_num_tc(tc_map) > 1) {
		device_printf(dev, "Multiple traffic classes enabled\n");
		ice_set_state(&sc->state, ICE_STATE_MULTIPLE_TCS);
	} else {
		device_printf(dev, "Multiple traffic classes disabled\n");
		ice_clear_state(&sc->state, ICE_STATE_MULTIPLE_TCS);
	}

	/* Disable PF VSI since it's going to be reconfigured */
	ice_stop_pf_vsi(sc);

	/* Query ETS configuration and update SW Tx scheduler info */
	status = ice_query_port_ets(pi, &port_ets, sizeof(port_ets), NULL);
	if (status != ICE_SUCCESS) {
		device_printf(dev,
		    "Query Port ETS AQ call failed, err %s aq_err %s\n",
		    ice_status_str(status),
		    ice_aq_str(hw->adminq.sq_last_status));
		/* This won't break traffic, but QoS will not work as expected */
	}

	/* Change PF VSI configuration */
	ice_dcb_recfg(sc);

	ice_request_stack_reinit(sc);
}

/**
 * ice_handle_mib_change_event - helper function to handle LLDP MIB change events
 * @sc: the device private softc
 * @event: event received on a control queue
 *
 * Checks the updated MIB it receives and possibly reconfigures the PF LAN
 * VSI depending on what has changed. This will also print out some debug
 * information about the MIB event if ICE_DBG_DCB is enabled in the debug_mask.
 */
static void
ice_handle_mib_change_event(struct ice_softc *sc, struct ice_rq_event_info *event)
{
	struct ice_aqc_lldp_get_mib *params =
	    (struct ice_aqc_lldp_get_mib *)&event->desc.params.lldp_get_mib;
	struct ice_dcbx_cfg tmp_dcbx_cfg, *local_dcbx_cfg;
	struct ice_port_info *pi;
	device_t dev = sc->dev;
	struct ice_hw *hw = &sc->hw;
	bool needs_reconfig;
	enum ice_status status;
	u8 mib_type, bridge_type;

	ASSERT_CFG_LOCKED(sc);

	ice_debug_print_mib_change_event(sc, event);

	pi = sc->hw.port_info;

	mib_type = (params->type & ICE_AQ_LLDP_MIB_TYPE_M) >>
	    ICE_AQ_LLDP_MIB_TYPE_S;
	bridge_type = (params->type & ICE_AQ_LLDP_BRID_TYPE_M) >>
	    ICE_AQ_LLDP_BRID_TYPE_S;

	/* Ignore if event is not for Nearest Bridge */
	if (bridge_type != ICE_AQ_LLDP_BRID_TYPE_NEAREST_BRID)
		return;

	/* Check MIB Type and return if event for Remote MIB update */
	if (mib_type == ICE_AQ_LLDP_MIB_REMOTE) {
		/* Update the cached remote MIB and return */
		status = ice_aq_get_dcb_cfg(pi->hw, ICE_AQ_LLDP_MIB_REMOTE,
					 ICE_AQ_LLDP_BRID_TYPE_NEAREST_BRID,
					 &pi->qos_cfg.remote_dcbx_cfg);
		if (status)
			device_printf(dev,
			    "%s: Failed to get Remote DCB config; status %s, aq_err %s\n",
			    __func__, ice_status_str(status),
			    ice_aq_str(hw->adminq.sq_last_status));
		/* Not fatal if this fails */
		return;
	}

	/* Save line length by aliasing the local dcbx cfg */
	local_dcbx_cfg = &pi->qos_cfg.local_dcbx_cfg;
	/* Save off the old configuration and clear current config */
	tmp_dcbx_cfg = *local_dcbx_cfg;
	memset(local_dcbx_cfg, 0, sizeof(*local_dcbx_cfg));

	/* Get updated DCBX data from firmware */
	status = ice_get_dcb_cfg(pi);
	if (status) {
		device_printf(dev,
		    "%s: Failed to get Local DCB config; status %s, aq_err %s\n",
		    __func__, ice_status_str(status),
		    ice_aq_str(hw->adminq.sq_last_status));
		return;
	}

	/* No change detected in DCBX config */
	if (!memcmp(&tmp_dcbx_cfg, local_dcbx_cfg,
		    sizeof(tmp_dcbx_cfg))) {
		ice_debug(hw, ICE_DBG_DCB, "No change detected in local DCBX configuration\n");
		return;
	}

	/* Check to see if DCB needs reconfiguring */
	needs_reconfig = ice_dcb_needs_reconfig(sc, &tmp_dcbx_cfg,
	    local_dcbx_cfg);

	if (!needs_reconfig)
		return;

	/* Reconfigure */
	ice_do_dcb_reconfig(sc);
}

/**
 * ice_send_version - Send driver version to firmware
 * @sc: the device private softc
 *
 * Send the driver version to the firmware. This must be called as early as
 * possible after ice_init_hw().
 */
int
ice_send_version(struct ice_softc *sc)
{
	struct ice_driver_ver driver_version = {0};
	struct ice_hw *hw = &sc->hw;
	device_t dev = sc->dev;
	enum ice_status status;

	driver_version.major_ver = ice_major_version;
	driver_version.minor_ver = ice_minor_version;
	driver_version.build_ver = ice_patch_version;
	driver_version.subbuild_ver = ice_rc_version;

	strlcpy((char *)driver_version.driver_string, ice_driver_version,
		sizeof(driver_version.driver_string));

	status = ice_aq_send_driver_ver(hw, &driver_version, NULL);
	if (status) {
		device_printf(dev, "Unable to send driver version to firmware, err %s aq_err %s\n",
			      ice_status_str(status), ice_aq_str(hw->adminq.sq_last_status));
		return (EIO);
	}

	return (0);
}

/**
 * ice_handle_lan_overflow_event - helper function to log LAN overflow events
 * @sc: device softc
 * @event: event received on a control queue
 *
 * Prints out a message when a LAN overflow event is detected on a receive
 * queue.
 */
static void
ice_handle_lan_overflow_event(struct ice_softc *sc, struct ice_rq_event_info *event)
{
	struct ice_aqc_event_lan_overflow *params =
	    (struct ice_aqc_event_lan_overflow *)&event->desc.params.lan_overflow;
	struct ice_hw *hw = &sc->hw;

	ice_debug(hw, ICE_DBG_DCB, "LAN overflow event detected, prtdcb_ruptq=0x%08x, qtx_ctl=0x%08x\n",
		  LE32_TO_CPU(params->prtdcb_ruptq),
		  LE32_TO_CPU(params->qtx_ctl));
}

/**
 * ice_add_ethertype_to_list - Add an Ethertype filter to a filter list
 * @vsi: the VSI to target packets to
 * @list: the list to add the filter to
 * @ethertype: the Ethertype to filter on
 * @direction: The direction of the filter (Tx or Rx)
 * @action: the action to take
 *
 * Add an Ethertype filter to a filter list. Used to forward a series of
 * filters to the firmware for configuring the switch.
 *
 * Returns 0 on success, and an error code on failure.
 */
static int
ice_add_ethertype_to_list(struct ice_vsi *vsi, struct ice_list_head *list,
			  u16 ethertype, u16 direction,
			  enum ice_sw_fwd_act_type action)
{
	struct ice_fltr_list_entry *entry;

	MPASS((direction == ICE_FLTR_TX) || (direction == ICE_FLTR_RX));

	entry = (__typeof(entry))malloc(sizeof(*entry), M_ICE, M_NOWAIT|M_ZERO);
	if (!entry)
		return (ENOMEM);

	entry->fltr_info.flag = direction;
	entry->fltr_info.src_id = ICE_SRC_ID_VSI;
	entry->fltr_info.lkup_type = ICE_SW_LKUP_ETHERTYPE;
	entry->fltr_info.fltr_act = action;
	entry->fltr_info.vsi_handle = vsi->idx;
	entry->fltr_info.l_data.ethertype_mac.ethertype = ethertype;

	LIST_ADD(&entry->list_entry, list);

	return 0;
}

#define ETHERTYPE_PAUSE_FRAMES 0x8808
#define ETHERTYPE_LLDP_FRAMES 0x88cc

/**
 * ice_cfg_pf_ethertype_filters - Configure switch to drop ethertypes
 * @sc: the device private softc
 *
 * Configure the switch to drop PAUSE frames and LLDP frames transmitted from
 * the host. This prevents malicious VFs from sending these frames and being
 * able to control or configure the network.
 */
int
ice_cfg_pf_ethertype_filters(struct ice_softc *sc)
{
	struct ice_list_head ethertype_list;
	struct ice_vsi *vsi = &sc->pf_vsi;
	struct ice_hw *hw = &sc->hw;
	device_t dev = sc->dev;
	enum ice_status status;
	int err = 0;

	INIT_LIST_HEAD(&ethertype_list);

	/*
	 * Note that the switch filters will ignore the VSI index for the drop
	 * action, so we only need to program drop filters once for the main
	 * VSI.
	 */

	/* Configure switch to drop all Tx pause frames coming from any VSI. */
	if (sc->enable_tx_fc_filter) {
		err = ice_add_ethertype_to_list(vsi, &ethertype_list,
						ETHERTYPE_PAUSE_FRAMES,
						ICE_FLTR_TX, ICE_DROP_PACKET);
		if (err)
			goto free_ethertype_list;
	}

	/* Configure switch to drop LLDP frames coming from any VSI */
	if (sc->enable_tx_lldp_filter) {
		err = ice_add_ethertype_to_list(vsi, &ethertype_list,
						ETHERTYPE_LLDP_FRAMES,
						ICE_FLTR_TX, ICE_DROP_PACKET);
		if (err)
			goto free_ethertype_list;
	}

	status = ice_add_eth_mac(hw, &ethertype_list);
	if (status) {
		device_printf(dev,
			      "Failed to add Tx Ethertype filters, err %s aq_err %s\n",
			      ice_status_str(status),
			      ice_aq_str(hw->adminq.sq_last_status));
		err = (EIO);
	}

free_ethertype_list:
	ice_free_fltr_list(&ethertype_list);
	return err;
}

/**
 * ice_add_rx_lldp_filter - add ethertype filter for Rx LLDP frames
 * @sc: the device private structure
 *
 * Add a switch ethertype filter which forwards the LLDP frames to the main PF
 * VSI. Called when the fw_lldp_agent is disabled, to allow the LLDP frames to
 * be forwarded to the stack.
 */
static void
ice_add_rx_lldp_filter(struct ice_softc *sc)
{
	struct ice_list_head ethertype_list;
	struct ice_vsi *vsi = &sc->pf_vsi;
	struct ice_hw *hw = &sc->hw;
	device_t dev = sc->dev;
	enum ice_status status;
	int err;
	u16 vsi_num;

	/*
	 * If FW is new enough, use a direct AQ command to perform the filter
	 * addition.
	 */
	if (ice_fw_supports_lldp_fltr_ctrl(hw)) {
		vsi_num = ice_get_hw_vsi_num(hw, vsi->idx);
		status = ice_lldp_fltr_add_remove(hw, vsi_num, true);
		if (status) {
			device_printf(dev,
			    "Failed to add Rx LLDP filter, err %s aq_err %s\n",
			    ice_status_str(status),
			    ice_aq_str(hw->adminq.sq_last_status));
		} else
			ice_set_state(&sc->state,
			    ICE_STATE_LLDP_RX_FLTR_FROM_DRIVER);
		return;
	}

	INIT_LIST_HEAD(&ethertype_list);

	/* Forward Rx LLDP frames to the stack */
	err = ice_add_ethertype_to_list(vsi, &ethertype_list,
					ETHERTYPE_LLDP_FRAMES,
					ICE_FLTR_RX, ICE_FWD_TO_VSI);
	if (err) {
		device_printf(dev,
			      "Failed to add Rx LLDP filter, err %s\n",
			      ice_err_str(err));
		goto free_ethertype_list;
	}

	status = ice_add_eth_mac(hw, &ethertype_list);
	if (status && status != ICE_ERR_ALREADY_EXISTS) {
		device_printf(dev,
			      "Failed to add Rx LLDP filter, err %s aq_err %s\n",
			      ice_status_str(status),
			      ice_aq_str(hw->adminq.sq_last_status));
	} else {
		/*
		 * If status == ICE_ERR_ALREADY_EXISTS, we won't treat an
		 * already existing filter as an error case.
		 */
		ice_set_state(&sc->state, ICE_STATE_LLDP_RX_FLTR_FROM_DRIVER);
	}

free_ethertype_list:
	ice_free_fltr_list(&ethertype_list);
}

/**
 * ice_del_rx_lldp_filter - Remove ethertype filter for Rx LLDP frames
 * @sc: the device private structure
 *
 * Remove the switch filter forwarding LLDP frames to the main PF VSI, called
 * when the firmware LLDP agent is enabled, to stop routing LLDP frames to the
 * stack.
 */
static void
ice_del_rx_lldp_filter(struct ice_softc *sc)
{
	struct ice_list_head ethertype_list;
	struct ice_vsi *vsi = &sc->pf_vsi;
	struct ice_hw *hw = &sc->hw;
	device_t dev = sc->dev;
	enum ice_status status;
	int err;
	u16 vsi_num;

	/*
	 * Only in the scenario where the driver added the filter during
	 * this session (while the driver was loaded) would we be able to
	 * delete this filter.
	 */
	if (!ice_test_state(&sc->state, ICE_STATE_LLDP_RX_FLTR_FROM_DRIVER))
		return;

	/*
	 * If FW is new enough, use a direct AQ command to perform the filter
	 * removal.
	 */
	if (ice_fw_supports_lldp_fltr_ctrl(hw)) {
		vsi_num = ice_get_hw_vsi_num(hw, vsi->idx);
		status = ice_lldp_fltr_add_remove(hw, vsi_num, false);
		if (status) {
			device_printf(dev,
			    "Failed to remove Rx LLDP filter, err %s aq_err %s\n",
			    ice_status_str(status),
			    ice_aq_str(hw->adminq.sq_last_status));
		}
		return;
	}

	INIT_LIST_HEAD(&ethertype_list);

	/* Remove filter forwarding Rx LLDP frames to the stack */
	err = ice_add_ethertype_to_list(vsi, &ethertype_list,
					ETHERTYPE_LLDP_FRAMES,
					ICE_FLTR_RX, ICE_FWD_TO_VSI);
	if (err) {
		device_printf(dev,
			      "Failed to remove Rx LLDP filter, err %s\n",
			      ice_err_str(err));
		goto free_ethertype_list;
	}

	status = ice_remove_eth_mac(hw, &ethertype_list);
	if (status == ICE_ERR_DOES_NOT_EXIST) {
		; /* Don't complain if we try to remove a filter that doesn't exist */
	} else if (status) {
		device_printf(dev,
			      "Failed to remove Rx LLDP filter, err %s aq_err %s\n",
			      ice_status_str(status),
			      ice_aq_str(hw->adminq.sq_last_status));
	}

free_ethertype_list:
	ice_free_fltr_list(&ethertype_list);
}

/**
 * ice_init_link_configuration -- Setup link in different ways depending
 * on whether media is available or not.
 * @sc: device private structure
 *
 * Called at the end of the attach process to either set default link
 * parameters if there is media available, or force HW link down and
 * set a state bit if there is no media.
 */
void
ice_init_link_configuration(struct ice_softc *sc)
{
	struct ice_port_info *pi = sc->hw.port_info;
	struct ice_hw *hw = &sc->hw;
	device_t dev = sc->dev;
	enum ice_status status;

	pi->phy.get_link_info = true;
	status = ice_get_link_status(pi, &sc->link_up);
	if (status != ICE_SUCCESS) {
		device_printf(dev,
		    "%s: ice_get_link_status failed; status %s, aq_err %s\n",
		    __func__, ice_status_str(status),
		    ice_aq_str(hw->adminq.sq_last_status));
		return;
	}

	if (pi->phy.link_info.link_info & ICE_AQ_MEDIA_AVAILABLE) {
		ice_clear_state(&sc->state, ICE_STATE_NO_MEDIA);
		/* Apply default link settings */
		ice_apply_saved_phy_cfg(sc, ICE_APPLY_LS_FEC_FC);
	} else {
		 /* Set link down, and poll for media available in timer. This prevents the
		  * driver from receiving spurious link-related events.
		  */
		ice_set_state(&sc->state, ICE_STATE_NO_MEDIA);
		status = ice_aq_set_link_restart_an(pi, false, NULL);
		if (status != ICE_SUCCESS)
			device_printf(dev,
			    "%s: ice_aq_set_link_restart_an: status %s, aq_err %s\n",
			    __func__, ice_status_str(status),
			    ice_aq_str(hw->adminq.sq_last_status));
	}
}

/**
 * ice_apply_saved_phy_req_to_cfg -- Write saved user PHY settings to cfg data
 * @sc: device private structure
 * @cfg: new PHY config data to be modified
 *
 * Applies user settings for advertised speeds to the PHY type fields in the
 * supplied PHY config struct. It uses the data from pcaps to check if the
 * saved settings are invalid and uses the pcaps data instead if they are
 * invalid.
 */
static int
ice_apply_saved_phy_req_to_cfg(struct ice_softc *sc,
			       struct ice_aqc_set_phy_cfg_data *cfg)
{
	struct ice_phy_data phy_data = { 0 };
	struct ice_port_info *pi = sc->hw.port_info;
	u64 phy_low = 0, phy_high = 0;
	u16 link_speeds;
	int ret;

	link_speeds = pi->phy.curr_user_speed_req;

	if (ice_is_bit_set(sc->feat_en, ICE_FEATURE_LINK_MGMT_VER_2)) {
		memset(&phy_data, 0, sizeof(phy_data));
		phy_data.report_mode = ICE_AQC_REPORT_DFLT_CFG;
		phy_data.user_speeds_orig = link_speeds;
		ret = ice_intersect_phy_types_and_speeds(sc, &phy_data);
		if (ret != 0) {
			/* Error message already printed within function */
			return (ret);
		}
		phy_low = phy_data.phy_low_intr;
		phy_high = phy_data.phy_high_intr;

		if (link_speeds == 0 || phy_data.user_speeds_intr)
			goto finalize_link_speed;
		if (ice_is_bit_set(sc->feat_en, ICE_FEATURE_LENIENT_LINK_MODE)) {
			memset(&phy_data, 0, sizeof(phy_data));
			phy_data.report_mode = ICE_AQC_REPORT_TOPO_CAP_NO_MEDIA;
			phy_data.user_speeds_orig = link_speeds;
			ret = ice_intersect_phy_types_and_speeds(sc, &phy_data);
			if (ret != 0) {
				/* Error message already printed within function */
				return (ret);
			}
			phy_low = phy_data.phy_low_intr;
			phy_high = phy_data.phy_high_intr;

			if (!phy_data.user_speeds_intr) {
				phy_low = phy_data.phy_low_orig;
				phy_high = phy_data.phy_high_orig;
			}
			goto finalize_link_speed;
		}
		/* If we're here, then it means the benefits of Version 2
		 * link management aren't utilized.  We fall through to
		 * handling Strict Link Mode the same as Version 1 link
		 * management.
		 */
	}

	memset(&phy_data, 0, sizeof(phy_data));
	if ((link_speeds == 0) &&
	    (sc->ldo_tlv.phy_type_low || sc->ldo_tlv.phy_type_high))
		phy_data.report_mode = ICE_AQC_REPORT_TOPO_CAP_NO_MEDIA;
	else
		phy_data.report_mode = ICE_AQC_REPORT_TOPO_CAP_MEDIA;
	phy_data.user_speeds_orig = link_speeds;
	ret = ice_intersect_phy_types_and_speeds(sc, &phy_data);
	if (ret != 0) {
		/* Error message already printed within function */
		return (ret);
	}
	phy_low = phy_data.phy_low_intr;
	phy_high = phy_data.phy_high_intr;

	if (!ice_is_bit_set(sc->feat_en, ICE_FEATURE_LENIENT_LINK_MODE)) {
		if (phy_low == 0 && phy_high == 0) {
			device_printf(sc->dev,
			    "The selected speed is not supported by the current media. Please select a link speed that is supported by the current media.\n");
			return (EINVAL);
		}
	} else {
		if (link_speeds == 0) {
			if (sc->ldo_tlv.phy_type_low & phy_low ||
			    sc->ldo_tlv.phy_type_high & phy_high) {
				phy_low &= sc->ldo_tlv.phy_type_low;
				phy_high &= sc->ldo_tlv.phy_type_high;
			}
		} else if (phy_low == 0 && phy_high == 0) {
			memset(&phy_data, 0, sizeof(phy_data));
			phy_data.report_mode = ICE_AQC_REPORT_TOPO_CAP_NO_MEDIA;
			phy_data.user_speeds_orig = link_speeds;
			ret = ice_intersect_phy_types_and_speeds(sc, &phy_data);
			if (ret != 0) {
				/* Error message already printed within function */
				return (ret);
			}
			phy_low = phy_data.phy_low_intr;
			phy_high = phy_data.phy_high_intr;

			if (!phy_data.user_speeds_intr) {
				phy_low = phy_data.phy_low_orig;
				phy_high = phy_data.phy_high_orig;
			}
		}
	}

finalize_link_speed:

	/* Cache new user settings for speeds */
	pi->phy.curr_user_speed_req = phy_data.user_speeds_intr;
	cfg->phy_type_low = htole64(phy_low);
	cfg->phy_type_high = htole64(phy_high);

	return (ret);
}

/**
 * ice_apply_saved_fec_req_to_cfg -- Write saved user FEC mode to cfg data
 * @sc: device private structure
 * @cfg: new PHY config data to be modified
 *
 * Applies user setting for FEC mode to PHY config struct. It uses the data
 * from pcaps to check if the saved settings are invalid and uses the pcaps
 * data instead if they are invalid.
 */
static int
ice_apply_saved_fec_req_to_cfg(struct ice_softc *sc,
			       struct ice_aqc_set_phy_cfg_data *cfg)
{
	struct ice_port_info *pi = sc->hw.port_info;
	enum ice_status status;

	cfg->caps &= ~ICE_AQC_PHY_EN_AUTO_FEC;
	status = ice_cfg_phy_fec(pi, cfg, pi->phy.curr_user_fec_req);
	if (status)
		return (EIO);

	return (0);
}

/**
 * ice_apply_saved_fc_req_to_cfg -- Write saved user flow control mode to cfg data
 * @pi: port info struct
 * @cfg: new PHY config data to be modified
 *
 * Applies user setting for flow control mode to PHY config struct. There are
 * no invalid flow control mode settings; if there are, then this function
 * treats them like "ICE_FC_NONE".
 */
static void
ice_apply_saved_fc_req_to_cfg(struct ice_port_info *pi,
			      struct ice_aqc_set_phy_cfg_data *cfg)
{
	cfg->caps &= ~(ICE_AQ_PHY_ENA_TX_PAUSE_ABILITY |
		       ICE_AQ_PHY_ENA_RX_PAUSE_ABILITY);

	switch (pi->phy.curr_user_fc_req) {
	case ICE_FC_FULL:
		cfg->caps |= ICE_AQ_PHY_ENA_TX_PAUSE_ABILITY |
			     ICE_AQ_PHY_ENA_RX_PAUSE_ABILITY;
		break;
	case ICE_FC_RX_PAUSE:
		cfg->caps |= ICE_AQ_PHY_ENA_RX_PAUSE_ABILITY;
		break;
	case ICE_FC_TX_PAUSE:
		cfg->caps |= ICE_AQ_PHY_ENA_TX_PAUSE_ABILITY;
		break;
	default:
		/* ICE_FC_NONE */
		break;
	}
}

/**
 * ice_apply_saved_phy_cfg -- Re-apply user PHY config settings
 * @sc: device private structure
 * @settings: which settings to apply
 *
 * Applies user settings for advertised speeds, FEC mode, and flow
 * control mode to a PHY config struct; it uses the data from pcaps
 * to check if the saved settings are invalid and uses the pcaps
 * data instead if they are invalid.
 *
 * For things like sysctls where only one setting needs to be
 * updated, the bitmap allows the caller to specify which setting
 * to update.
 */
int
ice_apply_saved_phy_cfg(struct ice_softc *sc, u8 settings)
{
	struct ice_aqc_set_phy_cfg_data cfg = { 0 };
	struct ice_port_info *pi = sc->hw.port_info;
	struct ice_aqc_get_phy_caps_data pcaps = { 0 };
	struct ice_hw *hw = &sc->hw;
	device_t dev = sc->dev;
	u64 phy_low, phy_high;
	enum ice_status status;
	enum ice_fec_mode dflt_fec_mode;
	u16 dflt_user_speed;

	if (!settings || settings > ICE_APPLY_LS_FEC_FC) {
		ice_debug(hw, ICE_DBG_LINK, "Settings out-of-bounds: %u\n",
		    settings);
	}

	status = ice_aq_get_phy_caps(pi, false, ICE_AQC_REPORT_ACTIVE_CFG,
				     &pcaps, NULL);
	if (status != ICE_SUCCESS) {
		device_printf(dev,
		    "%s: ice_aq_get_phy_caps (ACTIVE) failed; status %s, aq_err %s\n",
		    __func__, ice_status_str(status),
		    ice_aq_str(hw->adminq.sq_last_status));
		return (EIO);
	}

	phy_low = le64toh(pcaps.phy_type_low);
	phy_high = le64toh(pcaps.phy_type_high);

	/* Save off initial config parameters */
	dflt_user_speed = ice_aq_phy_types_to_link_speeds(phy_low, phy_high);
	dflt_fec_mode = ice_caps_to_fec_mode(pcaps.caps, pcaps.link_fec_options);

	/* Setup new PHY config */
	ice_copy_phy_caps_to_cfg(pi, &pcaps, &cfg);

	/* On error, restore active configuration values */
	if ((settings & ICE_APPLY_LS) &&
	    ice_apply_saved_phy_req_to_cfg(sc, &cfg)) {
		pi->phy.curr_user_speed_req = dflt_user_speed;
		cfg.phy_type_low = pcaps.phy_type_low;
		cfg.phy_type_high = pcaps.phy_type_high;
	}
	if ((settings & ICE_APPLY_FEC) &&
	    ice_apply_saved_fec_req_to_cfg(sc, &cfg)) {
		pi->phy.curr_user_fec_req = dflt_fec_mode;
	}
	if (settings & ICE_APPLY_FC) {
		/* No real error indicators for this process,
		 * so we'll just have to assume it works. */
		ice_apply_saved_fc_req_to_cfg(pi, &cfg);
	}

	/* Enable link and re-negotiate it */
	cfg.caps |= ICE_AQ_PHY_ENA_AUTO_LINK_UPDT | ICE_AQ_PHY_ENA_LINK;

	status = ice_aq_set_phy_cfg(hw, pi, &cfg, NULL);
	if (status != ICE_SUCCESS) {
		/* Don't indicate failure if there's no media in the port.
		 * The settings have been saved and will apply when media
		 * is inserted.
		 */
		if ((status == ICE_ERR_AQ_ERROR) &&
		    (hw->adminq.sq_last_status == ICE_AQ_RC_EBUSY)) {
			device_printf(dev,
			    "%s: Setting will be applied when media is inserted\n",
			    __func__);
			return (0);
		} else {
			device_printf(dev,
			    "%s: ice_aq_set_phy_cfg failed; status %s, aq_err %s\n",
			    __func__, ice_status_str(status),
			    ice_aq_str(hw->adminq.sq_last_status));
			return (EIO);
		}
	}

	return (0);
}

/**
 * ice_print_ldo_tlv - Print out LDO TLV information
 * @sc: device private structure
 * @tlv: LDO TLV information from the adapter NVM
 *
 * Dump out the information in tlv to the kernel message buffer; intended for
 * debugging purposes.
 */
static void
ice_print_ldo_tlv(struct ice_softc *sc, struct ice_link_default_override_tlv *tlv)
{
	device_t dev = sc->dev;

	device_printf(dev, "TLV: -options     0x%02x\n", tlv->options);
	device_printf(dev, "     -phy_config  0x%02x\n", tlv->phy_config);
	device_printf(dev, "     -fec_options 0x%02x\n", tlv->fec_options);
	device_printf(dev, "     -phy_high    0x%016llx\n",
	    (unsigned long long)tlv->phy_type_high);
	device_printf(dev, "     -phy_low     0x%016llx\n",
	    (unsigned long long)tlv->phy_type_low);
}

/**
 * ice_set_link_management_mode -- Strict or lenient link management
 * @sc: device private structure
 *
 * Some NVMs give the adapter the option to advertise a superset of link
 * configurations.  This checks to see if that option is enabled.
 * Further, the NVM could also provide a specific set of configurations
 * to try; these are cached in the driver's private structure if they
 * are available.
 */
void
ice_set_link_management_mode(struct ice_softc *sc)
{
	struct ice_port_info *pi = sc->hw.port_info;
	device_t dev = sc->dev;
	struct ice_link_default_override_tlv tlv = { 0 };
	enum ice_status status;

	/* Port must be in strict mode if FW version is below a certain
	 * version. (i.e. Don't set lenient mode features)
	 */
	if (!(ice_fw_supports_link_override(&sc->hw)))
		return;

	status = ice_get_link_default_override(&tlv, pi);
	if (status != ICE_SUCCESS) {
		device_printf(dev,
		    "%s: ice_get_link_default_override failed; status %s, aq_err %s\n",
		    __func__, ice_status_str(status),
		    ice_aq_str(sc->hw.adminq.sq_last_status));
		return;
	}

	if (sc->hw.debug_mask & ICE_DBG_LINK)
		ice_print_ldo_tlv(sc, &tlv);

	/* Set lenient link mode */
	if (ice_is_bit_set(sc->feat_cap, ICE_FEATURE_LENIENT_LINK_MODE) &&
	    (!(tlv.options & ICE_LINK_OVERRIDE_STRICT_MODE)))
		ice_set_bit(ICE_FEATURE_LENIENT_LINK_MODE, sc->feat_en);

	/* FW supports reporting a default configuration */
	if (ice_is_bit_set(sc->feat_cap, ICE_FEATURE_LINK_MGMT_VER_2) &&
	    ice_fw_supports_report_dflt_cfg(&sc->hw)) {
		ice_set_bit(ICE_FEATURE_LINK_MGMT_VER_2, sc->feat_en);
		/* Knowing we're at a high enough firmware revision to
		 * support this link management configuration, we don't
		 * need to check/support earlier versions.
		 */
		return;
	}

	/* Default overrides only work if in lenient link mode */
	if (ice_is_bit_set(sc->feat_cap, ICE_FEATURE_LINK_MGMT_VER_1) &&
	    ice_is_bit_set(sc->feat_en, ICE_FEATURE_LENIENT_LINK_MODE) &&
	    (tlv.options & ICE_LINK_OVERRIDE_EN))
		ice_set_bit(ICE_FEATURE_LINK_MGMT_VER_1, sc->feat_en);

	/* Cache the LDO TLV structure in the driver, since it
	 * won't change during the driver's lifetime.
	 */
	sc->ldo_tlv = tlv;
}

/**
 * ice_init_saved_phy_cfg -- Set cached user PHY cfg settings with NVM defaults
 * @sc: device private structure
 *
 * This should be called before the tunables for these link settings
 * (e.g. advertise_speed) are added -- so that these defaults don't overwrite
 * the cached values that the sysctl handlers will write.
 *
 * This also needs to be called before ice_init_link_configuration, to ensure
 * that there are sane values that can be written if there is media available
 * in the port.
 */
void
ice_init_saved_phy_cfg(struct ice_softc *sc)
{
	struct ice_port_info *pi = sc->hw.port_info;
	struct ice_aqc_get_phy_caps_data pcaps = { 0 };
	struct ice_hw *hw = &sc->hw;
	device_t dev = sc->dev;
	enum ice_status status;
	u64 phy_low, phy_high;
	u8 report_mode = ICE_AQC_REPORT_TOPO_CAP_MEDIA;

	if (ice_is_bit_set(sc->feat_en, ICE_FEATURE_LINK_MGMT_VER_2))
		report_mode = ICE_AQC_REPORT_DFLT_CFG;
	status = ice_aq_get_phy_caps(pi, false, report_mode, &pcaps, NULL);
	if (status != ICE_SUCCESS) {
		device_printf(dev,
		    "%s: ice_aq_get_phy_caps (%s) failed; status %s, aq_err %s\n",
		    __func__,
		    report_mode == ICE_AQC_REPORT_DFLT_CFG ? "DFLT" : "w/MEDIA",
		    ice_status_str(status),
		    ice_aq_str(hw->adminq.sq_last_status));
		return;
	}

	phy_low = le64toh(pcaps.phy_type_low);
	phy_high = le64toh(pcaps.phy_type_high);

	/* Save off initial config parameters */
	pi->phy.curr_user_speed_req =
	   ice_aq_phy_types_to_link_speeds(phy_low, phy_high);
	pi->phy.curr_user_fec_req = ice_caps_to_fec_mode(pcaps.caps,
	    pcaps.link_fec_options);
	pi->phy.curr_user_fc_req = ice_caps_to_fc_mode(pcaps.caps);
}

/**
 * ice_module_init - Driver callback to handle module load
 *
 * Callback for handling module load events. This function should initialize
 * any data structures that are used for the life of the device driver.
 */
static int
ice_module_init(void)
{
	return (0);
}

/**
 * ice_module_exit - Driver callback to handle module exit
 *
 * Callback for handling module unload events. This function should release
 * any resources initialized during ice_module_init.
 *
 * If this function returns non-zero, the module will not be unloaded. It
 * should only return such a value if the module cannot be unloaded at all,
 * such as due to outstanding memory references that cannot be revoked.
 */
static int
ice_module_exit(void)
{
	return (0);
}

/**
 * ice_module_event_handler - Callback for module events
 * @mod: unused module_t parameter
 * @what: the event requested
 * @arg: unused event argument
 *
 * Callback used to handle module events from the stack. Used to allow the
 * driver to define custom behavior that should happen at module load and
 * unload.
 */
int
ice_module_event_handler(module_t __unused mod, int what, void __unused *arg)
{
	switch (what) {
	case MOD_LOAD:
		return ice_module_init();
	case MOD_UNLOAD:
		return ice_module_exit();
	default:
		/* TODO: do we need to handle MOD_QUIESCE and MOD_SHUTDOWN? */
		return (EOPNOTSUPP);
	}
}

/**
 * ice_handle_nvm_access_ioctl - Handle an NVM access ioctl request
 * @sc: the device private softc
 * @ifd: ifdrv ioctl request pointer
 */
int
ice_handle_nvm_access_ioctl(struct ice_softc *sc, struct ifdrv *ifd)
{
	union ice_nvm_access_data *data;
	struct ice_nvm_access_cmd *cmd;
	size_t ifd_len = ifd->ifd_len, malloc_len;
	struct ice_hw *hw = &sc->hw;
	device_t dev = sc->dev;
	enum ice_status status;
	u8 *nvm_buffer;
	int err;

	/*
	 * ifioctl forwards SIOCxDRVSPEC to iflib without performing
	 * a privilege check. In turn, iflib forwards the ioctl to the driver
	 * without performing a privilege check. Perform one here to ensure
	 * that non-privileged threads cannot access this interface.
	 */
	err = priv_check(curthread, PRIV_DRIVER);
	if (err)
		return (err);

	if (ifd_len < sizeof(struct ice_nvm_access_cmd)) {
		device_printf(dev, "%s: ifdrv length is too small. Got %zu, but expected %zu\n",
			      __func__, ifd_len, sizeof(struct ice_nvm_access_cmd));
		return (EINVAL);
	}

	if (ifd->ifd_data == NULL) {
		device_printf(dev, "%s: ifd data buffer not present.\n",
			      __func__);
		return (EINVAL);
	}

	/*
	 * If everything works correctly, ice_handle_nvm_access should not
	 * modify data past the size of the ioctl length. However, it could
	 * lead to memory corruption if it did. Make sure to allocate at least
	 * enough space for the command and data regardless. This
	 * ensures that any access to the data union will not access invalid
	 * memory.
	 */
	malloc_len = max(ifd_len, sizeof(*data) + sizeof(*cmd));

	nvm_buffer = (u8 *)malloc(malloc_len, M_ICE, M_ZERO | M_WAITOK);
	if (!nvm_buffer)
		return (ENOMEM);

	/* Copy the NVM access command and data in from user space */
	/* coverity[tainted_data_argument] */
	err = copyin(ifd->ifd_data, nvm_buffer, ifd_len);
	if (err) {
		device_printf(dev, "%s: Copying request from user space failed, err %s\n",
			      __func__, ice_err_str(err));
		goto cleanup_free_nvm_buffer;
	}

	/*
	 * The NVM command structure is immediately followed by data which
	 * varies in size based on the command.
	 */
	cmd = (struct ice_nvm_access_cmd *)nvm_buffer;
	data = (union ice_nvm_access_data *)(nvm_buffer + sizeof(struct ice_nvm_access_cmd));

	/* Handle the NVM access request */
	status = ice_handle_nvm_access(hw, cmd, data);
	if (status)
		ice_debug(hw, ICE_DBG_NVM,
			  "NVM access request failed, err %s\n",
			  ice_status_str(status));

	/* Copy the possibly modified contents of the handled request out */
	err = copyout(nvm_buffer, ifd->ifd_data, ifd_len);
	if (err) {
		device_printf(dev, "%s: Copying response back to user space failed, err %s\n",
			      __func__, ice_err_str(err));
		goto cleanup_free_nvm_buffer;
	}

	/* Convert private status to an error code for proper ioctl response */
	switch (status) {
	case ICE_SUCCESS:
		err = (0);
		break;
	case ICE_ERR_NO_MEMORY:
		err = (ENOMEM);
		break;
	case ICE_ERR_OUT_OF_RANGE:
		err = (ENOTTY);
		break;
	case ICE_ERR_PARAM:
	default:
		err = (EINVAL);
		break;
	}

cleanup_free_nvm_buffer:
	free(nvm_buffer, M_ICE);
	return err;
}

/**
 * ice_read_sff_eeprom - Read data from SFF eeprom
 * @sc: device softc
 * @dev_addr: I2C device address (typically 0xA0 or 0xA2)
 * @offset: offset into the eeprom
 * @data: pointer to data buffer to store read data in
 * @length: length to read; max length is 16
 *
 * Read from the SFF eeprom in the module for this PF's port. For more details
 * on the contents of an SFF eeprom, refer to SFF-8724 (SFP), SFF-8636 (QSFP),
 * and SFF-8024 (both).
 */
int
ice_read_sff_eeprom(struct ice_softc *sc, u16 dev_addr, u16 offset, u8* data, u16 length)
{
	struct ice_hw *hw = &sc->hw;
	int ret = 0, retries = 0;
	enum ice_status status;

	if (length > 16)
		return (EINVAL);

	if (ice_test_state(&sc->state, ICE_STATE_RECOVERY_MODE))
		return (ENOSYS);

	if (ice_test_state(&sc->state, ICE_STATE_NO_MEDIA))
		return (ENXIO);

	do {
		status = ice_aq_sff_eeprom(hw, 0, dev_addr,
					   offset, 0, 0, data, length,
					   false, NULL);
		if (!status) {
			ret = 0;
			break;
		}
		if (status == ICE_ERR_AQ_ERROR &&
		    hw->adminq.sq_last_status == ICE_AQ_RC_EBUSY) {
			ret = EBUSY;
			continue;
		}
		if (status == ICE_ERR_AQ_ERROR &&
		    hw->adminq.sq_last_status == ICE_AQ_RC_EACCES) {
			/* FW says I2C access isn't supported */
			ret = EACCES;
			break;
		}
		if (status == ICE_ERR_AQ_ERROR &&
		    hw->adminq.sq_last_status == ICE_AQ_RC_EPERM) {
			device_printf(sc->dev,
				  "%s: Module pointer location specified in command does not permit the required operation.\n",
				  __func__);
			ret = EPERM;
			break;
		} else {
			device_printf(sc->dev,
				  "%s: Error reading I2C data: err %s aq_err %s\n",
				  __func__, ice_status_str(status),
				  ice_aq_str(hw->adminq.sq_last_status));
			ret = EIO;
			break;
		}
	} while (retries++ < ICE_I2C_MAX_RETRIES);

	if (ret == EBUSY)
		device_printf(sc->dev,
			  "%s: Error reading I2C data after %d retries\n",
			  __func__, ICE_I2C_MAX_RETRIES);

	return (ret);
}

/**
 * ice_handle_i2c_req - Driver independent I2C request handler
 * @sc: device softc
 * @req: The I2C parameters to use
 *
 * Read from the port's I2C eeprom using the parameters from the ioctl.
 */
int
ice_handle_i2c_req(struct ice_softc *sc, struct ifi2creq *req)
{
	return ice_read_sff_eeprom(sc, req->dev_addr, req->offset, req->data, req->len);
}

/**
 * ice_sysctl_read_i2c_diag_data - Read some module diagnostic data via i2c
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: unused
 * @req: sysctl request pointer
 *
 * Read 8 bytes of diagnostic data from the SFF eeprom in the (Q)SFP module
 * inserted into the port.
 *
 *             | SFP A2  | QSFP Lower Page
 * ------------|---------|----------------
 * Temperature | 96-97	 | 22-23
 * Vcc         | 98-99   | 26-27
 * TX power    | 102-103 | 34-35..40-41
 * RX power    | 104-105 | 50-51..56-57
 */
static int
ice_sysctl_read_i2c_diag_data(SYSCTL_HANDLER_ARGS)
{
	struct ice_softc *sc = (struct ice_softc *)arg1;
	device_t dev = sc->dev;
	struct sbuf *sbuf;
	int ret;
	u8 data[16];

	UNREFERENCED_PARAMETER(arg2);
	UNREFERENCED_PARAMETER(oidp);

	if (ice_driver_is_detaching(sc))
		return (ESHUTDOWN);

	if (req->oldptr == NULL) {
		ret = SYSCTL_OUT(req, 0, 128);
		return (ret);
	}

	ret = ice_read_sff_eeprom(sc, 0xA0, 0, data, 1);
	if (ret)
		return (ret);

	/* 0x3 for SFP; 0xD/0x11 for QSFP+/QSFP28 */
	if (data[0] == 0x3) {
		/*
		 * Check for:
		 * - Internally calibrated data
		 * - Diagnostic monitoring is implemented
		 */
		ice_read_sff_eeprom(sc, 0xA0, 92, data, 1);
		if (!(data[0] & 0x60)) {
			device_printf(dev, "Module doesn't support diagnostics: 0xA0[92] = %02X\n", data[0]);
			return (ENODEV);
		}

		sbuf = sbuf_new_for_sysctl(NULL, NULL, 128, req);

		ice_read_sff_eeprom(sc, 0xA2, 96, data, 4);
		for (int i = 0; i < 4; i++)
			sbuf_printf(sbuf, "%02X ", data[i]);

		ice_read_sff_eeprom(sc, 0xA2, 102, data, 4);
		for (int i = 0; i < 4; i++)
			sbuf_printf(sbuf, "%02X ", data[i]);
	} else if (data[0] == 0xD || data[0] == 0x11) {
		/*
		 * QSFP+ modules are always internally calibrated, and must indicate
		 * what types of diagnostic monitoring are implemented
		 */
		sbuf = sbuf_new_for_sysctl(NULL, NULL, 128, req);

		ice_read_sff_eeprom(sc, 0xA0, 22, data, 2);
		for (int i = 0; i < 2; i++)
			sbuf_printf(sbuf, "%02X ", data[i]);

		ice_read_sff_eeprom(sc, 0xA0, 26, data, 2);
		for (int i = 0; i < 2; i++)
			sbuf_printf(sbuf, "%02X ", data[i]);

		ice_read_sff_eeprom(sc, 0xA0, 34, data, 2);
		for (int i = 0; i < 2; i++)
			sbuf_printf(sbuf, "%02X ", data[i]);

		ice_read_sff_eeprom(sc, 0xA0, 50, data, 2);
		for (int i = 0; i < 2; i++)
			sbuf_printf(sbuf, "%02X ", data[i]);
	} else {
		device_printf(dev, "Module is not SFP/SFP+/SFP28/QSFP+ (%02X)\n", data[0]);
		return (ENODEV);
	}

	sbuf_finish(sbuf);
	sbuf_delete(sbuf);

	return (0);
}

/**
 * ice_alloc_intr_tracking - Setup interrupt tracking structures
 * @sc: device softc structure
 *
 * Sets up the resource manager for keeping track of interrupt allocations,
 * and initializes the tracking maps for the PF's interrupt allocations.
 *
 * Unlike the scheme for queues, this is done in one step since both the
 * manager and the maps both have the same lifetime.
 *
 * @returns 0 on success, or an error code on failure.
 */
int
ice_alloc_intr_tracking(struct ice_softc *sc)
{
	struct ice_hw *hw = &sc->hw;
	device_t dev = sc->dev;
	int err;

	/* Initialize the interrupt allocation manager */
	err = ice_resmgr_init_contig_only(&sc->imgr,
	    hw->func_caps.common_cap.num_msix_vectors);
	if (err) {
		device_printf(dev, "Unable to initialize PF interrupt manager: %s\n",
			      ice_err_str(err));
		return (err);
	}

	/* Allocate PF interrupt mapping storage */
	if (!(sc->pf_imap =
	      (u16 *)malloc(sizeof(u16) * hw->func_caps.common_cap.num_msix_vectors,
	      M_ICE, M_NOWAIT))) {
		device_printf(dev, "Unable to allocate PF imap memory\n");
		err = ENOMEM;
		goto free_imgr;
	}
	for (u32 i = 0; i < hw->func_caps.common_cap.num_msix_vectors; i++) {
		sc->pf_imap[i] = ICE_INVALID_RES_IDX;
	}

	return (0);

free_imgr:
	ice_resmgr_destroy(&sc->imgr);
	return (err);
}

/**
 * ice_free_intr_tracking - Free PF interrupt tracking structures
 * @sc: device softc structure
 *
 * Frees the interrupt resource allocation manager and the PF's owned maps.
 *
 * VF maps are released when the owning VF's are destroyed, which should always
 * happen before this function is called.
 */
void
ice_free_intr_tracking(struct ice_softc *sc)
{
	if (sc->pf_imap) {
		ice_resmgr_release_map(&sc->imgr, sc->pf_imap,
				       sc->lan_vectors);
		free(sc->pf_imap, M_ICE);
		sc->pf_imap = NULL;
	}

	ice_resmgr_destroy(&sc->imgr);
}

/**
 * ice_apply_supported_speed_filter - Mask off unsupported speeds
 * @report_speeds: bit-field for the desired link speeds
 * @mod_type: type of module/sgmii connection we have
 *
 * Given a bitmap of the desired lenient mode link speeds,
 * this function will mask off the speeds that are not currently
 * supported by the device.
 */
static u16
ice_apply_supported_speed_filter(u16 report_speeds, u8 mod_type)
{
	u16 speed_mask;
	enum { IS_SGMII, IS_SFP, IS_QSFP } module;

	/*
	 * The SFF specification says 0 is unknown, so we'll
	 * treat it like we're connected through SGMII for now.
	 * This may need revisiting if a new type is supported
	 * in the future.
	 */
	switch (mod_type) {
	case 0:
		module = IS_SGMII;
		break;
	case 3:
		module = IS_SFP;
		break;
	default:
		module = IS_QSFP;
		break;
	}

	/* We won't offer anything lower than 100M for any part,
	 * but we'll need to mask off other speeds based on the
	 * device and module type.
	 */
	speed_mask = ~((u16)ICE_AQ_LINK_SPEED_100MB - 1);
	if ((report_speeds & ICE_AQ_LINK_SPEED_10GB) && (module == IS_SFP))
		speed_mask = ~((u16)ICE_AQ_LINK_SPEED_1000MB - 1);
	if (report_speeds & ICE_AQ_LINK_SPEED_25GB)
		speed_mask = ~((u16)ICE_AQ_LINK_SPEED_1000MB - 1);
	if (report_speeds & ICE_AQ_LINK_SPEED_50GB) {
		speed_mask = ~((u16)ICE_AQ_LINK_SPEED_1000MB - 1);
		if (module == IS_QSFP)
			speed_mask = ~((u16)ICE_AQ_LINK_SPEED_10GB - 1);
	}
	if (report_speeds & ICE_AQ_LINK_SPEED_100GB)
		speed_mask = ~((u16)ICE_AQ_LINK_SPEED_25GB - 1);
	return (report_speeds & speed_mask);
}

/**
 * ice_init_health_events - Enable FW health event reporting
 * @sc: device softc
 *
 * Will try to enable firmware health event reporting, but shouldn't
 * cause any grief (to the caller) if this fails.
 */
void
ice_init_health_events(struct ice_softc *sc)
{
	enum ice_status status;
	u8 health_mask;

	if ((!ice_is_bit_set(sc->feat_cap, ICE_FEATURE_HEALTH_STATUS)) ||
	    (!sc->enable_health_events))
		return;

	health_mask = ICE_AQC_HEALTH_STATUS_SET_PF_SPECIFIC_MASK |
		      ICE_AQC_HEALTH_STATUS_SET_GLOBAL_MASK;

	status = ice_aq_set_health_status_config(&sc->hw, health_mask, NULL);
	if (status)
		device_printf(sc->dev,
		    "Failed to enable firmware health events, err %s aq_err %s\n",
		    ice_status_str(status),
		    ice_aq_str(sc->hw.adminq.sq_last_status));
	else
		ice_set_bit(ICE_FEATURE_HEALTH_STATUS, sc->feat_en);
}

/**
 * ice_print_health_status_string - Print message for given FW health event
 * @dev: the PCIe device
 * @elem: health status element containing status code
 *
 * A rather large list of possible health status codes and their associated
 * messages.
 */
static void
ice_print_health_status_string(device_t dev,
			       struct ice_aqc_health_status_elem *elem)
{
	u16 status_code = le16toh(elem->health_status_code);

	switch (status_code) {
	case ICE_AQC_HEALTH_STATUS_INFO_RECOVERY:
		device_printf(dev, "The device is in firmware recovery mode.\n");
		device_printf(dev, "Possible Solution: Update to the latest NVM image.\n");
		break;
	case ICE_AQC_HEALTH_STATUS_ERR_FLASH_ACCESS:
		device_printf(dev, "The flash chip cannot be accessed.\n");
		device_printf(dev, "Possible Solution: If issue persists, call customer support.\n");
		break;
	case ICE_AQC_HEALTH_STATUS_ERR_NVM_AUTH:
		device_printf(dev, "NVM authentication failed.\n");
		device_printf(dev, "Possible Solution: Update to the latest NVM image.\n");
		break;
	case ICE_AQC_HEALTH_STATUS_ERR_OROM_AUTH:
		device_printf(dev, "Option ROM authentication failed.\n");
		device_printf(dev, "Possible Solution: Update to the latest NVM image.\n");
		break;
	case ICE_AQC_HEALTH_STATUS_ERR_DDP_AUTH:
		device_printf(dev, "DDP package failed.\n");
		device_printf(dev, "Possible Solution: Update to latest base driver and DDP package.\n");
		break;
	case ICE_AQC_HEALTH_STATUS_ERR_NVM_COMPAT:
		device_printf(dev, "NVM image is incompatible.\n");
		device_printf(dev, "Possible Solution: Update to the latest NVM image.\n");
		break;
	case ICE_AQC_HEALTH_STATUS_ERR_OROM_COMPAT:
		device_printf(dev, "Option ROM is incompatible.\n");
		device_printf(dev, "Possible Solution: Update to the latest NVM image.\n");
		break;
	case ICE_AQC_HEALTH_STATUS_ERR_DCB_MIB:
		device_printf(dev, "Supplied MIB file is invalid. DCB reverted to default configuration.\n");
		device_printf(dev, "Possible Solution: Disable FW-LLDP and check DCBx system configuration.\n");
		break;
	case ICE_AQC_HEALTH_STATUS_ERR_UNKNOWN_MOD_STRICT:
		device_printf(dev, "An unsupported module was detected.\n");
		device_printf(dev, "Possible Solution 1: Check your cable connection.\n");
		device_printf(dev, "Possible Solution 2: Change or replace the module or cable.\n");
		break;
	case ICE_AQC_HEALTH_STATUS_ERR_MOD_TYPE:
		device_printf(dev, "Module type is not supported.\n");
		device_printf(dev, "Possible Solution: Change or replace the module or cable.\n");
		break;
	case ICE_AQC_HEALTH_STATUS_ERR_MOD_QUAL:
		device_printf(dev, "Module is not qualified.\n");
		device_printf(dev, "Possible Solution 1: Check your cable connection.\n");
		device_printf(dev, "Possible Solution 2: Change or replace the module or cable.\n");
		device_printf(dev, "Possible Solution 3: Manually set speed and duplex.\n");
		break;
	case ICE_AQC_HEALTH_STATUS_ERR_MOD_COMM:
		device_printf(dev, "Device cannot communicate with the module.\n");
		device_printf(dev, "Possible Solution 1: Check your cable connection.\n");
		device_printf(dev, "Possible Solution 2: Change or replace the module or cable.\n");
		device_printf(dev, "Possible Solution 3: Manually set speed and duplex.\n");
		break;
	case ICE_AQC_HEALTH_STATUS_ERR_MOD_CONFLICT:
		device_printf(dev, "Unresolved module conflict.\n");
		device_printf(dev, "Possible Solution 1: Manually set speed/duplex or use Intel(R) Ethernet Port Configuration Tool to change the port option.\n");
		device_printf(dev, "Possible Solution 2: If the problem persists, use a cable/module that is found in the supported modules and cables list for this device.\n");
		break;
	case ICE_AQC_HEALTH_STATUS_ERR_MOD_NOT_PRESENT:
		device_printf(dev, "Module is not present.\n");
		device_printf(dev, "Possible Solution 1: Check that the module is inserted correctly.\n");
		device_printf(dev, "Possible Solution 2: If the problem persists, use a cable/module that is found in the supported modules and cables list for this device.\n");
		break;
	case ICE_AQC_HEALTH_STATUS_INFO_MOD_UNDERUTILIZED:
		device_printf(dev, "Underutilized module.\n");
		device_printf(dev, "Possible Solution 1: Change or replace the module or cable.\n");
		device_printf(dev, "Possible Solution 2: Use Intel(R) Ethernet Port Configuration Tool to change the port option.\n");
		break;
	case ICE_AQC_HEALTH_STATUS_ERR_UNKNOWN_MOD_LENIENT:
		device_printf(dev, "An unsupported module was detected.\n");
		device_printf(dev, "Possible Solution 1: Check your cable connection.\n");
		device_printf(dev, "Possible Solution 2: Change or replace the module or cable.\n");
		device_printf(dev, "Possible Solution 3: Manually set speed and duplex.\n");
		break;
	case ICE_AQC_HEALTH_STATUS_ERR_INVALID_LINK_CFG:
		device_printf(dev, "Invalid link configuration.\n");
		break;
	case ICE_AQC_HEALTH_STATUS_ERR_PORT_ACCESS:
		device_printf(dev, "Port hardware access error.\n");
		device_printf(dev, "Possible Solution: Update to the latest NVM image.\n");
		break;
	case ICE_AQC_HEALTH_STATUS_ERR_PORT_UNREACHABLE:
		device_printf(dev, "A port is unreachable.\n");
		device_printf(dev, "Possible Solution 1: Use Intel(R) Ethernet Port Configuration Tool to change the port option.\n");
		device_printf(dev, "Possible Solution 2: Update to the latest NVM image.\n");
		break;
	case ICE_AQC_HEALTH_STATUS_INFO_PORT_SPEED_MOD_LIMITED:
		device_printf(dev, "Port speed is limited due to module.\n");
		device_printf(dev, "Possible Solution: Change the module or use Intel(R) Ethernet Port Configuration Tool to configure the port option to match the current module speed.\n");
		break;
	case ICE_AQC_HEALTH_STATUS_ERR_PARALLEL_FAULT:
		device_printf(dev, "A parallel fault was detected.\n");
		device_printf(dev, "Possible Solution: Check link partner connection and configuration.\n");
		break;
	case ICE_AQC_HEALTH_STATUS_INFO_PORT_SPEED_PHY_LIMITED:
		device_printf(dev, "Port speed is limited by PHY capabilities.\n");
		device_printf(dev, "Possible Solution 1: Change the module to align to port option.\n");
		device_printf(dev, "Possible Solution 2: Use Intel(R) Ethernet Port Configuration Tool to change the port option.\n");
		break;
	case ICE_AQC_HEALTH_STATUS_ERR_NETLIST_TOPO:
		device_printf(dev, "LOM topology netlist is corrupted.\n");
		device_printf(dev, "Possible Solution: Update to the latest NVM image.\n");
		break;
	case ICE_AQC_HEALTH_STATUS_ERR_NETLIST:
		device_printf(dev, "Unrecoverable netlist error.\n");
		device_printf(dev, "Possible Solution: Update to the latest NVM image.\n");
		break;
	case ICE_AQC_HEALTH_STATUS_ERR_TOPO_CONFLICT:
		device_printf(dev, "Port topology conflict.\n");
		device_printf(dev, "Possible Solution 1: Use Intel(R) Ethernet Port Configuration Tool to change the port option.\n");
		device_printf(dev, "Possible Solution 2: Update to the latest NVM image.\n");
		break;
	case ICE_AQC_HEALTH_STATUS_ERR_LINK_HW_ACCESS:
		device_printf(dev, "Unrecoverable hardware access error.\n");
		device_printf(dev, "Possible Solution: Update to the latest NVM image.\n");
		break;
	case ICE_AQC_HEALTH_STATUS_ERR_LINK_RUNTIME:
		device_printf(dev, "Unrecoverable runtime error.\n");
		device_printf(dev, "Possible Solution: Update to the latest NVM image.\n");
		break;
	case ICE_AQC_HEALTH_STATUS_ERR_DNL_INIT:
		device_printf(dev, "Link management engine failed to initialize.\n");
		device_printf(dev, "Possible Solution: Update to the latest NVM image.\n");
		break;
	default:
		break;
	}
}

/**
 * ice_handle_health_status_event - helper function to output health status
 * @sc: device softc structure
 * @event: event received on a control queue
 *
 * Prints out the appropriate string based on the given Health Status Event
 * code.
 */
static void
ice_handle_health_status_event(struct ice_softc *sc,
			       struct ice_rq_event_info *event)
{
	struct ice_aqc_health_status_elem *health_info;
	u16 status_count;
	int i;

	if (!ice_is_bit_set(sc->feat_en, ICE_FEATURE_HEALTH_STATUS))
		return;

	health_info = (struct ice_aqc_health_status_elem *)event->msg_buf;
	status_count = le16toh(event->desc.params.get_health_status.health_status_count);

	if (status_count > (event->buf_len / sizeof(*health_info))) {
		device_printf(sc->dev, "Received a health status event with invalid event count\n");
		return;
	}

	for (i = 0; i < status_count; i++) {
		ice_print_health_status_string(sc->dev, health_info);
		health_info++;
	}
}

/**
 * ice_set_default_local_lldp_mib - Set Local LLDP MIB to default settings
 * @sc: device softc structure
 *
 * This function needs to be called after link up; it makes sure the FW
 * has certain PFC/DCB settings. This is intended to workaround a FW behavior
 * where these settings seem to be cleared on link up.
 */
void
ice_set_default_local_lldp_mib(struct ice_softc *sc)
{
	struct ice_dcbx_cfg *dcbcfg;
	struct ice_hw *hw = &sc->hw;
	struct ice_port_info *pi;
	device_t dev = sc->dev;
	enum ice_status status;
	u8 maxtcs, maxtcs_ets;

	pi = hw->port_info;

	dcbcfg = &pi->qos_cfg.local_dcbx_cfg;

	maxtcs = hw->func_caps.common_cap.maxtc;
	/* This value is only 3 bits; 8 TCs maps to 0 */
	maxtcs_ets = maxtcs & ICE_IEEE_ETS_MAXTC_M;

	/**
	 * Setup the default settings used by the driver for the Set Local
	 * LLDP MIB Admin Queue command (0x0A08). (1TC w/ 100% BW, ETS, no
	 * PFC).
	 */
	memset(dcbcfg, 0, sizeof(*dcbcfg));
	dcbcfg->etscfg.willing = 1;
	dcbcfg->etscfg.tcbwtable[0] = 100;
	dcbcfg->etscfg.maxtcs = maxtcs_ets;
	dcbcfg->etsrec = dcbcfg->etscfg;
	dcbcfg->pfc.willing = 1;
	dcbcfg->pfc.pfccap = maxtcs;

	status = ice_set_dcb_cfg(pi);

	if (status)
		device_printf(dev,
		    "Error setting Local LLDP MIB: %s aq_err %s\n",
		    ice_status_str(status),
		    ice_aq_str(hw->adminq.sq_last_status));
}

/**
 * ice_sbuf_print_ets_cfg - Helper function to print ETS cfg
 * @sbuf: string buffer to print to
 * @name: prefix string to use
 * @ets: structure to pull values from
 *
 * A helper function for ice_sysctl_dump_dcbx_cfg(), this
 * formats the ETS rec and cfg TLVs into text.
 */
static void
ice_sbuf_print_ets_cfg(struct sbuf *sbuf, const char *name, struct ice_dcb_ets_cfg *ets)
{
	sbuf_printf(sbuf, "%s.willing: %u\n", name, ets->willing);
	sbuf_printf(sbuf, "%s.cbs: %u\n", name, ets->cbs);
	sbuf_printf(sbuf, "%s.maxtcs: %u\n", name, ets->maxtcs);

	sbuf_printf(sbuf, "%s.prio_table:", name);
	for (int i = 0; i < ICE_MAX_TRAFFIC_CLASS; i++)
		sbuf_printf(sbuf, " %d", ets->prio_table[i]);
	sbuf_printf(sbuf, "\n");

	sbuf_printf(sbuf, "%s.tcbwtable:", name);
	for (int i = 0; i < ICE_MAX_TRAFFIC_CLASS; i++)
		sbuf_printf(sbuf, " %d", ets->tcbwtable[i]);
	sbuf_printf(sbuf, "\n");

	sbuf_printf(sbuf, "%s.tsatable:", name);
	for (int i = 0; i < ICE_MAX_TRAFFIC_CLASS; i++)
		sbuf_printf(sbuf, " %d", ets->tsatable[i]);
	sbuf_printf(sbuf, "\n");
}

/**
 * ice_sysctl_dump_dcbx_cfg - Print out DCBX/DCB config info
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: AQ define for either Local or Remote MIB
 * @req: sysctl request pointer
 *
 * Prints out DCB/DCBX configuration, including the contents
 * of either the local or remote MIB, depending on the value
 * used in arg2.
 */
static int
ice_sysctl_dump_dcbx_cfg(SYSCTL_HANDLER_ARGS)
{
	struct ice_softc *sc = (struct ice_softc *)arg1;
	struct ice_aqc_get_cee_dcb_cfg_resp cee_cfg = {};
	struct ice_dcbx_cfg dcb_buf = {};
	struct ice_dcbx_cfg *dcbcfg;
	struct ice_hw *hw = &sc->hw;
	device_t dev = sc->dev;
	struct sbuf *sbuf;
	enum ice_status status;
	u8 maxtcs, dcbx_status, is_sw_lldp;

	UNREFERENCED_PARAMETER(oidp);

	if (ice_driver_is_detaching(sc))
		return (ESHUTDOWN);

	is_sw_lldp = hw->port_info->qos_cfg.is_sw_lldp;

	/* The driver doesn't receive a Remote MIB via SW */
	if (is_sw_lldp && arg2 == ICE_AQ_LLDP_MIB_REMOTE)
		return (ENOENT);

	dcbcfg = &hw->port_info->qos_cfg.local_dcbx_cfg;
	if (!is_sw_lldp) {
		/* Collect information from the FW in FW LLDP mode */
		dcbcfg = &dcb_buf;
		status = ice_aq_get_dcb_cfg(hw, (u8)arg2,
		    ICE_AQ_LLDP_BRID_TYPE_NEAREST_BRID, dcbcfg);
		if (status && arg2 == ICE_AQ_LLDP_MIB_REMOTE &&
		    hw->adminq.sq_last_status == ICE_AQ_RC_ENOENT) {
			device_printf(dev,
			    "Unable to query Remote MIB; port has not received one yet\n");
			return (ENOENT);
		}
		if (status) {
			device_printf(dev, "Unable to query LLDP MIB, err %s aq_err %s\n",
			    ice_status_str(status),
			    ice_aq_str(hw->adminq.sq_last_status));
			return (EIO);
		}
	}

	status = ice_aq_get_cee_dcb_cfg(hw, &cee_cfg, NULL);
	if (status == ICE_SUCCESS)
		dcbcfg->dcbx_mode = ICE_DCBX_MODE_CEE;
	else if (hw->adminq.sq_last_status == ICE_AQ_RC_ENOENT)
		dcbcfg->dcbx_mode = ICE_DCBX_MODE_IEEE;

	maxtcs = hw->func_caps.common_cap.maxtc;
	dcbx_status = ice_get_dcbx_status(hw);

	sbuf = sbuf_new_for_sysctl(NULL, NULL, 128, req);

	/* Do the actual printing */
	sbuf_printf(sbuf, "\n");
	sbuf_printf(sbuf, "SW LLDP mode: %d\n", is_sw_lldp);
	sbuf_printf(sbuf, "Function caps maxtcs: %d\n", maxtcs);
	sbuf_printf(sbuf, "dcbx_status: %d\n", dcbx_status);

	sbuf_printf(sbuf, "numapps: %u\n", dcbcfg->numapps);
	sbuf_printf(sbuf, "CEE TLV status: %u\n", dcbcfg->tlv_status);
	sbuf_printf(sbuf, "pfc_mode: %s\n", (dcbcfg->pfc_mode == ICE_QOS_MODE_DSCP) ?
	    "DSCP" : "VLAN");
	sbuf_printf(sbuf, "dcbx_mode: %s\n",
	    (dcbcfg->dcbx_mode == ICE_DCBX_MODE_IEEE) ? "IEEE" :
	    (dcbcfg->dcbx_mode == ICE_DCBX_MODE_CEE) ? "CEE" :
	    "Unknown");

	ice_sbuf_print_ets_cfg(sbuf, "etscfg", &dcbcfg->etscfg);
	ice_sbuf_print_ets_cfg(sbuf, "etsrec", &dcbcfg->etsrec);

	sbuf_printf(sbuf, "pfc.willing: %u\n", dcbcfg->pfc.willing);
	sbuf_printf(sbuf, "pfc.mbc: %u\n", dcbcfg->pfc.mbc);
	sbuf_printf(sbuf, "pfc.pfccap: 0x%0x\n", dcbcfg->pfc.pfccap);
	sbuf_printf(sbuf, "pfc.pfcena: 0x%0x\n", dcbcfg->pfc.pfcena);

	if (arg2 == ICE_AQ_LLDP_MIB_LOCAL) {
		sbuf_printf(sbuf, "\nLocal registers:\n");
		sbuf_printf(sbuf, "PRTDCB_GENC.NUMTC: %d\n",
		    (rd32(hw, PRTDCB_GENC) & PRTDCB_GENC_NUMTC_M)
		        >> PRTDCB_GENC_NUMTC_S);
		sbuf_printf(sbuf, "PRTDCB_TUP2TC: 0x%0x\n",
		    (rd32(hw, PRTDCB_TUP2TC)));
		sbuf_printf(sbuf, "PRTDCB_RUP2TC: 0x%0x\n",
		    (rd32(hw, PRTDCB_RUP2TC)));
		sbuf_printf(sbuf, "GLDCB_TC2PFC: 0x%0x\n",
		    (rd32(hw, GLDCB_TC2PFC)));
	}

	/* Finish */
	sbuf_finish(sbuf);
	sbuf_delete(sbuf);

	return (0);
}

/**
 * ice_sysctl_dump_vsi_cfg - print PF LAN VSI configuration
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: unused
 * @req: sysctl request pointer
 *
 * XXX: This could be extended to apply to arbitrary PF-owned VSIs,
 * but for simplicity, this only works on the PF's LAN VSI.
 */
static int
ice_sysctl_dump_vsi_cfg(SYSCTL_HANDLER_ARGS)
{
	struct ice_softc *sc = (struct ice_softc *)arg1;
	struct ice_vsi_ctx ctx = { 0 };
	struct ice_hw *hw = &sc->hw;
	device_t dev = sc->dev;
	struct sbuf *sbuf;
	enum ice_status status;

	UNREFERENCED_PARAMETER(oidp);
	UNREFERENCED_PARAMETER(arg2);

	if (ice_driver_is_detaching(sc))
		return (ESHUTDOWN);

	/* Get HW absolute index of a VSI */
	ctx.vsi_num = ice_get_hw_vsi_num(hw, sc->pf_vsi.idx);

	status = ice_aq_get_vsi_params(hw, &ctx, NULL);
	if (status != ICE_SUCCESS) {
		device_printf(dev,
		    "Get VSI AQ call failed, err %s aq_err %s\n",
		    ice_status_str(status),
		    ice_aq_str(hw->adminq.sq_last_status));
		return (EIO);
	}

	sbuf = sbuf_new_for_sysctl(NULL, NULL, 128, req);

	/* Do the actual printing */
	sbuf_printf(sbuf, "\n");

	sbuf_printf(sbuf, "VSI NUM: %d\n", ctx.vsi_num);
	sbuf_printf(sbuf, "VF  NUM: %d\n", ctx.vf_num);
	sbuf_printf(sbuf, "VSIs allocated: %d\n", ctx.vsis_allocd);
	sbuf_printf(sbuf, "VSIs unallocated: %d\n", ctx.vsis_unallocated);

	sbuf_printf(sbuf, "Rx Queue Map method: %d\n",
	    LE16_TO_CPU(ctx.info.mapping_flags));
	/* The PF VSI is always contiguous, so there's no if-statement here */
	sbuf_printf(sbuf, "Rx Queue base: %d\n",
	    LE16_TO_CPU(ctx.info.q_mapping[0]));
	sbuf_printf(sbuf, "Rx Queue count: %d\n",
	    LE16_TO_CPU(ctx.info.q_mapping[1]));

	sbuf_printf(sbuf, "TC qbases  :");
	for (int i = 0; i < ICE_MAX_TRAFFIC_CLASS; i++) {
		sbuf_printf(sbuf, " %4d",
		    ctx.info.tc_mapping[i] & ICE_AQ_VSI_TC_Q_OFFSET_M);
	}
	sbuf_printf(sbuf, "\n");

	sbuf_printf(sbuf, "TC qcounts :");
	for (int i = 0; i < ICE_MAX_TRAFFIC_CLASS; i++) {
		sbuf_printf(sbuf, " %4d",
		    1 << (ctx.info.tc_mapping[i] >> ICE_AQ_VSI_TC_Q_NUM_S));
	}

	/* Finish */
	sbuf_finish(sbuf);
	sbuf_delete(sbuf);

	return (0);
}

/**
 * ice_ets_str_to_tbl - Parse string into ETS table
 * @str: input string to parse
 * @table: output eight values used for ETS values
 * @limit: max valid value to accept for ETS values
 *
 * Parses a string and converts the eight values within
 * into a table that can be used in setting ETS settings
 * in a MIB.
 *
 * @return 0 on success, EINVAL if a parsed value is
 * not between 0 and limit.
 */
static int
ice_ets_str_to_tbl(const char *str, u8 *table, u8 limit)
{
	const char *str_start = str;
	char *str_end;
	long token;

	for (int i = 0; i < ICE_MAX_TRAFFIC_CLASS; i++) {
		token = strtol(str_start, &str_end, 0);
		if (token < 0 || token > limit)
			return (EINVAL);

		table[i] = (u8)token;
		str_start = (str_end + 1);
	}

	return (0);
}

/**
 * ice_check_ets_bw - Check if ETS bw vals are valid
 * @table: eight values used for ETS bandwidth
 *
 * @return true if the sum of all 8 values in table
 * equals 100.
 */
static bool
ice_check_ets_bw(u8 *table)
{
	int sum = 0;
	for (int i = 0; i < ICE_MAX_TRAFFIC_CLASS; i++)
		sum += (int)table[i];

	return (sum == 100);
}

/**
 * ice_cfg_pba_num - Determine if PBA Number is retrievable
 * @sc: the device private softc structure
 *
 * Sets the feature flag for the existence of a PBA number
 * based on the success of the read command.  This does not
 * cache the result.
 */
void
ice_cfg_pba_num(struct ice_softc *sc)
{
	u8 pba_string[32] = "";

	if ((ice_is_bit_set(sc->feat_cap, ICE_FEATURE_HAS_PBA)) &&
	    (ice_read_pba_string(&sc->hw, pba_string, sizeof(pba_string)) == 0))
		ice_set_bit(ICE_FEATURE_HAS_PBA, sc->feat_en);
}

/**
 * ice_sysctl_query_port_ets - print Port ETS Config from AQ
 * @oidp: sysctl oid structure
 * @arg1: pointer to private data structure
 * @arg2: unused
 * @req: sysctl request pointer
 */
static int
ice_sysctl_query_port_ets(SYSCTL_HANDLER_ARGS)
{
	struct ice_softc *sc = (struct ice_softc *)arg1;
	struct ice_aqc_port_ets_elem port_ets = { 0 };
	struct ice_hw *hw = &sc->hw;
	struct ice_port_info *pi;
	device_t dev = sc->dev;
	struct sbuf *sbuf;
	enum ice_status status;
	int i = 0;

	UNREFERENCED_PARAMETER(oidp);
	UNREFERENCED_PARAMETER(arg2);

	if (ice_driver_is_detaching(sc))
		return (ESHUTDOWN);

	pi = hw->port_info;

	status = ice_aq_query_port_ets(pi, &port_ets, sizeof(port_ets), NULL);
	if (status != ICE_SUCCESS) {
		device_printf(dev,
		    "Query Port ETS AQ call failed, err %s aq_err %s\n",
		    ice_status_str(status),
		    ice_aq_str(hw->adminq.sq_last_status));
		return (EIO);
	}

	sbuf = sbuf_new_for_sysctl(NULL, NULL, 128, req);

	/* Do the actual printing */
	sbuf_printf(sbuf, "\n");

	sbuf_printf(sbuf, "Valid TC map: 0x%x\n", port_ets.tc_valid_bits);

	sbuf_printf(sbuf, "TC BW %%:");
	ice_for_each_traffic_class(i) {
		sbuf_printf(sbuf, " %3d", port_ets.tc_bw_share[i]);
	}
	sbuf_printf(sbuf, "\n");

	sbuf_printf(sbuf, "EIR profile ID: %d\n", port_ets.port_eir_prof_id);
	sbuf_printf(sbuf, "CIR profile ID: %d\n", port_ets.port_cir_prof_id);
	sbuf_printf(sbuf, "TC Node prio: 0x%x\n", port_ets.tc_node_prio);

	sbuf_printf(sbuf, "TC Node TEIDs:\n");
	ice_for_each_traffic_class(i) {
		sbuf_printf(sbuf, "%d: %d\n", i, port_ets.tc_node_teid[i]);
	}

	/* Finish */
	sbuf_finish(sbuf);
	sbuf_delete(sbuf);

	return (0);
}