Training courses

Kernel and Embedded Linux

Bootlin training courses

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

Bootlin logo

Elixir Cross Referencer

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

#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include "opt_inet.h"
#include "opt_inet6.h"
#include "opt_kern_tls.h"
#include "opt_ratelimit.h"

#include <sys/types.h>
#include <sys/eventhandler.h>
#include <sys/mbuf.h>
#include <sys/socket.h>
#include <sys/kernel.h>
#include <sys/ktls.h>
#include <sys/malloc.h>
#include <sys/queue.h>
#include <sys/sbuf.h>
#include <sys/taskqueue.h>
#include <sys/time.h>
#include <sys/sglist.h>
#include <sys/sysctl.h>
#include <sys/smp.h>
#include <sys/socketvar.h>
#include <sys/counter.h>
#include <net/bpf.h>
#include <net/ethernet.h>
#include <net/if.h>
#include <net/if_vlan_var.h>
#include <net/if_vxlan.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip6.h>
#include <netinet/tcp.h>
#include <netinet/udp.h>
#include <machine/in_cksum.h>
#include <machine/md_var.h>
#include <vm/vm.h>
#include <vm/pmap.h>
#ifdef DEV_NETMAP
#include <machine/bus.h>
#include <sys/selinfo.h>
#include <net/if_var.h>
#include <net/netmap.h>
#include <dev/netmap/netmap_kern.h>
#endif

#include "common/common.h"
#include "common/t4_regs.h"
#include "common/t4_regs_values.h"
#include "common/t4_msg.h"
#include "t4_l2t.h"
#include "t4_mp_ring.h"

#ifdef T4_PKT_TIMESTAMP
#define RX_COPY_THRESHOLD (MINCLSIZE - 8)
#else
#define RX_COPY_THRESHOLD MINCLSIZE
#endif

/* Internal mbuf flags stored in PH_loc.eight[1]. */
#define	MC_NOMAP		0x01
#define	MC_RAW_WR		0x02
#define	MC_TLS			0x04

/*
 * Ethernet frames are DMA'd at this byte offset into the freelist buffer.
 * 0-7 are valid values.
 */
static int fl_pktshift = 0;
SYSCTL_INT(_hw_cxgbe, OID_AUTO, fl_pktshift, CTLFLAG_RDTUN, &fl_pktshift, 0,
    "payload DMA offset in rx buffer (bytes)");

/*
 * Pad ethernet payload up to this boundary.
 * -1: driver should figure out a good value.
 *  0: disable padding.
 *  Any power of 2 from 32 to 4096 (both inclusive) is also a valid value.
 */
int fl_pad = -1;
SYSCTL_INT(_hw_cxgbe, OID_AUTO, fl_pad, CTLFLAG_RDTUN, &fl_pad, 0,
    "payload pad boundary (bytes)");

/*
 * Status page length.
 * -1: driver should figure out a good value.
 *  64 or 128 are the only other valid values.
 */
static int spg_len = -1;
SYSCTL_INT(_hw_cxgbe, OID_AUTO, spg_len, CTLFLAG_RDTUN, &spg_len, 0,
    "status page size (bytes)");

/*
 * Congestion drops.
 * -1: no congestion feedback (not recommended).
 *  0: backpressure the channel instead of dropping packets right away.
 *  1: no backpressure, drop packets for the congested queue immediately.
 */
static int cong_drop = 0;
SYSCTL_INT(_hw_cxgbe, OID_AUTO, cong_drop, CTLFLAG_RDTUN, &cong_drop, 0,
    "Congestion control for RX queues (0 = backpressure, 1 = drop");

/*
 * Deliver multiple frames in the same free list buffer if they fit.
 * -1: let the driver decide whether to enable buffer packing or not.
 *  0: disable buffer packing.
 *  1: enable buffer packing.
 */
static int buffer_packing = -1;
SYSCTL_INT(_hw_cxgbe, OID_AUTO, buffer_packing, CTLFLAG_RDTUN, &buffer_packing,
    0, "Enable buffer packing");

/*
 * Start next frame in a packed buffer at this boundary.
 * -1: driver should figure out a good value.
 * T4: driver will ignore this and use the same value as fl_pad above.
 * T5: 16, or a power of 2 from 64 to 4096 (both inclusive) is a valid value.
 */
static int fl_pack = -1;
SYSCTL_INT(_hw_cxgbe, OID_AUTO, fl_pack, CTLFLAG_RDTUN, &fl_pack, 0,
    "payload pack boundary (bytes)");

/*
 * Largest rx cluster size that the driver is allowed to allocate.
 */
static int largest_rx_cluster = MJUM16BYTES;
SYSCTL_INT(_hw_cxgbe, OID_AUTO, largest_rx_cluster, CTLFLAG_RDTUN,
    &largest_rx_cluster, 0, "Largest rx cluster (bytes)");

/*
 * Size of cluster allocation that's most likely to succeed.  The driver will
 * fall back to this size if it fails to allocate clusters larger than this.
 */
static int safest_rx_cluster = PAGE_SIZE;
SYSCTL_INT(_hw_cxgbe, OID_AUTO, safest_rx_cluster, CTLFLAG_RDTUN,
    &safest_rx_cluster, 0, "Safe rx cluster (bytes)");

#ifdef RATELIMIT
/*
 * Knob to control TCP timestamp rewriting, and the granularity of the tick used
 * for rewriting.  -1 and 0-3 are all valid values.
 * -1: hardware should leave the TCP timestamps alone.
 * 0: 1ms
 * 1: 100us
 * 2: 10us
 * 3: 1us
 */
static int tsclk = -1;
SYSCTL_INT(_hw_cxgbe, OID_AUTO, tsclk, CTLFLAG_RDTUN, &tsclk, 0,
    "Control TCP timestamp rewriting when using pacing");

static int eo_max_backlog = 1024 * 1024;
SYSCTL_INT(_hw_cxgbe, OID_AUTO, eo_max_backlog, CTLFLAG_RDTUN, &eo_max_backlog,
    0, "Maximum backlog of ratelimited data per flow");
#endif

/*
 * The interrupt holdoff timers are multiplied by this value on T6+.
 * 1 and 3-17 (both inclusive) are legal values.
 */
static int tscale = 1;
SYSCTL_INT(_hw_cxgbe, OID_AUTO, tscale, CTLFLAG_RDTUN, &tscale, 0,
    "Interrupt holdoff timer scale on T6+");

/*
 * Number of LRO entries in the lro_ctrl structure per rx queue.
 */
static int lro_entries = TCP_LRO_ENTRIES;
SYSCTL_INT(_hw_cxgbe, OID_AUTO, lro_entries, CTLFLAG_RDTUN, &lro_entries, 0,
    "Number of LRO entries per RX queue");

/*
 * This enables presorting of frames before they're fed into tcp_lro_rx.
 */
static int lro_mbufs = 0;
SYSCTL_INT(_hw_cxgbe, OID_AUTO, lro_mbufs, CTLFLAG_RDTUN, &lro_mbufs, 0,
    "Enable presorting of LRO frames");

static counter_u64_t pullups;
SYSCTL_COUNTER_U64(_hw_cxgbe, OID_AUTO, pullups, CTLFLAG_RD, &pullups,
    "Number of mbuf pullups performed");

static counter_u64_t defrags;
SYSCTL_COUNTER_U64(_hw_cxgbe, OID_AUTO, defrags, CTLFLAG_RD, &defrags,
    "Number of mbuf defrags performed");


static int service_iq(struct sge_iq *, int);
static int service_iq_fl(struct sge_iq *, int);
static struct mbuf *get_fl_payload(struct adapter *, struct sge_fl *, uint32_t);
static int eth_rx(struct adapter *, struct sge_rxq *, const struct iq_desc *,
    u_int);
static inline void init_iq(struct sge_iq *, struct adapter *, int, int, int);
static inline void init_fl(struct adapter *, struct sge_fl *, int, int, char *);
static inline void init_eq(struct adapter *, struct sge_eq *, int, int, uint8_t,
    uint16_t, char *);
static int alloc_ring(struct adapter *, size_t, bus_dma_tag_t *, bus_dmamap_t *,
    bus_addr_t *, void **);
static int free_ring(struct adapter *, bus_dma_tag_t, bus_dmamap_t, bus_addr_t,
    void *);
static int alloc_iq_fl(struct vi_info *, struct sge_iq *, struct sge_fl *,
    int, int);
static int free_iq_fl(struct vi_info *, struct sge_iq *, struct sge_fl *);
static void add_iq_sysctls(struct sysctl_ctx_list *, struct sysctl_oid *,
    struct sge_iq *);
static void add_fl_sysctls(struct adapter *, struct sysctl_ctx_list *,
    struct sysctl_oid *, struct sge_fl *);
static int alloc_fwq(struct adapter *);
static int free_fwq(struct adapter *);
static int alloc_ctrlq(struct adapter *, struct sge_wrq *, int,
    struct sysctl_oid *);
static int alloc_rxq(struct vi_info *, struct sge_rxq *, int, int,
    struct sysctl_oid *);
static int free_rxq(struct vi_info *, struct sge_rxq *);
#ifdef TCP_OFFLOAD
static int alloc_ofld_rxq(struct vi_info *, struct sge_ofld_rxq *, int, int,
    struct sysctl_oid *);
static int free_ofld_rxq(struct vi_info *, struct sge_ofld_rxq *);
#endif
#ifdef DEV_NETMAP
static int alloc_nm_rxq(struct vi_info *, struct sge_nm_rxq *, int, int,
    struct sysctl_oid *);
static int free_nm_rxq(struct vi_info *, struct sge_nm_rxq *);
static int alloc_nm_txq(struct vi_info *, struct sge_nm_txq *, int, int,
    struct sysctl_oid *);
static int free_nm_txq(struct vi_info *, struct sge_nm_txq *);
#endif
static int ctrl_eq_alloc(struct adapter *, struct sge_eq *);
static int eth_eq_alloc(struct adapter *, struct vi_info *, struct sge_eq *);
#if defined(TCP_OFFLOAD) || defined(RATELIMIT)
static int ofld_eq_alloc(struct adapter *, struct vi_info *, struct sge_eq *);
#endif
static int alloc_eq(struct adapter *, struct vi_info *, struct sge_eq *);
static int free_eq(struct adapter *, struct sge_eq *);
static int alloc_wrq(struct adapter *, struct vi_info *, struct sge_wrq *,
    struct sysctl_oid *);
static int free_wrq(struct adapter *, struct sge_wrq *);
static int alloc_txq(struct vi_info *, struct sge_txq *, int,
    struct sysctl_oid *);
static int free_txq(struct vi_info *, struct sge_txq *);
static void oneseg_dma_callback(void *, bus_dma_segment_t *, int, int);
static inline void ring_fl_db(struct adapter *, struct sge_fl *);
static int refill_fl(struct adapter *, struct sge_fl *, int);
static void refill_sfl(void *);
static int alloc_fl_sdesc(struct sge_fl *);
static void free_fl_sdesc(struct adapter *, struct sge_fl *);
static int find_refill_source(struct adapter *, int, bool);
static void add_fl_to_sfl(struct adapter *, struct sge_fl *);

static inline void get_pkt_gl(struct mbuf *, struct sglist *);
static inline u_int txpkt_len16(u_int, const u_int);
static inline u_int txpkt_vm_len16(u_int, const u_int);
static inline void calculate_mbuf_len16(struct mbuf *, bool);
static inline u_int txpkts0_len16(u_int);
static inline u_int txpkts1_len16(void);
static u_int write_raw_wr(struct sge_txq *, void *, struct mbuf *, u_int);
static u_int write_txpkt_wr(struct adapter *, struct sge_txq *, struct mbuf *,
    u_int);
static u_int write_txpkt_vm_wr(struct adapter *, struct sge_txq *,
    struct mbuf *);
static int add_to_txpkts_vf(struct adapter *, struct sge_txq *, struct mbuf *,
    int, bool *);
static int add_to_txpkts_pf(struct adapter *, struct sge_txq *, struct mbuf *,
    int, bool *);
static u_int write_txpkts_wr(struct adapter *, struct sge_txq *);
static u_int write_txpkts_vm_wr(struct adapter *, struct sge_txq *);
static void write_gl_to_txd(struct sge_txq *, struct mbuf *, caddr_t *, int);
static inline void copy_to_txd(struct sge_eq *, caddr_t, caddr_t *, int);
static inline void ring_eq_db(struct adapter *, struct sge_eq *, u_int);
static inline uint16_t read_hw_cidx(struct sge_eq *);
static inline u_int reclaimable_tx_desc(struct sge_eq *);
static inline u_int total_available_tx_desc(struct sge_eq *);
static u_int reclaim_tx_descs(struct sge_txq *, u_int);
static void tx_reclaim(void *, int);
static __be64 get_flit(struct sglist_seg *, int, int);
static int handle_sge_egr_update(struct sge_iq *, const struct rss_header *,
    struct mbuf *);
static int handle_fw_msg(struct sge_iq *, const struct rss_header *,
    struct mbuf *);
static int t4_handle_wrerr_rpl(struct adapter *, const __be64 *);
static void wrq_tx_drain(void *, int);
static void drain_wrq_wr_list(struct adapter *, struct sge_wrq *);

static int sysctl_uint16(SYSCTL_HANDLER_ARGS);
static int sysctl_bufsizes(SYSCTL_HANDLER_ARGS);
#ifdef RATELIMIT
static inline u_int txpkt_eo_len16(u_int, u_int, u_int);
static int ethofld_fw4_ack(struct sge_iq *, const struct rss_header *,
    struct mbuf *);
#endif

static counter_u64_t extfree_refs;
static counter_u64_t extfree_rels;

an_handler_t t4_an_handler;
fw_msg_handler_t t4_fw_msg_handler[NUM_FW6_TYPES];
cpl_handler_t t4_cpl_handler[NUM_CPL_CMDS];
cpl_handler_t set_tcb_rpl_handlers[NUM_CPL_COOKIES];
cpl_handler_t l2t_write_rpl_handlers[NUM_CPL_COOKIES];
cpl_handler_t act_open_rpl_handlers[NUM_CPL_COOKIES];
cpl_handler_t abort_rpl_rss_handlers[NUM_CPL_COOKIES];
cpl_handler_t fw4_ack_handlers[NUM_CPL_COOKIES];

void
t4_register_an_handler(an_handler_t h)
{
	uintptr_t *loc;

	MPASS(h == NULL || t4_an_handler == NULL);

	loc = (uintptr_t *)&t4_an_handler;
	atomic_store_rel_ptr(loc, (uintptr_t)h);
}

void
t4_register_fw_msg_handler(int type, fw_msg_handler_t h)
{
	uintptr_t *loc;

	MPASS(type < nitems(t4_fw_msg_handler));
	MPASS(h == NULL || t4_fw_msg_handler[type] == NULL);
	/*
	 * These are dispatched by the handler for FW{4|6}_CPL_MSG using the CPL
	 * handler dispatch table.  Reject any attempt to install a handler for
	 * this subtype.
	 */
	MPASS(type != FW_TYPE_RSSCPL);
	MPASS(type != FW6_TYPE_RSSCPL);

	loc = (uintptr_t *)&t4_fw_msg_handler[type];
	atomic_store_rel_ptr(loc, (uintptr_t)h);
}

void
t4_register_cpl_handler(int opcode, cpl_handler_t h)
{
	uintptr_t *loc;

	MPASS(opcode < nitems(t4_cpl_handler));
	MPASS(h == NULL || t4_cpl_handler[opcode] == NULL);

	loc = (uintptr_t *)&t4_cpl_handler[opcode];
	atomic_store_rel_ptr(loc, (uintptr_t)h);
}

static int
set_tcb_rpl_handler(struct sge_iq *iq, const struct rss_header *rss,
    struct mbuf *m)
{
	const struct cpl_set_tcb_rpl *cpl = (const void *)(rss + 1);
	u_int tid;
	int cookie;

	MPASS(m == NULL);

	tid = GET_TID(cpl);
	if (is_hpftid(iq->adapter, tid) || is_ftid(iq->adapter, tid)) {
		/*
		 * The return code for filter-write is put in the CPL cookie so
		 * we have to rely on the hardware tid (is_ftid) to determine
		 * that this is a response to a filter.
		 */
		cookie = CPL_COOKIE_FILTER;
	} else {
		cookie = G_COOKIE(cpl->cookie);
	}
	MPASS(cookie > CPL_COOKIE_RESERVED);
	MPASS(cookie < nitems(set_tcb_rpl_handlers));

	return (set_tcb_rpl_handlers[cookie](iq, rss, m));
}

static int
l2t_write_rpl_handler(struct sge_iq *iq, const struct rss_header *rss,
    struct mbuf *m)
{
	const struct cpl_l2t_write_rpl *rpl = (const void *)(rss + 1);
	unsigned int cookie;

	MPASS(m == NULL);

	cookie = GET_TID(rpl) & F_SYNC_WR ? CPL_COOKIE_TOM : CPL_COOKIE_FILTER;
	return (l2t_write_rpl_handlers[cookie](iq, rss, m));
}

static int
act_open_rpl_handler(struct sge_iq *iq, const struct rss_header *rss,
    struct mbuf *m)
{
	const struct cpl_act_open_rpl *cpl = (const void *)(rss + 1);
	u_int cookie = G_TID_COOKIE(G_AOPEN_ATID(be32toh(cpl->atid_status)));

	MPASS(m == NULL);
	MPASS(cookie != CPL_COOKIE_RESERVED);

	return (act_open_rpl_handlers[cookie](iq, rss, m));
}

static int
abort_rpl_rss_handler(struct sge_iq *iq, const struct rss_header *rss,
    struct mbuf *m)
{
	struct adapter *sc = iq->adapter;
	u_int cookie;

	MPASS(m == NULL);
	if (is_hashfilter(sc))
		cookie = CPL_COOKIE_HASHFILTER;
	else
		cookie = CPL_COOKIE_TOM;

	return (abort_rpl_rss_handlers[cookie](iq, rss, m));
}

static int
fw4_ack_handler(struct sge_iq *iq, const struct rss_header *rss, struct mbuf *m)
{
	struct adapter *sc = iq->adapter;
	const struct cpl_fw4_ack *cpl = (const void *)(rss + 1);
	unsigned int tid = G_CPL_FW4_ACK_FLOWID(be32toh(OPCODE_TID(cpl)));
	u_int cookie;

	MPASS(m == NULL);
	if (is_etid(sc, tid))
		cookie = CPL_COOKIE_ETHOFLD;
	else
		cookie = CPL_COOKIE_TOM;

	return (fw4_ack_handlers[cookie](iq, rss, m));
}

static void
t4_init_shared_cpl_handlers(void)
{

	t4_register_cpl_handler(CPL_SET_TCB_RPL, set_tcb_rpl_handler);
	t4_register_cpl_handler(CPL_L2T_WRITE_RPL, l2t_write_rpl_handler);
	t4_register_cpl_handler(CPL_ACT_OPEN_RPL, act_open_rpl_handler);
	t4_register_cpl_handler(CPL_ABORT_RPL_RSS, abort_rpl_rss_handler);
	t4_register_cpl_handler(CPL_FW4_ACK, fw4_ack_handler);
}

void
t4_register_shared_cpl_handler(int opcode, cpl_handler_t h, int cookie)
{
	uintptr_t *loc;

	MPASS(opcode < nitems(t4_cpl_handler));
	MPASS(cookie > CPL_COOKIE_RESERVED);
	MPASS(cookie < NUM_CPL_COOKIES);
	MPASS(t4_cpl_handler[opcode] != NULL);

	switch (opcode) {
	case CPL_SET_TCB_RPL:
		loc = (uintptr_t *)&set_tcb_rpl_handlers[cookie];
		break;
	case CPL_L2T_WRITE_RPL:
		loc = (uintptr_t *)&l2t_write_rpl_handlers[cookie];
		break;
	case CPL_ACT_OPEN_RPL:
		loc = (uintptr_t *)&act_open_rpl_handlers[cookie];
		break;
	case CPL_ABORT_RPL_RSS:
		loc = (uintptr_t *)&abort_rpl_rss_handlers[cookie];
		break;
	case CPL_FW4_ACK:
		loc = (uintptr_t *)&fw4_ack_handlers[cookie];
		break;
	default:
		MPASS(0);
		return;
	}
	MPASS(h == NULL || *loc == (uintptr_t)NULL);
	atomic_store_rel_ptr(loc, (uintptr_t)h);
}

/*
 * Called on MOD_LOAD.  Validates and calculates the SGE tunables.
 */
void
t4_sge_modload(void)
{

	if (fl_pktshift < 0 || fl_pktshift > 7) {
		printf("Invalid hw.cxgbe.fl_pktshift value (%d),"
		    " using 0 instead.\n", fl_pktshift);
		fl_pktshift = 0;
	}

	if (spg_len != 64 && spg_len != 128) {
		int len;

#if defined(__i386__) || defined(__amd64__)
		len = cpu_clflush_line_size > 64 ? 128 : 64;
#else
		len = 64;
#endif
		if (spg_len != -1) {
			printf("Invalid hw.cxgbe.spg_len value (%d),"
			    " using %d instead.\n", spg_len, len);
		}
		spg_len = len;
	}

	if (cong_drop < -1 || cong_drop > 1) {
		printf("Invalid hw.cxgbe.cong_drop value (%d),"
		    " using 0 instead.\n", cong_drop);
		cong_drop = 0;
	}

	if (tscale != 1 && (tscale < 3 || tscale > 17)) {
		printf("Invalid hw.cxgbe.tscale value (%d),"
		    " using 1 instead.\n", tscale);
		tscale = 1;
	}

	if (largest_rx_cluster != MCLBYTES &&
#if MJUMPAGESIZE != MCLBYTES
	    largest_rx_cluster != MJUMPAGESIZE &&
#endif
	    largest_rx_cluster != MJUM9BYTES &&
	    largest_rx_cluster != MJUM16BYTES) {
		printf("Invalid hw.cxgbe.largest_rx_cluster value (%d),"
		    " using %d instead.\n", largest_rx_cluster, MJUM16BYTES);
		largest_rx_cluster = MJUM16BYTES;
	}

	if (safest_rx_cluster != MCLBYTES &&
#if MJUMPAGESIZE != MCLBYTES
	    safest_rx_cluster != MJUMPAGESIZE &&
#endif
	    safest_rx_cluster != MJUM9BYTES &&
	    safest_rx_cluster != MJUM16BYTES) {
		printf("Invalid hw.cxgbe.safest_rx_cluster value (%d),"
		    " using %d instead.\n", safest_rx_cluster, MJUMPAGESIZE);
		safest_rx_cluster = MJUMPAGESIZE;
	}

	extfree_refs = counter_u64_alloc(M_WAITOK);
	extfree_rels = counter_u64_alloc(M_WAITOK);
	pullups = counter_u64_alloc(M_WAITOK);
	defrags = counter_u64_alloc(M_WAITOK);
	counter_u64_zero(extfree_refs);
	counter_u64_zero(extfree_rels);
	counter_u64_zero(pullups);
	counter_u64_zero(defrags);

	t4_init_shared_cpl_handlers();
	t4_register_cpl_handler(CPL_FW4_MSG, handle_fw_msg);
	t4_register_cpl_handler(CPL_FW6_MSG, handle_fw_msg);
	t4_register_cpl_handler(CPL_SGE_EGR_UPDATE, handle_sge_egr_update);
#ifdef RATELIMIT
	t4_register_shared_cpl_handler(CPL_FW4_ACK, ethofld_fw4_ack,
	    CPL_COOKIE_ETHOFLD);
#endif
	t4_register_fw_msg_handler(FW6_TYPE_CMD_RPL, t4_handle_fw_rpl);
	t4_register_fw_msg_handler(FW6_TYPE_WRERR_RPL, t4_handle_wrerr_rpl);
}

void
t4_sge_modunload(void)
{

	counter_u64_free(extfree_refs);
	counter_u64_free(extfree_rels);
	counter_u64_free(pullups);
	counter_u64_free(defrags);
}

uint64_t
t4_sge_extfree_refs(void)
{
	uint64_t refs, rels;

	rels = counter_u64_fetch(extfree_rels);
	refs = counter_u64_fetch(extfree_refs);

	return (refs - rels);
}

/* max 4096 */
#define MAX_PACK_BOUNDARY 512

static inline void
setup_pad_and_pack_boundaries(struct adapter *sc)
{
	uint32_t v, m;
	int pad, pack, pad_shift;

	pad_shift = chip_id(sc) > CHELSIO_T5 ? X_T6_INGPADBOUNDARY_SHIFT :
	    X_INGPADBOUNDARY_SHIFT;
	pad = fl_pad;
	if (fl_pad < (1 << pad_shift) ||
	    fl_pad > (1 << (pad_shift + M_INGPADBOUNDARY)) ||
	    !powerof2(fl_pad)) {
		/*
		 * If there is any chance that we might use buffer packing and
		 * the chip is a T4, then pick 64 as the pad/pack boundary.  Set
		 * it to the minimum allowed in all other cases.
		 */
		pad = is_t4(sc) && buffer_packing ? 64 : 1 << pad_shift;

		/*
		 * For fl_pad = 0 we'll still write a reasonable value to the
		 * register but all the freelists will opt out of padding.
		 * We'll complain here only if the user tried to set it to a
		 * value greater than 0 that was invalid.
		 */
		if (fl_pad > 0) {
			device_printf(sc->dev, "Invalid hw.cxgbe.fl_pad value"
			    " (%d), using %d instead.\n", fl_pad, pad);
		}
	}
	m = V_INGPADBOUNDARY(M_INGPADBOUNDARY);
	v = V_INGPADBOUNDARY(ilog2(pad) - pad_shift);
	t4_set_reg_field(sc, A_SGE_CONTROL, m, v);

	if (is_t4(sc)) {
		if (fl_pack != -1 && fl_pack != pad) {
			/* Complain but carry on. */
			device_printf(sc->dev, "hw.cxgbe.fl_pack (%d) ignored,"
			    " using %d instead.\n", fl_pack, pad);
		}
		return;
	}

	pack = fl_pack;
	if (fl_pack < 16 || fl_pack == 32 || fl_pack > 4096 ||
	    !powerof2(fl_pack)) {
		if (sc->params.pci.mps > MAX_PACK_BOUNDARY)
			pack = MAX_PACK_BOUNDARY;
		else
			pack = max(sc->params.pci.mps, CACHE_LINE_SIZE);
		MPASS(powerof2(pack));
		if (pack < 16)
			pack = 16;
		if (pack == 32)
			pack = 64;
		if (pack > 4096)
			pack = 4096;
		if (fl_pack != -1) {
			device_printf(sc->dev, "Invalid hw.cxgbe.fl_pack value"
			    " (%d), using %d instead.\n", fl_pack, pack);
		}
	}
	m = V_INGPACKBOUNDARY(M_INGPACKBOUNDARY);
	if (pack == 16)
		v = V_INGPACKBOUNDARY(0);
	else
		v = V_INGPACKBOUNDARY(ilog2(pack) - 5);

	MPASS(!is_t4(sc));	/* T4 doesn't have SGE_CONTROL2 */
	t4_set_reg_field(sc, A_SGE_CONTROL2, m, v);
}

/*
 * adap->params.vpd.cclk must be set up before this is called.
 */
void
t4_tweak_chip_settings(struct adapter *sc)
{
	int i, reg;
	uint32_t v, m;
	int intr_timer[SGE_NTIMERS] = {1, 5, 10, 50, 100, 200};
	int timer_max = M_TIMERVALUE0 * 1000 / sc->params.vpd.cclk;
	int intr_pktcount[SGE_NCOUNTERS] = {1, 8, 16, 32}; /* 63 max */
	uint16_t indsz = min(RX_COPY_THRESHOLD - 1, M_INDICATESIZE);
	static int sw_buf_sizes[] = {
		MCLBYTES,
#if MJUMPAGESIZE != MCLBYTES
		MJUMPAGESIZE,
#endif
		MJUM9BYTES,
		MJUM16BYTES
	};

	KASSERT(sc->flags & MASTER_PF,
	    ("%s: trying to change chip settings when not master.", __func__));

	m = V_PKTSHIFT(M_PKTSHIFT) | F_RXPKTCPLMODE | F_EGRSTATUSPAGESIZE;
	v = V_PKTSHIFT(fl_pktshift) | F_RXPKTCPLMODE |
	    V_EGRSTATUSPAGESIZE(spg_len == 128);
	t4_set_reg_field(sc, A_SGE_CONTROL, m, v);

	setup_pad_and_pack_boundaries(sc);

	v = V_HOSTPAGESIZEPF0(PAGE_SHIFT - 10) |
	    V_HOSTPAGESIZEPF1(PAGE_SHIFT - 10) |
	    V_HOSTPAGESIZEPF2(PAGE_SHIFT - 10) |
	    V_HOSTPAGESIZEPF3(PAGE_SHIFT - 10) |
	    V_HOSTPAGESIZEPF4(PAGE_SHIFT - 10) |
	    V_HOSTPAGESIZEPF5(PAGE_SHIFT - 10) |
	    V_HOSTPAGESIZEPF6(PAGE_SHIFT - 10) |
	    V_HOSTPAGESIZEPF7(PAGE_SHIFT - 10);
	t4_write_reg(sc, A_SGE_HOST_PAGE_SIZE, v);

	t4_write_reg(sc, A_SGE_FL_BUFFER_SIZE0, 4096);
	t4_write_reg(sc, A_SGE_FL_BUFFER_SIZE1, 65536);
	reg = A_SGE_FL_BUFFER_SIZE2;
	for (i = 0; i < nitems(sw_buf_sizes); i++) {
		MPASS(reg <= A_SGE_FL_BUFFER_SIZE15);
		t4_write_reg(sc, reg, sw_buf_sizes[i]);
		reg += 4;
		MPASS(reg <= A_SGE_FL_BUFFER_SIZE15);
		t4_write_reg(sc, reg, sw_buf_sizes[i] - CL_METADATA_SIZE);
		reg += 4;
	}

	v = V_THRESHOLD_0(intr_pktcount[0]) | V_THRESHOLD_1(intr_pktcount[1]) |
	    V_THRESHOLD_2(intr_pktcount[2]) | V_THRESHOLD_3(intr_pktcount[3]);
	t4_write_reg(sc, A_SGE_INGRESS_RX_THRESHOLD, v);

	KASSERT(intr_timer[0] <= timer_max,
	    ("%s: not a single usable timer (%d, %d)", __func__, intr_timer[0],
	    timer_max));
	for (i = 1; i < nitems(intr_timer); i++) {
		KASSERT(intr_timer[i] >= intr_timer[i - 1],
		    ("%s: timers not listed in increasing order (%d)",
		    __func__, i));

		while (intr_timer[i] > timer_max) {
			if (i == nitems(intr_timer) - 1) {
				intr_timer[i] = timer_max;
				break;
			}
			intr_timer[i] += intr_timer[i - 1];
			intr_timer[i] /= 2;
		}
	}

	v = V_TIMERVALUE0(us_to_core_ticks(sc, intr_timer[0])) |
	    V_TIMERVALUE1(us_to_core_ticks(sc, intr_timer[1]));
	t4_write_reg(sc, A_SGE_TIMER_VALUE_0_AND_1, v);
	v = V_TIMERVALUE2(us_to_core_ticks(sc, intr_timer[2])) |
	    V_TIMERVALUE3(us_to_core_ticks(sc, intr_timer[3]));
	t4_write_reg(sc, A_SGE_TIMER_VALUE_2_AND_3, v);
	v = V_TIMERVALUE4(us_to_core_ticks(sc, intr_timer[4])) |
	    V_TIMERVALUE5(us_to_core_ticks(sc, intr_timer[5]));
	t4_write_reg(sc, A_SGE_TIMER_VALUE_4_AND_5, v);

	if (chip_id(sc) >= CHELSIO_T6) {
		m = V_TSCALE(M_TSCALE);
		if (tscale == 1)
			v = 0;
		else
			v = V_TSCALE(tscale - 2);
		t4_set_reg_field(sc, A_SGE_ITP_CONTROL, m, v);

		if (sc->debug_flags & DF_DISABLE_TCB_CACHE) {
			m = V_RDTHRESHOLD(M_RDTHRESHOLD) | F_WRTHRTHRESHEN |
			    V_WRTHRTHRESH(M_WRTHRTHRESH);
			t4_tp_pio_read(sc, &v, 1, A_TP_CMM_CONFIG, 1);
			v &= ~m;
			v |= V_RDTHRESHOLD(1) | F_WRTHRTHRESHEN |
			    V_WRTHRTHRESH(16);
			t4_tp_pio_write(sc, &v, 1, A_TP_CMM_CONFIG, 1);
		}
	}

	/* 4K, 16K, 64K, 256K DDP "page sizes" for TDDP */
	v = V_HPZ0(0) | V_HPZ1(2) | V_HPZ2(4) | V_HPZ3(6);
	t4_write_reg(sc, A_ULP_RX_TDDP_PSZ, v);

	/*
	 * 4K, 8K, 16K, 64K DDP "page sizes" for iSCSI DDP.  These have been
	 * chosen with MAXPHYS = 128K in mind.  The largest DDP buffer that we
	 * may have to deal with is MAXPHYS + 1 page.
	 */
	v = V_HPZ0(0) | V_HPZ1(1) | V_HPZ2(2) | V_HPZ3(4);
	t4_write_reg(sc, A_ULP_RX_ISCSI_PSZ, v);

	/* We use multiple DDP page sizes both in plain-TOE and ISCSI modes. */
	m = v = F_TDDPTAGTCB | F_ISCSITAGTCB;
	t4_set_reg_field(sc, A_ULP_RX_CTL, m, v);

	m = V_INDICATESIZE(M_INDICATESIZE) | F_REARMDDPOFFSET |
	    F_RESETDDPOFFSET;
	v = V_INDICATESIZE(indsz) | F_REARMDDPOFFSET | F_RESETDDPOFFSET;
	t4_set_reg_field(sc, A_TP_PARA_REG5, m, v);
}

/*
 * SGE wants the buffer to be at least 64B and then a multiple of 16.  Its
 * address mut be 16B aligned.  If padding is in use the buffer's start and end
 * need to be aligned to the pad boundary as well.  We'll just make sure that
 * the size is a multiple of the pad boundary here, it is up to the buffer
 * allocation code to make sure the start of the buffer is aligned.
 */
static inline int
hwsz_ok(struct adapter *sc, int hwsz)
{
	int mask = fl_pad ? sc->params.sge.pad_boundary - 1 : 16 - 1;

	return (hwsz >= 64 && (hwsz & mask) == 0);
}

/*
 * XXX: driver really should be able to deal with unexpected settings.
 */
int
t4_read_chip_settings(struct adapter *sc)
{
	struct sge *s = &sc->sge;
	struct sge_params *sp = &sc->params.sge;
	int i, j, n, rc = 0;
	uint32_t m, v, r;
	uint16_t indsz = min(RX_COPY_THRESHOLD - 1, M_INDICATESIZE);
	static int sw_buf_sizes[] = {	/* Sorted by size */
		MCLBYTES,
#if MJUMPAGESIZE != MCLBYTES
		MJUMPAGESIZE,
#endif
		MJUM9BYTES,
		MJUM16BYTES
	};
	struct rx_buf_info *rxb;

	m = F_RXPKTCPLMODE;
	v = F_RXPKTCPLMODE;
	r = sc->params.sge.sge_control;
	if ((r & m) != v) {
		device_printf(sc->dev, "invalid SGE_CONTROL(0x%x)\n", r);
		rc = EINVAL;
	}

	/*
	 * If this changes then every single use of PAGE_SHIFT in the driver
	 * needs to be carefully reviewed for PAGE_SHIFT vs sp->page_shift.
	 */
	if (sp->page_shift != PAGE_SHIFT) {
		device_printf(sc->dev, "invalid SGE_HOST_PAGE_SIZE(0x%x)\n", r);
		rc = EINVAL;
	}

	s->safe_zidx = -1;
	rxb = &s->rx_buf_info[0];
	for (i = 0; i < SW_ZONE_SIZES; i++, rxb++) {
		rxb->size1 = sw_buf_sizes[i];
		rxb->zone = m_getzone(rxb->size1);
		rxb->type = m_gettype(rxb->size1);
		rxb->size2 = 0;
		rxb->hwidx1 = -1;
		rxb->hwidx2 = -1;
		for (j = 0; j < SGE_FLBUF_SIZES; j++) {
			int hwsize = sp->sge_fl_buffer_size[j];

			if (!hwsz_ok(sc, hwsize))
				continue;

			/* hwidx for size1 */
			if (rxb->hwidx1 == -1 && rxb->size1 == hwsize)
				rxb->hwidx1 = j;

			/* hwidx for size2 (buffer packing) */
			if (rxb->size1 - CL_METADATA_SIZE < hwsize)
				continue;
			n = rxb->size1 - hwsize - CL_METADATA_SIZE;
			if (n == 0) {
				rxb->hwidx2 = j;
				rxb->size2 = hwsize;
				break;	/* stop looking */
			}
			if (rxb->hwidx2 != -1) {
				if (n < sp->sge_fl_buffer_size[rxb->hwidx2] -
				    hwsize - CL_METADATA_SIZE) {
					rxb->hwidx2 = j;
					rxb->size2 = hwsize;
				}
			} else if (n <= 2 * CL_METADATA_SIZE) {
				rxb->hwidx2 = j;
				rxb->size2 = hwsize;
			}
		}
		if (rxb->hwidx2 != -1)
			sc->flags |= BUF_PACKING_OK;
		if (s->safe_zidx == -1 && rxb->size1 == safest_rx_cluster)
			s->safe_zidx = i;
	}

	if (sc->flags & IS_VF)
		return (0);

	v = V_HPZ0(0) | V_HPZ1(2) | V_HPZ2(4) | V_HPZ3(6);
	r = t4_read_reg(sc, A_ULP_RX_TDDP_PSZ);
	if (r != v) {
		device_printf(sc->dev, "invalid ULP_RX_TDDP_PSZ(0x%x)\n", r);
		rc = EINVAL;
	}

	m = v = F_TDDPTAGTCB;
	r = t4_read_reg(sc, A_ULP_RX_CTL);
	if ((r & m) != v) {
		device_printf(sc->dev, "invalid ULP_RX_CTL(0x%x)\n", r);
		rc = EINVAL;
	}

	m = V_INDICATESIZE(M_INDICATESIZE) | F_REARMDDPOFFSET |
	    F_RESETDDPOFFSET;
	v = V_INDICATESIZE(indsz) | F_REARMDDPOFFSET | F_RESETDDPOFFSET;
	r = t4_read_reg(sc, A_TP_PARA_REG5);
	if ((r & m) != v) {
		device_printf(sc->dev, "invalid TP_PARA_REG5(0x%x)\n", r);
		rc = EINVAL;
	}

	t4_init_tp_params(sc, 1);

	t4_read_mtu_tbl(sc, sc->params.mtus, NULL);
	t4_load_mtus(sc, sc->params.mtus, sc->params.a_wnd, sc->params.b_wnd);

	return (rc);
}

int
t4_create_dma_tag(struct adapter *sc)
{
	int rc;

	rc = bus_dma_tag_create(bus_get_dma_tag(sc->dev), 1, 0,
	    BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL, BUS_SPACE_MAXSIZE,
	    BUS_SPACE_UNRESTRICTED, BUS_SPACE_MAXSIZE, BUS_DMA_ALLOCNOW, NULL,
	    NULL, &sc->dmat);
	if (rc != 0) {
		device_printf(sc->dev,
		    "failed to create main DMA tag: %d\n", rc);
	}

	return (rc);
}

void
t4_sge_sysctls(struct adapter *sc, struct sysctl_ctx_list *ctx,
    struct sysctl_oid_list *children)
{
	struct sge_params *sp = &sc->params.sge;

	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "buffer_sizes",
	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
	    sysctl_bufsizes, "A", "freelist buffer sizes");

	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "fl_pktshift", CTLFLAG_RD,
	    NULL, sp->fl_pktshift, "payload DMA offset in rx buffer (bytes)");

	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "fl_pad", CTLFLAG_RD,
	    NULL, sp->pad_boundary, "payload pad boundary (bytes)");

	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "spg_len", CTLFLAG_RD,
	    NULL, sp->spg_len, "status page size (bytes)");

	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_drop", CTLFLAG_RD,
	    NULL, cong_drop, "congestion drop setting");

	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "fl_pack", CTLFLAG_RD,
	    NULL, sp->pack_boundary, "payload pack boundary (bytes)");
}

int
t4_destroy_dma_tag(struct adapter *sc)
{
	if (sc->dmat)
		bus_dma_tag_destroy(sc->dmat);

	return (0);
}

/*
 * Allocate and initialize the firmware event queue, control queues, and special
 * purpose rx queues owned by the adapter.
 *
 * Returns errno on failure.  Resources allocated up to that point may still be
 * allocated.  Caller is responsible for cleanup in case this function fails.
 */
int
t4_setup_adapter_queues(struct adapter *sc)
{
	struct sysctl_oid *oid;
	struct sysctl_oid_list *children;
	int rc, i;

	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);

	sysctl_ctx_init(&sc->ctx);
	sc->flags |= ADAP_SYSCTL_CTX;

	/*
	 * Firmware event queue
	 */
	rc = alloc_fwq(sc);
	if (rc != 0)
		return (rc);

	/*
	 * That's all for the VF driver.
	 */
	if (sc->flags & IS_VF)
		return (rc);

	oid = device_get_sysctl_tree(sc->dev);
	children = SYSCTL_CHILDREN(oid);

	/*
	 * XXX: General purpose rx queues, one per port.
	 */

	/*
	 * Control queues, one per port.
	 */
	oid = SYSCTL_ADD_NODE(&sc->ctx, children, OID_AUTO, "ctrlq",
	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "control queues");
	for_each_port(sc, i) {
		struct sge_wrq *ctrlq = &sc->sge.ctrlq[i];

		rc = alloc_ctrlq(sc, ctrlq, i, oid);
		if (rc != 0)
			return (rc);
	}

	return (rc);
}

/*
 * Idempotent
 */
int
t4_teardown_adapter_queues(struct adapter *sc)
{
	int i;

	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);

	/* Do this before freeing the queue */
	if (sc->flags & ADAP_SYSCTL_CTX) {
		sysctl_ctx_free(&sc->ctx);
		sc->flags &= ~ADAP_SYSCTL_CTX;
	}

	if (!(sc->flags & IS_VF)) {
		for_each_port(sc, i)
			free_wrq(sc, &sc->sge.ctrlq[i]);
	}
	free_fwq(sc);

	return (0);
}

/* Maximum payload that could arrive with a single iq descriptor. */
static inline int
max_rx_payload(struct adapter *sc, struct ifnet *ifp, const bool ofld)
{
	int maxp;

	/* large enough even when hw VLAN extraction is disabled */
	maxp = sc->params.sge.fl_pktshift + ETHER_HDR_LEN +
	    ETHER_VLAN_ENCAP_LEN + ifp->if_mtu;
	if (ofld && sc->tt.tls && sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS &&
	    maxp < sc->params.tp.max_rx_pdu)
		maxp = sc->params.tp.max_rx_pdu;
	return (maxp);
}

int
t4_setup_vi_queues(struct vi_info *vi)
{
	int rc = 0, i, intr_idx, iqidx;
	struct sge_rxq *rxq;
	struct sge_txq *txq;
#ifdef TCP_OFFLOAD
	struct sge_ofld_rxq *ofld_rxq;
#endif
#if defined(TCP_OFFLOAD) || defined(RATELIMIT)
	struct sge_wrq *ofld_txq;
#endif
#ifdef DEV_NETMAP
	int saved_idx;
	struct sge_nm_rxq *nm_rxq;
	struct sge_nm_txq *nm_txq;
#endif
	char name[16];
	struct port_info *pi = vi->pi;
	struct adapter *sc = pi->adapter;
	struct ifnet *ifp = vi->ifp;
	struct sysctl_oid *oid = device_get_sysctl_tree(vi->dev);
	struct sysctl_oid_list *children = SYSCTL_CHILDREN(oid);
	int maxp;

	/* Interrupt vector to start from (when using multiple vectors) */
	intr_idx = vi->first_intr;

#ifdef DEV_NETMAP
	saved_idx = intr_idx;
	if (ifp->if_capabilities & IFCAP_NETMAP) {

		/* netmap is supported with direct interrupts only. */
		MPASS(!forwarding_intr_to_fwq(sc));

		/*
		 * We don't have buffers to back the netmap rx queues
		 * right now so we create the queues in a way that
		 * doesn't set off any congestion signal in the chip.
		 */
		oid = SYSCTL_ADD_NODE(&vi->ctx, children, OID_AUTO, "nm_rxq",
		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "rx queues");
		for_each_nm_rxq(vi, i, nm_rxq) {
			rc = alloc_nm_rxq(vi, nm_rxq, intr_idx, i, oid);
			if (rc != 0)
				goto done;
			intr_idx++;
		}

		oid = SYSCTL_ADD_NODE(&vi->ctx, children, OID_AUTO, "nm_txq",
		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "tx queues");
		for_each_nm_txq(vi, i, nm_txq) {
			iqidx = vi->first_nm_rxq + (i % vi->nnmrxq);
			rc = alloc_nm_txq(vi, nm_txq, iqidx, i, oid);
			if (rc != 0)
				goto done;
		}
	}

	/* Normal rx queues and netmap rx queues share the same interrupts. */
	intr_idx = saved_idx;
#endif

	/*
	 * Allocate rx queues first because a default iqid is required when
	 * creating a tx queue.
	 */
	maxp = max_rx_payload(sc, ifp, false);
	oid = SYSCTL_ADD_NODE(&vi->ctx, children, OID_AUTO, "rxq",
	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "rx queues");
	for_each_rxq(vi, i, rxq) {

		init_iq(&rxq->iq, sc, vi->tmr_idx, vi->pktc_idx, vi->qsize_rxq);

		snprintf(name, sizeof(name), "%s rxq%d-fl",
		    device_get_nameunit(vi->dev), i);
		init_fl(sc, &rxq->fl, vi->qsize_rxq / 8, maxp, name);

		rc = alloc_rxq(vi, rxq,
		    forwarding_intr_to_fwq(sc) ? -1 : intr_idx, i, oid);
		if (rc != 0)
			goto done;
		intr_idx++;
	}
#ifdef DEV_NETMAP
	if (ifp->if_capabilities & IFCAP_NETMAP)
		intr_idx = saved_idx + max(vi->nrxq, vi->nnmrxq);
#endif
#ifdef TCP_OFFLOAD
	maxp = max_rx_payload(sc, ifp, true);
	oid = SYSCTL_ADD_NODE(&vi->ctx, children, OID_AUTO, "ofld_rxq",
	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "rx queues for offloaded TCP connections");
	for_each_ofld_rxq(vi, i, ofld_rxq) {

		init_iq(&ofld_rxq->iq, sc, vi->ofld_tmr_idx, vi->ofld_pktc_idx,
		    vi->qsize_rxq);

		snprintf(name, sizeof(name), "%s ofld_rxq%d-fl",
		    device_get_nameunit(vi->dev), i);
		init_fl(sc, &ofld_rxq->fl, vi->qsize_rxq / 8, maxp, name);

		rc = alloc_ofld_rxq(vi, ofld_rxq,
		    forwarding_intr_to_fwq(sc) ? -1 : intr_idx, i, oid);
		if (rc != 0)
			goto done;
		intr_idx++;
	}
#endif

	/*
	 * Now the tx queues.
	 */
	oid = SYSCTL_ADD_NODE(&vi->ctx, children, OID_AUTO, "txq",
	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "tx queues");
	for_each_txq(vi, i, txq) {
		iqidx = vi->first_rxq + (i % vi->nrxq);
		snprintf(name, sizeof(name), "%s txq%d",
		    device_get_nameunit(vi->dev), i);
		init_eq(sc, &txq->eq, EQ_ETH, vi->qsize_txq, pi->tx_chan,
		    sc->sge.rxq[iqidx].iq.cntxt_id, name);

		rc = alloc_txq(vi, txq, i, oid);
		if (rc != 0)
			goto done;
	}
#if defined(TCP_OFFLOAD) || defined(RATELIMIT)
	oid = SYSCTL_ADD_NODE(&vi->ctx, children, OID_AUTO, "ofld_txq",
	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "tx queues for TOE/ETHOFLD");
	for_each_ofld_txq(vi, i, ofld_txq) {
		struct sysctl_oid *oid2;

		snprintf(name, sizeof(name), "%s ofld_txq%d",
		    device_get_nameunit(vi->dev), i);
		if (vi->nofldrxq > 0) {
			iqidx = vi->first_ofld_rxq + (i % vi->nofldrxq);
			init_eq(sc, &ofld_txq->eq, EQ_OFLD, vi->qsize_txq,
			    pi->tx_chan, sc->sge.ofld_rxq[iqidx].iq.cntxt_id,
			    name);
		} else {
			iqidx = vi->first_rxq + (i % vi->nrxq);
			init_eq(sc, &ofld_txq->eq, EQ_OFLD, vi->qsize_txq,
			    pi->tx_chan, sc->sge.rxq[iqidx].iq.cntxt_id, name);
		}

		snprintf(name, sizeof(name), "%d", i);
		oid2 = SYSCTL_ADD_NODE(&vi->ctx, SYSCTL_CHILDREN(oid), OID_AUTO,
		    name, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "offload tx queue");

		rc = alloc_wrq(sc, vi, ofld_txq, oid2);
		if (rc != 0)
			goto done;
	}
#endif
done:
	if (rc)
		t4_teardown_vi_queues(vi);

	return (rc);
}

/*
 * Idempotent
 */
int
t4_teardown_vi_queues(struct vi_info *vi)
{
	int i;
	struct sge_rxq *rxq;
	struct sge_txq *txq;
#if defined(TCP_OFFLOAD) || defined(RATELIMIT)
	struct port_info *pi = vi->pi;
	struct adapter *sc = pi->adapter;
	struct sge_wrq *ofld_txq;
#endif
#ifdef TCP_OFFLOAD
	struct sge_ofld_rxq *ofld_rxq;
#endif
#ifdef DEV_NETMAP
	struct sge_nm_rxq *nm_rxq;
	struct sge_nm_txq *nm_txq;
#endif

	/* Do this before freeing the queues */
	if (vi->flags & VI_SYSCTL_CTX) {
		sysctl_ctx_free(&vi->ctx);
		vi->flags &= ~VI_SYSCTL_CTX;
	}

#ifdef DEV_NETMAP
	if (vi->ifp->if_capabilities & IFCAP_NETMAP) {
		for_each_nm_txq(vi, i, nm_txq) {
			free_nm_txq(vi, nm_txq);
		}

		for_each_nm_rxq(vi, i, nm_rxq) {
			free_nm_rxq(vi, nm_rxq);
		}
	}
#endif

	/*
	 * Take down all the tx queues first, as they reference the rx queues
	 * (for egress updates, etc.).
	 */

	for_each_txq(vi, i, txq) {
		free_txq(vi, txq);
	}
#if defined(TCP_OFFLOAD) || defined(RATELIMIT)
	for_each_ofld_txq(vi, i, ofld_txq) {
		free_wrq(sc, ofld_txq);
	}
#endif

	/*
	 * Then take down the rx queues.
	 */

	for_each_rxq(vi, i, rxq) {
		free_rxq(vi, rxq);
	}
#ifdef TCP_OFFLOAD
	for_each_ofld_rxq(vi, i, ofld_rxq) {
		free_ofld_rxq(vi, ofld_rxq);
	}
#endif

	return (0);
}

/*
 * Interrupt handler when the driver is using only 1 interrupt.  This is a very
 * unusual scenario.
 *
 * a) Deals with errors, if any.
 * b) Services firmware event queue, which is taking interrupts for all other
 *    queues.
 */
void
t4_intr_all(void *arg)
{
	struct adapter *sc = arg;
	struct sge_iq *fwq = &sc->sge.fwq;

	MPASS(sc->intr_count == 1);

	if (sc->intr_type == INTR_INTX)
		t4_write_reg(sc, MYPF_REG(A_PCIE_PF_CLI), 0);

	t4_intr_err(arg);
	t4_intr_evt(fwq);
}

/*
 * Interrupt handler for errors (installed directly when multiple interrupts are
 * being used, or called by t4_intr_all).
 */
void
t4_intr_err(void *arg)
{
	struct adapter *sc = arg;
	uint32_t v;
	const bool verbose = (sc->debug_flags & DF_VERBOSE_SLOWINTR) != 0;

	if (sc->flags & ADAP_ERR)
		return;

	v = t4_read_reg(sc, MYPF_REG(A_PL_PF_INT_CAUSE));
	if (v & F_PFSW) {
		sc->swintr++;
		t4_write_reg(sc, MYPF_REG(A_PL_PF_INT_CAUSE), v);
	}

	t4_slow_intr_handler(sc, verbose);
}

/*
 * Interrupt handler for iq-only queues.  The firmware event queue is the only
 * such queue right now.
 */
void
t4_intr_evt(void *arg)
{
	struct sge_iq *iq = arg;

	if (atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_BUSY)) {
		service_iq(iq, 0);
		(void) atomic_cmpset_int(&iq->state, IQS_BUSY, IQS_IDLE);
	}
}

/*
 * Interrupt handler for iq+fl queues.
 */
void
t4_intr(void *arg)
{
	struct sge_iq *iq = arg;

	if (atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_BUSY)) {
		service_iq_fl(iq, 0);
		(void) atomic_cmpset_int(&iq->state, IQS_BUSY, IQS_IDLE);
	}
}

#ifdef DEV_NETMAP
/*
 * Interrupt handler for netmap rx queues.
 */
void
t4_nm_intr(void *arg)
{
	struct sge_nm_rxq *nm_rxq = arg;

	if (atomic_cmpset_int(&nm_rxq->nm_state, NM_ON, NM_BUSY)) {
		service_nm_rxq(nm_rxq);
		(void) atomic_cmpset_int(&nm_rxq->nm_state, NM_BUSY, NM_ON);
	}
}

/*
 * Interrupt handler for vectors shared between NIC and netmap rx queues.
 */
void
t4_vi_intr(void *arg)
{
	struct irq *irq = arg;

	MPASS(irq->nm_rxq != NULL);
	t4_nm_intr(irq->nm_rxq);

	MPASS(irq->rxq != NULL);
	t4_intr(irq->rxq);
}
#endif

/*
 * Deals with interrupts on an iq-only (no freelist) queue.
 */
static int
service_iq(struct sge_iq *iq, int budget)
{
	struct sge_iq *q;
	struct adapter *sc = iq->adapter;
	struct iq_desc *d = &iq->desc[iq->cidx];
	int ndescs = 0, limit;
	int rsp_type;
	uint32_t lq;
	STAILQ_HEAD(, sge_iq) iql = STAILQ_HEAD_INITIALIZER(iql);

	KASSERT(iq->state == IQS_BUSY, ("%s: iq %p not BUSY", __func__, iq));
	KASSERT((iq->flags & IQ_HAS_FL) == 0,
	    ("%s: called for iq %p with fl (iq->flags 0x%x)", __func__, iq,
	    iq->flags));
	MPASS((iq->flags & IQ_ADJ_CREDIT) == 0);
	MPASS((iq->flags & IQ_LRO_ENABLED) == 0);

	limit = budget ? budget : iq->qsize / 16;

	/*
	 * We always come back and check the descriptor ring for new indirect
	 * interrupts and other responses after running a single handler.
	 */
	for (;;) {
		while ((d->rsp.u.type_gen & F_RSPD_GEN) == iq->gen) {

			rmb();

			rsp_type = G_RSPD_TYPE(d->rsp.u.type_gen);
			lq = be32toh(d->rsp.pldbuflen_qid);

			switch (rsp_type) {
			case X_RSPD_TYPE_FLBUF:
				panic("%s: data for an iq (%p) with no freelist",
				    __func__, iq);

				/* NOTREACHED */

			case X_RSPD_TYPE_CPL:
				KASSERT(d->rss.opcode < NUM_CPL_CMDS,
				    ("%s: bad opcode %02x.", __func__,
				    d->rss.opcode));
				t4_cpl_handler[d->rss.opcode](iq, &d->rss, NULL);
				break;

			case X_RSPD_TYPE_INTR:
				/*
				 * There are 1K interrupt-capable queues (qids 0
				 * through 1023).  A response type indicating a
				 * forwarded interrupt with a qid >= 1K is an
				 * iWARP async notification.
				 */
				if (__predict_true(lq >= 1024)) {
					t4_an_handler(iq, &d->rsp);
					break;
				}

				q = sc->sge.iqmap[lq - sc->sge.iq_start -
				    sc->sge.iq_base];
				if (atomic_cmpset_int(&q->state, IQS_IDLE,
				    IQS_BUSY)) {
					if (service_iq_fl(q, q->qsize / 16) == 0) {
						(void) atomic_cmpset_int(&q->state,
						    IQS_BUSY, IQS_IDLE);
					} else {
						STAILQ_INSERT_TAIL(&iql, q,
						    link);
					}
				}
				break;

			default:
				KASSERT(0,
				    ("%s: illegal response type %d on iq %p",
				    __func__, rsp_type, iq));
				log(LOG_ERR,
				    "%s: illegal response type %d on iq %p",
				    device_get_nameunit(sc->dev), rsp_type, iq);
				break;
			}

			d++;
			if (__predict_false(++iq->cidx == iq->sidx)) {
				iq->cidx = 0;
				iq->gen ^= F_RSPD_GEN;
				d = &iq->desc[0];
			}
			if (__predict_false(++ndescs == limit)) {
				t4_write_reg(sc, sc->sge_gts_reg,
				    V_CIDXINC(ndescs) |
				    V_INGRESSQID(iq->cntxt_id) |
				    V_SEINTARM(V_QINTR_TIMER_IDX(X_TIMERREG_UPDATE_CIDX)));
				ndescs = 0;

				if (budget) {
					return (EINPROGRESS);
				}
			}
		}

		if (STAILQ_EMPTY(&iql))
			break;

		/*
		 * Process the head only, and send it to the back of the list if
		 * it's still not done.
		 */
		q = STAILQ_FIRST(&iql);
		STAILQ_REMOVE_HEAD(&iql, link);
		if (service_iq_fl(q, q->qsize / 8) == 0)
			(void) atomic_cmpset_int(&q->state, IQS_BUSY, IQS_IDLE);
		else
			STAILQ_INSERT_TAIL(&iql, q, link);
	}

	t4_write_reg(sc, sc->sge_gts_reg, V_CIDXINC(ndescs) |
	    V_INGRESSQID((u32)iq->cntxt_id) | V_SEINTARM(iq->intr_params));

	return (0);
}

static inline int
sort_before_lro(struct lro_ctrl *lro)
{

	return (lro->lro_mbuf_max != 0);
}

static inline uint64_t
last_flit_to_ns(struct adapter *sc, uint64_t lf)
{
	uint64_t n = be64toh(lf) & 0xfffffffffffffff;	/* 60b, not 64b. */

	if (n > UINT64_MAX / 1000000)
		return (n / sc->params.vpd.cclk * 1000000);
	else
		return (n * 1000000 / sc->params.vpd.cclk);
}

static inline void
move_to_next_rxbuf(struct sge_fl *fl)
{

	fl->rx_offset = 0;
	if (__predict_false((++fl->cidx & 7) == 0)) {
		uint16_t cidx = fl->cidx >> 3;

		if (__predict_false(cidx == fl->sidx))
			fl->cidx = cidx = 0;
		fl->hw_cidx = cidx;
	}
}

/*
 * Deals with interrupts on an iq+fl queue.
 */
static int
service_iq_fl(struct sge_iq *iq, int budget)
{
	struct sge_rxq *rxq = iq_to_rxq(iq);
	struct sge_fl *fl;
	struct adapter *sc = iq->adapter;
	struct iq_desc *d = &iq->desc[iq->cidx];
	int ndescs, limit;
	int rsp_type, starved;
	uint32_t lq;
	uint16_t fl_hw_cidx;
	struct mbuf *m0;
#if defined(INET) || defined(INET6)
	const struct timeval lro_timeout = {0, sc->lro_timeout};
	struct lro_ctrl *lro = &rxq->lro;
#endif

	KASSERT(iq->state == IQS_BUSY, ("%s: iq %p not BUSY", __func__, iq));
	MPASS(iq->flags & IQ_HAS_FL);

	ndescs = 0;
#if defined(INET) || defined(INET6)
	if (iq->flags & IQ_ADJ_CREDIT) {
		MPASS(sort_before_lro(lro));
		iq->flags &= ~IQ_ADJ_CREDIT;
		if ((d->rsp.u.type_gen & F_RSPD_GEN) != iq->gen) {
			tcp_lro_flush_all(lro);
			t4_write_reg(sc, sc->sge_gts_reg, V_CIDXINC(1) |
			    V_INGRESSQID((u32)iq->cntxt_id) |
			    V_SEINTARM(iq->intr_params));
			return (0);
		}
		ndescs = 1;
	}
#else
	MPASS((iq->flags & IQ_ADJ_CREDIT) == 0);
#endif

	limit = budget ? budget : iq->qsize / 16;
	fl = &rxq->fl;
	fl_hw_cidx = fl->hw_cidx;	/* stable snapshot */
	while ((d->rsp.u.type_gen & F_RSPD_GEN) == iq->gen) {

		rmb();

		m0 = NULL;
		rsp_type = G_RSPD_TYPE(d->rsp.u.type_gen);
		lq = be32toh(d->rsp.pldbuflen_qid);

		switch (rsp_type) {
		case X_RSPD_TYPE_FLBUF:
			if (lq & F_RSPD_NEWBUF) {
				if (fl->rx_offset > 0)
					move_to_next_rxbuf(fl);
				lq = G_RSPD_LEN(lq);
			}
			if (IDXDIFF(fl->hw_cidx, fl_hw_cidx, fl->sidx) > 4) {
				FL_LOCK(fl);
				refill_fl(sc, fl, 64);
				FL_UNLOCK(fl);
				fl_hw_cidx = fl->hw_cidx;
			}

			if (d->rss.opcode == CPL_RX_PKT) {
				if (__predict_true(eth_rx(sc, rxq, d, lq) == 0))
					break;
				goto out;
			}
			m0 = get_fl_payload(sc, fl, lq);
			if (__predict_false(m0 == NULL))
				goto out;

			/* fall through */

		case X_RSPD_TYPE_CPL:
			KASSERT(d->rss.opcode < NUM_CPL_CMDS,
			    ("%s: bad opcode %02x.", __func__, d->rss.opcode));
			t4_cpl_handler[d->rss.opcode](iq, &d->rss, m0);
			break;

		case X_RSPD_TYPE_INTR:

			/*
			 * There are 1K interrupt-capable queues (qids 0
			 * through 1023).  A response type indicating a
			 * forwarded interrupt with a qid >= 1K is an
			 * iWARP async notification.  That is the only
			 * acceptable indirect interrupt on this queue.
			 */
			if (__predict_false(lq < 1024)) {
				panic("%s: indirect interrupt on iq_fl %p "
				    "with qid %u", __func__, iq, lq);
			}

			t4_an_handler(iq, &d->rsp);
			break;

		default:
			KASSERT(0, ("%s: illegal response type %d on iq %p",
			    __func__, rsp_type, iq));
			log(LOG_ERR, "%s: illegal response type %d on iq %p",
			    device_get_nameunit(sc->dev), rsp_type, iq);
			break;
		}

		d++;
		if (__predict_false(++iq->cidx == iq->sidx)) {
			iq->cidx = 0;
			iq->gen ^= F_RSPD_GEN;
			d = &iq->desc[0];
		}
		if (__predict_false(++ndescs == limit)) {
			t4_write_reg(sc, sc->sge_gts_reg, V_CIDXINC(ndescs) |
			    V_INGRESSQID(iq->cntxt_id) |
			    V_SEINTARM(V_QINTR_TIMER_IDX(X_TIMERREG_UPDATE_CIDX)));

#if defined(INET) || defined(INET6)
			if (iq->flags & IQ_LRO_ENABLED &&
			    !sort_before_lro(lro) &&
			    sc->lro_timeout != 0) {
				tcp_lro_flush_inactive(lro, &lro_timeout);
			}
#endif
			if (budget)
				return (EINPROGRESS);
			ndescs = 0;
		}
	}
out:
#if defined(INET) || defined(INET6)
	if (iq->flags & IQ_LRO_ENABLED) {
		if (ndescs > 0 && lro->lro_mbuf_count > 8) {
			MPASS(sort_before_lro(lro));
			/* hold back one credit and don't flush LRO state */
			iq->flags |= IQ_ADJ_CREDIT;
			ndescs--;
		} else {
			tcp_lro_flush_all(lro);
		}
	}
#endif

	t4_write_reg(sc, sc->sge_gts_reg, V_CIDXINC(ndescs) |
	    V_INGRESSQID((u32)iq->cntxt_id) | V_SEINTARM(iq->intr_params));

	FL_LOCK(fl);
	starved = refill_fl(sc, fl, 64);
	FL_UNLOCK(fl);
	if (__predict_false(starved != 0))
		add_fl_to_sfl(sc, fl);

	return (0);
}

static inline struct cluster_metadata *
cl_metadata(struct fl_sdesc *sd)
{

	return ((void *)(sd->cl + sd->moff));
}

static void
rxb_free(struct mbuf *m)
{
	struct cluster_metadata *clm = m->m_ext.ext_arg1;

	uma_zfree(clm->zone, clm->cl);
	counter_u64_add(extfree_rels, 1);
}

/*
 * The mbuf returned comes from zone_muf and carries the payload in one of these
 * ways
 * a) complete frame inside the mbuf
 * b) m_cljset (for clusters without metadata)
 * d) m_extaddref (cluster with metadata)
 */
static struct mbuf *
get_scatter_segment(struct adapter *sc, struct sge_fl *fl, int fr_offset,
    int remaining)
{
	struct mbuf *m;
	struct fl_sdesc *sd = &fl->sdesc[fl->cidx];
	struct rx_buf_info *rxb = &sc->sge.rx_buf_info[sd->zidx];
	struct cluster_metadata *clm;
	int len, blen;
	caddr_t payload;

	if (fl->flags & FL_BUF_PACKING) {
		u_int l, pad;

		blen = rxb->size2 - fl->rx_offset;	/* max possible in this buf */
		len = min(remaining, blen);
		payload = sd->cl + fl->rx_offset;

		l = fr_offset + len;
		pad = roundup2(l, fl->buf_boundary) - l;
		if (fl->rx_offset + len + pad < rxb->size2)
			blen = len + pad;
		MPASS(fl->rx_offset + blen <= rxb->size2);
	} else {
		MPASS(fl->rx_offset == 0);	/* not packing */
		blen = rxb->size1;
		len = min(remaining, blen);
		payload = sd->cl;
	}

	if (fr_offset == 0) {
		m = m_gethdr(M_NOWAIT, MT_DATA);
		if (__predict_false(m == NULL))
			return (NULL);
		m->m_pkthdr.len = remaining;
	} else {
		m = m_get(M_NOWAIT, MT_DATA);
		if (__predict_false(m == NULL))
			return (NULL);
	}
	m->m_len = len;

	if (sc->sc_do_rxcopy && len < RX_COPY_THRESHOLD) {
		/* copy data to mbuf */
		bcopy(payload, mtod(m, caddr_t), len);
		if (fl->flags & FL_BUF_PACKING) {
			fl->rx_offset += blen;
			MPASS(fl->rx_offset <= rxb->size2);
			if (fl->rx_offset < rxb->size2)
				return (m);	/* without advancing the cidx */
		}
	} else if (fl->flags & FL_BUF_PACKING) {
		clm = cl_metadata(sd);
		if (sd->nmbuf++ == 0) {
			clm->refcount = 1;
			clm->zone = rxb->zone;
			clm->cl = sd->cl;
			counter_u64_add(extfree_refs, 1);
		}
		m_extaddref(m, payload, blen, &clm->refcount, rxb_free, clm,
		    NULL);

		fl->rx_offset += blen;
		MPASS(fl->rx_offset <= rxb->size2);
		if (fl->rx_offset < rxb->size2)
			return (m);	/* without advancing the cidx */
	} else {
		m_cljset(m, sd->cl, rxb->type);
		sd->cl = NULL;	/* consumed, not a recycle candidate */
	}

	move_to_next_rxbuf(fl);

	return (m);
}

static struct mbuf *
get_fl_payload(struct adapter *sc, struct sge_fl *fl, const u_int plen)
{
	struct mbuf *m0, *m, **pnext;
	u_int remaining;

	if (__predict_false(fl->flags & FL_BUF_RESUME)) {
		M_ASSERTPKTHDR(fl->m0);
		MPASS(fl->m0->m_pkthdr.len == plen);
		MPASS(fl->remaining < plen);

		m0 = fl->m0;
		pnext = fl->pnext;
		remaining = fl->remaining;
		fl->flags &= ~FL_BUF_RESUME;
		goto get_segment;
	}

	/*
	 * Payload starts at rx_offset in the current hw buffer.  Its length is
	 * 'len' and it may span multiple hw buffers.
	 */

	m0 = get_scatter_segment(sc, fl, 0, plen);
	if (m0 == NULL)
		return (NULL);
	remaining = plen - m0->m_len;
	pnext = &m0->m_next;
	while (remaining > 0) {
get_segment:
		MPASS(fl->rx_offset == 0);
		m = get_scatter_segment(sc, fl, plen - remaining, remaining);
		if (__predict_false(m == NULL)) {
			fl->m0 = m0;
			fl->pnext = pnext;
			fl->remaining = remaining;
			fl->flags |= FL_BUF_RESUME;
			return (NULL);
		}
		*pnext = m;
		pnext = &m->m_next;
		remaining -= m->m_len;
	}
	*pnext = NULL;

	M_ASSERTPKTHDR(m0);
	return (m0);
}

static int
skip_scatter_segment(struct adapter *sc, struct sge_fl *fl, int fr_offset,
    int remaining)
{
	struct fl_sdesc *sd = &fl->sdesc[fl->cidx];
	struct rx_buf_info *rxb = &sc->sge.rx_buf_info[sd->zidx];
	int len, blen;

	if (fl->flags & FL_BUF_PACKING) {
		u_int l, pad;

		blen = rxb->size2 - fl->rx_offset;	/* max possible in this buf */
		len = min(remaining, blen);

		l = fr_offset + len;
		pad = roundup2(l, fl->buf_boundary) - l;
		if (fl->rx_offset + len + pad < rxb->size2)
			blen = len + pad;
		fl->rx_offset += blen;
		MPASS(fl->rx_offset <= rxb->size2);
		if (fl->rx_offset < rxb->size2)
			return (len);	/* without advancing the cidx */
	} else {
		MPASS(fl->rx_offset == 0);	/* not packing */
		blen = rxb->size1;
		len = min(remaining, blen);
	}
	move_to_next_rxbuf(fl);
	return (len);
}

static inline void
skip_fl_payload(struct adapter *sc, struct sge_fl *fl, int plen)
{
	int remaining, fr_offset, len;

	fr_offset = 0;
	remaining = plen;
	while (remaining > 0) {
		len = skip_scatter_segment(sc, fl, fr_offset, remaining);
		fr_offset += len;
		remaining -= len;
	}
}

static inline int
get_segment_len(struct adapter *sc, struct sge_fl *fl, int plen)
{
	int len;
	struct fl_sdesc *sd = &fl->sdesc[fl->cidx];
	struct rx_buf_info *rxb = &sc->sge.rx_buf_info[sd->zidx];

	if (fl->flags & FL_BUF_PACKING)
		len = rxb->size2 - fl->rx_offset;
	else
		len = rxb->size1;

	return (min(plen, len));
}

static int
eth_rx(struct adapter *sc, struct sge_rxq *rxq, const struct iq_desc *d,
    u_int plen)
{
	struct mbuf *m0;
	struct ifnet *ifp = rxq->ifp;
	struct sge_fl *fl = &rxq->fl;
	struct vi_info *vi = ifp->if_softc;
	const struct cpl_rx_pkt *cpl;
#if defined(INET) || defined(INET6)
	struct lro_ctrl *lro = &rxq->lro;
#endif
	uint16_t err_vec, tnl_type, tnlhdr_len;
	static const int sw_hashtype[4][2] = {
		{M_HASHTYPE_NONE, M_HASHTYPE_NONE},
		{M_HASHTYPE_RSS_IPV4, M_HASHTYPE_RSS_IPV6},
		{M_HASHTYPE_RSS_TCP_IPV4, M_HASHTYPE_RSS_TCP_IPV6},
		{M_HASHTYPE_RSS_UDP_IPV4, M_HASHTYPE_RSS_UDP_IPV6},
	};
	static const int sw_csum_flags[2][2] = {
		{
			/* IP, inner IP */
			CSUM_ENCAP_VXLAN |
			    CSUM_L3_CALC | CSUM_L3_VALID |
			    CSUM_L4_CALC | CSUM_L4_VALID |
			    CSUM_INNER_L3_CALC | CSUM_INNER_L3_VALID |
			    CSUM_INNER_L4_CALC | CSUM_INNER_L4_VALID,

			/* IP, inner IP6 */
			CSUM_ENCAP_VXLAN |
			    CSUM_L3_CALC | CSUM_L3_VALID |
			    CSUM_L4_CALC | CSUM_L4_VALID |
			    CSUM_INNER_L4_CALC | CSUM_INNER_L4_VALID,
		},
		{
			/* IP6, inner IP */
			CSUM_ENCAP_VXLAN |
			    CSUM_L4_CALC | CSUM_L4_VALID |
			    CSUM_INNER_L3_CALC | CSUM_INNER_L3_VALID |
			    CSUM_INNER_L4_CALC | CSUM_INNER_L4_VALID,

			/* IP6, inner IP6 */
			CSUM_ENCAP_VXLAN |
			    CSUM_L4_CALC | CSUM_L4_VALID |
			    CSUM_INNER_L4_CALC | CSUM_INNER_L4_VALID,
		},
	};

	MPASS(plen > sc->params.sge.fl_pktshift);
	if (vi->pfil != NULL && PFIL_HOOKED_IN(vi->pfil) &&
	    __predict_true((fl->flags & FL_BUF_RESUME) == 0)) {
		struct fl_sdesc *sd = &fl->sdesc[fl->cidx];
		caddr_t frame;
		int rc, slen;

		slen = get_segment_len(sc, fl, plen) -
		    sc->params.sge.fl_pktshift;
		frame = sd->cl + fl->rx_offset + sc->params.sge.fl_pktshift;
		CURVNET_SET_QUIET(ifp->if_vnet);
		rc = pfil_run_hooks(vi->pfil, frame, ifp,
		    slen | PFIL_MEMPTR | PFIL_IN, NULL);
		CURVNET_RESTORE();
		if (rc == PFIL_DROPPED || rc == PFIL_CONSUMED) {
			skip_fl_payload(sc, fl, plen);
			return (0);
		}
		if (rc == PFIL_REALLOCED) {
			skip_fl_payload(sc, fl, plen);
			m0 = pfil_mem2mbuf(frame);
			goto have_mbuf;
		}
	}

	m0 = get_fl_payload(sc, fl, plen);
	if (__predict_false(m0 == NULL))
		return (ENOMEM);

	m0->m_pkthdr.len -= sc->params.sge.fl_pktshift;
	m0->m_len -= sc->params.sge.fl_pktshift;
	m0->m_data += sc->params.sge.fl_pktshift;

have_mbuf:
	m0->m_pkthdr.rcvif = ifp;
	M_HASHTYPE_SET(m0, sw_hashtype[d->rss.hash_type][d->rss.ipv6]);
	m0->m_pkthdr.flowid = be32toh(d->rss.hash_val);

	cpl = (const void *)(&d->rss + 1);
	if (sc->params.tp.rx_pkt_encap) {
		const uint16_t ev = be16toh(cpl->err_vec);

		err_vec = G_T6_COMPR_RXERR_VEC(ev);
		tnl_type = G_T6_RX_TNL_TYPE(ev);
		tnlhdr_len = G_T6_RX_TNLHDR_LEN(ev);
	} else {
		err_vec = be16toh(cpl->err_vec);
		tnl_type = 0;
		tnlhdr_len = 0;
	}
	if (cpl->csum_calc && err_vec == 0) {
		int ipv6 = !!(cpl->l2info & htobe32(F_RXF_IP6));

		/* checksum(s) calculated and found to be correct. */

		MPASS((cpl->l2info & htobe32(F_RXF_IP)) ^
		    (cpl->l2info & htobe32(F_RXF_IP6)));
		m0->m_pkthdr.csum_data = be16toh(cpl->csum);
		if (tnl_type == 0) {
	    		if (!ipv6 && ifp->if_capenable & IFCAP_RXCSUM) {
				m0->m_pkthdr.csum_flags = CSUM_L3_CALC |
				    CSUM_L3_VALID | CSUM_L4_CALC |
				    CSUM_L4_VALID;
			} else if (ipv6 && ifp->if_capenable & IFCAP_RXCSUM_IPV6) {
				m0->m_pkthdr.csum_flags = CSUM_L4_CALC |
				    CSUM_L4_VALID;
			}
			rxq->rxcsum++;
		} else {
			MPASS(tnl_type == RX_PKT_TNL_TYPE_VXLAN);
			if (__predict_false(cpl->ip_frag)) {
				/*
				 * csum_data is for the inner frame (which is an
				 * IP fragment) and is not 0xffff.  There is no
				 * way to pass the inner csum_data to the stack.
				 * We don't want the stack to use the inner
				 * csum_data to validate the outer frame or it
				 * will get rejected.  So we fix csum_data here
				 * and let sw do the checksum of inner IP
				 * fragments.
				 *
				 * XXX: Need 32b for csum_data2 in an rx mbuf.
				 * Maybe stuff it into rcv_tstmp?
				 */
				m0->m_pkthdr.csum_data = 0xffff;
				if (ipv6) {
					m0->m_pkthdr.csum_flags = CSUM_L4_CALC |
					    CSUM_L4_VALID;
				} else {
					m0->m_pkthdr.csum_flags = CSUM_L3_CALC |
					    CSUM_L3_VALID | CSUM_L4_CALC |
					    CSUM_L4_VALID;
				}
			} else {
				int outer_ipv6;

				MPASS(m0->m_pkthdr.csum_data == 0xffff);

				outer_ipv6 = tnlhdr_len >=
				    sizeof(struct ether_header) +
				    sizeof(struct ip6_hdr);
				m0->m_pkthdr.csum_flags =
				    sw_csum_flags[outer_ipv6][ipv6];
			}
			rxq->vxlan_rxcsum++;
		}
	}

	if (cpl->vlan_ex) {
		m0->m_pkthdr.ether_vtag = be16toh(cpl->vlan);
		m0->m_flags |= M_VLANTAG;
		rxq->vlan_extraction++;
	}

	if (rxq->iq.flags & IQ_RX_TIMESTAMP) {
		/*
		 * Fill up rcv_tstmp but do not set M_TSTMP.
		 * rcv_tstmp is not in the format that the
		 * kernel expects and we don't want to mislead
		 * it.  For now this is only for custom code
		 * that knows how to interpret cxgbe's stamp.
		 */
		m0->m_pkthdr.rcv_tstmp =
		    last_flit_to_ns(sc, d->rsp.u.last_flit);
#ifdef notyet
		m0->m_flags |= M_TSTMP;
#endif
	}

#ifdef NUMA
	m0->m_pkthdr.numa_domain = ifp->if_numa_domain;
#endif
#if defined(INET) || defined(INET6)
	if (rxq->iq.flags & IQ_LRO_ENABLED && tnl_type == 0 &&
	    (M_HASHTYPE_GET(m0) == M_HASHTYPE_RSS_TCP_IPV4 ||
	    M_HASHTYPE_GET(m0) == M_HASHTYPE_RSS_TCP_IPV6)) {
		if (sort_before_lro(lro)) {
			tcp_lro_queue_mbuf(lro, m0);
			return (0); /* queued for sort, then LRO */
		}
		if (tcp_lro_rx(lro, m0, 0) == 0)
			return (0); /* queued for LRO */
	}
#endif
	ifp->if_input(ifp, m0);

	return (0);
}

/*
 * Must drain the wrq or make sure that someone else will.
 */
static void
wrq_tx_drain(void *arg, int n)
{
	struct sge_wrq *wrq = arg;
	struct sge_eq *eq = &wrq->eq;

	EQ_LOCK(eq);
	if (TAILQ_EMPTY(&wrq->incomplete_wrs) && !STAILQ_EMPTY(&wrq->wr_list))
		drain_wrq_wr_list(wrq->adapter, wrq);
	EQ_UNLOCK(eq);
}

static void
drain_wrq_wr_list(struct adapter *sc, struct sge_wrq *wrq)
{
	struct sge_eq *eq = &wrq->eq;
	u_int available, dbdiff;	/* # of hardware descriptors */
	u_int n;
	struct wrqe *wr;
	struct fw_eth_tx_pkt_wr *dst;	/* any fw WR struct will do */

	EQ_LOCK_ASSERT_OWNED(eq);
	MPASS(TAILQ_EMPTY(&wrq->incomplete_wrs));
	wr = STAILQ_FIRST(&wrq->wr_list);
	MPASS(wr != NULL);	/* Must be called with something useful to do */
	MPASS(eq->pidx == eq->dbidx);
	dbdiff = 0;

	do {
		eq->cidx = read_hw_cidx(eq);
		if (eq->pidx == eq->cidx)
			available = eq->sidx - 1;
		else
			available = IDXDIFF(eq->cidx, eq->pidx, eq->sidx) - 1;

		MPASS(wr->wrq == wrq);
		n = howmany(wr->wr_len, EQ_ESIZE);
		if (available < n)
			break;

		dst = (void *)&eq->desc[eq->pidx];
		if (__predict_true(eq->sidx - eq->pidx > n)) {
			/* Won't wrap, won't end exactly at the status page. */
			bcopy(&wr->wr[0], dst, wr->wr_len);
			eq->pidx += n;
		} else {
			int first_portion = (eq->sidx - eq->pidx) * EQ_ESIZE;

			bcopy(&wr->wr[0], dst, first_portion);
			if (wr->wr_len > first_portion) {
				bcopy(&wr->wr[first_portion], &eq->desc[0],
				    wr->wr_len - first_portion);
			}
			eq->pidx = n - (eq->sidx - eq->pidx);
		}
		wrq->tx_wrs_copied++;

		if (available < eq->sidx / 4 &&
		    atomic_cmpset_int(&eq->equiq, 0, 1)) {
				/*
				 * XXX: This is not 100% reliable with some
				 * types of WRs.  But this is a very unusual
				 * situation for an ofld/ctrl queue anyway.
				 */
			dst->equiq_to_len16 |= htobe32(F_FW_WR_EQUIQ |
			    F_FW_WR_EQUEQ);
		}

		dbdiff += n;
		if (dbdiff >= 16) {
			ring_eq_db(sc, eq, dbdiff);
			dbdiff = 0;
		}

		STAILQ_REMOVE_HEAD(&wrq->wr_list, link);
		free_wrqe(wr);
		MPASS(wrq->nwr_pending > 0);
		wrq->nwr_pending--;
		MPASS(wrq->ndesc_needed >= n);
		wrq->ndesc_needed -= n;
	} while ((wr = STAILQ_FIRST(&wrq->wr_list)) != NULL);

	if (dbdiff)
		ring_eq_db(sc, eq, dbdiff);
}

/*
 * Doesn't fail.  Holds on to work requests it can't send right away.
 */
void
t4_wrq_tx_locked(struct adapter *sc, struct sge_wrq *wrq, struct wrqe *wr)
{
#ifdef INVARIANTS
	struct sge_eq *eq = &wrq->eq;
#endif

	EQ_LOCK_ASSERT_OWNED(eq);
	MPASS(wr != NULL);
	MPASS(wr->wr_len > 0 && wr->wr_len <= SGE_MAX_WR_LEN);
	MPASS((wr->wr_len & 0x7) == 0);

	STAILQ_INSERT_TAIL(&wrq->wr_list, wr, link);
	wrq->nwr_pending++;
	wrq->ndesc_needed += howmany(wr->wr_len, EQ_ESIZE);

	if (!TAILQ_EMPTY(&wrq->incomplete_wrs))
		return;	/* commit_wrq_wr will drain wr_list as well. */

	drain_wrq_wr_list(sc, wrq);

	/* Doorbell must have caught up to the pidx. */
	MPASS(eq->pidx == eq->dbidx);
}

void
t4_update_fl_bufsize(struct ifnet *ifp)
{
	struct vi_info *vi = ifp->if_softc;
	struct adapter *sc = vi->adapter;
	struct sge_rxq *rxq;
#ifdef TCP_OFFLOAD
	struct sge_ofld_rxq *ofld_rxq;
#endif
	struct sge_fl *fl;
	int i, maxp;

	maxp = max_rx_payload(sc, ifp, false);
	for_each_rxq(vi, i, rxq) {
		fl = &rxq->fl;

		FL_LOCK(fl);
		fl->zidx = find_refill_source(sc, maxp,
		    fl->flags & FL_BUF_PACKING);
		FL_UNLOCK(fl);
	}
#ifdef TCP_OFFLOAD
	maxp = max_rx_payload(sc, ifp, true);
	for_each_ofld_rxq(vi, i, ofld_rxq) {
		fl = &ofld_rxq->fl;

		FL_LOCK(fl);
		fl->zidx = find_refill_source(sc, maxp,
		    fl->flags & FL_BUF_PACKING);
		FL_UNLOCK(fl);
	}
#endif
}

static inline int
mbuf_nsegs(struct mbuf *m)
{

	M_ASSERTPKTHDR(m);
	KASSERT(m->m_pkthdr.inner_l5hlen > 0,
	    ("%s: mbuf %p missing information on # of segments.", __func__, m));

	return (m->m_pkthdr.inner_l5hlen);
}

static inline void
set_mbuf_nsegs(struct mbuf *m, uint8_t nsegs)
{

	M_ASSERTPKTHDR(m);
	m->m_pkthdr.inner_l5hlen = nsegs;
}

static inline int
mbuf_cflags(struct mbuf *m)
{

	M_ASSERTPKTHDR(m);
	return (m->m_pkthdr.PH_loc.eight[4]);
}

static inline void
set_mbuf_cflags(struct mbuf *m, uint8_t flags)
{

	M_ASSERTPKTHDR(m);
	m->m_pkthdr.PH_loc.eight[4] = flags;
}

static inline int
mbuf_len16(struct mbuf *m)
{
	int n;

	M_ASSERTPKTHDR(m);
	n = m->m_pkthdr.PH_loc.eight[0];
	if (!(mbuf_cflags(m) & MC_TLS))
		MPASS(n > 0 && n <= SGE_MAX_WR_LEN / 16);

	return (n);
}

static inline void
set_mbuf_len16(struct mbuf *m, uint8_t len16)
{

	M_ASSERTPKTHDR(m);
	if (!(mbuf_cflags(m) & MC_TLS))
		MPASS(len16 > 0 && len16 <= SGE_MAX_WR_LEN / 16);
	m->m_pkthdr.PH_loc.eight[0] = len16;
}

#ifdef RATELIMIT
static inline int
mbuf_eo_nsegs(struct mbuf *m)
{

	M_ASSERTPKTHDR(m);
	return (m->m_pkthdr.PH_loc.eight[1]);
}

static inline void
set_mbuf_eo_nsegs(struct mbuf *m, uint8_t nsegs)
{

	M_ASSERTPKTHDR(m);
	m->m_pkthdr.PH_loc.eight[1] = nsegs;
}

static inline int
mbuf_eo_len16(struct mbuf *m)
{
	int n;

	M_ASSERTPKTHDR(m);
	n = m->m_pkthdr.PH_loc.eight[2];
	MPASS(n > 0 && n <= SGE_MAX_WR_LEN / 16);

	return (n);
}

static inline void
set_mbuf_eo_len16(struct mbuf *m, uint8_t len16)
{

	M_ASSERTPKTHDR(m);
	m->m_pkthdr.PH_loc.eight[2] = len16;
}

static inline int
mbuf_eo_tsclk_tsoff(struct mbuf *m)
{

	M_ASSERTPKTHDR(m);
	return (m->m_pkthdr.PH_loc.eight[3]);
}

static inline void
set_mbuf_eo_tsclk_tsoff(struct mbuf *m, uint8_t tsclk_tsoff)
{

	M_ASSERTPKTHDR(m);
	m->m_pkthdr.PH_loc.eight[3] = tsclk_tsoff;
}

static inline int
needs_eo(struct m_snd_tag *mst)
{

	return (mst != NULL && mst->type == IF_SND_TAG_TYPE_RATE_LIMIT);
}
#endif

/*
 * Try to allocate an mbuf to contain a raw work request.  To make it
 * easy to construct the work request, don't allocate a chain but a
 * single mbuf.
 */
struct mbuf *
alloc_wr_mbuf(int len, int how)
{
	struct mbuf *m;

	if (len <= MHLEN)
		m = m_gethdr(how, MT_DATA);
	else if (len <= MCLBYTES)
		m = m_getcl(how, MT_DATA, M_PKTHDR);
	else
		m = NULL;
	if (m == NULL)
		return (NULL);
	m->m_pkthdr.len = len;
	m->m_len = len;
	set_mbuf_cflags(m, MC_RAW_WR);
	set_mbuf_len16(m, howmany(len, 16));
	return (m);
}

static inline bool
needs_hwcsum(struct mbuf *m)
{
	const uint32_t csum_flags = CSUM_IP | CSUM_IP_UDP | CSUM_IP_TCP |
	    CSUM_IP_TSO | CSUM_INNER_IP | CSUM_INNER_IP_UDP |
	    CSUM_INNER_IP_TCP | CSUM_INNER_IP_TSO | CSUM_IP6_UDP |
	    CSUM_IP6_TCP | CSUM_IP6_TSO | CSUM_INNER_IP6_UDP |
	    CSUM_INNER_IP6_TCP | CSUM_INNER_IP6_TSO;

	M_ASSERTPKTHDR(m);

	return (m->m_pkthdr.csum_flags & csum_flags);
}

static inline bool
needs_tso(struct mbuf *m)
{
	const uint32_t csum_flags = CSUM_IP_TSO | CSUM_IP6_TSO |
	    CSUM_INNER_IP_TSO | CSUM_INNER_IP6_TSO;

	M_ASSERTPKTHDR(m);

	return (m->m_pkthdr.csum_flags & csum_flags);
}

static inline bool
needs_vxlan_csum(struct mbuf *m)
{

	M_ASSERTPKTHDR(m);

	return (m->m_pkthdr.csum_flags & CSUM_ENCAP_VXLAN);
}

static inline bool
needs_vxlan_tso(struct mbuf *m)
{
	const uint32_t csum_flags = CSUM_ENCAP_VXLAN | CSUM_INNER_IP_TSO |
	    CSUM_INNER_IP6_TSO;

	M_ASSERTPKTHDR(m);

	return ((m->m_pkthdr.csum_flags & csum_flags) != 0 &&
	    (m->m_pkthdr.csum_flags & csum_flags) != CSUM_ENCAP_VXLAN);
}

static inline bool
needs_inner_tcp_csum(struct mbuf *m)
{
	const uint32_t csum_flags = CSUM_INNER_IP_TSO | CSUM_INNER_IP6_TSO;

	M_ASSERTPKTHDR(m);

	return (m->m_pkthdr.csum_flags & csum_flags);
}

static inline bool
needs_l3_csum(struct mbuf *m)
{
	const uint32_t csum_flags = CSUM_IP | CSUM_IP_TSO | CSUM_INNER_IP |
	    CSUM_INNER_IP_TSO;

	M_ASSERTPKTHDR(m);

	return (m->m_pkthdr.csum_flags & csum_flags);
}

static inline bool
needs_outer_tcp_csum(struct mbuf *m)
{
	const uint32_t csum_flags = CSUM_IP_TCP | CSUM_IP_TSO | CSUM_IP6_TCP |
	    CSUM_IP6_TSO;

	M_ASSERTPKTHDR(m);

	return (m->m_pkthdr.csum_flags & csum_flags);
}

#ifdef RATELIMIT
static inline bool
needs_outer_l4_csum(struct mbuf *m)
{
	const uint32_t csum_flags = CSUM_IP_UDP | CSUM_IP_TCP | CSUM_IP_TSO |
	    CSUM_IP6_UDP | CSUM_IP6_TCP | CSUM_IP6_TSO;

	M_ASSERTPKTHDR(m);

	return (m->m_pkthdr.csum_flags & csum_flags);
}

static inline bool
needs_outer_udp_csum(struct mbuf *m)
{
	const uint32_t csum_flags = CSUM_IP_UDP | CSUM_IP6_UDP;

	M_ASSERTPKTHDR(m);

	return (m->m_pkthdr.csum_flags & csum_flags);
}
#endif

static inline bool
needs_vlan_insertion(struct mbuf *m)
{

	M_ASSERTPKTHDR(m);

	return (m->m_flags & M_VLANTAG);
}

static void *
m_advance(struct mbuf **pm, int *poffset, int len)
{
	struct mbuf *m = *pm;
	int offset = *poffset;
	uintptr_t p = 0;

	MPASS(len > 0);

	for (;;) {
		if (offset + len < m->m_len) {
			offset += len;
			p = mtod(m, uintptr_t) + offset;
			break;
		}
		len -= m->m_len - offset;
		m = m->m_next;
		offset = 0;
		MPASS(m != NULL);
	}
	*poffset = offset;
	*pm = m;
	return ((void *)p);
}

static inline int
count_mbuf_ext_pgs(struct mbuf *m, int skip, vm_paddr_t *nextaddr)
{
	vm_paddr_t paddr;
	int i, len, off, pglen, pgoff, seglen, segoff;
	int nsegs = 0;

	M_ASSERTEXTPG(m);
	off = mtod(m, vm_offset_t);
	len = m->m_len;
	off += skip;
	len -= skip;

	if (m->m_epg_hdrlen != 0) {
		if (off >= m->m_epg_hdrlen) {
			off -= m->m_epg_hdrlen;
		} else {
			seglen = m->m_epg_hdrlen - off;
			segoff = off;
			seglen = min(seglen, len);
			off = 0;
			len -= seglen;
			paddr = pmap_kextract(
			    (vm_offset_t)&m->m_epg_hdr[segoff]);
			if (*nextaddr != paddr)
				nsegs++;
			*nextaddr = paddr + seglen;
		}
	}
	pgoff = m->m_epg_1st_off;
	for (i = 0; i < m->m_epg_npgs && len > 0; i++) {
		pglen = m_epg_pagelen(m, i, pgoff);
		if (off >= pglen) {
			off -= pglen;
			pgoff = 0;
			continue;
		}
		seglen = pglen - off;
		segoff = pgoff + off;
		off = 0;
		seglen = min(seglen, len);
		len -= seglen;
		paddr = m->m_epg_pa[i] + segoff;
		if (*nextaddr != paddr)
			nsegs++;
		*nextaddr = paddr + seglen;
		pgoff = 0;
	};
	if (len != 0) {
		seglen = min(len, m->m_epg_trllen - off);
		len -= seglen;
		paddr = pmap_kextract((vm_offset_t)&m->m_epg_trail[off]);
		if (*nextaddr != paddr)
			nsegs++;
		*nextaddr = paddr + seglen;
	}

	return (nsegs);
}


/*
 * Can deal with empty mbufs in the chain that have m_len = 0, but the chain
 * must have at least one mbuf that's not empty.  It is possible for this
 * routine to return 0 if skip accounts for all the contents of the mbuf chain.
 */
static inline int
count_mbuf_nsegs(struct mbuf *m, int skip, uint8_t *cflags)
{
	vm_paddr_t nextaddr, paddr;
	vm_offset_t va;
	int len, nsegs;

	M_ASSERTPKTHDR(m);
	MPASS(m->m_pkthdr.len > 0);
	MPASS(m->m_pkthdr.len >= skip);

	nsegs = 0;
	nextaddr = 0;
	for (; m; m = m->m_next) {
		len = m->m_len;
		if (__predict_false(len == 0))
			continue;
		if (skip >= len) {
			skip -= len;
			continue;
		}
		if ((m->m_flags & M_EXTPG) != 0) {
			*cflags |= MC_NOMAP;
			nsegs += count_mbuf_ext_pgs(m, skip, &nextaddr);
			skip = 0;
			continue;
		}
		va = mtod(m, vm_offset_t) + skip;
		len -= skip;
		skip = 0;
		paddr = pmap_kextract(va);
		nsegs += sglist_count((void *)(uintptr_t)va, len);
		if (paddr == nextaddr)
			nsegs--;
		nextaddr = pmap_kextract(va + len - 1) + 1;
	}

	return (nsegs);
}

/*
 * The maximum number of segments that can fit in a WR.
 */
static int
max_nsegs_allowed(struct mbuf *m, bool vm_wr)
{

	if (vm_wr) {
		if (needs_tso(m))
			return (TX_SGL_SEGS_VM_TSO);
		return (TX_SGL_SEGS_VM);
	}

	if (needs_tso(m)) {
		if (needs_vxlan_tso(m))
			return (TX_SGL_SEGS_VXLAN_TSO);
		else
			return (TX_SGL_SEGS_TSO);
	}

	return (TX_SGL_SEGS);
}

/*
 * Analyze the mbuf to determine its tx needs.  The mbuf passed in may change:
 * a) caller can assume it's been freed if this function returns with an error.
 * b) it may get defragged up if the gather list is too long for the hardware.
 */
int
parse_pkt(struct mbuf **mp, bool vm_wr)
{
	struct mbuf *m0 = *mp, *m;
	int rc, nsegs, defragged = 0, offset;
	struct ether_header *eh;
	void *l3hdr;
#if defined(INET) || defined(INET6)
	struct tcphdr *tcp;
#endif
#if defined(KERN_TLS) || defined(RATELIMIT)
	struct m_snd_tag *mst;
#endif
	uint16_t eh_type;
	uint8_t cflags;

	cflags = 0;
	M_ASSERTPKTHDR(m0);
	if (__predict_false(m0->m_pkthdr.len < ETHER_HDR_LEN)) {
		rc = EINVAL;
fail:
		m_freem(m0);
		*mp = NULL;
		return (rc);
	}
restart:
	/*
	 * First count the number of gather list segments in the payload.
	 * Defrag the mbuf if nsegs exceeds the hardware limit.
	 */
	M_ASSERTPKTHDR(m0);
	MPASS(m0->m_pkthdr.len > 0);
	nsegs = count_mbuf_nsegs(m0, 0, &cflags);
#if defined(KERN_TLS) || defined(RATELIMIT)
	if (m0->m_pkthdr.csum_flags & CSUM_SND_TAG)
		mst = m0->m_pkthdr.snd_tag;
	else
		mst = NULL;
#endif
#ifdef KERN_TLS
	if (mst != NULL && mst->type == IF_SND_TAG_TYPE_TLS) {
		int len16;

		cflags |= MC_TLS;
		set_mbuf_cflags(m0, cflags);
		rc = t6_ktls_parse_pkt(m0, &nsegs, &len16);
		if (rc != 0)
			goto fail;
		set_mbuf_nsegs(m0, nsegs);
		set_mbuf_len16(m0, len16);
		return (0);
	}
#endif
	if (nsegs > max_nsegs_allowed(m0, vm_wr)) {
		if (defragged++ > 0) {
			rc = EFBIG;
			goto fail;
		}
		counter_u64_add(defrags, 1);
		if ((m = m_defrag(m0, M_NOWAIT)) == NULL) {
			rc = ENOMEM;
			goto fail;
		}
		*mp = m0 = m;	/* update caller's copy after defrag */
		goto restart;
	}

	if (__predict_false(nsegs > 2 && m0->m_pkthdr.len <= MHLEN &&
	    !(cflags & MC_NOMAP))) {
		counter_u64_add(pullups, 1);
		m0 = m_pullup(m0, m0->m_pkthdr.len);
		if (m0 == NULL) {
			/* Should have left well enough alone. */
			rc = EFBIG;
			goto fail;
		}
		*mp = m0;	/* update caller's copy after pullup */
		goto restart;
	}
	set_mbuf_nsegs(m0, nsegs);
	set_mbuf_cflags(m0, cflags);
	calculate_mbuf_len16(m0, vm_wr);

#ifdef RATELIMIT
	/*
	 * Ethofld is limited to TCP and UDP for now, and only when L4 hw
	 * checksumming is enabled.  needs_outer_l4_csum happens to check for
	 * all the right things.
	 */
	if (__predict_false(needs_eo(mst) && !needs_outer_l4_csum(m0))) {
		m_snd_tag_rele(m0->m_pkthdr.snd_tag);
		m0->m_pkthdr.snd_tag = NULL;
		m0->m_pkthdr.csum_flags &= ~CSUM_SND_TAG;
		mst = NULL;
	}
#endif

	if (!needs_hwcsum(m0)
#ifdef RATELIMIT
   		 && !needs_eo(mst)
#endif
	)
		return (0);

	m = m0;
	eh = mtod(m, struct ether_header *);
	eh_type = ntohs(eh->ether_type);
	if (eh_type == ETHERTYPE_VLAN) {
		struct ether_vlan_header *evh = (void *)eh;

		eh_type = ntohs(evh->evl_proto);
		m0->m_pkthdr.l2hlen = sizeof(*evh);
	} else
		m0->m_pkthdr.l2hlen = sizeof(*eh);

	offset = 0;
	l3hdr = m_advance(&m, &offset, m0->m_pkthdr.l2hlen);

	switch (eh_type) {
#ifdef INET6
	case ETHERTYPE_IPV6:
		m0->m_pkthdr.l3hlen = sizeof(struct ip6_hdr);
		break;
#endif
#ifdef INET
	case ETHERTYPE_IP:
	{
		struct ip *ip = l3hdr;

		if (needs_vxlan_csum(m0)) {
			/* Driver will do the outer IP hdr checksum. */
			ip->ip_sum = 0;
			if (needs_vxlan_tso(m0)) {
				const uint16_t ipl = ip->ip_len;

				ip->ip_len = 0;
				ip->ip_sum = ~in_cksum_hdr(ip);
				ip->ip_len = ipl;
			} else
				ip->ip_sum = in_cksum_hdr(ip);
		}
		m0->m_pkthdr.l3hlen = ip->ip_hl << 2;
		break;
	}
#endif
	default:
		panic("%s: ethertype 0x%04x unknown.  if_cxgbe must be compiled"
		    " with the same INET/INET6 options as the kernel.",
		    __func__, eh_type);
	}

	if (needs_vxlan_csum(m0)) {
		m0->m_pkthdr.l4hlen = sizeof(struct udphdr);
		m0->m_pkthdr.l5hlen = sizeof(struct vxlan_header);

		/* Inner headers. */
		eh = m_advance(&m, &offset, m0->m_pkthdr.l3hlen +
		    sizeof(struct udphdr) + sizeof(struct vxlan_header));
		eh_type = ntohs(eh->ether_type);
		if (eh_type == ETHERTYPE_VLAN) {
			struct ether_vlan_header *evh = (void *)eh;

			eh_type = ntohs(evh->evl_proto);
			m0->m_pkthdr.inner_l2hlen = sizeof(*evh);
		} else
			m0->m_pkthdr.inner_l2hlen = sizeof(*eh);
		l3hdr = m_advance(&m, &offset, m0->m_pkthdr.inner_l2hlen);

		switch (eh_type) {
#ifdef INET6
		case ETHERTYPE_IPV6:
			m0->m_pkthdr.inner_l3hlen = sizeof(struct ip6_hdr);
			break;
#endif
#ifdef INET
		case ETHERTYPE_IP:
		{
			struct ip *ip = l3hdr;

			m0->m_pkthdr.inner_l3hlen = ip->ip_hl << 2;
			break;
		}
#endif
		default:
			panic("%s: VXLAN hw offload requested with unknown "
			    "ethertype 0x%04x.  if_cxgbe must be compiled"
			    " with the same INET/INET6 options as the kernel.",
			    __func__, eh_type);
		}
#if defined(INET) || defined(INET6)
		if (needs_inner_tcp_csum(m0)) {
			tcp = m_advance(&m, &offset, m0->m_pkthdr.inner_l3hlen);
			m0->m_pkthdr.inner_l4hlen = tcp->th_off * 4;
		}
#endif
		MPASS((m0->m_pkthdr.csum_flags & CSUM_SND_TAG) == 0);
		m0->m_pkthdr.csum_flags &= CSUM_INNER_IP6_UDP |
		    CSUM_INNER_IP6_TCP | CSUM_INNER_IP6_TSO | CSUM_INNER_IP |
		    CSUM_INNER_IP_UDP | CSUM_INNER_IP_TCP | CSUM_INNER_IP_TSO |
		    CSUM_ENCAP_VXLAN;
	}

#if defined(INET) || defined(INET6)
	if (needs_outer_tcp_csum(m0)) {
		tcp = m_advance(&m, &offset, m0->m_pkthdr.l3hlen);
		m0->m_pkthdr.l4hlen = tcp->th_off * 4;
#ifdef RATELIMIT
		if (tsclk >= 0 && *(uint32_t *)(tcp + 1) == ntohl(0x0101080a)) {
			set_mbuf_eo_tsclk_tsoff(m0,
			    V_FW_ETH_TX_EO_WR_TSCLK(tsclk) |
			    V_FW_ETH_TX_EO_WR_TSOFF(sizeof(*tcp) / 2 + 1));
		} else
			set_mbuf_eo_tsclk_tsoff(m0, 0);
	} else if (needs_outer_udp_csum(m0)) {
		m0->m_pkthdr.l4hlen = sizeof(struct udphdr);
#endif
	}
#ifdef RATELIMIT
	if (needs_eo(mst)) {
		u_int immhdrs;

		/* EO WRs have the headers in the WR and not the GL. */
		immhdrs = m0->m_pkthdr.l2hlen + m0->m_pkthdr.l3hlen +
		    m0->m_pkthdr.l4hlen;
		cflags = 0;
		nsegs = count_mbuf_nsegs(m0, immhdrs, &cflags);
		MPASS(cflags == mbuf_cflags(m0));
		set_mbuf_eo_nsegs(m0, nsegs);
		set_mbuf_eo_len16(m0,
		    txpkt_eo_len16(nsegs, immhdrs, needs_tso(m0)));
	}
#endif
#endif
	MPASS(m0 == *mp);
	return (0);
}

void *
start_wrq_wr(struct sge_wrq *wrq, int len16, struct wrq_cookie *cookie)
{
	struct sge_eq *eq = &wrq->eq;
	struct adapter *sc = wrq->adapter;
	int ndesc, available;
	struct wrqe *wr;
	void *w;

	MPASS(len16 > 0);
	ndesc = tx_len16_to_desc(len16);
	MPASS(ndesc > 0 && ndesc <= SGE_MAX_WR_NDESC);

	EQ_LOCK(eq);

	if (TAILQ_EMPTY(&wrq->incomplete_wrs) && !STAILQ_EMPTY(&wrq->wr_list))
		drain_wrq_wr_list(sc, wrq);

	if (!STAILQ_EMPTY(&wrq->wr_list)) {
slowpath:
		EQ_UNLOCK(eq);
		wr = alloc_wrqe(len16 * 16, wrq);
		if (__predict_false(wr == NULL))
			return (NULL);
		cookie->pidx = -1;
		cookie->ndesc = ndesc;
		return (&wr->wr);
	}

	eq->cidx = read_hw_cidx(eq);
	if (eq->pidx == eq->cidx)
		available = eq->sidx - 1;
	else
		available = IDXDIFF(eq->cidx, eq->pidx, eq->sidx) - 1;
	if (available < ndesc)
		goto slowpath;

	cookie->pidx = eq->pidx;
	cookie->ndesc = ndesc;
	TAILQ_INSERT_TAIL(&wrq->incomplete_wrs, cookie, link);

	w = &eq->desc[eq->pidx];
	IDXINCR(eq->pidx, ndesc, eq->sidx);
	if (__predict_false(cookie->pidx + ndesc > eq->sidx)) {
		w = &wrq->ss[0];
		wrq->ss_pidx = cookie->pidx;
		wrq->ss_len = len16 * 16;
	}

	EQ_UNLOCK(eq);

	return (w);
}

void
commit_wrq_wr(struct sge_wrq *wrq, void *w, struct wrq_cookie *cookie)
{
	struct sge_eq *eq = &wrq->eq;
	struct adapter *sc = wrq->adapter;
	int ndesc, pidx;
	struct wrq_cookie *prev, *next;

	if (cookie->pidx == -1) {
		struct wrqe *wr = __containerof(w, struct wrqe, wr);

		t4_wrq_tx(sc, wr);
		return;
	}

	if (__predict_false(w == &wrq->ss[0])) {
		int n = (eq->sidx - wrq->ss_pidx) * EQ_ESIZE;

		MPASS(wrq->ss_len > n);	/* WR had better wrap around. */
		bcopy(&wrq->ss[0], &eq->desc[wrq->ss_pidx], n);
		bcopy(&wrq->ss[n], &eq->desc[0], wrq->ss_len - n);
		wrq->tx_wrs_ss++;
	} else
		wrq->tx_wrs_direct++;

	EQ_LOCK(eq);
	ndesc = cookie->ndesc;	/* Can be more than SGE_MAX_WR_NDESC here. */
	pidx = cookie->pidx;
	MPASS(pidx >= 0 && pidx < eq->sidx);
	prev = TAILQ_PREV(cookie, wrq_incomplete_wrs, link);
	next = TAILQ_NEXT(cookie, link);
	if (prev == NULL) {
		MPASS(pidx == eq->dbidx);
		if (next == NULL || ndesc >= 16) {
			int available;
			struct fw_eth_tx_pkt_wr *dst;	/* any fw WR struct will do */

			/*
			 * Note that the WR via which we'll request tx updates
			 * is at pidx and not eq->pidx, which has moved on
			 * already.
			 */
			dst = (void *)&eq->desc[pidx];
			available = IDXDIFF(eq->cidx, eq->pidx, eq->sidx) - 1;
			if (available < eq->sidx / 4 &&
			    atomic_cmpset_int(&eq->equiq, 0, 1)) {
				/*
				 * XXX: This is not 100% reliable with some
				 * types of WRs.  But this is a very unusual
				 * situation for an ofld/ctrl queue anyway.
				 */
				dst->equiq_to_len16 |= htobe32(F_FW_WR_EQUIQ |
				    F_FW_WR_EQUEQ);
			}

			ring_eq_db(wrq->adapter, eq, ndesc);
		} else {
			MPASS(IDXDIFF(next->pidx, pidx, eq->sidx) == ndesc);
			next->pidx = pidx;
			next->ndesc += ndesc;
		}
	} else {
		MPASS(IDXDIFF(pidx, prev->pidx, eq->sidx) == prev->ndesc);
		prev->ndesc += ndesc;
	}
	TAILQ_REMOVE(&wrq->incomplete_wrs, cookie, link);

	if (TAILQ_EMPTY(&wrq->incomplete_wrs) && !STAILQ_EMPTY(&wrq->wr_list))
		drain_wrq_wr_list(sc, wrq);

#ifdef INVARIANTS
	if (TAILQ_EMPTY(&wrq->incomplete_wrs)) {
		/* Doorbell must have caught up to the pidx. */
		MPASS(wrq->eq.pidx == wrq->eq.dbidx);
	}
#endif
	EQ_UNLOCK(eq);
}

static u_int
can_resume_eth_tx(struct mp_ring *r)
{
	struct sge_eq *eq = r->cookie;

	return (total_available_tx_desc(eq) > eq->sidx / 8);
}

static inline bool
cannot_use_txpkts(struct mbuf *m)
{
	/* maybe put a GL limit too, to avoid silliness? */

	return (needs_tso(m) || (mbuf_cflags(m) & (MC_RAW_WR | MC_TLS)) != 0);
}

static inline int
discard_tx(struct sge_eq *eq)
{

	return ((eq->flags & (EQ_ENABLED | EQ_QFLUSH)) != EQ_ENABLED);
}

static inline int
wr_can_update_eq(void *p)
{
	struct fw_eth_tx_pkts_wr *wr = p;

	switch (G_FW_WR_OP(be32toh(wr->op_pkd))) {
	case FW_ULPTX_WR:
	case FW_ETH_TX_PKT_WR:
	case FW_ETH_TX_PKTS_WR:
	case FW_ETH_TX_PKTS2_WR:
	case FW_ETH_TX_PKT_VM_WR:
	case FW_ETH_TX_PKTS_VM_WR:
		return (1);
	default:
		return (0);
	}
}

static inline void
set_txupdate_flags(struct sge_txq *txq, u_int avail,
    struct fw_eth_tx_pkt_wr *wr)
{
	struct sge_eq *eq = &txq->eq;
	struct txpkts *txp = &txq->txp;

	if ((txp->npkt > 0 || avail < eq->sidx / 2) &&
	    atomic_cmpset_int(&eq->equiq, 0, 1)) {
		wr->equiq_to_len16 |= htobe32(F_FW_WR_EQUEQ | F_FW_WR_EQUIQ);
		eq->equeqidx = eq->pidx;
	} else if (IDXDIFF(eq->pidx, eq->equeqidx, eq->sidx) >= 32) {
		wr->equiq_to_len16 |= htobe32(F_FW_WR_EQUEQ);
		eq->equeqidx = eq->pidx;
	}
}

/*
 * r->items[cidx] to r->items[pidx], with a wraparound at r->size, are ready to
 * be consumed.  Return the actual number consumed.  0 indicates a stall.
 */
static u_int
eth_tx(struct mp_ring *r, u_int cidx, u_int pidx, bool *coalescing)
{
	struct sge_txq *txq = r->cookie;
	struct ifnet *ifp = txq->ifp;
	struct sge_eq *eq = &txq->eq;
	struct txpkts *txp = &txq->txp;
	struct vi_info *vi = ifp->if_softc;
	struct adapter *sc = vi->adapter;
	u_int total, remaining;		/* # of packets */
	u_int n, avail, dbdiff;		/* # of hardware descriptors */
	int i, rc;
	struct mbuf *m0;
	bool snd;
	void *wr;	/* start of the last WR written to the ring */

	TXQ_LOCK_ASSERT_OWNED(txq);

	remaining = IDXDIFF(pidx, cidx, r->size);
	if (__predict_false(discard_tx(eq))) {
		for (i = 0; i < txp->npkt; i++)
			m_freem(txp->mb[i]);
		txp->npkt = 0;
		while (cidx != pidx) {
			m0 = r->items[cidx];
			m_freem(m0);
			if (++cidx == r->size)
				cidx = 0;
		}
		reclaim_tx_descs(txq, eq->sidx);
		*coalescing = false;
		return (remaining);	/* emptied */
	}

	/* How many hardware descriptors do we have readily available. */
	if (eq->pidx == eq->cidx) {
		avail = eq->sidx - 1;
		if (txp->score++ >= 5)
			txp->score = 5;	/* tx is completely idle, reset. */
	} else
		avail = IDXDIFF(eq->cidx, eq->pidx, eq->sidx) - 1;

	total = 0;
	if (remaining == 0) {
		if (txp->score-- == 1)	/* egr_update had to drain txpkts */
			txp->score = 1;
		goto send_txpkts;
	}

	dbdiff = 0;
	MPASS(remaining > 0);
	while (remaining > 0) {
		m0 = r->items[cidx];
		M_ASSERTPKTHDR(m0);
		MPASS(m0->m_nextpkt == NULL);

		if (avail < 2 * SGE_MAX_WR_NDESC)
			avail += reclaim_tx_descs(txq, 64);

		if (txp->npkt > 0 || remaining > 1 || txp->score > 3 ||
		    atomic_load_int(&txq->eq.equiq) != 0) {
			if (vi->flags & TX_USES_VM_WR)
				rc = add_to_txpkts_vf(sc, txq, m0, avail, &snd);
			else
				rc = add_to_txpkts_pf(sc, txq, m0, avail, &snd);
		} else {
			snd = false;
			rc = EINVAL;
		}
		if (snd) {
			MPASS(txp->npkt > 0);
			for (i = 0; i < txp->npkt; i++)
				ETHER_BPF_MTAP(ifp, txp->mb[i]);
			if (txp->npkt > 1) {
				if (txp->score++ >= 10)
					txp->score = 10;
				MPASS(avail >= tx_len16_to_desc(txp->len16));
				if (vi->flags & TX_USES_VM_WR)
					n = write_txpkts_vm_wr(sc, txq);
				else
					n = write_txpkts_wr(sc, txq);
			} else {
				MPASS(avail >=
				    tx_len16_to_desc(mbuf_len16(txp->mb[0])));
				if (vi->flags & TX_USES_VM_WR)
					n = write_txpkt_vm_wr(sc, txq,
					    txp->mb[0]);
				else
					n = write_txpkt_wr(sc, txq, txp->mb[0],
					    avail);
			}
			MPASS(n <= SGE_MAX_WR_NDESC);
			avail -= n;
			dbdiff += n;
			wr = &eq->desc[eq->pidx];
			IDXINCR(eq->pidx, n, eq->sidx);
			txp->npkt = 0;	/* emptied */
		}
		if (rc == 0) {
			/* m0 was coalesced into txq->txpkts. */
			goto next_mbuf;
		}
		if (rc == EAGAIN) {
			/*
			 * m0 is suitable for tx coalescing but could not be
			 * combined with the existing txq->txpkts, which has now
			 * been transmitted.  Start a new txpkts with m0.
			 */
			MPASS(snd);
			MPASS(txp->npkt == 0);
			continue;
		}

		MPASS(rc != 0 && rc != EAGAIN);
		MPASS(txp->npkt == 0);

		n = tx_len16_to_desc(mbuf_len16(m0));
		if (__predict_false(avail < n)) {
			avail += reclaim_tx_descs(txq, min(n, 32));
			if (avail < n)
				break;	/* out of descriptors */
		}

		wr = &eq->desc[eq->pidx];
		if (mbuf_cflags(m0) & MC_RAW_WR) {
			n = write_raw_wr(txq, wr, m0, avail);
#ifdef KERN_TLS
		} else if (mbuf_cflags(m0) & MC_TLS) {
			ETHER_BPF_MTAP(ifp, m0);
			n = t6_ktls_write_wr(txq, wr, m0, mbuf_nsegs(m0),
			    avail);
#endif
		} else {
			ETHER_BPF_MTAP(ifp, m0);
			if (vi->flags & TX_USES_VM_WR)
				n = write_txpkt_vm_wr(sc, txq, m0);
			else
				n = write_txpkt_wr(sc, txq, m0, avail);
		}
		MPASS(n >= 1 && n <= avail);
		if (!(mbuf_cflags(m0) & MC_TLS))
			MPASS(n <= SGE_MAX_WR_NDESC);

		avail -= n;
		dbdiff += n;
		IDXINCR(eq->pidx, n, eq->sidx);

		if (dbdiff >= 512 / EQ_ESIZE) {	/* X_FETCHBURSTMAX_512B */
			if (wr_can_update_eq(wr))
				set_txupdate_flags(txq, avail, wr);
			ring_eq_db(sc, eq, dbdiff);
			avail += reclaim_tx_descs(txq, 32);
			dbdiff = 0;
		}
next_mbuf:
		total++;
		remaining--;
		if (__predict_false(++cidx == r->size))
			cidx = 0;
	}
	if (dbdiff != 0) {
		if (wr_can_update_eq(wr))
			set_txupdate_flags(txq, avail, wr);
		ring_eq_db(sc, eq, dbdiff);
		reclaim_tx_descs(txq, 32);
	} else if (eq->pidx == eq->cidx && txp->npkt > 0 &&
	    atomic_load_int(&txq->eq.equiq) == 0) {
		/*
		 * If nothing was submitted to the chip for tx (it was coalesced
		 * into txpkts instead) and there is no tx update outstanding
		 * then we need to send txpkts now.
		 */
send_txpkts:
		MPASS(txp->npkt > 0);
		for (i = 0; i < txp->npkt; i++)
			ETHER_BPF_MTAP(ifp, txp->mb[i]);
		if (txp->npkt > 1) {
			MPASS(avail >= tx_len16_to_desc(txp->len16));
			if (vi->flags & TX_USES_VM_WR)
				n = write_txpkts_vm_wr(sc, txq);
			else
				n = write_txpkts_wr(sc, txq);
		} else {
			MPASS(avail >=
			    tx_len16_to_desc(mbuf_len16(txp->mb[0])));
			if (vi->flags & TX_USES_VM_WR)
				n = write_txpkt_vm_wr(sc, txq, txp->mb[0]);
			else
				n = write_txpkt_wr(sc, txq, txp->mb[0], avail);
		}
		MPASS(n <= SGE_MAX_WR_NDESC);
		wr = &eq->desc[eq->pidx];
		IDXINCR(eq->pidx, n, eq->sidx);
		txp->npkt = 0;	/* emptied */

		MPASS(wr_can_update_eq(wr));
		set_txupdate_flags(txq, avail - n, wr);
		ring_eq_db(sc, eq, n);
		reclaim_tx_descs(txq, 32);
	}
	*coalescing = txp->npkt > 0;

	return (total);
}

static inline void
init_iq(struct sge_iq *iq, struct adapter *sc, int tmr_idx, int pktc_idx,
    int qsize)
{

	KASSERT(tmr_idx >= 0 && tmr_idx < SGE_NTIMERS,
	    ("%s: bad tmr_idx %d", __func__, tmr_idx));
	KASSERT(pktc_idx < SGE_NCOUNTERS,	/* -ve is ok, means don't use */
	    ("%s: bad pktc_idx %d", __func__, pktc_idx));

	iq->flags = 0;
	iq->adapter = sc;
	iq->intr_params = V_QINTR_TIMER_IDX(tmr_idx);
	iq->intr_pktc_idx = SGE_NCOUNTERS - 1;
	if (pktc_idx >= 0) {
		iq->intr_params |= F_QINTR_CNT_EN;
		iq->intr_pktc_idx = pktc_idx;
	}
	iq->qsize = roundup2(qsize, 16);	/* See FW_IQ_CMD/iqsize */
	iq->sidx = iq->qsize - sc->params.sge.spg_len / IQ_ESIZE;
}

static inline void
init_fl(struct adapter *sc, struct sge_fl *fl, int qsize, int maxp, char *name)
{

	fl->qsize = qsize;
	fl->sidx = qsize - sc->params.sge.spg_len / EQ_ESIZE;
	strlcpy(fl->lockname, name, sizeof(fl->lockname));
	if (sc->flags & BUF_PACKING_OK &&
	    ((!is_t4(sc) && buffer_packing) ||	/* T5+: enabled unless 0 */
	    (is_t4(sc) && buffer_packing == 1)))/* T4: disabled unless 1 */
		fl->flags |= FL_BUF_PACKING;
	fl->zidx = find_refill_source(sc, maxp, fl->flags & FL_BUF_PACKING);
	fl->safe_zidx = sc->sge.safe_zidx;
}

static inline void
init_eq(struct adapter *sc, struct sge_eq *eq, int eqtype, int qsize,
    uint8_t tx_chan, uint16_t iqid, char *name)
{
	KASSERT(eqtype <= EQ_TYPEMASK, ("%s: bad qtype %d", __func__, eqtype));

	eq->flags = eqtype & EQ_TYPEMASK;
	eq->tx_chan = tx_chan;
	eq->iqid = iqid;
	eq->sidx = qsize - sc->params.sge.spg_len / EQ_ESIZE;
	strlcpy(eq->lockname, name, sizeof(eq->lockname));
}

static int
alloc_ring(struct adapter *sc, size_t len, bus_dma_tag_t *tag,
    bus_dmamap_t *map, bus_addr_t *pa, void **va)
{
	int rc;

	rc = bus_dma_tag_create(sc->dmat, 512, 0, BUS_SPACE_MAXADDR,
	    BUS_SPACE_MAXADDR, NULL, NULL, len, 1, len, 0, NULL, NULL, tag);
	if (rc != 0) {
		device_printf(sc->dev, "cannot allocate DMA tag: %d\n", rc);
		goto done;
	}

	rc = bus_dmamem_alloc(*tag, va,
	    BUS_DMA_WAITOK | BUS_DMA_COHERENT | BUS_DMA_ZERO, map);
	if (rc != 0) {
		device_printf(sc->dev, "cannot allocate DMA memory: %d\n", rc);
		goto done;
	}

	rc = bus_dmamap_load(*tag, *map, *va, len, oneseg_dma_callback, pa, 0);
	if (rc != 0) {
		device_printf(sc->dev, "cannot load DMA map: %d\n", rc);
		goto done;
	}
done:
	if (rc)
		free_ring(sc, *tag, *map, *pa, *va);

	return (rc);
}

static int
free_ring(struct adapter *sc, bus_dma_tag_t tag, bus_dmamap_t map,
    bus_addr_t pa, void *va)
{
	if (pa)
		bus_dmamap_unload(tag, map);
	if (va)
		bus_dmamem_free(tag, va, map);
	if (tag)
		bus_dma_tag_destroy(tag);

	return (0);
}

/*
 * Allocates the ring for an ingress queue and an optional freelist.  If the
 * freelist is specified it will be allocated and then associated with the
 * ingress queue.
 *
 * Returns errno on failure.  Resources allocated up to that point may still be
 * allocated.  Caller is responsible for cleanup in case this function fails.
 *
 * If the ingress queue will take interrupts directly then the intr_idx
 * specifies the vector, starting from 0.  -1 means the interrupts for this
 * queue should be forwarded to the fwq.
 */
static int
alloc_iq_fl(struct vi_info *vi, struct sge_iq *iq, struct sge_fl *fl,
    int intr_idx, int cong)
{
	int rc, i, cntxt_id;
	size_t len;
	struct fw_iq_cmd c;
	struct port_info *pi = vi->pi;
	struct adapter *sc = iq->adapter;
	struct sge_params *sp = &sc->params.sge;
	__be32 v = 0;

	len = iq->qsize * IQ_ESIZE;
	rc = alloc_ring(sc, len, &iq->desc_tag, &iq->desc_map, &iq->ba,
	    (void **)&iq->desc);
	if (rc != 0)
		return (rc);

	bzero(&c, sizeof(c));
	c.op_to_vfn = htobe32(V_FW_CMD_OP(FW_IQ_CMD) | F_FW_CMD_REQUEST |
	    F_FW_CMD_WRITE | F_FW_CMD_EXEC | V_FW_IQ_CMD_PFN(sc->pf) |
	    V_FW_IQ_CMD_VFN(0));

	c.alloc_to_len16 = htobe32(F_FW_IQ_CMD_ALLOC | F_FW_IQ_CMD_IQSTART |
	    FW_LEN16(c));

	/* Special handling for firmware event queue */
	if (iq == &sc->sge.fwq)
		v |= F_FW_IQ_CMD_IQASYNCH;

	if (intr_idx < 0) {
		/* Forwarded interrupts, all headed to fwq */
		v |= F_FW_IQ_CMD_IQANDST;
		v |= V_FW_IQ_CMD_IQANDSTINDEX(sc->sge.fwq.cntxt_id);
	} else {
		KASSERT(intr_idx < sc->intr_count,
		    ("%s: invalid direct intr_idx %d", __func__, intr_idx));
		v |= V_FW_IQ_CMD_IQANDSTINDEX(intr_idx);
	}

	c.type_to_iqandstindex = htobe32(v |
	    V_FW_IQ_CMD_TYPE(FW_IQ_TYPE_FL_INT_CAP) |
	    V_FW_IQ_CMD_VIID(vi->viid) |
	    V_FW_IQ_CMD_IQANUD(X_UPDATEDELIVERY_INTERRUPT));
	c.iqdroprss_to_iqesize = htobe16(V_FW_IQ_CMD_IQPCIECH(pi->tx_chan) |
	    F_FW_IQ_CMD_IQGTSMODE |
	    V_FW_IQ_CMD_IQINTCNTTHRESH(iq->intr_pktc_idx) |
	    V_FW_IQ_CMD_IQESIZE(ilog2(IQ_ESIZE) - 4));
	c.iqsize = htobe16(iq->qsize);
	c.iqaddr = htobe64(iq->ba);
	if (cong >= 0)
		c.iqns_to_fl0congen = htobe32(F_FW_IQ_CMD_IQFLINTCONGEN);

	if (fl) {
		mtx_init(&fl->fl_lock, fl->lockname, NULL, MTX_DEF);

		len = fl->qsize * EQ_ESIZE;
		rc = alloc_ring(sc, len, &fl->desc_tag, &fl->desc_map,
		    &fl->ba, (void **)&fl->desc);
		if (rc)
			return (rc);

		/* Allocate space for one software descriptor per buffer. */
		rc = alloc_fl_sdesc(fl);
		if (rc != 0) {
			device_printf(sc->dev,
			    "failed to setup fl software descriptors: %d\n",
			    rc);
			return (rc);
		}

		if (fl->flags & FL_BUF_PACKING) {
			fl->lowat = roundup2(sp->fl_starve_threshold2, 8);
			fl->buf_boundary = sp->pack_boundary;
		} else {
			fl->lowat = roundup2(sp->fl_starve_threshold, 8);
			fl->buf_boundary = 16;
		}
		if (fl_pad && fl->buf_boundary < sp->pad_boundary)
			fl->buf_boundary = sp->pad_boundary;

		c.iqns_to_fl0congen |=
		    htobe32(V_FW_IQ_CMD_FL0HOSTFCMODE(X_HOSTFCMODE_NONE) |
			F_FW_IQ_CMD_FL0FETCHRO | F_FW_IQ_CMD_FL0DATARO |
			(fl_pad ? F_FW_IQ_CMD_FL0PADEN : 0) |
			(fl->flags & FL_BUF_PACKING ? F_FW_IQ_CMD_FL0PACKEN :
			    0));
		if (cong >= 0) {
			c.iqns_to_fl0congen |=
				htobe32(V_FW_IQ_CMD_FL0CNGCHMAP(cong) |
				    F_FW_IQ_CMD_FL0CONGCIF |
				    F_FW_IQ_CMD_FL0CONGEN);
		}
		c.fl0dcaen_to_fl0cidxfthresh =
		    htobe16(V_FW_IQ_CMD_FL0FBMIN(chip_id(sc) <= CHELSIO_T5 ?
			X_FETCHBURSTMIN_128B : X_FETCHBURSTMIN_64B_T6) |
			V_FW_IQ_CMD_FL0FBMAX(chip_id(sc) <= CHELSIO_T5 ?
			X_FETCHBURSTMAX_512B : X_FETCHBURSTMAX_256B));
		c.fl0size = htobe16(fl->qsize);
		c.fl0addr = htobe64(fl->ba);
	}

	rc = -t4_wr_mbox(sc, sc->mbox, &c, sizeof(c), &c);
	if (rc != 0) {
		device_printf(sc->dev,
		    "failed to create ingress queue: %d\n", rc);
		return (rc);
	}

	iq->cidx = 0;
	iq->gen = F_RSPD_GEN;
	iq->intr_next = iq->intr_params;
	iq->cntxt_id = be16toh(c.iqid);
	iq->abs_id = be16toh(c.physiqid);
	iq->flags |= IQ_ALLOCATED;

	cntxt_id = iq->cntxt_id - sc->sge.iq_start;
	if (cntxt_id >= sc->sge.iqmap_sz) {
		panic ("%s: iq->cntxt_id (%d) more than the max (%d)", __func__,
		    cntxt_id, sc->sge.iqmap_sz - 1);
	}
	sc->sge.iqmap[cntxt_id] = iq;

	if (fl) {
		u_int qid;

		iq->flags |= IQ_HAS_FL;
		fl->cntxt_id = be16toh(c.fl0id);
		fl->pidx = fl->cidx = 0;

		cntxt_id = fl->cntxt_id - sc->sge.eq_start;
		if (cntxt_id >= sc->sge.eqmap_sz) {
			panic("%s: fl->cntxt_id (%d) more than the max (%d)",
			    __func__, cntxt_id, sc->sge.eqmap_sz - 1);
		}
		sc->sge.eqmap[cntxt_id] = (void *)fl;

		qid = fl->cntxt_id;
		if (isset(&sc->doorbells, DOORBELL_UDB)) {
			uint32_t s_qpp = sc->params.sge.eq_s_qpp;
			uint32_t mask = (1 << s_qpp) - 1;
			volatile uint8_t *udb;

			udb = sc->udbs_base + UDBS_DB_OFFSET;
			udb += (qid >> s_qpp) << PAGE_SHIFT;
			qid &= mask;
			if (qid < PAGE_SIZE / UDBS_SEG_SIZE) {
				udb += qid << UDBS_SEG_SHIFT;
				qid = 0;
			}
			fl->udb = (volatile void *)udb;
		}
		fl->dbval = V_QID(qid) | sc->chip_params->sge_fl_db;

		FL_LOCK(fl);
		/* Enough to make sure the SGE doesn't think it's starved */
		refill_fl(sc, fl, fl->lowat);
		FL_UNLOCK(fl);
	}

	if (chip_id(sc) >= CHELSIO_T5 && !(sc->flags & IS_VF) && cong >= 0) {
		uint32_t param, val;

		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DMAQ) |
		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DMAQ_CONM_CTXT) |
		    V_FW_PARAMS_PARAM_YZ(iq->cntxt_id);
		if (cong == 0)
			val = 1 << 19;
		else {
			val = 2 << 19;
			for (i = 0; i < 4; i++) {
				if (cong & (1 << i))
					val |= 1 << (i << 2);
			}
		}

		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
		if (rc != 0) {
			/* report error but carry on */
			device_printf(sc->dev,
			    "failed to set congestion manager context for "
			    "ingress queue %d: %d\n", iq->cntxt_id, rc);
		}
	}

	/* Enable IQ interrupts */
	atomic_store_rel_int(&iq->state, IQS_IDLE);
	t4_write_reg(sc, sc->sge_gts_reg, V_SEINTARM(iq->intr_params) |
	    V_INGRESSQID(iq->cntxt_id));

	return (0);
}

static int
free_iq_fl(struct vi_info *vi, struct sge_iq *iq, struct sge_fl *fl)
{
	int rc;
	struct adapter *sc = iq->adapter;
	device_t dev;

	if (sc == NULL)
		return (0);	/* nothing to do */

	dev = vi ? vi->dev : sc->dev;

	if (iq->flags & IQ_ALLOCATED) {
		rc = -t4_iq_free(sc, sc->mbox, sc->pf, 0,
		    FW_IQ_TYPE_FL_INT_CAP, iq->cntxt_id,
		    fl ? fl->cntxt_id : 0xffff, 0xffff);
		if (rc != 0) {
			device_printf(dev,
			    "failed to free queue %p: %d\n", iq, rc);
			return (rc);
		}
		iq->flags &= ~IQ_ALLOCATED;
	}

	free_ring(sc, iq->desc_tag, iq->desc_map, iq->ba, iq->desc);

	bzero(iq, sizeof(*iq));

	if (fl) {
		free_ring(sc, fl->desc_tag, fl->desc_map, fl->ba,
		    fl->desc);

		if (fl->sdesc)
			free_fl_sdesc(sc, fl);

		if (mtx_initialized(&fl->fl_lock))
			mtx_destroy(&fl->fl_lock);

		bzero(fl, sizeof(*fl));
	}

	return (0);
}

static void
add_iq_sysctls(struct sysctl_ctx_list *ctx, struct sysctl_oid *oid,
    struct sge_iq *iq)
{
	struct sysctl_oid_list *children = SYSCTL_CHILDREN(oid);

	SYSCTL_ADD_UAUTO(ctx, children, OID_AUTO, "ba", CTLFLAG_RD, &iq->ba,
	    "bus address of descriptor ring");
	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dmalen", CTLFLAG_RD, NULL,
	    iq->qsize * IQ_ESIZE, "descriptor ring size in bytes");
	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "abs_id",
	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, &iq->abs_id, 0,
	    sysctl_uint16, "I", "absolute id of the queue");
	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cntxt_id",
	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, &iq->cntxt_id, 0,
	    sysctl_uint16, "I", "SGE context id of the queue");
	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cidx",
	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, &iq->cidx, 0,
	    sysctl_uint16, "I", "consumer index");
}

static void
add_fl_sysctls(struct adapter *sc, struct sysctl_ctx_list *ctx,
    struct sysctl_oid *oid, struct sge_fl *fl)
{
	struct sysctl_oid_list *children = SYSCTL_CHILDREN(oid);

	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "fl",
	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "freelist");
	children = SYSCTL_CHILDREN(oid);

	SYSCTL_ADD_UAUTO(ctx, children, OID_AUTO, "ba", CTLFLAG_RD,
	    &fl->ba, "bus address of descriptor ring");
	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dmalen", CTLFLAG_RD, NULL,
	    fl->sidx * EQ_ESIZE + sc->params.sge.spg_len,
	    "desc ring size in bytes");
	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cntxt_id",
	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, &fl->cntxt_id, 0,
	    sysctl_uint16, "I", "SGE context id of the freelist");
	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "padding", CTLFLAG_RD, NULL,
	    fl_pad ? 1 : 0, "padding enabled");
	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "packing", CTLFLAG_RD, NULL,
	    fl->flags & FL_BUF_PACKING ? 1 : 0, "packing enabled");
	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cidx", CTLFLAG_RD, &fl->cidx,
	    0, "consumer index");
	if (fl->flags & FL_BUF_PACKING) {
		SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rx_offset",
		    CTLFLAG_RD, &fl->rx_offset, 0, "packing rx offset");
	}
	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "pidx", CTLFLAG_RD, &fl->pidx,
	    0, "producer index");
	SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, "cluster_allocated",
	    CTLFLAG_RD, &fl->cl_allocated, "# of clusters allocated");
	SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, "cluster_recycled",
	    CTLFLAG_RD, &fl->cl_recycled, "# of clusters recycled");
	SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, "cluster_fast_recycled",
	    CTLFLAG_RD, &fl->cl_fast_recycled, "# of clusters recycled (fast)");
}

static int
alloc_fwq(struct adapter *sc)
{
	int rc, intr_idx;
	struct sge_iq *fwq = &sc->sge.fwq;
	struct sysctl_oid *oid = device_get_sysctl_tree(sc->dev);
	struct sysctl_oid_list *children = SYSCTL_CHILDREN(oid);

	init_iq(fwq, sc, 0, 0, FW_IQ_QSIZE);
	if (sc->flags & IS_VF)
		intr_idx = 0;
	else
		intr_idx = sc->intr_count > 1 ? 1 : 0;
	rc = alloc_iq_fl(&sc->port[0]->vi[0], fwq, NULL, intr_idx, -1);
	if (rc != 0) {
		device_printf(sc->dev,
		    "failed to create firmware event queue: %d\n", rc);
		return (rc);
	}

	oid = SYSCTL_ADD_NODE(&sc->ctx, children, OID_AUTO, "fwq",
	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "firmware event queue");
	add_iq_sysctls(&sc->ctx, oid, fwq);

	return (0);
}

static int
free_fwq(struct adapter *sc)
{
	return free_iq_fl(NULL, &sc->sge.fwq, NULL);
}

static int
alloc_ctrlq(struct adapter *sc, struct sge_wrq *ctrlq, int idx,
    struct sysctl_oid *oid)
{
	int rc;
	char name[16];
	struct sysctl_oid_list *children;

	snprintf(name, sizeof(name), "%s ctrlq%d", device_get_nameunit(sc->dev),
	    idx);
	init_eq(sc, &ctrlq->eq, EQ_CTRL, CTRL_EQ_QSIZE, sc->port[idx]->tx_chan,
	    sc->sge.fwq.cntxt_id, name);

	children = SYSCTL_CHILDREN(oid);
	snprintf(name, sizeof(name), "%d", idx);
	oid = SYSCTL_ADD_NODE(&sc->ctx, children, OID_AUTO, name,
	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "ctrl queue");
	rc = alloc_wrq(sc, NULL, ctrlq, oid);

	return (rc);
}

int
tnl_cong(struct port_info *pi, int drop)
{

	if (drop == -1)
		return (-1);
	else if (drop == 1)
		return (0);
	else
		return (pi->rx_e_chan_map);
}

static int
alloc_rxq(struct vi_info *vi, struct sge_rxq *rxq, int intr_idx, int idx,
    struct sysctl_oid *oid)
{
	int rc;
	struct adapter *sc = vi->adapter;
	struct sysctl_oid_list *children;
	char name[16];

	rc = alloc_iq_fl(vi, &rxq->iq, &rxq->fl, intr_idx,
	    tnl_cong(vi->pi, cong_drop));
	if (rc != 0)
		return (rc);

	if (idx == 0)
		sc->sge.iq_base = rxq->iq.abs_id - rxq->iq.cntxt_id;
	else
		KASSERT(rxq->iq.cntxt_id + sc->sge.iq_base == rxq->iq.abs_id,
		    ("iq_base mismatch"));
	KASSERT(sc->sge.iq_base == 0 || sc->flags & IS_VF,
	    ("PF with non-zero iq_base"));

	/*
	 * The freelist is just barely above the starvation threshold right now,
	 * fill it up a bit more.
	 */
	FL_LOCK(&rxq->fl);
	refill_fl(sc, &rxq->fl, 128);
	FL_UNLOCK(&rxq->fl);

#if defined(INET) || defined(INET6)
	rc = tcp_lro_init_args(&rxq->lro, vi->ifp, lro_entries, lro_mbufs);
	if (rc != 0)
		return (rc);
	MPASS(rxq->lro.ifp == vi->ifp);	/* also indicates LRO init'ed */

	if (vi->ifp->if_capenable & IFCAP_LRO)
		rxq->iq.flags |= IQ_LRO_ENABLED;
#endif
	if (vi->ifp->if_capenable & IFCAP_HWRXTSTMP)
		rxq->iq.flags |= IQ_RX_TIMESTAMP;
	rxq->ifp = vi->ifp;

	children = SYSCTL_CHILDREN(oid);

	snprintf(name, sizeof(name), "%d", idx);
	oid = SYSCTL_ADD_NODE(&vi->ctx, children, OID_AUTO, name,
	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "rx queue");
	children = SYSCTL_CHILDREN(oid);

	add_iq_sysctls(&vi->ctx, oid, &rxq->iq);
#if defined(INET) || defined(INET6)
	SYSCTL_ADD_U64(&vi->ctx, children, OID_AUTO, "lro_queued", CTLFLAG_RD,
	    &rxq->lro.lro_queued, 0, NULL);
	SYSCTL_ADD_U64(&vi->ctx, children, OID_AUTO, "lro_flushed", CTLFLAG_RD,
	    &rxq->lro.lro_flushed, 0, NULL);
#endif
	SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO, "rxcsum", CTLFLAG_RD,
	    &rxq->rxcsum, "# of times hardware assisted with checksum");
	SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO, "vlan_extraction",
	    CTLFLAG_RD, &rxq->vlan_extraction,
	    "# of times hardware extracted 802.1Q tag");
	SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO, "vxlan_rxcsum",
	    CTLFLAG_RD, &rxq->vxlan_rxcsum,
	    "# of times hardware assisted with inner checksum (VXLAN) ");

	add_fl_sysctls(sc, &vi->ctx, oid, &rxq->fl);

	return (rc);
}

static int
free_rxq(struct vi_info *vi, struct sge_rxq *rxq)
{
	int rc;

#if defined(INET) || defined(INET6)
	if (rxq->lro.ifp) {
		tcp_lro_free(&rxq->lro);
		rxq->lro.ifp = NULL;
	}
#endif

	rc = free_iq_fl(vi, &rxq->iq, &rxq->fl);
	if (rc == 0)
		bzero(rxq, sizeof(*rxq));

	return (rc);
}

#ifdef TCP_OFFLOAD
static int
alloc_ofld_rxq(struct vi_info *vi, struct sge_ofld_rxq *ofld_rxq,
    int intr_idx, int idx, struct sysctl_oid *oid)
{
	struct port_info *pi = vi->pi;
	int rc;
	struct sysctl_oid_list *children;
	char name[16];

	rc = alloc_iq_fl(vi, &ofld_rxq->iq, &ofld_rxq->fl, intr_idx, 0);
	if (rc != 0)
		return (rc);

	children = SYSCTL_CHILDREN(oid);

	snprintf(name, sizeof(name), "%d", idx);
	oid = SYSCTL_ADD_NODE(&vi->ctx, children, OID_AUTO, name,
	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "rx queue");
	add_iq_sysctls(&vi->ctx, oid, &ofld_rxq->iq);
	add_fl_sysctls(pi->adapter, &vi->ctx, oid, &ofld_rxq->fl);

	return (rc);
}

static int
free_ofld_rxq(struct vi_info *vi, struct sge_ofld_rxq *ofld_rxq)
{
	int rc;

	rc = free_iq_fl(vi, &ofld_rxq->iq, &ofld_rxq->fl);
	if (rc == 0)
		bzero(ofld_rxq, sizeof(*ofld_rxq));

	return (rc);
}
#endif

#ifdef DEV_NETMAP
static int
alloc_nm_rxq(struct vi_info *vi, struct sge_nm_rxq *nm_rxq, int intr_idx,
    int idx, struct sysctl_oid *oid)
{
	int rc;
	struct sysctl_oid_list *children;
	struct sysctl_ctx_list *ctx;
	char name[16];
	size_t len;
	struct adapter *sc = vi->adapter;
	struct netmap_adapter *na = NA(vi->ifp);

	MPASS(na != NULL);

	len = vi->qsize_rxq * IQ_ESIZE;
	rc = alloc_ring(sc, len, &nm_rxq->iq_desc_tag, &nm_rxq->iq_desc_map,
	    &nm_rxq->iq_ba, (void **)&nm_rxq->iq_desc);
	if (rc != 0)
		return (rc);

	len = na->num_rx_desc * EQ_ESIZE + sc->params.sge.spg_len;
	rc = alloc_ring(sc, len, &nm_rxq->fl_desc_tag, &nm_rxq->fl_desc_map,
	    &nm_rxq->fl_ba, (void **)&nm_rxq->fl_desc);
	if (rc != 0)
		return (rc);

	nm_rxq->vi = vi;
	nm_rxq->nid = idx;
	nm_rxq->iq_cidx = 0;
	nm_rxq->iq_sidx = vi->qsize_rxq - sc->params.sge.spg_len / IQ_ESIZE;
	nm_rxq->iq_gen = F_RSPD_GEN;
	nm_rxq->fl_pidx = nm_rxq->fl_cidx = 0;
	nm_rxq->fl_sidx = na->num_rx_desc;
	nm_rxq->fl_sidx2 = nm_rxq->fl_sidx;	/* copy for rxsync cacheline */
	nm_rxq->intr_idx = intr_idx;
	nm_rxq->iq_cntxt_id = INVALID_NM_RXQ_CNTXT_ID;

	ctx = &vi->ctx;
	children = SYSCTL_CHILDREN(oid);

	snprintf(name, sizeof(name), "%d", idx);
	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, name,
	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "rx queue");
	children = SYSCTL_CHILDREN(oid);

	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "abs_id",
	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, &nm_rxq->iq_abs_id,
	    0, sysctl_uint16, "I", "absolute id of the queue");
	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cntxt_id",
	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, &nm_rxq->iq_cntxt_id,
	    0, sysctl_uint16, "I", "SGE context id of the queue");
	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cidx",
	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, &nm_rxq->iq_cidx, 0,
	    sysctl_uint16, "I", "consumer index");

	children = SYSCTL_CHILDREN(oid);
	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "fl",
	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "freelist");
	children = SYSCTL_CHILDREN(oid);

	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cntxt_id",
	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, &nm_rxq->fl_cntxt_id,
	    0, sysctl_uint16, "I", "SGE context id of the freelist");
	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cidx", CTLFLAG_RD,
	    &nm_rxq->fl_cidx, 0, "consumer index");
	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "pidx", CTLFLAG_RD,
	    &nm_rxq->fl_pidx, 0, "producer index");

	return (rc);
}


static int
free_nm_rxq(struct vi_info *vi, struct sge_nm_rxq *nm_rxq)
{
	struct adapter *sc = vi->adapter;

	if (vi->flags & VI_INIT_DONE)
		MPASS(nm_rxq->iq_cntxt_id == INVALID_NM_RXQ_CNTXT_ID);
	else
		MPASS(nm_rxq->iq_cntxt_id == 0);

	free_ring(sc, nm_rxq->iq_desc_tag, nm_rxq->iq_desc_map, nm_rxq->iq_ba,
	    nm_rxq->iq_desc);
	free_ring(sc, nm_rxq->fl_desc_tag, nm_rxq->fl_desc_map, nm_rxq->fl_ba,
	    nm_rxq->fl_desc);

	return (0);
}

static int
alloc_nm_txq(struct vi_info *vi, struct sge_nm_txq *nm_txq, int iqidx, int idx,
    struct sysctl_oid *oid)
{
	int rc;
	size_t len;
	struct port_info *pi = vi->pi;
	struct adapter *sc = pi->adapter;
	struct netmap_adapter *na = NA(vi->ifp);
	char name[16];
	struct sysctl_oid_list *children = SYSCTL_CHILDREN(oid);

	len = na->num_tx_desc * EQ_ESIZE + sc->params.sge.spg_len;
	rc = alloc_ring(sc, len, &nm_txq->desc_tag, &nm_txq->desc_map,
	    &nm_txq->ba, (void **)&nm_txq->desc);
	if (rc)
		return (rc);

	nm_txq->pidx = nm_txq->cidx = 0;
	nm_txq->sidx = na->num_tx_desc;
	nm_txq->nid = idx;
	nm_txq->iqidx = iqidx;
	nm_txq->cpl_ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT) |
	    V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_PF(sc->pf) |
	    V_TXPKT_VF(vi->vin) | V_TXPKT_VF_VLD(vi->vfvld));
	if (sc->params.fw_vers >= FW_VERSION32(1, 24, 11, 0))
		nm_txq->op_pkd = htobe32(V_FW_WR_OP(FW_ETH_TX_PKTS2_WR));
	else
		nm_txq->op_pkd = htobe32(V_FW_WR_OP(FW_ETH_TX_PKTS_WR));
	nm_txq->cntxt_id = INVALID_NM_TXQ_CNTXT_ID;

	snprintf(name, sizeof(name), "%d", idx);
	oid = SYSCTL_ADD_NODE(&vi->ctx, children, OID_AUTO, name,
	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap tx queue");
	children = SYSCTL_CHILDREN(oid);

	SYSCTL_ADD_UINT(&vi->ctx, children, OID_AUTO, "cntxt_id", CTLFLAG_RD,
	    &nm_txq->cntxt_id, 0, "SGE context id of the queue");
	SYSCTL_ADD_PROC(&vi->ctx, children, OID_AUTO, "cidx",
	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, &nm_txq->cidx, 0,
	    sysctl_uint16, "I", "consumer index");
	SYSCTL_ADD_PROC(&vi->ctx, children, OID_AUTO, "pidx",
	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, &nm_txq->pidx, 0,
	    sysctl_uint16, "I", "producer index");

	return (rc);
}

static int
free_nm_txq(struct vi_info *vi, struct sge_nm_txq *nm_txq)
{
	struct adapter *sc = vi->adapter;

	if (vi->flags & VI_INIT_DONE)
		MPASS(nm_txq->cntxt_id == INVALID_NM_TXQ_CNTXT_ID);
	else
		MPASS(nm_txq->cntxt_id == 0);

	free_ring(sc, nm_txq->desc_tag, nm_txq->desc_map, nm_txq->ba,
	    nm_txq->desc);

	return (0);
}
#endif

/*
 * Returns a reasonable automatic cidx flush threshold for a given queue size.
 */
static u_int
qsize_to_fthresh(int qsize)
{
	u_int fthresh;

	while (!powerof2(qsize))
		qsize++;
	fthresh = ilog2(qsize);
	if (fthresh > X_CIDXFLUSHTHRESH_128)
		fthresh = X_CIDXFLUSHTHRESH_128;

	return (fthresh);
}

static int
ctrl_eq_alloc(struct adapter *sc, struct sge_eq *eq)
{
	int rc, cntxt_id;
	struct fw_eq_ctrl_cmd c;
	int qsize = eq->sidx + sc->params.sge.spg_len / EQ_ESIZE;

	bzero(&c, sizeof(c));

	c.op_to_vfn = htobe32(V_FW_CMD_OP(FW_EQ_CTRL_CMD) | F_FW_CMD_REQUEST |
	    F_FW_CMD_WRITE | F_FW_CMD_EXEC | V_FW_EQ_CTRL_CMD_PFN(sc->pf) |
	    V_FW_EQ_CTRL_CMD_VFN(0));
	c.alloc_to_len16 = htobe32(F_FW_EQ_CTRL_CMD_ALLOC |
	    F_FW_EQ_CTRL_CMD_EQSTART | FW_LEN16(c));
	c.cmpliqid_eqid = htonl(V_FW_EQ_CTRL_CMD_CMPLIQID(eq->iqid));
	c.physeqid_pkd = htobe32(0);
	c.fetchszm_to_iqid =
	    htobe32(V_FW_EQ_CTRL_CMD_HOSTFCMODE(X_HOSTFCMODE_STATUS_PAGE) |
		V_FW_EQ_CTRL_CMD_PCIECHN(eq->tx_chan) |
		F_FW_EQ_CTRL_CMD_FETCHRO | V_FW_EQ_CTRL_CMD_IQID(eq->iqid));
	c.dcaen_to_eqsize =
	    htobe32(V_FW_EQ_CTRL_CMD_FBMIN(chip_id(sc) <= CHELSIO_T5 ?
		X_FETCHBURSTMIN_64B : X_FETCHBURSTMIN_64B_T6) |
		V_FW_EQ_CTRL_CMD_FBMAX(X_FETCHBURSTMAX_512B) |
		V_FW_EQ_CTRL_CMD_CIDXFTHRESH(qsize_to_fthresh(qsize)) |
		V_FW_EQ_CTRL_CMD_EQSIZE(qsize));
	c.eqaddr = htobe64(eq->ba);

	rc = -t4_wr_mbox(sc, sc->mbox, &c, sizeof(c), &c);
	if (rc != 0) {
		device_printf(sc->dev,
		    "failed to create control queue %d: %d\n", eq->tx_chan, rc);
		return (rc);
	}
	eq->flags |= EQ_ALLOCATED;

	eq->cntxt_id = G_FW_EQ_CTRL_CMD_EQID(be32toh(c.cmpliqid_eqid));
	cntxt_id = eq->cntxt_id - sc->sge.eq_start;
	if (cntxt_id >= sc->sge.eqmap_sz)
	    panic("%s: eq->cntxt_id (%d) more than the max (%d)", __func__,
		cntxt_id, sc->sge.eqmap_sz - 1);
	sc->sge.eqmap[cntxt_id] = eq;

	return (rc);
}

static int
eth_eq_alloc(struct adapter *sc, struct vi_info *vi, struct sge_eq *eq)
{
	int rc, cntxt_id;
	struct fw_eq_eth_cmd c;
	int qsize = eq->sidx + sc->params.sge.spg_len / EQ_ESIZE;

	bzero(&c, sizeof(c));

	c.op_to_vfn = htobe32(V_FW_CMD_OP(FW_EQ_ETH_CMD) | F_FW_CMD_REQUEST |
	    F_FW_CMD_WRITE | F_FW_CMD_EXEC | V_FW_EQ_ETH_CMD_PFN(sc->pf) |
	    V_FW_EQ_ETH_CMD_VFN(0));
	c.alloc_to_len16 = htobe32(F_FW_EQ_ETH_CMD_ALLOC |
	    F_FW_EQ_ETH_CMD_EQSTART | FW_LEN16(c));
	c.autoequiqe_to_viid = htobe32(F_FW_EQ_ETH_CMD_AUTOEQUIQE |
	    F_FW_EQ_ETH_CMD_AUTOEQUEQE | V_FW_EQ_ETH_CMD_VIID(vi->viid));
	c.fetchszm_to_iqid =
	    htobe32(V_FW_EQ_ETH_CMD_HOSTFCMODE(X_HOSTFCMODE_NONE) |
		V_FW_EQ_ETH_CMD_PCIECHN(eq->tx_chan) | F_FW_EQ_ETH_CMD_FETCHRO |
		V_FW_EQ_ETH_CMD_IQID(eq->iqid));
	c.dcaen_to_eqsize =
	    htobe32(V_FW_EQ_ETH_CMD_FBMIN(chip_id(sc) <= CHELSIO_T5 ?
		X_FETCHBURSTMIN_64B : X_FETCHBURSTMIN_64B_T6) |
		V_FW_EQ_ETH_CMD_FBMAX(X_FETCHBURSTMAX_512B) |
		V_FW_EQ_ETH_CMD_EQSIZE(qsize));
	c.eqaddr = htobe64(eq->ba);

	rc = -t4_wr_mbox(sc, sc->mbox, &c, sizeof(c), &c);
	if (rc != 0) {
		device_printf(vi->dev,
		    "failed to create Ethernet egress queue: %d\n", rc);
		return (rc);
	}
	eq->flags |= EQ_ALLOCATED;

	eq->cntxt_id = G_FW_EQ_ETH_CMD_EQID(be32toh(c.eqid_pkd));
	eq->abs_id = G_FW_EQ_ETH_CMD_PHYSEQID(be32toh(c.physeqid_pkd));
	cntxt_id = eq->cntxt_id - sc->sge.eq_start;
	if (cntxt_id >= sc->sge.eqmap_sz)
	    panic("%s: eq->cntxt_id (%d) more than the max (%d)", __func__,
		cntxt_id, sc->sge.eqmap_sz - 1);
	sc->sge.eqmap[cntxt_id] = eq;

	return (rc);
}

#if defined(TCP_OFFLOAD) || defined(RATELIMIT)
static int
ofld_eq_alloc(struct adapter *sc, struct vi_info *vi, struct sge_eq *eq)
{
	int rc, cntxt_id;
	struct fw_eq_ofld_cmd c;
	int qsize = eq->sidx + sc->params.sge.spg_len / EQ_ESIZE;

	bzero(&c, sizeof(c));

	c.op_to_vfn = htonl(V_FW_CMD_OP(FW_EQ_OFLD_CMD) | F_FW_CMD_REQUEST |
	    F_FW_CMD_WRITE | F_FW_CMD_EXEC | V_FW_EQ_OFLD_CMD_PFN(sc->pf) |
	    V_FW_EQ_OFLD_CMD_VFN(0));
	c.alloc_to_len16 = htonl(F_FW_EQ_OFLD_CMD_ALLOC |
	    F_FW_EQ_OFLD_CMD_EQSTART | FW_LEN16(c));
	c.fetchszm_to_iqid =
		htonl(V_FW_EQ_OFLD_CMD_HOSTFCMODE(X_HOSTFCMODE_STATUS_PAGE) |
		    V_FW_EQ_OFLD_CMD_PCIECHN(eq->tx_chan) |
		    F_FW_EQ_OFLD_CMD_FETCHRO | V_FW_EQ_OFLD_CMD_IQID(eq->iqid));
	c.dcaen_to_eqsize =
	    htobe32(V_FW_EQ_OFLD_CMD_FBMIN(chip_id(sc) <= CHELSIO_T5 ?
		X_FETCHBURSTMIN_64B : X_FETCHBURSTMIN_64B_T6) |
		V_FW_EQ_OFLD_CMD_FBMAX(X_FETCHBURSTMAX_512B) |
		V_FW_EQ_OFLD_CMD_CIDXFTHRESH(qsize_to_fthresh(qsize)) |
		V_FW_EQ_OFLD_CMD_EQSIZE(qsize));
	c.eqaddr = htobe64(eq->ba);

	rc = -t4_wr_mbox(sc, sc->mbox, &c, sizeof(c), &c);
	if (rc != 0) {
		device_printf(vi->dev,
		    "failed to create egress queue for TCP offload: %d\n", rc);
		return (rc);
	}
	eq->flags |= EQ_ALLOCATED;

	eq->cntxt_id = G_FW_EQ_OFLD_CMD_EQID(be32toh(c.eqid_pkd));
	cntxt_id = eq->cntxt_id - sc->sge.eq_start;
	if (cntxt_id >= sc->sge.eqmap_sz)
	    panic("%s: eq->cntxt_id (%d) more than the max (%d)", __func__,
		cntxt_id, sc->sge.eqmap_sz - 1);
	sc->sge.eqmap[cntxt_id] = eq;

	return (rc);
}
#endif

static int
alloc_eq(struct adapter *sc, struct vi_info *vi, struct sge_eq *eq)
{
	int rc, qsize;
	size_t len;

	mtx_init(&eq->eq_lock, eq->lockname, NULL, MTX_DEF);

	qsize = eq->sidx + sc->params.sge.spg_len / EQ_ESIZE;
	len = qsize * EQ_ESIZE;
	rc = alloc_ring(sc, len, &eq->desc_tag, &eq->desc_map,
	    &eq->ba, (void **)&eq->desc);
	if (rc)
		return (rc);

	eq->pidx = eq->cidx = eq->dbidx = 0;
	/* Note that equeqidx is not used with sge_wrq (OFLD/CTRL) queues. */
	eq->equeqidx = 0;
	eq->doorbells = sc->doorbells;

	switch (eq->flags & EQ_TYPEMASK) {
	case EQ_CTRL:
		rc = ctrl_eq_alloc(sc, eq);
		break;

	case EQ_ETH:
		rc = eth_eq_alloc(sc, vi, eq);
		break;

#if defined(TCP_OFFLOAD) || defined(RATELIMIT)
	case EQ_OFLD:
		rc = ofld_eq_alloc(sc, vi, eq);
		break;
#endif

	default:
		panic("%s: invalid eq type %d.", __func__,
		    eq->flags & EQ_TYPEMASK);
	}
	if (rc != 0) {
		device_printf(sc->dev,
		    "failed to allocate egress queue(%d): %d\n",
		    eq->flags & EQ_TYPEMASK, rc);
	}

	if (isset(&eq->doorbells, DOORBELL_UDB) ||
	    isset(&eq->doorbells, DOORBELL_UDBWC) ||
	    isset(&eq->doorbells, DOORBELL_WCWR)) {
		uint32_t s_qpp = sc->params.sge.eq_s_qpp;
		uint32_t mask = (1 << s_qpp) - 1;
		volatile uint8_t *udb;

		udb = sc->udbs_base + UDBS_DB_OFFSET;
		udb += (eq->cntxt_id >> s_qpp) << PAGE_SHIFT;	/* pg offset */
		eq->udb_qid = eq->cntxt_id & mask;		/* id in page */
		if (eq->udb_qid >= PAGE_SIZE / UDBS_SEG_SIZE)
	    		clrbit(&eq->doorbells, DOORBELL_WCWR);
		else {
			udb += eq->udb_qid << UDBS_SEG_SHIFT;	/* seg offset */
			eq->udb_qid = 0;
		}
		eq->udb = (volatile void *)udb;
	}

	return (rc);
}

static int
free_eq(struct adapter *sc, struct sge_eq *eq)
{
	int rc;

	if (eq->flags & EQ_ALLOCATED) {
		switch (eq->flags & EQ_TYPEMASK) {
		case EQ_CTRL:
			rc = -t4_ctrl_eq_free(sc, sc->mbox, sc->pf, 0,
			    eq->cntxt_id);
			break;

		case EQ_ETH:
			rc = -t4_eth_eq_free(sc, sc->mbox, sc->pf, 0,
			    eq->cntxt_id);
			break;

#if defined(TCP_OFFLOAD) || defined(RATELIMIT)
		case EQ_OFLD:
			rc = -t4_ofld_eq_free(sc, sc->mbox, sc->pf, 0,
			    eq->cntxt_id);
			break;
#endif

		default:
			panic("%s: invalid eq type %d.", __func__,
			    eq->flags & EQ_TYPEMASK);
		}
		if (rc != 0) {
			device_printf(sc->dev,
			    "failed to free egress queue (%d): %d\n",
			    eq->flags & EQ_TYPEMASK, rc);
			return (rc);
		}
		eq->flags &= ~EQ_ALLOCATED;
	}

	free_ring(sc, eq->desc_tag, eq->desc_map, eq->ba, eq->desc);

	if (mtx_initialized(&eq->eq_lock))
		mtx_destroy(&eq->eq_lock);

	bzero(eq, sizeof(*eq));
	return (0);
}

static int
alloc_wrq(struct adapter *sc, struct vi_info *vi, struct sge_wrq *wrq,
    struct sysctl_oid *oid)
{
	int rc;
	struct sysctl_ctx_list *ctx = vi ? &vi->ctx : &sc->ctx;
	struct sysctl_oid_list *children = SYSCTL_CHILDREN(oid);

	rc = alloc_eq(sc, vi, &wrq->eq);
	if (rc)
		return (rc);

	wrq->adapter = sc;
	TASK_INIT(&wrq->wrq_tx_task, 0, wrq_tx_drain, wrq);
	TAILQ_INIT(&wrq->incomplete_wrs);
	STAILQ_INIT(&wrq->wr_list);
	wrq->nwr_pending = 0;
	wrq->ndesc_needed = 0;

	SYSCTL_ADD_UAUTO(ctx, children, OID_AUTO, "ba", CTLFLAG_RD,
	    &wrq->eq.ba, "bus address of descriptor ring");
	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dmalen", CTLFLAG_RD, NULL,
	    wrq->eq.sidx * EQ_ESIZE + sc->params.sge.spg_len,
	    "desc ring size in bytes");
	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cntxt_id", CTLFLAG_RD,
	    &wrq->eq.cntxt_id, 0, "SGE context id of the queue");
	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cidx",
	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, &wrq->eq.cidx, 0,
	    sysctl_uint16, "I", "consumer index");
	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pidx",
	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, &wrq->eq.pidx, 0,
	    sysctl_uint16, "I", "producer index");
	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sidx", CTLFLAG_RD, NULL,
	    wrq->eq.sidx, "status page index");
	SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, "tx_wrs_direct", CTLFLAG_RD,
	    &wrq->tx_wrs_direct, "# of work requests (direct)");
	SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, "tx_wrs_copied", CTLFLAG_RD,
	    &wrq->tx_wrs_copied, "# of work requests (copied)");
	SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, "tx_wrs_sspace", CTLFLAG_RD,
	    &wrq->tx_wrs_ss, "# of work requests (copied from scratch space)");

	return (rc);
}

static int
free_wrq(struct adapter *sc, struct sge_wrq *wrq)
{
	int rc;

	rc = free_eq(sc, &wrq->eq);
	if (rc)
		return (rc);

	bzero(wrq, sizeof(*wrq));
	return (0);
}

static int
alloc_txq(struct vi_info *vi, struct sge_txq *txq, int idx,
    struct sysctl_oid *oid)
{
	int rc;
	struct port_info *pi = vi->pi;
	struct adapter *sc = pi->adapter;
	struct sge_eq *eq = &txq->eq;
	struct txpkts *txp;
	char name[16];
	struct sysctl_oid_list *children = SYSCTL_CHILDREN(oid);

	rc = mp_ring_alloc(&txq->r, eq->sidx, txq, eth_tx, can_resume_eth_tx,
	    M_CXGBE, &eq->eq_lock, M_WAITOK);
	if (rc != 0) {
		device_printf(sc->dev, "failed to allocate mp_ring: %d\n", rc);
		return (rc);
	}

	rc = alloc_eq(sc, vi, eq);
	if (rc != 0) {
		mp_ring_free(txq->r);
		txq->r = NULL;
		return (rc);
	}

	/* Can't fail after this point. */

	if (idx == 0)
		sc->sge.eq_base = eq->abs_id - eq->cntxt_id;
	else
		KASSERT(eq->cntxt_id + sc->sge.eq_base == eq->abs_id,
		    ("eq_base mismatch"));
	KASSERT(sc->sge.eq_base == 0 || sc->flags & IS_VF,
	    ("PF with non-zero eq_base"));

	TASK_INIT(&txq->tx_reclaim_task, 0, tx_reclaim, eq);
	txq->ifp = vi->ifp;
	txq->gl = sglist_alloc(TX_SGL_SEGS, M_WAITOK);
	if (vi->flags & TX_USES_VM_WR)
		txq->cpl_ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
		    V_TXPKT_INTF(pi->tx_chan));
	else
		txq->cpl_ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
		    V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_PF(sc->pf) |
		    V_TXPKT_VF(vi->vin) | V_TXPKT_VF_VLD(vi->vfvld));
	txq->tc_idx = -1;
	txq->sdesc = malloc(eq->sidx * sizeof(struct tx_sdesc), M_CXGBE,
	    M_ZERO | M_WAITOK);

	txp = &txq->txp;
	txp->score = 5;
	MPASS(nitems(txp->mb) >= sc->params.max_pkts_per_eth_tx_pkts_wr);
	txq->txp.max_npkt = min(nitems(txp->mb),
	    sc->params.max_pkts_per_eth_tx_pkts_wr);
	if (vi->flags & TX_USES_VM_WR && !(sc->flags & IS_VF))
		txq->txp.max_npkt--;

	snprintf(name, sizeof(name), "%d", idx);
	oid = SYSCTL_ADD_NODE(&vi->ctx, children, OID_AUTO, name,
	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "tx queue");
	children = SYSCTL_CHILDREN(oid);

	SYSCTL_ADD_UAUTO(&vi->ctx, children, OID_AUTO, "ba", CTLFLAG_RD,
	    &eq->ba, "bus address of descriptor ring");
	SYSCTL_ADD_INT(&vi->ctx, children, OID_AUTO, "dmalen", CTLFLAG_RD, NULL,
	    eq->sidx * EQ_ESIZE + sc->params.sge.spg_len,
	    "desc ring size in bytes");
	SYSCTL_ADD_UINT(&vi->ctx, children, OID_AUTO, "abs_id", CTLFLAG_RD,
	    &eq->abs_id, 0, "absolute id of the queue");
	SYSCTL_ADD_UINT(&vi->ctx, children, OID_AUTO, "cntxt_id", CTLFLAG_RD,
	    &eq->cntxt_id, 0, "SGE context id of the queue");
	SYSCTL_ADD_PROC(&vi->ctx, children, OID_AUTO, "cidx",
	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, &eq->cidx, 0,
	    sysctl_uint16, "I", "consumer index");
	SYSCTL_ADD_PROC(&vi->ctx, children, OID_AUTO, "pidx",
	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, &eq->pidx, 0,
	    sysctl_uint16, "I", "producer index");
	SYSCTL_ADD_INT(&vi->ctx, children, OID_AUTO, "sidx", CTLFLAG_RD, NULL,
	    eq->sidx, "status page index");

	SYSCTL_ADD_PROC(&vi->ctx, children, OID_AUTO, "tc",
	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, idx, sysctl_tc,
	    "I", "traffic class (-1 means none)");

	SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO, "txcsum", CTLFLAG_RD,
	    &txq->txcsum, "# of times hardware assisted with checksum");
	SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO, "vlan_insertion",
	    CTLFLAG_RD, &txq->vlan_insertion,
	    "# of times hardware inserted 802.1Q tag");
	SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO, "tso_wrs", CTLFLAG_RD,
	    &txq->tso_wrs, "# of TSO work requests");
	SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO, "imm_wrs", CTLFLAG_RD,
	    &txq->imm_wrs, "# of work requests with immediate data");
	SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO, "sgl_wrs", CTLFLAG_RD,
	    &txq->sgl_wrs, "# of work requests with direct SGL");
	SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO, "txpkt_wrs", CTLFLAG_RD,
	    &txq->txpkt_wrs, "# of txpkt work requests (one pkt/WR)");
	SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO, "txpkts0_wrs",
	    CTLFLAG_RD, &txq->txpkts0_wrs,
	    "# of txpkts (type 0) work requests");
	SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO, "txpkts1_wrs",
	    CTLFLAG_RD, &txq->txpkts1_wrs,
	    "# of txpkts (type 1) work requests");
	SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO, "txpkts0_pkts",
	    CTLFLAG_RD, &txq->txpkts0_pkts,
	    "# of frames tx'd using type0 txpkts work requests");
	SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO, "txpkts1_pkts",
	    CTLFLAG_RD, &txq->txpkts1_pkts,
	    "# of frames tx'd using type1 txpkts work requests");
	SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO, "raw_wrs", CTLFLAG_RD,
	    &txq->raw_wrs, "# of raw work requests (non-packets)");
	SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO, "vxlan_tso_wrs",
	    CTLFLAG_RD, &txq->vxlan_tso_wrs, "# of VXLAN TSO work requests");
	SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO, "vxlan_txcsum",
	    CTLFLAG_RD, &txq->vxlan_txcsum,
	    "# of times hardware assisted with inner checksums (VXLAN)");

#ifdef KERN_TLS
	if (sc->flags & KERN_TLS_OK) {
		SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO,
		    "kern_tls_records", CTLFLAG_RD, &txq->kern_tls_records,
		    "# of NIC TLS records transmitted");
		SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO,
		    "kern_tls_short", CTLFLAG_RD, &txq->kern_tls_short,
		    "# of short NIC TLS records transmitted");
		SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO,
		    "kern_tls_partial", CTLFLAG_RD, &txq->kern_tls_partial,
		    "# of partial NIC TLS records transmitted");
		SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO,
		    "kern_tls_full", CTLFLAG_RD, &txq->kern_tls_full,
		    "# of full NIC TLS records transmitted");
		SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO,
		    "kern_tls_octets", CTLFLAG_RD, &txq->kern_tls_octets,
		    "# of payload octets in transmitted NIC TLS records");
		SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO,
		    "kern_tls_waste", CTLFLAG_RD, &txq->kern_tls_waste,
		    "# of octets DMAd but not transmitted in NIC TLS records");
		SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO,
		    "kern_tls_options", CTLFLAG_RD, &txq->kern_tls_options,
		    "# of NIC TLS options-only packets transmitted");
		SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO,
		    "kern_tls_header", CTLFLAG_RD, &txq->kern_tls_header,
		    "# of NIC TLS header-only packets transmitted");
		SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO,
		    "kern_tls_fin", CTLFLAG_RD, &txq->kern_tls_fin,
		    "# of NIC TLS FIN-only packets transmitted");
		SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO,
		    "kern_tls_fin_short", CTLFLAG_RD, &txq->kern_tls_fin_short,
		    "# of NIC TLS padded FIN packets on short TLS records");
		SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO,
		    "kern_tls_cbc", CTLFLAG_RD, &txq->kern_tls_cbc,
		    "# of NIC TLS sessions using AES-CBC");
		SYSCTL_ADD_UQUAD(&vi->ctx, children, OID_AUTO,
		    "kern_tls_gcm", CTLFLAG_RD, &txq->kern_tls_gcm,
		    "# of NIC TLS sessions using AES-GCM");
	}
#endif
	mp_ring_sysctls(txq->r, &vi->ctx, children);

	return (0);
}

static int
free_txq(struct vi_info *vi, struct sge_txq *txq)
{
	int rc;
	struct adapter *sc = vi->adapter;
	struct sge_eq *eq = &txq->eq;

	rc = free_eq(sc, eq);
	if (rc)
		return (rc);

	sglist_free(txq->gl);
	free(txq->sdesc, M_CXGBE);
	mp_ring_free(txq->r);

	bzero(txq, sizeof(*txq));
	return (0);
}

static void
oneseg_dma_callback(void *arg, bus_dma_segment_t *segs, int nseg, int error)
{
	bus_addr_t *ba = arg;

	KASSERT(nseg == 1,
	    ("%s meant for single segment mappings only.", __func__));

	*ba = error ? 0 : segs->ds_addr;
}

static inline void
ring_fl_db(struct adapter *sc, struct sge_fl *fl)
{
	uint32_t n, v;

	n = IDXDIFF(fl->pidx >> 3, fl->dbidx, fl->sidx);
	MPASS(n > 0);

	wmb();
	v = fl->dbval | V_PIDX(n);
	if (fl->udb)
		*fl->udb = htole32(v);
	else
		t4_write_reg(sc, sc->sge_kdoorbell_reg, v);
	IDXINCR(fl->dbidx, n, fl->sidx);
}

/*
 * Fills up the freelist by allocating up to 'n' buffers.  Buffers that are
 * recycled do not count towards this allocation budget.
 *
 * Returns non-zero to indicate that this freelist should be added to the list
 * of starving freelists.
 */
static int
refill_fl(struct adapter *sc, struct sge_fl *fl, int n)
{
	__be64 *d;
	struct fl_sdesc *sd;
	uintptr_t pa;
	caddr_t cl;
	struct rx_buf_info *rxb;
	struct cluster_metadata *clm;
	uint16_t max_pidx;
	uint16_t hw_cidx = fl->hw_cidx;		/* stable snapshot */

	FL_LOCK_ASSERT_OWNED(fl);

	/*
	 * We always stop at the beginning of the hardware descriptor that's just
	 * before the one with the hw cidx.  This is to avoid hw pidx = hw cidx,
	 * which would mean an empty freelist to the chip.
	 */
	max_pidx = __predict_false(hw_cidx == 0) ? fl->sidx - 1 : hw_cidx - 1;
	if (fl->pidx == max_pidx * 8)
		return (0);

	d = &fl->desc[fl->pidx];
	sd = &fl->sdesc[fl->pidx];

	while (n > 0) {

		if (sd->cl != NULL) {

			if (sd->nmbuf == 0) {
				/*
				 * Fast recycle without involving any atomics on
				 * the cluster's metadata (if the cluster has
				 * metadata).  This happens when all frames
				 * received in the cluster were small enough to
				 * fit within a single mbuf each.
				 */
				fl->cl_fast_recycled++;
				goto recycled;
			}

			/*
			 * Cluster is guaranteed to have metadata.  Clusters
			 * without metadata always take the fast recycle path
			 * when they're recycled.
			 */
			clm = cl_metadata(sd);
			MPASS(clm != NULL);

			if (atomic_fetchadd_int(&clm->refcount, -1) == 1) {
				fl->cl_recycled++;
				counter_u64_add(extfree_rels, 1);
				goto recycled;
			}
			sd->cl = NULL;	/* gave up my reference */
		}
		MPASS(sd->cl == NULL);
		rxb = &sc->sge.rx_buf_info[fl->zidx];
		cl = uma_zalloc(rxb->zone, M_NOWAIT);
		if (__predict_false(cl == NULL)) {
			if (fl->zidx != fl->safe_zidx) {
				rxb = &sc->sge.rx_buf_info[fl->safe_zidx];
				cl = uma_zalloc(rxb->zone, M_NOWAIT);
			}
			if (cl == NULL)
				break;
		}
		fl->cl_allocated++;
		n--;

		pa = pmap_kextract((vm_offset_t)cl);
		sd->cl = cl;
		sd->zidx = fl->zidx;

		if (fl->flags & FL_BUF_PACKING) {
			*d = htobe64(pa | rxb->hwidx2);
			sd->moff = rxb->size2;
		} else {
			*d = htobe64(pa | rxb->hwidx1);
			sd->moff = 0;
		}
recycled:
		sd->nmbuf = 0;
		d++;
		sd++;
		if (__predict_false((++fl->pidx & 7) == 0)) {
			uint16_t pidx = fl->pidx >> 3;

			if (__predict_false(pidx == fl->sidx)) {
				fl->pidx = 0;
				pidx = 0;
				sd = fl->sdesc;
				d = fl->desc;
			}
			if (n < 8 || pidx == max_pidx)
				break;

			if (IDXDIFF(pidx, fl->dbidx, fl->sidx) >= 4)
				ring_fl_db(sc, fl);
		}
	}

	if ((fl->pidx >> 3) != fl->dbidx)
		ring_fl_db(sc, fl);

	return (FL_RUNNING_LOW(fl) && !(fl->flags & FL_STARVING));
}

/*
 * Attempt to refill all starving freelists.
 */
static void
refill_sfl(void *arg)
{
	struct adapter *sc = arg;
	struct sge_fl *fl, *fl_temp;

	mtx_assert(&sc->sfl_lock, MA_OWNED);
	TAILQ_FOREACH_SAFE(fl, &sc->sfl, link, fl_temp) {
		FL_LOCK(fl);
		refill_fl(sc, fl, 64);
		if (FL_NOT_RUNNING_LOW(fl) || fl->flags & FL_DOOMED) {
			TAILQ_REMOVE(&sc->sfl, fl, link);
			fl->flags &= ~FL_STARVING;
		}
		FL_UNLOCK(fl);
	}

	if (!TAILQ_EMPTY(&sc->sfl))
		callout_schedule(&sc->sfl_callout, hz / 5);
}

static int
alloc_fl_sdesc(struct sge_fl *fl)
{

	fl->sdesc = malloc(fl->sidx * 8 * sizeof(struct fl_sdesc), M_CXGBE,
	    M_ZERO | M_WAITOK);

	return (0);
}

static void
free_fl_sdesc(struct adapter *sc, struct sge_fl *fl)
{
	struct fl_sdesc *sd;
	struct cluster_metadata *clm;
	int i;

	sd = fl->sdesc;
	for (i = 0; i < fl->sidx * 8; i++, sd++) {
		if (sd->cl == NULL)
			continue;

		if (sd->nmbuf == 0)
			uma_zfree(sc->sge.rx_buf_info[sd->zidx].zone, sd->cl);
		else if (fl->flags & FL_BUF_PACKING) {
			clm = cl_metadata(sd);
			if (atomic_fetchadd_int(&clm->refcount, -1) == 1) {
				uma_zfree(sc->sge.rx_buf_info[sd->zidx].zone,
				    sd->cl);
				counter_u64_add(extfree_rels, 1);
			}
		}
		sd->cl = NULL;
	}

	free(fl->sdesc, M_CXGBE);
	fl->sdesc = NULL;
}

static inline void
get_pkt_gl(struct mbuf *m, struct sglist *gl)
{
	int rc;

	M_ASSERTPKTHDR(m);

	sglist_reset(gl);
	rc = sglist_append_mbuf(gl, m);
	if (__predict_false(rc != 0)) {
		panic("%s: mbuf %p (%d segs) was vetted earlier but now fails "
		    "with %d.", __func__, m, mbuf_nsegs(m), rc);
	}

	KASSERT(gl->sg_nseg == mbuf_nsegs(m),
	    ("%s: nsegs changed for mbuf %p from %d to %d", __func__, m,
	    mbuf_nsegs(m), gl->sg_nseg));
#if 0	/* vm_wr not readily available here. */
	KASSERT(gl->sg_nseg > 0 && gl->sg_nseg <= max_nsegs_allowed(m, vm_wr),
	    ("%s: %d segments, should have been 1 <= nsegs <= %d", __func__,
		gl->sg_nseg, max_nsegs_allowed(m, vm_wr)));
#endif
}

/*
 * len16 for a txpkt WR with a GL.  Includes the firmware work request header.
 */
static inline u_int
txpkt_len16(u_int nsegs, const u_int extra)
{
	u_int n;

	MPASS(nsegs > 0);

	nsegs--; /* first segment is part of ulptx_sgl */
	n = extra + sizeof(struct fw_eth_tx_pkt_wr) +
	    sizeof(struct cpl_tx_pkt_core) +
	    sizeof(struct ulptx_sgl) + 8 * ((3 * nsegs) / 2 + (nsegs & 1));

	return (howmany(n, 16));
}

/*
 * len16 for a txpkt_vm WR with a GL.  Includes the firmware work
 * request header.
 */
static inline u_int
txpkt_vm_len16(u_int nsegs, const u_int extra)
{
	u_int n;

	MPASS(nsegs > 0);

	nsegs--; /* first segment is part of ulptx_sgl */
	n = extra + sizeof(struct fw_eth_tx_pkt_vm_wr) +
	    sizeof(struct cpl_tx_pkt_core) +
	    sizeof(struct ulptx_sgl) + 8 * ((3 * nsegs) / 2 + (nsegs & 1));

	return (howmany(n, 16));
}

static inline void
calculate_mbuf_len16(struct mbuf *m, bool vm_wr)
{
	const int lso = sizeof(struct cpl_tx_pkt_lso_core);
	const int tnl_lso = sizeof(struct cpl_tx_tnl_lso);

	if (vm_wr) {
		if (needs_tso(m))
			set_mbuf_len16(m, txpkt_vm_len16(mbuf_nsegs(m), lso));
		else
			set_mbuf_len16(m, txpkt_vm_len16(mbuf_nsegs(m), 0));
		return;
	}

	if (needs_tso(m)) {
		if (needs_vxlan_tso(m))
			set_mbuf_len16(m, txpkt_len16(mbuf_nsegs(m), tnl_lso));
		else
			set_mbuf_len16(m, txpkt_len16(mbuf_nsegs(m), lso));
	} else
		set_mbuf_len16(m, txpkt_len16(mbuf_nsegs(m), 0));
}

/*
 * len16 for a txpkts type 0 WR with a GL.  Does not include the firmware work
 * request header.
 */
static inline u_int
txpkts0_len16(u_int nsegs)
{
	u_int n;

	MPASS(nsegs > 0);

	nsegs--; /* first segment is part of ulptx_sgl */
	n = sizeof(struct ulp_txpkt) + sizeof(struct ulptx_idata) +
	    sizeof(struct cpl_tx_pkt_core) + sizeof(struct ulptx_sgl) +
	    8 * ((3 * nsegs) / 2 + (nsegs & 1));

	return (howmany(n, 16));
}

/*
 * len16 for a txpkts type 1 WR with a GL.  Does not include the firmware work
 * request header.
 */
static inline u_int
txpkts1_len16(void)
{
	u_int n;

	n = sizeof(struct cpl_tx_pkt_core) + sizeof(struct ulptx_sgl);

	return (howmany(n, 16));
}

static inline u_int
imm_payload(u_int ndesc)
{
	u_int n;

	n = ndesc * EQ_ESIZE - sizeof(struct fw_eth_tx_pkt_wr) -
	    sizeof(struct cpl_tx_pkt_core);

	return (n);
}

static inline uint64_t
csum_to_ctrl(struct adapter *sc, struct mbuf *m)
{
	uint64_t ctrl;
	int csum_type, l2hlen, l3hlen;
	int x, y;
	static const int csum_types[3][2] = {
		{TX_CSUM_TCPIP, TX_CSUM_TCPIP6},
		{TX_CSUM_UDPIP, TX_CSUM_UDPIP6},
		{TX_CSUM_IP, 0}
	};

	M_ASSERTPKTHDR(m);

	if (!needs_hwcsum(m))
		return (F_TXPKT_IPCSUM_DIS | F_TXPKT_L4CSUM_DIS);

	MPASS(m->m_pkthdr.l2hlen >= ETHER_HDR_LEN);
	MPASS(m->m_pkthdr.l3hlen >= sizeof(struct ip));

	if (needs_vxlan_csum(m)) {
		MPASS(m->m_pkthdr.l4hlen > 0);
		MPASS(m->m_pkthdr.l5hlen > 0);
		MPASS(m->m_pkthdr.inner_l2hlen >= ETHER_HDR_LEN);
		MPASS(m->m_pkthdr.inner_l3hlen >= sizeof(struct ip));

		l2hlen = m->m_pkthdr.l2hlen + m->m_pkthdr.l3hlen +
		    m->m_pkthdr.l4hlen + m->m_pkthdr.l5hlen +
		    m->m_pkthdr.inner_l2hlen - ETHER_HDR_LEN;
		l3hlen = m->m_pkthdr.inner_l3hlen;
	} else {
		l2hlen = m->m_pkthdr.l2hlen - ETHER_HDR_LEN;
		l3hlen = m->m_pkthdr.l3hlen;
	}

	ctrl = 0;
	if (!needs_l3_csum(m))
		ctrl |= F_TXPKT_IPCSUM_DIS;

	if (m->m_pkthdr.csum_flags & (CSUM_IP_TCP | CSUM_INNER_IP_TCP |
	    CSUM_IP6_TCP | CSUM_INNER_IP6_TCP))
		x = 0;	/* TCP */
	else if (m->m_pkthdr.csum_flags & (CSUM_IP_UDP | CSUM_INNER_IP_UDP |
	    CSUM_IP6_UDP | CSUM_INNER_IP6_UDP))
		x = 1;	/* UDP */
	else
		x = 2;

	if (m->m_pkthdr.csum_flags & (CSUM_IP | CSUM_IP_TCP | CSUM_IP_UDP |
	    CSUM_INNER_IP | CSUM_INNER_IP_TCP | CSUM_INNER_IP_UDP))
		y = 0;	/* IPv4 */
	else {
		MPASS(m->m_pkthdr.csum_flags & (CSUM_IP6_TCP | CSUM_IP6_UDP |
		    CSUM_INNER_IP6_TCP | CSUM_INNER_IP6_UDP));
		y = 1;	/* IPv6 */
	}
	/*
	 * needs_hwcsum returned true earlier so there must be some kind of
	 * checksum to calculate.
	 */
	csum_type = csum_types[x][y];
	MPASS(csum_type != 0);
	if (csum_type == TX_CSUM_IP)
		ctrl |= F_TXPKT_L4CSUM_DIS;
	ctrl |= V_TXPKT_CSUM_TYPE(csum_type) | V_TXPKT_IPHDR_LEN(l3hlen);
	if (chip_id(sc) <= CHELSIO_T5)
		ctrl |= V_TXPKT_ETHHDR_LEN(l2hlen);
	else
		ctrl |= V_T6_TXPKT_ETHHDR_LEN(l2hlen);

	return (ctrl);
}

static inline void *
write_lso_cpl(void *cpl, struct mbuf *m0)
{
	struct cpl_tx_pkt_lso_core *lso;
	uint32_t ctrl;

	KASSERT(m0->m_pkthdr.l2hlen > 0 && m0->m_pkthdr.l3hlen > 0 &&
	    m0->m_pkthdr.l4hlen > 0,
	    ("%s: mbuf %p needs TSO but missing header lengths",
		__func__, m0));

	ctrl = V_LSO_OPCODE(CPL_TX_PKT_LSO) |
	    F_LSO_FIRST_SLICE | F_LSO_LAST_SLICE |
	    V_LSO_ETHHDR_LEN((m0->m_pkthdr.l2hlen - ETHER_HDR_LEN) >> 2) |
	    V_LSO_IPHDR_LEN(m0->m_pkthdr.l3hlen >> 2) |
	    V_LSO_TCPHDR_LEN(m0->m_pkthdr.l4hlen >> 2);
	if (m0->m_pkthdr.l3hlen == sizeof(struct ip6_hdr))
		ctrl |= F_LSO_IPV6;

	lso = cpl;
	lso->lso_ctrl = htobe32(ctrl);
	lso->ipid_ofst = htobe16(0);
	lso->mss = htobe16(m0->m_pkthdr.tso_segsz);
	lso->seqno_offset = htobe32(0);
	lso->len = htobe32(m0->m_pkthdr.len);

	return (lso + 1);
}

static void *
write_tnl_lso_cpl(void *cpl, struct mbuf *m0)
{
	struct cpl_tx_tnl_lso *tnl_lso = cpl;
	uint32_t ctrl;

	KASSERT(m0->m_pkthdr.inner_l2hlen > 0 &&
	    m0->m_pkthdr.inner_l3hlen > 0 && m0->m_pkthdr.inner_l4hlen > 0 &&
	    m0->m_pkthdr.inner_l5hlen > 0,
	    ("%s: mbuf %p needs VXLAN_TSO but missing inner header lengths",
		__func__, m0));
	KASSERT(m0->m_pkthdr.l2hlen > 0 && m0->m_pkthdr.l3hlen > 0 &&
	    m0->m_pkthdr.l4hlen > 0 && m0->m_pkthdr.l5hlen > 0,
	    ("%s: mbuf %p needs VXLAN_TSO but missing outer header lengths",
		__func__, m0));

	/* Outer headers. */
	ctrl = V_CPL_TX_TNL_LSO_OPCODE(CPL_TX_TNL_LSO) |
	    F_CPL_TX_TNL_LSO_FIRST | F_CPL_TX_TNL_LSO_LAST |
	    V_CPL_TX_TNL_LSO_ETHHDRLENOUT(
		(m0->m_pkthdr.l2hlen - ETHER_HDR_LEN) >> 2) |
	    V_CPL_TX_TNL_LSO_IPHDRLENOUT(m0->m_pkthdr.l3hlen >> 2) |
	    F_CPL_TX_TNL_LSO_IPLENSETOUT;
	if (m0->m_pkthdr.l3hlen == sizeof(struct ip6_hdr))
		ctrl |= F_CPL_TX_TNL_LSO_IPV6OUT;
	else {
		ctrl |= F_CPL_TX_TNL_LSO_IPHDRCHKOUT |
		    F_CPL_TX_TNL_LSO_IPIDINCOUT;
	}
	tnl_lso->op_to_IpIdSplitOut = htobe32(ctrl);
	tnl_lso->IpIdOffsetOut = 0;
	tnl_lso->UdpLenSetOut_to_TnlHdrLen =
		htobe16(F_CPL_TX_TNL_LSO_UDPCHKCLROUT |
		    F_CPL_TX_TNL_LSO_UDPLENSETOUT |
		    V_CPL_TX_TNL_LSO_TNLHDRLEN(m0->m_pkthdr.l2hlen +
			m0->m_pkthdr.l3hlen + m0->m_pkthdr.l4hlen +
			m0->m_pkthdr.l5hlen) |
		    V_CPL_TX_TNL_LSO_TNLTYPE(TX_TNL_TYPE_VXLAN));
	tnl_lso->r1 = 0;

	/* Inner headers. */
	ctrl = V_CPL_TX_TNL_LSO_ETHHDRLEN(
	    (m0->m_pkthdr.inner_l2hlen - ETHER_HDR_LEN) >> 2) |
	    V_CPL_TX_TNL_LSO_IPHDRLEN(m0->m_pkthdr.inner_l3hlen >> 2) |
	    V_CPL_TX_TNL_LSO_TCPHDRLEN(m0->m_pkthdr.inner_l4hlen >> 2);
	if (m0->m_pkthdr.inner_l3hlen == sizeof(struct ip6_hdr))
		ctrl |= F_CPL_TX_TNL_LSO_IPV6;
	tnl_lso->Flow_to_TcpHdrLen = htobe32(ctrl);
	tnl_lso->IpIdOffset = 0;
	tnl_lso->IpIdSplit_to_Mss =
	    htobe16(V_CPL_TX_TNL_LSO_MSS(m0->m_pkthdr.tso_segsz));
	tnl_lso->TCPSeqOffset = 0;
	tnl_lso->EthLenOffset_Size =
	    htobe32(V_CPL_TX_TNL_LSO_SIZE(m0->m_pkthdr.len));

	return (tnl_lso + 1);
}

#define VM_TX_L2HDR_LEN	16	/* ethmacdst to vlantci */

/*
 * Write a VM txpkt WR for this packet to the hardware descriptors, update the
 * software descriptor, and advance the pidx.  It is guaranteed that enough
 * descriptors are available.
 *
 * The return value is the # of hardware descriptors used.
 */
static u_int
write_txpkt_vm_wr(struct adapter *sc, struct sge_txq *txq, struct mbuf *m0)
{
	struct sge_eq *eq;
	struct fw_eth_tx_pkt_vm_wr *wr;
	struct tx_sdesc *txsd;
	struct cpl_tx_pkt_core *cpl;
	uint32_t ctrl;	/* used in many unrelated places */
	uint64_t ctrl1;
	int len16, ndesc, pktlen, nsegs;
	caddr_t dst;

	TXQ_LOCK_ASSERT_OWNED(txq);
	M_ASSERTPKTHDR(m0);

	len16 = mbuf_len16(m0);
	nsegs = mbuf_nsegs(m0);
	pktlen = m0->m_pkthdr.len;
	ctrl = sizeof(struct cpl_tx_pkt_core);
	if (needs_tso(m0))
		ctrl += sizeof(struct cpl_tx_pkt_lso_core);
	ndesc = tx_len16_to_desc(len16);

	/* Firmware work request header */
	eq = &txq->eq;
	wr = (void *)&eq->desc[eq->pidx];
	wr->op_immdlen = htobe32(V_FW_WR_OP(FW_ETH_TX_PKT_VM_WR) |
	    V_FW_ETH_TX_PKT_WR_IMMDLEN(ctrl));

	ctrl = V_FW_WR_LEN16(len16);
	wr->equiq_to_len16 = htobe32(ctrl);
	wr->r3[0] = 0;
	wr->r3[1] = 0;

	/*
	 * Copy over ethmacdst, ethmacsrc, ethtype, and vlantci.
	 * vlantci is ignored unless the ethtype is 0x8100, so it's
	 * simpler to always copy it rather than making it
	 * conditional.  Also, it seems that we do not have to set
	 * vlantci or fake the ethtype when doing VLAN tag insertion.
	 */
	m_copydata(m0, 0, VM_TX_L2HDR_LEN, wr->ethmacdst);

	if (needs_tso(m0)) {
		cpl = write_lso_cpl(wr + 1, m0);
		txq->tso_wrs++;
	} else
		cpl = (void *)(wr + 1);

	/* Checksum offload */
	ctrl1 = csum_to_ctrl(sc, m0);
	if (ctrl1 != (F_TXPKT_IPCSUM_DIS | F_TXPKT_L4CSUM_DIS))
		txq->txcsum++;	/* some hardware assistance provided */

	/* VLAN tag insertion */
	if (needs_vlan_insertion(m0)) {
		ctrl1 |= F_TXPKT_VLAN_VLD |
		    V_TXPKT_VLAN(m0->m_pkthdr.ether_vtag);
		txq->vlan_insertion++;
	}

	/* CPL header */
	cpl->ctrl0 = txq->cpl_ctrl0;
	cpl->pack = 0;
	cpl->len = htobe16(pktlen);
	cpl->ctrl1 = htobe64(ctrl1);

	/* SGL */
	dst = (void *)(cpl + 1);

	/*
	 * A packet using TSO will use up an entire descriptor for the
	 * firmware work request header, LSO CPL, and TX_PKT_XT CPL.
	 * If this descriptor is the last descriptor in the ring, wrap
	 * around to the front of the ring explicitly for the start of
	 * the sgl.
	 */
	if (dst == (void *)&eq->desc[eq->sidx]) {
		dst = (void *)&eq->desc[0];
		write_gl_to_txd(txq, m0, &dst, 0);
	} else
		write_gl_to_txd(txq, m0, &dst, eq->sidx - ndesc < eq->pidx);
	txq->sgl_wrs++;
	txq->txpkt_wrs++;

	txsd = &txq->sdesc[eq->pidx];
	txsd->m = m0;
	txsd->desc_used = ndesc;

	return (ndesc);
}

/*
 * Write a raw WR to the hardware descriptors, update the software
 * descriptor, and advance the pidx.  It is guaranteed that enough
 * descriptors are available.
 *
 * The return value is the # of hardware descriptors used.
 */
static u_int
write_raw_wr(struct sge_txq *txq, void *wr, struct mbuf *m0, u_int available)
{
	struct sge_eq *eq = &txq->eq;
	struct tx_sdesc *txsd;
	struct mbuf *m;
	caddr_t dst;
	int len16, ndesc;

	len16 = mbuf_len16(m0);
	ndesc = tx_len16_to_desc(len16);
	MPASS(ndesc <= available);

	dst = wr;
	for (m = m0; m != NULL; m = m->m_next)
		copy_to_txd(eq, mtod(m, caddr_t), &dst, m->m_len);

	txq->raw_wrs++;

	txsd = &txq->sdesc[eq->pidx];
	txsd->m = m0;
	txsd->desc_used = ndesc;

	return (ndesc);
}

/*
 * Write a txpkt WR for this packet to the hardware descriptors, update the
 * software descriptor, and advance the pidx.  It is guaranteed that enough
 * descriptors are available.
 *
 * The return value is the # of hardware descriptors used.
 */
static u_int
write_txpkt_wr(struct adapter *sc, struct sge_txq *txq, struct mbuf *m0,
    u_int available)
{
	struct sge_eq *eq;
	struct fw_eth_tx_pkt_wr *wr;
	struct tx_sdesc *txsd;
	struct cpl_tx_pkt_core *cpl;
	uint32_t ctrl;	/* used in many unrelated places */
	uint64_t ctrl1;
	int len16, ndesc, pktlen, nsegs;
	caddr_t dst;

	TXQ_LOCK_ASSERT_OWNED(txq);
	M_ASSERTPKTHDR(m0);

	len16 = mbuf_len16(m0);
	nsegs = mbuf_nsegs(m0);
	pktlen = m0->m_pkthdr.len;
	ctrl = sizeof(struct cpl_tx_pkt_core);
	if (needs_tso(m0)) {
		if (needs_vxlan_tso(m0))
			ctrl += sizeof(struct cpl_tx_tnl_lso);
		else
			ctrl += sizeof(struct cpl_tx_pkt_lso_core);
	} else if (!(mbuf_cflags(m0) & MC_NOMAP) && pktlen <= imm_payload(2) &&
	    available >= 2) {
		/* Immediate data.  Recalculate len16 and set nsegs to 0. */
		ctrl += pktlen;
		len16 = howmany(sizeof(struct fw_eth_tx_pkt_wr) +
		    sizeof(struct cpl_tx_pkt_core) + pktlen, 16);
		nsegs = 0;
	}
	ndesc = tx_len16_to_desc(len16);
	MPASS(ndesc <= available);

	/* Firmware work request header */
	eq = &txq->eq;
	wr = (void *)&eq->desc[eq->pidx];
	wr->op_immdlen = htobe32(V_FW_WR_OP(FW_ETH_TX_PKT_WR) |
	    V_FW_ETH_TX_PKT_WR_IMMDLEN(ctrl));

	ctrl = V_FW_WR_LEN16(len16);
	wr->equiq_to_len16 = htobe32(ctrl);
	wr->r3 = 0;

	if (needs_tso(m0)) {
		if (needs_vxlan_tso(m0)) {
			cpl = write_tnl_lso_cpl(wr + 1, m0);
			txq->vxlan_tso_wrs++;
		} else {
			cpl = write_lso_cpl(wr + 1, m0);
			txq->tso_wrs++;
		}
	} else
		cpl = (void *)(wr + 1);

	/* Checksum offload */
	ctrl1 = csum_to_ctrl(sc, m0);
	if (ctrl1 != (F_TXPKT_IPCSUM_DIS | F_TXPKT_L4CSUM_DIS)) {
		/* some hardware assistance provided */
		if (needs_vxlan_csum(m0))
			txq->vxlan_txcsum++;
		else
			txq->txcsum++;
	}

	/* VLAN tag insertion */
	if (needs_vlan_insertion(m0)) {
		ctrl1 |= F_TXPKT_VLAN_VLD |
		    V_TXPKT_VLAN(m0->m_pkthdr.ether_vtag);
		txq->vlan_insertion++;
	}

	/* CPL header */
	cpl->ctrl0 = txq->cpl_ctrl0;
	cpl->pack = 0;
	cpl->len = htobe16(pktlen);
	cpl->ctrl1 = htobe64(ctrl1);

	/* SGL */
	dst = (void *)(cpl + 1);
	if (__predict_false((uintptr_t)dst == (uintptr_t)&eq->desc[eq->sidx]))
		dst = (caddr_t)&eq->desc[0];
	if (nsegs > 0) {

		write_gl_to_txd(txq, m0, &dst, eq->sidx - ndesc < eq->pidx);
		txq->sgl_wrs++;
	} else {
		struct mbuf *m;

		for (m = m0; m != NULL; m = m->m_next) {
			copy_to_txd(eq, mtod(m, caddr_t), &dst, m->m_len);
#ifdef INVARIANTS
			pktlen -= m->m_len;
#endif
		}
#ifdef INVARIANTS
		KASSERT(pktlen == 0, ("%s: %d bytes left.", __func__, pktlen));
#endif
		txq->imm_wrs++;
	}

	txq->txpkt_wrs++;

	txsd = &txq->sdesc[eq->pidx];
	txsd->m = m0;
	txsd->desc_used = ndesc;

	return (ndesc);
}

static inline bool
cmp_l2hdr(struct txpkts *txp, struct mbuf *m)
{
	int len;

	MPASS(txp->npkt > 0);
	MPASS(m->m_len >= VM_TX_L2HDR_LEN);

	if (txp->ethtype == be16toh(ETHERTYPE_VLAN))
		len = VM_TX_L2HDR_LEN;
	else
		len = sizeof(struct ether_header);

	return (memcmp(m->m_data, &txp->ethmacdst[0], len) != 0);
}

static inline void
save_l2hdr(struct txpkts *txp, struct mbuf *m)
{
	MPASS(m->m_len >= VM_TX_L2HDR_LEN);

	memcpy(&txp->ethmacdst[0], mtod(m, const void *), VM_TX_L2HDR_LEN);
}

static int
add_to_txpkts_vf(struct adapter *sc, struct sge_txq *txq, struct mbuf *m,
    int avail, bool *send)
{
	struct txpkts *txp = &txq->txp;

	/* Cannot have TSO and coalesce at the same time. */
	if (cannot_use_txpkts(m)) {
cannot_coalesce:
		*send = txp->npkt > 0;
		return (EINVAL);
	}

	/* VF allows coalescing of type 1 (1 GL) only */
	if (mbuf_nsegs(m) > 1)
		goto cannot_coalesce;

	*send = false;
	if (txp->npkt > 0) {
		MPASS(tx_len16_to_desc(txp->len16) <= avail);
		MPASS(txp->npkt < txp->max_npkt);
		MPASS(txp->wr_type == 1);	/* VF supports type 1 only */

		if (tx_len16_to_desc(txp->len16 + txpkts1_len16()) > avail) {
retry_after_send:
			*send = true;
			return (EAGAIN);
		}
		if (m->m_pkthdr.len + txp->plen > 65535)
			goto retry_after_send;
		if (cmp_l2hdr(txp, m))
			goto retry_after_send;

		txp->len16 += txpkts1_len16();
		txp->plen += m->m_pkthdr.len;
		txp->mb[txp->npkt++] = m;
		if (txp->npkt == txp->max_npkt)
			*send = true;
	} else {
		txp->len16 = howmany(sizeof(struct fw_eth_tx_pkts_vm_wr), 16) +
		    txpkts1_len16();
		if (tx_len16_to_desc(txp->len16) > avail)
			goto cannot_coalesce;
		txp->npkt = 1;
		txp->wr_type = 1;
		txp->plen = m->m_pkthdr.len;
		txp->mb[0] = m;
		save_l2hdr(txp, m);
	}
	return (0);
}

static int
add_to_txpkts_pf(struct adapter *sc, struct sge_txq *txq, struct mbuf *m,
    int avail, bool *send)
{
	struct txpkts *txp = &txq->txp;
	int nsegs;

	MPASS(!(sc->flags & IS_VF));

	/* Cannot have TSO and coalesce at the same time. */
	if (cannot_use_txpkts(m)) {
cannot_coalesce:
		*send = txp->npkt > 0;
		return (EINVAL);
	}

	*send = false;
	nsegs = mbuf_nsegs(m);
	if (txp->npkt == 0) {
		if (m->m_pkthdr.len > 65535)
			goto cannot_coalesce;
		if (nsegs > 1) {
			txp->wr_type = 0;
			txp->len16 =
			    howmany(sizeof(struct fw_eth_tx_pkts_wr), 16) +
			    txpkts0_len16(nsegs);
		} else {
			txp->wr_type = 1;
			txp->len16 =
			    howmany(sizeof(struct fw_eth_tx_pkts_wr), 16) +
			    txpkts1_len16();
		}
		if (tx_len16_to_desc(txp->len16) > avail)
			goto cannot_coalesce;
		txp->npkt = 1;
		txp->plen = m->m_pkthdr.len;
		txp->mb[0] = m;
	} else {
		MPASS(tx_len16_to_desc(txp->len16) <= avail);
		MPASS(txp->npkt < txp->max_npkt);

		if (m->m_pkthdr.len + txp->plen > 65535) {
retry_after_send:
			*send = true;
			return (EAGAIN);
		}

		MPASS(txp->wr_type == 0 || txp->wr_type == 1);
		if (txp->wr_type == 0) {
			if (tx_len16_to_desc(txp->len16 +
			    txpkts0_len16(nsegs)) > min(avail, SGE_MAX_WR_NDESC))
				goto retry_after_send;
			txp->len16 += txpkts0_len16(nsegs);
		} else {
			if (nsegs != 1)
				goto retry_after_send;
			if (tx_len16_to_desc(txp->len16 + txpkts1_len16()) >
			    avail)
				goto retry_after_send;
			txp->len16 += txpkts1_len16();
		}

		txp->plen += m->m_pkthdr.len;
		txp->mb[txp->npkt++] = m;
		if (txp->npkt == txp->max_npkt)
			*send = true;
	}
	return (0);
}

/*
 * Write a txpkts WR for the packets in txp to the hardware descriptors, update
 * the software descriptor, and advance the pidx.  It is guaranteed that enough
 * descriptors are available.
 *
 * The return value is the # of hardware descriptors used.
 */
static u_int
write_txpkts_wr(struct adapter *sc, struct sge_txq *txq)
{
	const struct txpkts *txp = &txq->txp;
	struct sge_eq *eq = &txq->eq;
	struct fw_eth_tx_pkts_wr *wr;
	struct tx_sdesc *txsd;
	struct cpl_tx_pkt_core *cpl;
	uint64_t ctrl1;
	int ndesc, i, checkwrap;
	struct mbuf *m, *last;
	void *flitp;

	TXQ_LOCK_ASSERT_OWNED(txq);
	MPASS(txp->npkt > 0);
	MPASS(txp->len16 <= howmany(SGE_MAX_WR_LEN, 16));

	wr = (void *)&eq->desc[eq->pidx];
	wr->op_pkd = htobe32(V_FW_WR_OP(FW_ETH_TX_PKTS_WR));
	wr->equiq_to_len16 = htobe32(V_FW_WR_LEN16(txp->len16));
	wr->plen = htobe16(txp->plen);
	wr->npkt = txp->npkt;
	wr->r3 = 0;
	wr->type = txp->wr_type;
	flitp = wr + 1;

	/*
	 * At this point we are 16B into a hardware descriptor.  If checkwrap is
	 * set then we know the WR is going to wrap around somewhere.  We'll
	 * check for that at appropriate points.
	 */
	ndesc = tx_len16_to_desc(txp->len16);
	last = NULL;
	checkwrap = eq->sidx - ndesc < eq->pidx;
	for (i = 0; i < txp->npkt; i++) {
		m = txp->mb[i];
		if (txp->wr_type == 0) {
			struct ulp_txpkt *ulpmc;
			struct ulptx_idata *ulpsc;

			/* ULP master command */
			ulpmc = flitp;
			ulpmc->cmd_dest = htobe32(V_ULPTX_CMD(ULP_TX_PKT) |
			    V_ULP_TXPKT_DEST(0) | V_ULP_TXPKT_FID(eq->iqid));
			ulpmc->len = htobe32(txpkts0_len16(mbuf_nsegs(m)));

			/* ULP subcommand */
			ulpsc = (void *)(ulpmc + 1);
			ulpsc->cmd_more = htobe32(V_ULPTX_CMD(ULP_TX_SC_IMM) |
			    F_ULP_TX_SC_MORE);
			ulpsc->len = htobe32(sizeof(struct cpl_tx_pkt_core));

			cpl = (void *)(ulpsc + 1);
			if (checkwrap &&
			    (uintptr_t)cpl == (uintptr_t)&eq->desc[eq->sidx])
				cpl = (void *)&eq->desc[0];
		} else {
			cpl = flitp;
		}

		/* Checksum offload */
		ctrl1 = csum_to_ctrl(sc, m);
		if (ctrl1 != (F_TXPKT_IPCSUM_DIS | F_TXPKT_L4CSUM_DIS)) {
			/* some hardware assistance provided */
			if (needs_vxlan_csum(m))
				txq->vxlan_txcsum++;
			else
				txq->txcsum++;
		}

		/* VLAN tag insertion */
		if (needs_vlan_insertion(m)) {
			ctrl1 |= F_TXPKT_VLAN_VLD |
			    V_TXPKT_VLAN(m->m_pkthdr.ether_vtag);
			txq->vlan_insertion++;
		}

		/* CPL header */
		cpl->ctrl0 = txq->cpl_ctrl0;
		cpl->pack = 0;
		cpl->len = htobe16(m->m_pkthdr.len);
		cpl->ctrl1 = htobe64(ctrl1);

		flitp = cpl + 1;
		if (checkwrap &&
		    (uintptr_t)flitp == (uintptr_t)&eq->desc[eq->sidx])
			flitp = (void *)&eq->desc[0];

		write_gl_to_txd(txq, m, (caddr_t *)(&flitp), checkwrap);

		if (last != NULL)
			last->m_nextpkt = m;
		last = m;
	}

	txq->sgl_wrs++;
	if (txp->wr_type == 0) {
		txq->txpkts0_pkts += txp->npkt;
		txq->txpkts0_wrs++;
	} else {
		txq->txpkts1_pkts += txp->npkt;
		txq->txpkts1_wrs++;
	}

	txsd = &txq->sdesc[eq->pidx];
	txsd->m = txp->mb[0];
	txsd->desc_used = ndesc;

	return (ndesc);
}

static u_int
write_txpkts_vm_wr(struct adapter *sc, struct sge_txq *txq)
{
	const struct txpkts *txp = &txq->txp;
	struct sge_eq *eq = &txq->eq;
	struct fw_eth_tx_pkts_vm_wr *wr;
	struct tx_sdesc *txsd;
	struct cpl_tx_pkt_core *cpl;
	uint64_t ctrl1;
	int ndesc, i;
	struct mbuf *m, *last;
	void *flitp;

	TXQ_LOCK_ASSERT_OWNED(txq);
	MPASS(txp->npkt > 0);
	MPASS(txp->wr_type == 1);	/* VF supports type 1 only */
	MPASS(txp->mb[0] != NULL);
	MPASS(txp->len16 <= howmany(SGE_MAX_WR_LEN, 16));

	wr = (void *)&eq->desc[eq->pidx];
	wr->op_pkd = htobe32(V_FW_WR_OP(FW_ETH_TX_PKTS_VM_WR));
	wr->equiq_to_len16 = htobe32(V_FW_WR_LEN16(txp->len16));
	wr->r3 = 0;
	wr->plen = htobe16(txp->plen);
	wr->npkt = txp->npkt;
	wr->r4 = 0;
	memcpy(&wr->ethmacdst[0], &txp->ethmacdst[0], 16);
	flitp = wr + 1;

	/*
	 * At this point we are 32B into a hardware descriptor.  Each mbuf in
	 * the WR will take 32B so we check for the end of the descriptor ring
	 * before writing odd mbufs (mb[1], 3, 5, ..)
	 */
	ndesc = tx_len16_to_desc(txp->len16);
	last = NULL;
	for (i = 0; i < txp->npkt; i++) {
		m = txp->mb[i];
		if (i & 1 && (uintptr_t)flitp == (uintptr_t)&eq->desc[eq->sidx])
			flitp = &eq->desc[0];
		cpl = flitp;

		/* Checksum offload */
		ctrl1 = csum_to_ctrl(sc, m);
		if (ctrl1 != (F_TXPKT_IPCSUM_DIS | F_TXPKT_L4CSUM_DIS))
			txq->txcsum++;	/* some hardware assistance provided */

		/* VLAN tag insertion */
		if (needs_vlan_insertion(m)) {
			ctrl1 |= F_TXPKT_VLAN_VLD |
			    V_TXPKT_VLAN(m->m_pkthdr.ether_vtag);
			txq->vlan_insertion++;
		}

		/* CPL header */
		cpl->ctrl0 = txq->cpl_ctrl0;
		cpl->pack = 0;
		cpl->len = htobe16(m->m_pkthdr.len);
		cpl->ctrl1 = htobe64(ctrl1);

		flitp = cpl + 1;
		MPASS(mbuf_nsegs(m) == 1);
		write_gl_to_txd(txq, m, (caddr_t *)(&flitp), 0);

		if (last != NULL)
			last->m_nextpkt = m;
		last = m;
	}

	txq->sgl_wrs++;
	txq->txpkts1_pkts += txp->npkt;
	txq->txpkts1_wrs++;

	txsd = &txq->sdesc[eq->pidx];
	txsd->m = txp->mb[0];
	txsd->desc_used = ndesc;

	return (ndesc);
}

/*
 * If the SGL ends on an address that is not 16 byte aligned, this function will
 * add a 0 filled flit at the end.
 */
static void
write_gl_to_txd(struct sge_txq *txq, struct mbuf *m, caddr_t *to, int checkwrap)
{
	struct sge_eq *eq = &txq->eq;
	struct sglist *gl = txq->gl;
	struct sglist_seg *seg;
	__be64 *flitp, *wrap;
	struct ulptx_sgl *usgl;
	int i, nflits, nsegs;

	KASSERT(((uintptr_t)(*to) & 0xf) == 0,
	    ("%s: SGL must start at a 16 byte boundary: %p", __func__, *to));
	MPASS((uintptr_t)(*to) >= (uintptr_t)&eq->desc[0]);
	MPASS((uintptr_t)(*to) < (uintptr_t)&eq->desc[eq->sidx]);

	get_pkt_gl(m, gl);
	nsegs = gl->sg_nseg;
	MPASS(nsegs > 0);

	nflits = (3 * (nsegs - 1)) / 2 + ((nsegs - 1) & 1) + 2;
	flitp = (__be64 *)(*to);
	wrap = (__be64 *)(&eq->desc[eq->sidx]);
	seg = &gl->sg_segs[0];
	usgl = (void *)flitp;

	/*
	 * We start at a 16 byte boundary somewhere inside the tx descriptor
	 * ring, so we're at least 16 bytes away from the status page.  There is
	 * no chance of a wrap around in the middle of usgl (which is 16 bytes).
	 */

	usgl->cmd_nsge = htobe32(V_ULPTX_CMD(ULP_TX_SC_DSGL) |
	    V_ULPTX_NSGE(nsegs));
	usgl->len0 = htobe32(seg->ss_len);
	usgl->addr0 = htobe64(seg->ss_paddr);
	seg++;

	if (checkwrap == 0 || (uintptr_t)(flitp + nflits) <= (uintptr_t)wrap) {

		/* Won't wrap around at all */

		for (i = 0; i < nsegs - 1; i++, seg++) {
			usgl->sge[i / 2].len[i & 1] = htobe32(seg->ss_len);
			usgl->sge[i / 2].addr[i & 1] = htobe64(seg->ss_paddr);
		}
		if (i & 1)
			usgl->sge[i / 2].len[1] = htobe32(0);
		flitp += nflits;
	} else {

		/* Will wrap somewhere in the rest of the SGL */

		/* 2 flits already written, write the rest flit by flit */
		flitp = (void *)(usgl + 1);
		for (i = 0; i < nflits - 2; i++) {
			if (flitp == wrap)
				flitp = (void *)eq->desc;
			*flitp++ = get_flit(seg, nsegs - 1, i);
		}
	}

	if (nflits & 1) {
		MPASS(((uintptr_t)flitp) & 0xf);
		*flitp++ = 0;
	}

	MPASS((((uintptr_t)flitp) & 0xf) == 0);
	if (__predict_false(flitp == wrap))
		*to = (void *)eq->desc;
	else
		*to = (void *)flitp;
}

static inline void
copy_to_txd(struct sge_eq *eq, caddr_t from, caddr_t *to, int len)
{

	MPASS((uintptr_t)(*to) >= (uintptr_t)&eq->desc[0]);
	MPASS((uintptr_t)(*to) < (uintptr_t)&eq->desc[eq->sidx]);

	if (__predict_true((uintptr_t)(*to) + len <=
	    (uintptr_t)&eq->desc[eq->sidx])) {
		bcopy(from, *to, len);
		(*to) += len;
	} else {
		int portion = (uintptr_t)&eq->desc[eq->sidx] - (uintptr_t)(*to);

		bcopy(from, *to, portion);
		from += portion;
		portion = len - portion;	/* remaining */
		bcopy(from, (void *)eq->desc, portion);
		(*to) = (caddr_t)eq->desc + portion;
	}
}

static inline void
ring_eq_db(struct adapter *sc, struct sge_eq *eq, u_int n)
{
	u_int db;

	MPASS(n > 0);

	db = eq->doorbells;
	if (n > 1)
		clrbit(&db, DOORBELL_WCWR);
	wmb();

	switch (ffs(db) - 1) {
	case DOORBELL_UDB:
		*eq->udb = htole32(V_QID(eq->udb_qid) | V_PIDX(n));
		break;

	case DOORBELL_WCWR: {
		volatile uint64_t *dst, *src;
		int i;

		/*
		 * Queues whose 128B doorbell segment fits in the page do not
		 * use relative qid (udb_qid is always 0).  Only queues with
		 * doorbell segments can do WCWR.
		 */
		KASSERT(eq->udb_qid == 0 && n == 1,
		    ("%s: inappropriate doorbell (0x%x, %d, %d) for eq %p",
		    __func__, eq->doorbells, n, eq->dbidx, eq));

		dst = (volatile void *)((uintptr_t)eq->udb + UDBS_WR_OFFSET -
		    UDBS_DB_OFFSET);
		i = eq->dbidx;
		src = (void *)&eq->desc[i];
		while (src != (void *)&eq->desc[i + 1])
			*dst++ = *src++;
		wmb();
		break;
	}

	case DOORBELL_UDBWC:
		*eq->udb = htole32(V_QID(eq->udb_qid) | V_PIDX(n));
		wmb();
		break;

	case DOORBELL_KDB:
		t4_write_reg(sc, sc->sge_kdoorbell_reg,
		    V_QID(eq->cntxt_id) | V_PIDX(n));
		break;
	}

	IDXINCR(eq->dbidx, n, eq->sidx);
}

static inline u_int
reclaimable_tx_desc(struct sge_eq *eq)
{
	uint16_t hw_cidx;

	hw_cidx = read_hw_cidx(eq);
	return (IDXDIFF(hw_cidx, eq->cidx, eq->sidx));
}

static inline u_int
total_available_tx_desc(struct sge_eq *eq)
{
	uint16_t hw_cidx, pidx;

	hw_cidx = read_hw_cidx(eq);
	pidx = eq->pidx;

	if (pidx == hw_cidx)
		return (eq->sidx - 1);
	else
		return (IDXDIFF(hw_cidx, pidx, eq->sidx) - 1);
}

static inline uint16_t
read_hw_cidx(struct sge_eq *eq)
{
	struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
	uint16_t cidx = spg->cidx;	/* stable snapshot */

	return (be16toh(cidx));
}

/*
 * Reclaim 'n' descriptors approximately.
 */
static u_int
reclaim_tx_descs(struct sge_txq *txq, u_int n)
{
	struct tx_sdesc *txsd;
	struct sge_eq *eq = &txq->eq;
	u_int can_reclaim, reclaimed;

	TXQ_LOCK_ASSERT_OWNED(txq);
	MPASS(n > 0);

	reclaimed = 0;
	can_reclaim = reclaimable_tx_desc(eq);
	while (can_reclaim && reclaimed < n) {
		int ndesc;
		struct mbuf *m, *nextpkt;

		txsd = &txq->sdesc[eq->cidx];
		ndesc = txsd->desc_used;

		/* Firmware doesn't return "partial" credits. */
		KASSERT(can_reclaim >= ndesc,
		    ("%s: unexpected number of credits: %d, %d",
		    __func__, can_reclaim, ndesc));
		KASSERT(ndesc != 0,
		    ("%s: descriptor with no credits: cidx %d",
		    __func__, eq->cidx));

		for (m = txsd->m; m != NULL; m = nextpkt) {
			nextpkt = m->m_nextpkt;
			m->m_nextpkt = NULL;
			m_freem(m);
		}
		reclaimed += ndesc;
		can_reclaim -= ndesc;
		IDXINCR(eq->cidx, ndesc, eq->sidx);
	}

	return (reclaimed);
}

static void
tx_reclaim(void *arg, int n)
{
	struct sge_txq *txq = arg;
	struct sge_eq *eq = &txq->eq;

	do {
		if (TXQ_TRYLOCK(txq) == 0)
			break;
		n = reclaim_tx_descs(txq, 32);
		if (eq->cidx == eq->pidx)
			eq->equeqidx = eq->pidx;
		TXQ_UNLOCK(txq);
	} while (n > 0);
}

static __be64
get_flit(struct sglist_seg *segs, int nsegs, int idx)
{
	int i = (idx / 3) * 2;

	switch (idx % 3) {
	case 0: {
		uint64_t rc;

		rc = (uint64_t)segs[i].ss_len << 32;
		if (i + 1 < nsegs)
			rc |= (uint64_t)(segs[i + 1].ss_len);

		return (htobe64(rc));
	}
	case 1:
		return (htobe64(segs[i].ss_paddr));
	case 2:
		return (htobe64(segs[i + 1].ss_paddr));
	}

	return (0);
}

static int
find_refill_source(struct adapter *sc, int maxp, bool packing)
{
	int i, zidx = -1;
	struct rx_buf_info *rxb = &sc->sge.rx_buf_info[0];

	if (packing) {
		for (i = 0; i < SW_ZONE_SIZES; i++, rxb++) {
			if (rxb->hwidx2 == -1)
				continue;
			if (rxb->size1 < PAGE_SIZE &&
			    rxb->size1 < largest_rx_cluster)
				continue;
			if (rxb->size1 > largest_rx_cluster)
				break;
			MPASS(rxb->size1 - rxb->size2 >= CL_METADATA_SIZE);
			if (rxb->size2 >= maxp)
				return (i);
			zidx = i;
		}
	} else {
		for (i = 0; i < SW_ZONE_SIZES; i++, rxb++) {
			if (rxb->hwidx1 == -1)
				continue;
			if (rxb->size1 > largest_rx_cluster)
				break;
			if (rxb->size1 >= maxp)
				return (i);
			zidx = i;
		}
	}

	return (zidx);
}

static void
add_fl_to_sfl(struct adapter *sc, struct sge_fl *fl)
{
	mtx_lock(&sc->sfl_lock);
	FL_LOCK(fl);
	if ((fl->flags & FL_DOOMED) == 0) {
		fl->flags |= FL_STARVING;
		TAILQ_INSERT_TAIL(&sc->sfl, fl, link);
		callout_reset(&sc->sfl_callout, hz / 5, refill_sfl, sc);
	}
	FL_UNLOCK(fl);
	mtx_unlock(&sc->sfl_lock);
}

static void
handle_wrq_egr_update(struct adapter *sc, struct sge_eq *eq)
{
	struct sge_wrq *wrq = (void *)eq;

	atomic_readandclear_int(&eq->equiq);
	taskqueue_enqueue(sc->tq[eq->tx_chan], &wrq->wrq_tx_task);
}

static void
handle_eth_egr_update(struct adapter *sc, struct sge_eq *eq)
{
	struct sge_txq *txq = (void *)eq;

	MPASS((eq->flags & EQ_TYPEMASK) == EQ_ETH);

	atomic_readandclear_int(&eq->equiq);
	if (mp_ring_is_idle(txq->r))
		taskqueue_enqueue(sc->tq[eq->tx_chan], &txq->tx_reclaim_task);
	else
		mp_ring_check_drainage(txq->r, 64);
}

static int
handle_sge_egr_update(struct sge_iq *iq, const struct rss_header *rss,
    struct mbuf *m)
{
	const struct cpl_sge_egr_update *cpl = (const void *)(rss + 1);
	unsigned int qid = G_EGR_QID(ntohl(cpl->opcode_qid));
	struct adapter *sc = iq->adapter;
	struct sge *s = &sc->sge;
	struct sge_eq *eq;
	static void (*h[])(struct adapter *, struct sge_eq *) = {NULL,
		&handle_wrq_egr_update, &handle_eth_egr_update,
		&handle_wrq_egr_update};

	KASSERT(m == NULL, ("%s: payload with opcode %02x", __func__,
	    rss->opcode));

	eq = s->eqmap[qid - s->eq_start - s->eq_base];
	(*h[eq->flags & EQ_TYPEMASK])(sc, eq);

	return (0);
}

/* handle_fw_msg works for both fw4_msg and fw6_msg because this is valid */
CTASSERT(offsetof(struct cpl_fw4_msg, data) == \
    offsetof(struct cpl_fw6_msg, data));

static int
handle_fw_msg(struct sge_iq *iq, const struct rss_header *rss, struct mbuf *m)
{
	struct adapter *sc = iq->adapter;
	const struct cpl_fw6_msg *cpl = (const void *)(rss + 1);

	KASSERT(m == NULL, ("%s: payload with opcode %02x", __func__,
	    rss->opcode));

	if (cpl->type == FW_TYPE_RSSCPL || cpl->type == FW6_TYPE_RSSCPL) {
		const struct rss_header *rss2;

		rss2 = (const struct rss_header *)&cpl->data[0];
		return (t4_cpl_handler[rss2->opcode](iq, rss2, m));
	}

	return (t4_fw_msg_handler[cpl->type](sc, &cpl->data[0]));
}

/**
 *	t4_handle_wrerr_rpl - process a FW work request error message
 *	@adap: the adapter
 *	@rpl: start of the FW message
 */
static int
t4_handle_wrerr_rpl(struct adapter *adap, const __be64 *rpl)
{
	u8 opcode = *(const u8 *)rpl;
	const struct fw_error_cmd *e = (const void *)rpl;
	unsigned int i;

	if (opcode != FW_ERROR_CMD) {
		log(LOG_ERR,
		    "%s: Received WRERR_RPL message with opcode %#x\n",
		    device_get_nameunit(adap->dev), opcode);
		return (EINVAL);
	}
	log(LOG_ERR, "%s: FW_ERROR (%s) ", device_get_nameunit(adap->dev),
	    G_FW_ERROR_CMD_FATAL(be32toh(e->op_to_type)) ? "fatal" :
	    "non-fatal");
	switch (G_FW_ERROR_CMD_TYPE(be32toh(e->op_to_type))) {
	case FW_ERROR_TYPE_EXCEPTION:
		log(LOG_ERR, "exception info:\n");
		for (i = 0; i < nitems(e->u.exception.info); i++)
			log(LOG_ERR, "%s%08x", i == 0 ? "\t" : " ",
			    be32toh(e->u.exception.info[i]));
		log(LOG_ERR, "\n");
		break;
	case FW_ERROR_TYPE_HWMODULE:
		log(LOG_ERR, "HW module regaddr %08x regval %08x\n",
		    be32toh(e->u.hwmodule.regaddr),
		    be32toh(e->u.hwmodule.regval));
		break;
	case FW_ERROR_TYPE_WR:
		log(LOG_ERR, "WR cidx %d PF %d VF %d eqid %d hdr:\n",
		    be16toh(e->u.wr.cidx),
		    G_FW_ERROR_CMD_PFN(be16toh(e->u.wr.pfn_vfn)),
		    G_FW_ERROR_CMD_VFN(be16toh(e->u.wr.pfn_vfn)),
		    be32toh(e->u.wr.eqid));
		for (i = 0; i < nitems(e->u.wr.wrhdr); i++)
			log(LOG_ERR, "%s%02x", i == 0 ? "\t" : " ",
			    e->u.wr.wrhdr[i]);
		log(LOG_ERR, "\n");
		break;
	case FW_ERROR_TYPE_ACL:
		log(LOG_ERR, "ACL cidx %d PF %d VF %d eqid %d %s",
		    be16toh(e->u.acl.cidx),
		    G_FW_ERROR_CMD_PFN(be16toh(e->u.acl.pfn_vfn)),
		    G_FW_ERROR_CMD_VFN(be16toh(e->u.acl.pfn_vfn)),
		    be32toh(e->u.acl.eqid),
		    G_FW_ERROR_CMD_MV(be16toh(e->u.acl.mv_pkd)) ? "vlanid" :
		    "MAC");
		for (i = 0; i < nitems(e->u.acl.val); i++)
			log(LOG_ERR, " %02x", e->u.acl.val[i]);
		log(LOG_ERR, "\n");
		break;
	default:
		log(LOG_ERR, "type %#x\n",
		    G_FW_ERROR_CMD_TYPE(be32toh(e->op_to_type)));
		return (EINVAL);
	}
	return (0);
}

static int
sysctl_uint16(SYSCTL_HANDLER_ARGS)
{
	uint16_t *id = arg1;
	int i = *id;

	return sysctl_handle_int(oidp, &i, 0, req);
}

static inline bool
bufidx_used(struct adapter *sc, int idx)
{
	struct rx_buf_info *rxb = &sc->sge.rx_buf_info[0];
	int i;

	for (i = 0; i < SW_ZONE_SIZES; i++, rxb++) {
		if (rxb->size1 > largest_rx_cluster)
			continue;
		if (rxb->hwidx1 == idx || rxb->hwidx2 == idx)
			return (true);
	}

	return (false);
}

static int
sysctl_bufsizes(SYSCTL_HANDLER_ARGS)
{
	struct adapter *sc = arg1;
	struct sge_params *sp = &sc->params.sge;
	int i, rc;
	struct sbuf sb;
	char c;

	sbuf_new(&sb, NULL, 128, SBUF_AUTOEXTEND);
	for (i = 0; i < SGE_FLBUF_SIZES; i++) {
		if (bufidx_used(sc, i))
			c = '*';
		else
			c = '\0';

		sbuf_printf(&sb, "%u%c ", sp->sge_fl_buffer_size[i], c);
	}
	sbuf_trim(&sb);
	sbuf_finish(&sb);
	rc = sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);
	sbuf_delete(&sb);
	return (rc);
}

#ifdef RATELIMIT
/*
 * len16 for a txpkt WR with a GL.  Includes the firmware work request header.
 */
static inline u_int
txpkt_eo_len16(u_int nsegs, u_int immhdrs, u_int tso)
{
	u_int n;

	MPASS(immhdrs > 0);

	n = roundup2(sizeof(struct fw_eth_tx_eo_wr) +
	    sizeof(struct cpl_tx_pkt_core) + immhdrs, 16);
	if (__predict_false(nsegs == 0))
		goto done;

	nsegs--; /* first segment is part of ulptx_sgl */
	n += sizeof(struct ulptx_sgl) + 8 * ((3 * nsegs) / 2 + (nsegs & 1));
	if (tso)
		n += sizeof(struct cpl_tx_pkt_lso_core);

done:
	return (howmany(n, 16));
}

#define ETID_FLOWC_NPARAMS 6
#define ETID_FLOWC_LEN (roundup2((sizeof(struct fw_flowc_wr) + \
    ETID_FLOWC_NPARAMS * sizeof(struct fw_flowc_mnemval)), 16))
#define ETID_FLOWC_LEN16 (howmany(ETID_FLOWC_LEN, 16))

static int
send_etid_flowc_wr(struct cxgbe_rate_tag *cst, struct port_info *pi,
    struct vi_info *vi)
{
	struct wrq_cookie cookie;
	u_int pfvf = pi->adapter->pf << S_FW_VIID_PFN;
	struct fw_flowc_wr *flowc;

	mtx_assert(&cst->lock, MA_OWNED);
	MPASS((cst->flags & (EO_FLOWC_PENDING | EO_FLOWC_RPL_PENDING)) ==
	    EO_FLOWC_PENDING);

	flowc = start_wrq_wr(cst->eo_txq, ETID_FLOWC_LEN16, &cookie);
	if (__predict_false(flowc == NULL))
		return (ENOMEM);

	bzero(flowc, ETID_FLOWC_LEN);
	flowc->op_to_nparams = htobe32(V_FW_WR_OP(FW_FLOWC_WR) |
	    V_FW_FLOWC_WR_NPARAMS(ETID_FLOWC_NPARAMS) | V_FW_WR_COMPL(0));
	flowc->flowid_len16 = htonl(V_FW_WR_LEN16(ETID_FLOWC_LEN16) |
	    V_FW_WR_FLOWID(cst->etid));
	flowc->mnemval[0].mnemonic = FW_FLOWC_MNEM_PFNVFN;
	flowc->mnemval[0].val = htobe32(pfvf);
	flowc->mnemval[1].mnemonic = FW_FLOWC_MNEM_CH;
	flowc->mnemval[1].val = htobe32(pi->tx_chan);
	flowc->mnemval[2].mnemonic = FW_FLOWC_MNEM_PORT;
	flowc->mnemval[2].val = htobe32(pi->tx_chan);
	flowc->mnemval[3].mnemonic = FW_FLOWC_MNEM_IQID;
	flowc->mnemval[3].val = htobe32(cst->iqid);
	flowc->mnemval[4].mnemonic = FW_FLOWC_MNEM_EOSTATE;
	flowc->mnemval[4].val = htobe32(FW_FLOWC_MNEM_EOSTATE_ESTABLISHED);
	flowc->mnemval[5].mnemonic = FW_FLOWC_MNEM_SCHEDCLASS;
	flowc->mnemval[5].val = htobe32(cst->schedcl);

	commit_wrq_wr(cst->eo_txq, flowc, &cookie);

	cst->flags &= ~EO_FLOWC_PENDING;
	cst->flags |= EO_FLOWC_RPL_PENDING;
	MPASS(cst->tx_credits >= ETID_FLOWC_LEN16);	/* flowc is first WR. */
	cst->tx_credits -= ETID_FLOWC_LEN16;

	return (0);
}

#define ETID_FLUSH_LEN16 (howmany(sizeof (struct fw_flowc_wr), 16))

void
send_etid_flush_wr(struct cxgbe_rate_tag *cst)
{
	struct fw_flowc_wr *flowc;
	struct wrq_cookie cookie;

	mtx_assert(&cst->lock, MA_OWNED);

	flowc = start_wrq_wr(cst->eo_txq, ETID_FLUSH_LEN16, &cookie);
	if (__predict_false(flowc == NULL))
		CXGBE_UNIMPLEMENTED(__func__);

	bzero(flowc, ETID_FLUSH_LEN16 * 16);
	flowc->op_to_nparams = htobe32(V_FW_WR_OP(FW_FLOWC_WR) |
	    V_FW_FLOWC_WR_NPARAMS(0) | F_FW_WR_COMPL);
	flowc->flowid_len16 = htobe32(V_FW_WR_LEN16(ETID_FLUSH_LEN16) |
	    V_FW_WR_FLOWID(cst->etid));

	commit_wrq_wr(cst->eo_txq, flowc, &cookie);

	cst->flags |= EO_FLUSH_RPL_PENDING;
	MPASS(cst->tx_credits >= ETID_FLUSH_LEN16);
	cst->tx_credits -= ETID_FLUSH_LEN16;
	cst->ncompl++;
}

static void
write_ethofld_wr(struct cxgbe_rate_tag *cst, struct fw_eth_tx_eo_wr *wr,
    struct mbuf *m0, int compl)
{
	struct cpl_tx_pkt_core *cpl;
	uint64_t ctrl1;
	uint32_t ctrl;	/* used in many unrelated places */
	int len16, pktlen, nsegs, immhdrs;
	caddr_t dst;
	uintptr_t p;
	struct ulptx_sgl *usgl;
	struct sglist sg;
	struct sglist_seg segs[38];	/* XXX: find real limit.  XXX: get off the stack */

	mtx_assert(&cst->lock, MA_OWNED);
	M_ASSERTPKTHDR(m0);
	KASSERT(m0->m_pkthdr.l2hlen > 0 && m0->m_pkthdr.l3hlen > 0 &&
	    m0->m_pkthdr.l4hlen > 0,
	    ("%s: ethofld mbuf %p is missing header lengths", __func__, m0));

	len16 = mbuf_eo_len16(m0);
	nsegs = mbuf_eo_nsegs(m0);
	pktlen = m0->m_pkthdr.len;
	ctrl = sizeof(struct cpl_tx_pkt_core);
	if (needs_tso(m0))
		ctrl += sizeof(struct cpl_tx_pkt_lso_core);
	immhdrs = m0->m_pkthdr.l2hlen + m0->m_pkthdr.l3hlen + m0->m_pkthdr.l4hlen;
	ctrl += immhdrs;

	wr->op_immdlen = htobe32(V_FW_WR_OP(FW_ETH_TX_EO_WR) |
	    V_FW_ETH_TX_EO_WR_IMMDLEN(ctrl) | V_FW_WR_COMPL(!!compl));
	wr->equiq_to_len16 = htobe32(V_FW_WR_LEN16(len16) |
	    V_FW_WR_FLOWID(cst->etid));
	wr->r3 = 0;
	if (needs_outer_udp_csum(m0)) {
		wr->u.udpseg.type = FW_ETH_TX_EO_TYPE_UDPSEG;
		wr->u.udpseg.ethlen = m0->m_pkthdr.l2hlen;
		wr->u.udpseg.iplen = htobe16(m0->m_pkthdr.l3hlen);
		wr->u.udpseg.udplen = m0->m_pkthdr.l4hlen;
		wr->u.udpseg.rtplen = 0;
		wr->u.udpseg.r4 = 0;
		wr->u.udpseg.mss = htobe16(pktlen - immhdrs);
		wr->u.udpseg.schedpktsize = wr->u.udpseg.mss;
		wr->u.udpseg.plen = htobe32(pktlen - immhdrs);
		cpl = (void *)(wr + 1);
	} else {
		MPASS(needs_outer_tcp_csum(m0));
		wr->u.tcpseg.type = FW_ETH_TX_EO_TYPE_TCPSEG;
		wr->u.tcpseg.ethlen = m0->m_pkthdr.l2hlen;
		wr->u.tcpseg.iplen = htobe16(m0->m_pkthdr.l3hlen);
		wr->u.tcpseg.tcplen = m0->m_pkthdr.l4hlen;
		wr->u.tcpseg.tsclk_tsoff = mbuf_eo_tsclk_tsoff(m0);
		wr->u.tcpseg.r4 = 0;
		wr->u.tcpseg.r5 = 0;
		wr->u.tcpseg.plen = htobe32(pktlen - immhdrs);

		if (needs_tso(m0)) {
			struct cpl_tx_pkt_lso_core *lso = (void *)(wr + 1);

			wr->u.tcpseg.mss = htobe16(m0->m_pkthdr.tso_segsz);

			ctrl = V_LSO_OPCODE(CPL_TX_PKT_LSO) |
			    F_LSO_FIRST_SLICE | F_LSO_LAST_SLICE |
			    V_LSO_ETHHDR_LEN((m0->m_pkthdr.l2hlen -
				ETHER_HDR_LEN) >> 2) |
			    V_LSO_IPHDR_LEN(m0->m_pkthdr.l3hlen >> 2) |
			    V_LSO_TCPHDR_LEN(m0->m_pkthdr.l4hlen >> 2);
			if (m0->m_pkthdr.l3hlen == sizeof(struct ip6_hdr))
				ctrl |= F_LSO_IPV6;
			lso->lso_ctrl = htobe32(ctrl);
			lso->ipid_ofst = htobe16(0);
			lso->mss = htobe16(m0->m_pkthdr.tso_segsz);
			lso->seqno_offset = htobe32(0);
			lso->len = htobe32(pktlen);

			cpl = (void *)(lso + 1);
		} else {
			wr->u.tcpseg.mss = htobe16(0xffff);
			cpl = (void *)(wr + 1);
		}
	}

	/* Checksum offload must be requested for ethofld. */
	MPASS(needs_outer_l4_csum(m0));
	ctrl1 = csum_to_ctrl(cst->adapter, m0);

	/* VLAN tag insertion */
	if (needs_vlan_insertion(m0)) {
		ctrl1 |= F_TXPKT_VLAN_VLD |
		    V_TXPKT_VLAN(m0->m_pkthdr.ether_vtag);
	}

	/* CPL header */
	cpl->ctrl0 = cst->ctrl0;
	cpl->pack = 0;
	cpl->len = htobe16(pktlen);
	cpl->ctrl1 = htobe64(ctrl1);

	/* Copy Ethernet, IP & TCP/UDP hdrs as immediate data */
	p = (uintptr_t)(cpl + 1);
	m_copydata(m0, 0, immhdrs, (void *)p);

	/* SGL */
	dst = (void *)(cpl + 1);
	if (nsegs > 0) {
		int i, pad;

		/* zero-pad upto next 16Byte boundary, if not 16Byte aligned */
		p += immhdrs;
		pad = 16 - (immhdrs & 0xf);
		bzero((void *)p, pad);

		usgl = (void *)(p + pad);
		usgl->cmd_nsge = htobe32(V_ULPTX_CMD(ULP_TX_SC_DSGL) |
		    V_ULPTX_NSGE(nsegs));

		sglist_init(&sg, nitems(segs), segs);
		for (; m0 != NULL; m0 = m0->m_next) {
			if (__predict_false(m0->m_len == 0))
				continue;
			if (immhdrs >= m0->m_len) {
				immhdrs -= m0->m_len;
				continue;
			}
			if (m0->m_flags & M_EXTPG)
				sglist_append_mbuf_epg(&sg, m0,
				    mtod(m0, vm_offset_t), m0->m_len);
                        else
				sglist_append(&sg, mtod(m0, char *) + immhdrs,
				    m0->m_len - immhdrs);
			immhdrs = 0;
		}
		MPASS(sg.sg_nseg == nsegs);

		/*
		 * Zero pad last 8B in case the WR doesn't end on a 16B
		 * boundary.
		 */
		*(uint64_t *)((char *)wr + len16 * 16 - 8) = 0;

		usgl->len0 = htobe32(segs[0].ss_len);
		usgl->addr0 = htobe64(segs[0].ss_paddr);
		for (i = 0; i < nsegs - 1; i++) {
			usgl->sge[i / 2].len[i & 1] = htobe32(segs[i + 1].ss_len);
			usgl->sge[i / 2].addr[i & 1] = htobe64(segs[i + 1].ss_paddr);
		}
		if (i & 1)
			usgl->sge[i / 2].len[1] = htobe32(0);
	}

}

static void
ethofld_tx(struct cxgbe_rate_tag *cst)
{
	struct mbuf *m;
	struct wrq_cookie cookie;
	int next_credits, compl;
	struct fw_eth_tx_eo_wr *wr;

	mtx_assert(&cst->lock, MA_OWNED);

	while ((m = mbufq_first(&cst->pending_tx)) != NULL) {
		M_ASSERTPKTHDR(m);

		/* How many len16 credits do we need to send this mbuf. */
		next_credits = mbuf_eo_len16(m);
		MPASS(next_credits > 0);
		if (next_credits > cst->tx_credits) {
			/*
			 * Tx will make progress eventually because there is at
			 * least one outstanding fw4_ack that will return
			 * credits and kick the tx.
			 */
			MPASS(cst->ncompl > 0);
			return;
		}
		wr = start_wrq_wr(cst->eo_txq, next_credits, &cookie);
		if (__predict_false(wr == NULL)) {
			/* XXX: wishful thinking, not a real assertion. */
			MPASS(cst->ncompl > 0);
			return;
		}
		cst->tx_credits -= next_credits;
		cst->tx_nocompl += next_credits;
		compl = cst->ncompl == 0 || cst->tx_nocompl >= cst->tx_total / 2;
		ETHER_BPF_MTAP(cst->com.ifp, m);
		write_ethofld_wr(cst, wr, m, compl);
		commit_wrq_wr(cst->eo_txq, wr, &cookie);
		if (compl) {
			cst->ncompl++;
			cst->tx_nocompl	= 0;
		}
		(void) mbufq_dequeue(&cst->pending_tx);

		/*
		 * Drop the mbuf's reference on the tag now rather
		 * than waiting until m_freem().  This ensures that
		 * cxgbe_rate_tag_free gets called when the inp drops
		 * its reference on the tag and there are no more
		 * mbufs in the pending_tx queue and can flush any
		 * pending requests.  Otherwise if the last mbuf
		 * doesn't request a completion the etid will never be
		 * released.
		 */
		m->m_pkthdr.snd_tag = NULL;
		m->m_pkthdr.csum_flags &= ~CSUM_SND_TAG;
		m_snd_tag_rele(&cst->com);

		mbufq_enqueue(&cst->pending_fwack, m);
	}
}

int
ethofld_transmit(struct ifnet *ifp, struct mbuf *m0)
{
	struct cxgbe_rate_tag *cst;
	int rc;

	MPASS(m0->m_nextpkt == NULL);
	MPASS(m0->m_pkthdr.csum_flags & CSUM_SND_TAG);
	MPASS(m0->m_pkthdr.snd_tag != NULL);
	cst = mst_to_crt(m0->m_pkthdr.snd_tag);

	mtx_lock(&cst->lock);
	MPASS(cst->flags & EO_SND_TAG_REF);

	if (__predict_false(cst->flags & EO_FLOWC_PENDING)) {
		struct vi_info *vi = ifp->if_softc;
		struct port_info *pi = vi->pi;
		struct adapter *sc = pi->adapter;
		const uint32_t rss_mask = vi->rss_size - 1;
		uint32_t rss_hash;

		cst->eo_txq = &sc->sge.ofld_txq[vi->first_ofld_txq];
		if (M_HASHTYPE_ISHASH(m0))
			rss_hash = m0->m_pkthdr.flowid;
		else
			rss_hash = arc4random();
		/* We assume RSS hashing */
		cst->iqid = vi->rss[rss_hash & rss_mask];
		cst->eo_txq += rss_hash % vi->nofldtxq;
		rc = send_etid_flowc_wr(cst, pi, vi);
		if (rc != 0)
			goto done;
	}

	if (__predict_false(cst->plen + m0->m_pkthdr.len > eo_max_backlog)) {
		rc = ENOBUFS;
		goto done;
	}

	mbufq_enqueue(&cst->pending_tx, m0);
	cst->plen += m0->m_pkthdr.len;

	/*
	 * Hold an extra reference on the tag while generating work
	 * requests to ensure that we don't try to free the tag during
	 * ethofld_tx() in case we are sending the final mbuf after
	 * the inp was freed.
	 */
	m_snd_tag_ref(&cst->com);
	ethofld_tx(cst);
	mtx_unlock(&cst->lock);
	m_snd_tag_rele(&cst->com);
	return (0);

done:
	mtx_unlock(&cst->lock);
	if (__predict_false(rc != 0))
		m_freem(m0);
	return (rc);
}

static int
ethofld_fw4_ack(struct sge_iq *iq, const struct rss_header *rss, struct mbuf *m0)
{
	struct adapter *sc = iq->adapter;
	const struct cpl_fw4_ack *cpl = (const void *)(rss + 1);
	struct mbuf *m;
	u_int etid = G_CPL_FW4_ACK_FLOWID(be32toh(OPCODE_TID(cpl)));
	struct cxgbe_rate_tag *cst;
	uint8_t credits = cpl->credits;

	cst = lookup_etid(sc, etid);
	mtx_lock(&cst->lock);
	if (__predict_false(cst->flags & EO_FLOWC_RPL_PENDING)) {
		MPASS(credits >= ETID_FLOWC_LEN16);
		credits -= ETID_FLOWC_LEN16;
		cst->flags &= ~EO_FLOWC_RPL_PENDING;
	}

	KASSERT(cst->ncompl > 0,
	    ("%s: etid %u (%p) wasn't expecting completion.",
	    __func__, etid, cst));
	cst->ncompl--;

	while (credits > 0) {
		m = mbufq_dequeue(&cst->pending_fwack);
		if (__predict_false(m == NULL)) {
			/*
			 * The remaining credits are for the final flush that
			 * was issued when the tag was freed by the kernel.
			 */
			MPASS((cst->flags &
			    (EO_FLUSH_RPL_PENDING | EO_SND_TAG_REF)) ==
			    EO_FLUSH_RPL_PENDING);
			MPASS(credits == ETID_FLUSH_LEN16);
			MPASS(cst->tx_credits + cpl->credits == cst->tx_total);
			MPASS(cst->ncompl == 0);

			cst->flags &= ~EO_FLUSH_RPL_PENDING;
			cst->tx_credits += cpl->credits;
			cxgbe_rate_tag_free_locked(cst);
			return (0);	/* cst is gone. */
		}
		KASSERT(m != NULL,
		    ("%s: too many credits (%u, %u)", __func__, cpl->credits,
		    credits));
		KASSERT(credits >= mbuf_eo_len16(m),
		    ("%s: too few credits (%u, %u, %u)", __func__,
		    cpl->credits, credits, mbuf_eo_len16(m)));
		credits -= mbuf_eo_len16(m);
		cst->plen -= m->m_pkthdr.len;
		m_freem(m);
	}

	cst->tx_credits += cpl->credits;
	MPASS(cst->tx_credits <= cst->tx_total);

	if (cst->flags & EO_SND_TAG_REF) {
		/*
		 * As with ethofld_transmit(), hold an extra reference
		 * so that the tag is stable across ethold_tx().
		 */
		m_snd_tag_ref(&cst->com);
		m = mbufq_first(&cst->pending_tx);
		if (m != NULL && cst->tx_credits >= mbuf_eo_len16(m))
			ethofld_tx(cst);
		mtx_unlock(&cst->lock);
		m_snd_tag_rele(&cst->com);
	} else {
		/*
		 * There shouldn't be any pending packets if the tag
		 * was freed by the kernel since any pending packet
		 * should hold a reference to the tag.
		 */
		MPASS(mbufq_first(&cst->pending_tx) == NULL);
		mtx_unlock(&cst->lock);
	}

	return (0);
}
#endif