summaryrefslogtreecommitdiffstats
path: root/sys/dev/ath/if_ath_tx.c
blob: 8bacd928aeacb69829d069cf552042226355c9cf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
/*-
 * Copyright (c) 2002-2009 Sam Leffler, Errno Consulting
 * Copyright (c) 2010-2012 Adrian Chadd, Xenion Pty Ltd
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer,
 *    without modification.
 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
 *    similar to the "NO WARRANTY" disclaimer below ("Disclaimer") and any
 *    redistribution must be conditioned upon including a substantially
 *    similar Disclaimer requirement for further binary redistribution.
 *
 * NO WARRANTY
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR 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 DAMAGES.
 */

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

/*
 * Driver for the Atheros Wireless LAN controller.
 *
 * This software is derived from work of Atsushi Onoe; his contribution
 * is greatly appreciated.
 */

#include "opt_inet.h"
#include "opt_ath.h"
#include "opt_wlan.h"

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/sysctl.h>
#include <sys/mbuf.h>
#include <sys/malloc.h>
#include <sys/lock.h>
#include <sys/mutex.h>
#include <sys/kernel.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/errno.h>
#include <sys/callout.h>
#include <sys/bus.h>
#include <sys/endian.h>
#include <sys/kthread.h>
#include <sys/taskqueue.h>
#include <sys/priv.h>

#include <machine/bus.h>

#include <net/if.h>
#include <net/if_dl.h>
#include <net/if_media.h>
#include <net/if_types.h>
#include <net/if_arp.h>
#include <net/ethernet.h>
#include <net/if_llc.h>

#include <net80211/ieee80211_var.h>
#include <net80211/ieee80211_regdomain.h>
#ifdef IEEE80211_SUPPORT_SUPERG
#include <net80211/ieee80211_superg.h>
#endif
#ifdef IEEE80211_SUPPORT_TDMA
#include <net80211/ieee80211_tdma.h>
#endif
#include <net80211/ieee80211_ht.h>

#include <net/bpf.h>

#ifdef INET
#include <netinet/in.h>
#include <netinet/if_ether.h>
#endif

#include <dev/ath/if_athvar.h>
#include <dev/ath/ath_hal/ah_devid.h>		/* XXX for softled */
#include <dev/ath/ath_hal/ah_diagcodes.h>

#include <dev/ath/if_ath_debug.h>

#ifdef ATH_TX99_DIAG
#include <dev/ath/ath_tx99/ath_tx99.h>
#endif

#include <dev/ath/if_ath_misc.h>
#include <dev/ath/if_ath_tx.h>
#include <dev/ath/if_ath_tx_ht.h>

#ifdef	ATH_DEBUG_ALQ
#include <dev/ath/if_ath_alq.h>
#endif

/*
 * How many retries to perform in software
 */
#define	SWMAX_RETRIES		10

/*
 * What queue to throw the non-QoS TID traffic into
 */
#define	ATH_NONQOS_TID_AC	WME_AC_VO

#if 0
static int ath_tx_node_is_asleep(struct ath_softc *sc, struct ath_node *an);
#endif
static int ath_tx_ampdu_pending(struct ath_softc *sc, struct ath_node *an,
    int tid);
static int ath_tx_ampdu_running(struct ath_softc *sc, struct ath_node *an,
    int tid);
static ieee80211_seq ath_tx_tid_seqno_assign(struct ath_softc *sc,
    struct ieee80211_node *ni, struct ath_buf *bf, struct mbuf *m0);
static int ath_tx_action_frame_override_queue(struct ath_softc *sc,
    struct ieee80211_node *ni, struct mbuf *m0, int *tid);
static struct ath_buf *
ath_tx_retry_clone(struct ath_softc *sc, struct ath_node *an,
    struct ath_tid *tid, struct ath_buf *bf);

#ifdef	ATH_DEBUG_ALQ
void
ath_tx_alq_post(struct ath_softc *sc, struct ath_buf *bf_first)
{
	struct ath_buf *bf;
	int i, n;
	const char *ds;

	/* XXX we should skip out early if debugging isn't enabled! */
	bf = bf_first;

	while (bf != NULL) {
		/* XXX should ensure bf_nseg > 0! */
		if (bf->bf_nseg == 0)
			break;
		n = ((bf->bf_nseg - 1) / sc->sc_tx_nmaps) + 1;
		for (i = 0, ds = (const char *) bf->bf_desc;
		    i < n;
		    i++, ds += sc->sc_tx_desclen) {
			if_ath_alq_post(&sc->sc_alq,
			    ATH_ALQ_EDMA_TXDESC,
			    sc->sc_tx_desclen,
			    ds);
		}
		bf = bf->bf_next;
	}
}
#endif /* ATH_DEBUG_ALQ */

/*
 * Whether to use the 11n rate scenario functions or not
 */
static inline int
ath_tx_is_11n(struct ath_softc *sc)
{
	return ((sc->sc_ah->ah_magic == 0x20065416) ||
		    (sc->sc_ah->ah_magic == 0x19741014));
}

/*
 * Obtain the current TID from the given frame.
 *
 * Non-QoS frames need to go into TID 16 (IEEE80211_NONQOS_TID.)
 * This has implications for which AC/priority the packet is placed
 * in.
 */
static int
ath_tx_gettid(struct ath_softc *sc, const struct mbuf *m0)
{
	const struct ieee80211_frame *wh;
	int pri = M_WME_GETAC(m0);

	wh = mtod(m0, const struct ieee80211_frame *);
	if (! IEEE80211_QOS_HAS_SEQ(wh))
		return IEEE80211_NONQOS_TID;
	else
		return WME_AC_TO_TID(pri);
}

static void
ath_tx_set_retry(struct ath_softc *sc, struct ath_buf *bf)
{
	struct ieee80211_frame *wh;

	wh = mtod(bf->bf_m, struct ieee80211_frame *);
	/* Only update/resync if needed */
	if (bf->bf_state.bfs_isretried == 0) {
		wh->i_fc[1] |= IEEE80211_FC1_RETRY;
		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
		    BUS_DMASYNC_PREWRITE);
	}
	bf->bf_state.bfs_isretried = 1;
	bf->bf_state.bfs_retries ++;
}

/*
 * Determine what the correct AC queue for the given frame
 * should be.
 *
 * This code assumes that the TIDs map consistently to
 * the underlying hardware (or software) ath_txq.
 * Since the sender may try to set an AC which is
 * arbitrary, non-QoS TIDs may end up being put on
 * completely different ACs. There's no way to put a
 * TID into multiple ath_txq's for scheduling, so
 * for now we override the AC/TXQ selection and set
 * non-QOS TID frames into the BE queue.
 *
 * This may be completely incorrect - specifically,
 * some management frames may end up out of order
 * compared to the QoS traffic they're controlling.
 * I'll look into this later.
 */
static int
ath_tx_getac(struct ath_softc *sc, const struct mbuf *m0)
{
	const struct ieee80211_frame *wh;
	int pri = M_WME_GETAC(m0);
	wh = mtod(m0, const struct ieee80211_frame *);
	if (IEEE80211_QOS_HAS_SEQ(wh))
		return pri;

	return ATH_NONQOS_TID_AC;
}

void
ath_txfrag_cleanup(struct ath_softc *sc,
	ath_bufhead *frags, struct ieee80211_node *ni)
{
	struct ath_buf *bf, *next;

	ATH_TXBUF_LOCK_ASSERT(sc);

	TAILQ_FOREACH_SAFE(bf, frags, bf_list, next) {
		/* NB: bf assumed clean */
		TAILQ_REMOVE(frags, bf, bf_list);
		ath_returnbuf_head(sc, bf);
		ieee80211_node_decref(ni);
	}
}

/*
 * Setup xmit of a fragmented frame.  Allocate a buffer
 * for each frag and bump the node reference count to
 * reflect the held reference to be setup by ath_tx_start.
 */
int
ath_txfrag_setup(struct ath_softc *sc, ath_bufhead *frags,
	struct mbuf *m0, struct ieee80211_node *ni)
{
	struct mbuf *m;
	struct ath_buf *bf;

	ATH_TXBUF_LOCK(sc);
	for (m = m0->m_nextpkt; m != NULL; m = m->m_nextpkt) {
		/* XXX non-management? */
		bf = _ath_getbuf_locked(sc, ATH_BUFTYPE_NORMAL);
		if (bf == NULL) {	/* out of buffers, cleanup */
			DPRINTF(sc, ATH_DEBUG_XMIT, "%s: no buffer?\n",
			    __func__);
			ath_txfrag_cleanup(sc, frags, ni);
			break;
		}
		ieee80211_node_incref(ni);
		TAILQ_INSERT_TAIL(frags, bf, bf_list);
	}
	ATH_TXBUF_UNLOCK(sc);

	return !TAILQ_EMPTY(frags);
}

/*
 * Reclaim mbuf resources.  For fragmented frames we
 * need to claim each frag chained with m_nextpkt.
 */
void
ath_freetx(struct mbuf *m)
{
	struct mbuf *next;

	do {
		next = m->m_nextpkt;
		m->m_nextpkt = NULL;
		m_freem(m);
	} while ((m = next) != NULL);
}

static int
ath_tx_dmasetup(struct ath_softc *sc, struct ath_buf *bf, struct mbuf *m0)
{
	struct mbuf *m;
	int error;

	/*
	 * Load the DMA map so any coalescing is done.  This
	 * also calculates the number of descriptors we need.
	 */
	error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m0,
				     bf->bf_segs, &bf->bf_nseg,
				     BUS_DMA_NOWAIT);
	if (error == EFBIG) {
		/* XXX packet requires too many descriptors */
		bf->bf_nseg = ATH_MAX_SCATTER + 1;
	} else if (error != 0) {
		sc->sc_stats.ast_tx_busdma++;
		ath_freetx(m0);
		return error;
	}
	/*
	 * Discard null packets and check for packets that
	 * require too many TX descriptors.  We try to convert
	 * the latter to a cluster.
	 */
	if (bf->bf_nseg > ATH_MAX_SCATTER) {		/* too many desc's, linearize */
		sc->sc_stats.ast_tx_linear++;
		m = m_collapse(m0, M_NOWAIT, ATH_MAX_SCATTER);
		if (m == NULL) {
			ath_freetx(m0);
			sc->sc_stats.ast_tx_nombuf++;
			return ENOMEM;
		}
		m0 = m;
		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m0,
					     bf->bf_segs, &bf->bf_nseg,
					     BUS_DMA_NOWAIT);
		if (error != 0) {
			sc->sc_stats.ast_tx_busdma++;
			ath_freetx(m0);
			return error;
		}
		KASSERT(bf->bf_nseg <= ATH_MAX_SCATTER,
		    ("too many segments after defrag; nseg %u", bf->bf_nseg));
	} else if (bf->bf_nseg == 0) {		/* null packet, discard */
		sc->sc_stats.ast_tx_nodata++;
		ath_freetx(m0);
		return EIO;
	}
	DPRINTF(sc, ATH_DEBUG_XMIT, "%s: m %p len %u\n",
		__func__, m0, m0->m_pkthdr.len);
	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
	bf->bf_m = m0;

	return 0;
}

/*
 * Chain together segments+descriptors for a frame - 11n or otherwise.
 *
 * For aggregates, this is called on each frame in the aggregate.
 */
static void
ath_tx_chaindesclist(struct ath_softc *sc, struct ath_desc *ds0,
    struct ath_buf *bf, int is_aggr, int is_first_subframe,
    int is_last_subframe)
{
	struct ath_hal *ah = sc->sc_ah;
	char *ds;
	int i, bp, dsp;
	HAL_DMA_ADDR bufAddrList[4];
	uint32_t segLenList[4];
	int numTxMaps = 1;
	int isFirstDesc = 1;

	/*
	 * XXX There's txdma and txdma_mgmt; the descriptor
	 * sizes must match.
	 */
	struct ath_descdma *dd = &sc->sc_txdma;

	/*
	 * Fillin the remainder of the descriptor info.
	 */

	/*
	 * We need the number of TX data pointers in each descriptor.
	 * EDMA and later chips support 4 TX buffers per descriptor;
	 * previous chips just support one.
	 */
	numTxMaps = sc->sc_tx_nmaps;

	/*
	 * For EDMA and later chips ensure the TX map is fully populated
	 * before advancing to the next descriptor.
	 */
	ds = (char *) bf->bf_desc;
	bp = dsp = 0;
	bzero(bufAddrList, sizeof(bufAddrList));
	bzero(segLenList, sizeof(segLenList));
	for (i = 0; i < bf->bf_nseg; i++) {
		bufAddrList[bp] = bf->bf_segs[i].ds_addr;
		segLenList[bp] = bf->bf_segs[i].ds_len;
		bp++;

		/*
		 * Go to the next segment if this isn't the last segment
		 * and there's space in the current TX map.
		 */
		if ((i != bf->bf_nseg - 1) && (bp < numTxMaps))
			continue;

		/*
		 * Last segment or we're out of buffer pointers.
		 */
		bp = 0;

		if (i == bf->bf_nseg - 1)
			ath_hal_settxdesclink(ah, (struct ath_desc *) ds, 0);
		else
			ath_hal_settxdesclink(ah, (struct ath_desc *) ds,
			    bf->bf_daddr + dd->dd_descsize * (dsp + 1));

		/*
		 * XXX This assumes that bfs_txq is the actual destination
		 * hardware queue at this point.  It may not have been
		 * assigned, it may actually be pointing to the multicast
		 * software TXQ id.  These must be fixed!
		 */
		ath_hal_filltxdesc(ah, (struct ath_desc *) ds
			, bufAddrList
			, segLenList
			, bf->bf_descid		/* XXX desc id */
			, bf->bf_state.bfs_tx_queue
			, isFirstDesc		/* first segment */
			, i == bf->bf_nseg - 1	/* last segment */
			, (struct ath_desc *) ds0	/* first descriptor */
		);

		/*
		 * Make sure the 11n aggregate fields are cleared.
		 *
		 * XXX TODO: this doesn't need to be called for
		 * aggregate frames; as it'll be called on all
		 * sub-frames.  Since the descriptors are in
		 * non-cacheable memory, this leads to some
		 * rather slow writes on MIPS/ARM platforms.
		 */
		if (ath_tx_is_11n(sc))
			ath_hal_clr11n_aggr(sc->sc_ah, (struct ath_desc *) ds);

		/*
		 * If 11n is enabled, set it up as if it's an aggregate
		 * frame.
		 */
		if (is_last_subframe) {
			ath_hal_set11n_aggr_last(sc->sc_ah,
			    (struct ath_desc *) ds);
		} else if (is_aggr) {
			/*
			 * This clears the aggrlen field; so
			 * the caller needs to call set_aggr_first()!
			 *
			 * XXX TODO: don't call this for the first
			 * descriptor in the first frame in an
			 * aggregate!
			 */
			ath_hal_set11n_aggr_middle(sc->sc_ah,
			    (struct ath_desc *) ds,
			    bf->bf_state.bfs_ndelim);
		}
		isFirstDesc = 0;
		bf->bf_lastds = (struct ath_desc *) ds;

		/*
		 * Don't forget to skip to the next descriptor.
		 */
		ds += sc->sc_tx_desclen;
		dsp++;

		/*
		 * .. and don't forget to blank these out!
		 */
		bzero(bufAddrList, sizeof(bufAddrList));
		bzero(segLenList, sizeof(segLenList));
	}
	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
}

/*
 * Set the rate control fields in the given descriptor based on
 * the bf_state fields and node state.
 *
 * The bfs fields should already be set with the relevant rate
 * control information, including whether MRR is to be enabled.
 *
 * Since the FreeBSD HAL currently sets up the first TX rate
 * in ath_hal_setuptxdesc(), this will setup the MRR
 * conditionally for the pre-11n chips, and call ath_buf_set_rate
 * unconditionally for 11n chips. These require the 11n rate
 * scenario to be set if MCS rates are enabled, so it's easier
 * to just always call it. The caller can then only set rates 2, 3
 * and 4 if multi-rate retry is needed.
 */
static void
ath_tx_set_ratectrl(struct ath_softc *sc, struct ieee80211_node *ni,
    struct ath_buf *bf)
{
	struct ath_rc_series *rc = bf->bf_state.bfs_rc;

	/* If mrr is disabled, blank tries 1, 2, 3 */
	if (! bf->bf_state.bfs_ismrr)
		rc[1].tries = rc[2].tries = rc[3].tries = 0;

#if 0
	/*
	 * If NOACK is set, just set ntries=1.
	 */
	else if (bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) {
		rc[1].tries = rc[2].tries = rc[3].tries = 0;
		rc[0].tries = 1;
	}
#endif

	/*
	 * Always call - that way a retried descriptor will
	 * have the MRR fields overwritten.
	 *
	 * XXX TODO: see if this is really needed - setting up
	 * the first descriptor should set the MRR fields to 0
	 * for us anyway.
	 */
	if (ath_tx_is_11n(sc)) {
		ath_buf_set_rate(sc, ni, bf);
	} else {
		ath_hal_setupxtxdesc(sc->sc_ah, bf->bf_desc
			, rc[1].ratecode, rc[1].tries
			, rc[2].ratecode, rc[2].tries
			, rc[3].ratecode, rc[3].tries
		);
	}
}

/*
 * Setup segments+descriptors for an 11n aggregate.
 * bf_first is the first buffer in the aggregate.
 * The descriptor list must already been linked together using
 * bf->bf_next.
 */
static void
ath_tx_setds_11n(struct ath_softc *sc, struct ath_buf *bf_first)
{
	struct ath_buf *bf, *bf_prev = NULL;
	struct ath_desc *ds0 = bf_first->bf_desc;

	DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR, "%s: nframes=%d, al=%d\n",
	    __func__, bf_first->bf_state.bfs_nframes,
	    bf_first->bf_state.bfs_al);

	bf = bf_first;

	if (bf->bf_state.bfs_txrate0 == 0)
		DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR, "%s: bf=%p, txrate0=%d\n",
		    __func__, bf, 0);
	if (bf->bf_state.bfs_rc[0].ratecode == 0)
		DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR, "%s: bf=%p, rix0=%d\n",
		    __func__, bf, 0);

	/*
	 * Setup all descriptors of all subframes - this will
	 * call ath_hal_set11naggrmiddle() on every frame.
	 */
	while (bf != NULL) {
		DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR,
		    "%s: bf=%p, nseg=%d, pktlen=%d, seqno=%d\n",
		    __func__, bf, bf->bf_nseg, bf->bf_state.bfs_pktlen,
		    SEQNO(bf->bf_state.bfs_seqno));

		/*
		 * Setup the initial fields for the first descriptor - all
		 * the non-11n specific stuff.
		 */
		ath_hal_setuptxdesc(sc->sc_ah, bf->bf_desc
			, bf->bf_state.bfs_pktlen	/* packet length */
			, bf->bf_state.bfs_hdrlen	/* header length */
			, bf->bf_state.bfs_atype	/* Atheros packet type */
			, bf->bf_state.bfs_txpower	/* txpower */
			, bf->bf_state.bfs_txrate0
			, bf->bf_state.bfs_try0		/* series 0 rate/tries */
			, bf->bf_state.bfs_keyix	/* key cache index */
			, bf->bf_state.bfs_txantenna	/* antenna mode */
			, bf->bf_state.bfs_txflags | HAL_TXDESC_INTREQ	/* flags */
			, bf->bf_state.bfs_ctsrate	/* rts/cts rate */
			, bf->bf_state.bfs_ctsduration	/* rts/cts duration */
		);

		/*
		 * First descriptor? Setup the rate control and initial
		 * aggregate header information.
		 */
		if (bf == bf_first) {
			/*
			 * setup first desc with rate and aggr info
			 */
			ath_tx_set_ratectrl(sc, bf->bf_node, bf);
		}

		/*
		 * Setup the descriptors for a multi-descriptor frame.
		 * This is both aggregate and non-aggregate aware.
		 */
		ath_tx_chaindesclist(sc, ds0, bf,
		    1, /* is_aggr */
		    !! (bf == bf_first), /* is_first_subframe */
		    !! (bf->bf_next == NULL) /* is_last_subframe */
		    );

		if (bf == bf_first) {
			/*
			 * Initialise the first 11n aggregate with the
			 * aggregate length and aggregate enable bits.
			 */
			ath_hal_set11n_aggr_first(sc->sc_ah,
			    ds0,
			    bf->bf_state.bfs_al,
			    bf->bf_state.bfs_ndelim);
		}

		/*
		 * Link the last descriptor of the previous frame
		 * to the beginning descriptor of this frame.
		 */
		if (bf_prev != NULL)
			ath_hal_settxdesclink(sc->sc_ah, bf_prev->bf_lastds,
			    bf->bf_daddr);

		/* Save a copy so we can link the next descriptor in */
		bf_prev = bf;
		bf = bf->bf_next;
	}

	/*
	 * Set the first descriptor bf_lastds field to point to
	 * the last descriptor in the last subframe, that's where
	 * the status update will occur.
	 */
	bf_first->bf_lastds = bf_prev->bf_lastds;

	/*
	 * And bf_last in the first descriptor points to the end of
	 * the aggregate list.
	 */
	bf_first->bf_last = bf_prev;

	/*
	 * For non-AR9300 NICs, which require the rate control
	 * in the final descriptor - let's set that up now.
	 *
	 * This is because the filltxdesc() HAL call doesn't
	 * populate the last segment with rate control information
	 * if firstSeg is also true.  For non-aggregate frames
	 * that is fine, as the first frame already has rate control
	 * info.  But if the last frame in an aggregate has one
	 * descriptor, both firstseg and lastseg will be true and
	 * the rate info isn't copied.
	 *
	 * This is inefficient on MIPS/ARM platforms that have
	 * non-cachable memory for TX descriptors, but we'll just
	 * make do for now.
	 *
	 * As to why the rate table is stashed in the last descriptor
	 * rather than the first descriptor?  Because proctxdesc()
	 * is called on the final descriptor in an MPDU or A-MPDU -
	 * ie, the one that gets updated by the hardware upon
	 * completion.  That way proctxdesc() doesn't need to know
	 * about the first _and_ last TX descriptor.
	 */
	ath_hal_setuplasttxdesc(sc->sc_ah, bf_prev->bf_lastds, ds0);

	DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR, "%s: end\n", __func__);
}

/*
 * Hand-off a frame to the multicast TX queue.
 *
 * This is a software TXQ which will be appended to the CAB queue
 * during the beacon setup code.
 *
 * XXX TODO: since the AR9300 EDMA TX queue support wants the QCU ID
 * as part of the TX descriptor, bf_state.bfs_tx_queue must be updated
 * with the actual hardware txq, or all of this will fall apart.
 *
 * XXX It may not be a bad idea to just stuff the QCU ID into bf_state
 * and retire bfs_tx_queue; then make sure the CABQ QCU ID is populated
 * correctly.
 */
static void
ath_tx_handoff_mcast(struct ath_softc *sc, struct ath_txq *txq,
    struct ath_buf *bf)
{
	ATH_TX_LOCK_ASSERT(sc);

	KASSERT((bf->bf_flags & ATH_BUF_BUSY) == 0,
	     ("%s: busy status 0x%x", __func__, bf->bf_flags));

	/*
	 * Ensure that the tx queue is the cabq, so things get
	 * mapped correctly.
	 */
	if (bf->bf_state.bfs_tx_queue != sc->sc_cabq->axq_qnum) {
		DPRINTF(sc, ATH_DEBUG_XMIT,
		    "%s: bf=%p, bfs_tx_queue=%d, axq_qnum=%d\n",
		    __func__, bf, bf->bf_state.bfs_tx_queue,
		    txq->axq_qnum);
	}

	ATH_TXQ_LOCK(txq);
	if (ATH_TXQ_LAST(txq, axq_q_s) != NULL) {
		struct ath_buf *bf_last = ATH_TXQ_LAST(txq, axq_q_s);
		struct ieee80211_frame *wh;

		/* mark previous frame */
		wh = mtod(bf_last->bf_m, struct ieee80211_frame *);
		wh->i_fc[1] |= IEEE80211_FC1_MORE_DATA;
		bus_dmamap_sync(sc->sc_dmat, bf_last->bf_dmamap,
		    BUS_DMASYNC_PREWRITE);

		/* link descriptor */
		ath_hal_settxdesclink(sc->sc_ah,
		    bf_last->bf_lastds,
		    bf->bf_daddr);
	}
	ATH_TXQ_INSERT_TAIL(txq, bf, bf_list);
	ATH_TXQ_UNLOCK(txq);
}

/*
 * Hand-off packet to a hardware queue.
 */
static void
ath_tx_handoff_hw(struct ath_softc *sc, struct ath_txq *txq,
    struct ath_buf *bf)
{
	struct ath_hal *ah = sc->sc_ah;
	struct ath_buf *bf_first;

	/*
	 * Insert the frame on the outbound list and pass it on
	 * to the hardware.  Multicast frames buffered for power
	 * save stations and transmit from the CAB queue are stored
	 * on a s/w only queue and loaded on to the CAB queue in
	 * the SWBA handler since frames only go out on DTIM and
	 * to avoid possible races.
	 */
	ATH_TX_LOCK_ASSERT(sc);
	KASSERT((bf->bf_flags & ATH_BUF_BUSY) == 0,
	     ("%s: busy status 0x%x", __func__, bf->bf_flags));
	KASSERT(txq->axq_qnum != ATH_TXQ_SWQ,
	     ("ath_tx_handoff_hw called for mcast queue"));

	/*
	 * XXX racy, should hold the PCU lock when checking this,
	 * and also should ensure that the TX counter is >0!
	 */
	KASSERT((sc->sc_inreset_cnt == 0),
	    ("%s: TX during reset?\n", __func__));

#if 0
	/*
	 * This causes a LOR. Find out where the PCU lock is being
	 * held whilst the TXQ lock is grabbed - that shouldn't
	 * be occuring.
	 */
	ATH_PCU_LOCK(sc);
	if (sc->sc_inreset_cnt) {
		ATH_PCU_UNLOCK(sc);
		DPRINTF(sc, ATH_DEBUG_RESET,
		    "%s: called with sc_in_reset != 0\n",
		    __func__);
		DPRINTF(sc, ATH_DEBUG_XMIT,
		    "%s: queued: TXDP[%u] = %p (%p) depth %d\n",
		    __func__, txq->axq_qnum,
		    (caddr_t)bf->bf_daddr, bf->bf_desc,
		    txq->axq_depth);
		/* XXX axq_link needs to be set and updated! */
		ATH_TXQ_INSERT_TAIL(txq, bf, bf_list);
		if (bf->bf_state.bfs_aggr)
			txq->axq_aggr_depth++;
		return;
		}
	ATH_PCU_UNLOCK(sc);
#endif

	ATH_TXQ_LOCK(txq);

	/*
	 * XXX TODO: if there's a holdingbf, then
	 * ATH_TXQ_PUTRUNNING should be clear.
	 *
	 * If there is a holdingbf and the list is empty,
	 * then axq_link should be pointing to the holdingbf.
	 *
	 * Otherwise it should point to the last descriptor
	 * in the last ath_buf.
	 *
	 * In any case, we should really ensure that we
	 * update the previous descriptor link pointer to
	 * this descriptor, regardless of all of the above state.
	 *
	 * For now this is captured by having axq_link point
	 * to either the holdingbf (if the TXQ list is empty)
	 * or the end of the list (if the TXQ list isn't empty.)
	 * I'd rather just kill axq_link here and do it as above.
	 */

	/*
	 * Append the frame to the TX queue.
	 */
	ATH_TXQ_INSERT_TAIL(txq, bf, bf_list);
	ATH_KTR(sc, ATH_KTR_TX, 3,
	    "ath_tx_handoff: non-tdma: txq=%u, add bf=%p "
	    "depth=%d",
	    txq->axq_qnum,
	    bf,
	    txq->axq_depth);

	/*
	 * If there's a link pointer, update it.
	 *
	 * XXX we should replace this with the above logic, just
	 * to kill axq_link with fire.
	 */
	if (txq->axq_link != NULL) {
		*txq->axq_link = bf->bf_daddr;
		DPRINTF(sc, ATH_DEBUG_XMIT,
		    "%s: link[%u](%p)=%p (%p) depth %d\n", __func__,
		    txq->axq_qnum, txq->axq_link,
		    (caddr_t)bf->bf_daddr, bf->bf_desc,
		    txq->axq_depth);
		ATH_KTR(sc, ATH_KTR_TX, 5,
		    "ath_tx_handoff: non-tdma: link[%u](%p)=%p (%p) "
		    "lastds=%d",
		    txq->axq_qnum, txq->axq_link,
		    (caddr_t)bf->bf_daddr, bf->bf_desc,
		    bf->bf_lastds);
	}

	/*
	 * If we've not pushed anything into the hardware yet,
	 * push the head of the queue into the TxDP.
	 *
	 * Once we've started DMA, there's no guarantee that
	 * updating the TxDP with a new value will actually work.
	 * So we just don't do that - if we hit the end of the list,
	 * we keep that buffer around (the "holding buffer") and
	 * re-start DMA by updating the link pointer of _that_
	 * descriptor and then restart DMA.
	 */
	if (! (txq->axq_flags & ATH_TXQ_PUTRUNNING)) {
		bf_first = TAILQ_FIRST(&txq->axq_q);
		txq->axq_flags |= ATH_TXQ_PUTRUNNING;
		ath_hal_puttxbuf(ah, txq->axq_qnum, bf_first->bf_daddr);
		DPRINTF(sc, ATH_DEBUG_XMIT,
		    "%s: TXDP[%u] = %p (%p) depth %d\n",
		    __func__, txq->axq_qnum,
		    (caddr_t)bf_first->bf_daddr, bf_first->bf_desc,
		    txq->axq_depth);
		ATH_KTR(sc, ATH_KTR_TX, 5,
		    "ath_tx_handoff: TXDP[%u] = %p (%p) "
		    "lastds=%p depth %d",
		    txq->axq_qnum,
		    (caddr_t)bf_first->bf_daddr, bf_first->bf_desc,
		    bf_first->bf_lastds,
		    txq->axq_depth);
	}

	/*
	 * Ensure that the bf TXQ matches this TXQ, so later
	 * checking and holding buffer manipulation is sane.
	 */
	if (bf->bf_state.bfs_tx_queue != txq->axq_qnum) {
		DPRINTF(sc, ATH_DEBUG_XMIT,
		    "%s: bf=%p, bfs_tx_queue=%d, axq_qnum=%d\n",
		    __func__, bf, bf->bf_state.bfs_tx_queue,
		    txq->axq_qnum);
	}

	/*
	 * Track aggregate queue depth.
	 */
	if (bf->bf_state.bfs_aggr)
		txq->axq_aggr_depth++;

	/*
	 * Update the link pointer.
	 */
	ath_hal_gettxdesclinkptr(ah, bf->bf_lastds, &txq->axq_link);

	/*
	 * Start DMA.
	 *
	 * If we wrote a TxDP above, DMA will start from here.
	 *
	 * If DMA is running, it'll do nothing.
	 *
	 * If the DMA engine hit the end of the QCU list (ie LINK=NULL,
	 * or VEOL) then it stops at the last transmitted write.
	 * We then append a new frame by updating the link pointer
	 * in that descriptor and then kick TxE here; it will re-read
	 * that last descriptor and find the new descriptor to transmit.
	 *
	 * This is why we keep the holding descriptor around.
	 */
	ath_hal_txstart(ah, txq->axq_qnum);
	ATH_TXQ_UNLOCK(txq);
	ATH_KTR(sc, ATH_KTR_TX, 1,
	    "ath_tx_handoff: txq=%u, txstart", txq->axq_qnum);
}

/*
 * Restart TX DMA for the given TXQ.
 *
 * This must be called whether the queue is empty or not.
 */
static void
ath_legacy_tx_dma_restart(struct ath_softc *sc, struct ath_txq *txq)
{
	struct ath_buf *bf, *bf_last;

	ATH_TXQ_LOCK_ASSERT(txq);

	/* XXX make this ATH_TXQ_FIRST */
	bf = TAILQ_FIRST(&txq->axq_q);
	bf_last = ATH_TXQ_LAST(txq, axq_q_s);

	if (bf == NULL)
		return;

	DPRINTF(sc, ATH_DEBUG_RESET,
	    "%s: Q%d: bf=%p, bf_last=%p, daddr=0x%08x\n",
	    __func__,
	    txq->axq_qnum,
	    bf,
	    bf_last,
	    (uint32_t) bf->bf_daddr);

#ifdef	ATH_DEBUG
	if (sc->sc_debug & ATH_DEBUG_RESET)
		ath_tx_dump(sc, txq);
#endif

	/*
	 * This is called from a restart, so DMA is known to be
	 * completely stopped.
	 */
	KASSERT((!(txq->axq_flags & ATH_TXQ_PUTRUNNING)),
	    ("%s: Q%d: called with PUTRUNNING=1\n",
	    __func__,
	    txq->axq_qnum));

	ath_hal_puttxbuf(sc->sc_ah, txq->axq_qnum, bf->bf_daddr);
	txq->axq_flags |= ATH_TXQ_PUTRUNNING;

	ath_hal_gettxdesclinkptr(sc->sc_ah, bf_last->bf_lastds,
	    &txq->axq_link);
	ath_hal_txstart(sc->sc_ah, txq->axq_qnum);
}

/*
 * Hand off a packet to the hardware (or mcast queue.)
 *
 * The relevant hardware txq should be locked.
 */
static void
ath_legacy_xmit_handoff(struct ath_softc *sc, struct ath_txq *txq,
    struct ath_buf *bf)
{
	ATH_TX_LOCK_ASSERT(sc);

#ifdef	ATH_DEBUG_ALQ
	if (if_ath_alq_checkdebug(&sc->sc_alq, ATH_ALQ_EDMA_TXDESC))
		ath_tx_alq_post(sc, bf);
#endif

	if (txq->axq_qnum == ATH_TXQ_SWQ)
		ath_tx_handoff_mcast(sc, txq, bf);
	else
		ath_tx_handoff_hw(sc, txq, bf);
}

static int
ath_tx_tag_crypto(struct ath_softc *sc, struct ieee80211_node *ni,
    struct mbuf *m0, int iswep, int isfrag, int *hdrlen, int *pktlen,
    int *keyix)
{
	DPRINTF(sc, ATH_DEBUG_XMIT,
	    "%s: hdrlen=%d, pktlen=%d, isfrag=%d, iswep=%d, m0=%p\n",
	    __func__,
	    *hdrlen,
	    *pktlen,
	    isfrag,
	    iswep,
	    m0);

	if (iswep) {
		const struct ieee80211_cipher *cip;
		struct ieee80211_key *k;

		/*
		 * Construct the 802.11 header+trailer for an encrypted
		 * frame. The only reason this can fail is because of an
		 * unknown or unsupported cipher/key type.
		 */
		k = ieee80211_crypto_encap(ni, m0);
		if (k == NULL) {
			/*
			 * This can happen when the key is yanked after the
			 * frame was queued.  Just discard the frame; the
			 * 802.11 layer counts failures and provides
			 * debugging/diagnostics.
			 */
			return (0);
		}
		/*
		 * Adjust the packet + header lengths for the crypto
		 * additions and calculate the h/w key index.  When
		 * a s/w mic is done the frame will have had any mic
		 * added to it prior to entry so m0->m_pkthdr.len will
		 * account for it. Otherwise we need to add it to the
		 * packet length.
		 */
		cip = k->wk_cipher;
		(*hdrlen) += cip->ic_header;
		(*pktlen) += cip->ic_header + cip->ic_trailer;
		/* NB: frags always have any TKIP MIC done in s/w */
		if ((k->wk_flags & IEEE80211_KEY_SWMIC) == 0 && !isfrag)
			(*pktlen) += cip->ic_miclen;
		(*keyix) = k->wk_keyix;
	} else if (ni->ni_ucastkey.wk_cipher == &ieee80211_cipher_none) {
		/*
		 * Use station key cache slot, if assigned.
		 */
		(*keyix) = ni->ni_ucastkey.wk_keyix;
		if ((*keyix) == IEEE80211_KEYIX_NONE)
			(*keyix) = HAL_TXKEYIX_INVALID;
	} else
		(*keyix) = HAL_TXKEYIX_INVALID;

	return (1);
}

/*
 * Calculate whether interoperability protection is required for
 * this frame.
 *
 * This requires the rate control information be filled in,
 * as the protection requirement depends upon the current
 * operating mode / PHY.
 */
static void
ath_tx_calc_protection(struct ath_softc *sc, struct ath_buf *bf)
{
	struct ieee80211_frame *wh;
	uint8_t rix;
	uint16_t flags;
	int shortPreamble;
	const HAL_RATE_TABLE *rt = sc->sc_currates;
	struct ifnet *ifp = sc->sc_ifp;
	struct ieee80211com *ic = ifp->if_l2com;

	flags = bf->bf_state.bfs_txflags;
	rix = bf->bf_state.bfs_rc[0].rix;
	shortPreamble = bf->bf_state.bfs_shpream;
	wh = mtod(bf->bf_m, struct ieee80211_frame *);

	/*
	 * If 802.11g protection is enabled, determine whether
	 * to use RTS/CTS or just CTS.  Note that this is only
	 * done for OFDM unicast frames.
	 */
	if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
	    rt->info[rix].phy == IEEE80211_T_OFDM &&
	    (flags & HAL_TXDESC_NOACK) == 0) {
		bf->bf_state.bfs_doprot = 1;
		/* XXX fragments must use CCK rates w/ protection */
		if (ic->ic_protmode == IEEE80211_PROT_RTSCTS) {
			flags |= HAL_TXDESC_RTSENA;
		} else if (ic->ic_protmode == IEEE80211_PROT_CTSONLY) {
			flags |= HAL_TXDESC_CTSENA;
		}
		/*
		 * For frags it would be desirable to use the
		 * highest CCK rate for RTS/CTS.  But stations
		 * farther away may detect it at a lower CCK rate
		 * so use the configured protection rate instead
		 * (for now).
		 */
		sc->sc_stats.ast_tx_protect++;
	}

	/*
	 * If 11n protection is enabled and it's a HT frame,
	 * enable RTS.
	 *
	 * XXX ic_htprotmode or ic_curhtprotmode?
	 * XXX should it_htprotmode only matter if ic_curhtprotmode 
	 * XXX indicates it's not a HT pure environment?
	 */
	if ((ic->ic_htprotmode == IEEE80211_PROT_RTSCTS) &&
	    rt->info[rix].phy == IEEE80211_T_HT &&
	    (flags & HAL_TXDESC_NOACK) == 0) {
		flags |= HAL_TXDESC_RTSENA;
		sc->sc_stats.ast_tx_htprotect++;
	}
	bf->bf_state.bfs_txflags = flags;
}

/*
 * Update the frame duration given the currently selected rate.
 *
 * This also updates the frame duration value, so it will require
 * a DMA flush.
 */
static void
ath_tx_calc_duration(struct ath_softc *sc, struct ath_buf *bf)
{
	struct ieee80211_frame *wh;
	uint8_t rix;
	uint16_t flags;
	int shortPreamble;
	struct ath_hal *ah = sc->sc_ah;
	const HAL_RATE_TABLE *rt = sc->sc_currates;
	int isfrag = bf->bf_m->m_flags & M_FRAG;

	flags = bf->bf_state.bfs_txflags;
	rix = bf->bf_state.bfs_rc[0].rix;
	shortPreamble = bf->bf_state.bfs_shpream;
	wh = mtod(bf->bf_m, struct ieee80211_frame *);

	/*
	 * Calculate duration.  This logically belongs in the 802.11
	 * layer but it lacks sufficient information to calculate it.
	 */
	if ((flags & HAL_TXDESC_NOACK) == 0 &&
	    (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) != IEEE80211_FC0_TYPE_CTL) {
		u_int16_t dur;
		if (shortPreamble)
			dur = rt->info[rix].spAckDuration;
		else
			dur = rt->info[rix].lpAckDuration;
		if (wh->i_fc[1] & IEEE80211_FC1_MORE_FRAG) {
			dur += dur;		/* additional SIFS+ACK */
			/*
			 * Include the size of next fragment so NAV is
			 * updated properly.  The last fragment uses only
			 * the ACK duration
			 *
			 * XXX TODO: ensure that the rate lookup for each
			 * fragment is the same as the rate used by the
			 * first fragment!
			 */
			dur += ath_hal_computetxtime(ah,
			    rt,
			    bf->bf_nextfraglen,
			    rix, shortPreamble);
		}
		if (isfrag) {
			/*
			 * Force hardware to use computed duration for next
			 * fragment by disabling multi-rate retry which updates
			 * duration based on the multi-rate duration table.
			 */
			bf->bf_state.bfs_ismrr = 0;
			bf->bf_state.bfs_try0 = ATH_TXMGTTRY;
			/* XXX update bfs_rc[0].try? */
		}

		/* Update the duration field itself */
		*(u_int16_t *)wh->i_dur = htole16(dur);
	}
}

static uint8_t
ath_tx_get_rtscts_rate(struct ath_hal *ah, const HAL_RATE_TABLE *rt,
    int cix, int shortPreamble)
{
	uint8_t ctsrate;

	/*
	 * CTS transmit rate is derived from the transmit rate
	 * by looking in the h/w rate table.  We must also factor
	 * in whether or not a short preamble is to be used.
	 */
	/* NB: cix is set above where RTS/CTS is enabled */
	KASSERT(cix != 0xff, ("cix not setup"));
	ctsrate = rt->info[cix].rateCode;

	/* XXX this should only matter for legacy rates */
	if (shortPreamble)
		ctsrate |= rt->info[cix].shortPreamble;

	return (ctsrate);
}

/*
 * Calculate the RTS/CTS duration for legacy frames.
 */
static int
ath_tx_calc_ctsduration(struct ath_hal *ah, int rix, int cix,
    int shortPreamble, int pktlen, const HAL_RATE_TABLE *rt,
    int flags)
{
	int ctsduration = 0;

	/* This mustn't be called for HT modes */
	if (rt->info[cix].phy == IEEE80211_T_HT) {
		printf("%s: HT rate where it shouldn't be (0x%x)\n",
		    __func__, rt->info[cix].rateCode);
		return (-1);
	}

	/*
	 * Compute the transmit duration based on the frame
	 * size and the size of an ACK frame.  We call into the
	 * HAL to do the computation since it depends on the
	 * characteristics of the actual PHY being used.
	 *
	 * NB: CTS is assumed the same size as an ACK so we can
	 *     use the precalculated ACK durations.
	 */
	if (shortPreamble) {
		if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
			ctsduration += rt->info[cix].spAckDuration;
		ctsduration += ath_hal_computetxtime(ah,
			rt, pktlen, rix, AH_TRUE);
		if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
			ctsduration += rt->info[rix].spAckDuration;
	} else {
		if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
			ctsduration += rt->info[cix].lpAckDuration;
		ctsduration += ath_hal_computetxtime(ah,
			rt, pktlen, rix, AH_FALSE);
		if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
			ctsduration += rt->info[rix].lpAckDuration;
	}

	return (ctsduration);
}

/*
 * Update the given ath_buf with updated rts/cts setup and duration
 * values.
 *
 * To support rate lookups for each software retry, the rts/cts rate
 * and cts duration must be re-calculated.
 *
 * This function assumes the RTS/CTS flags have been set as needed;
 * mrr has been disabled; and the rate control lookup has been done.
 *
 * XXX TODO: MRR need only be disabled for the pre-11n NICs.
 * XXX The 11n NICs support per-rate RTS/CTS configuration.
 */
static void
ath_tx_set_rtscts(struct ath_softc *sc, struct ath_buf *bf)
{
	uint16_t ctsduration = 0;
	uint8_t ctsrate = 0;
	uint8_t rix = bf->bf_state.bfs_rc[0].rix;
	uint8_t cix = 0;
	const HAL_RATE_TABLE *rt = sc->sc_currates;

	/*
	 * No RTS/CTS enabled? Don't bother.
	 */
	if ((bf->bf_state.bfs_txflags &
	    (HAL_TXDESC_RTSENA | HAL_TXDESC_CTSENA)) == 0) {
		/* XXX is this really needed? */
		bf->bf_state.bfs_ctsrate = 0;
		bf->bf_state.bfs_ctsduration = 0;
		return;
	}

	/*
	 * If protection is enabled, use the protection rix control
	 * rate. Otherwise use the rate0 control rate.
	 */
	if (bf->bf_state.bfs_doprot)
		rix = sc->sc_protrix;
	else
		rix = bf->bf_state.bfs_rc[0].rix;

	/*
	 * If the raw path has hard-coded ctsrate0 to something,
	 * use it.
	 */
	if (bf->bf_state.bfs_ctsrate0 != 0)
		cix = ath_tx_findrix(sc, bf->bf_state.bfs_ctsrate0);
	else
		/* Control rate from above */
		cix = rt->info[rix].controlRate;

	/* Calculate the rtscts rate for the given cix */
	ctsrate = ath_tx_get_rtscts_rate(sc->sc_ah, rt, cix,
	    bf->bf_state.bfs_shpream);

	/* The 11n chipsets do ctsduration calculations for you */
	if (! ath_tx_is_11n(sc))
		ctsduration = ath_tx_calc_ctsduration(sc->sc_ah, rix, cix,
		    bf->bf_state.bfs_shpream, bf->bf_state.bfs_pktlen,
		    rt, bf->bf_state.bfs_txflags);

	/* Squirrel away in ath_buf */
	bf->bf_state.bfs_ctsrate = ctsrate;
	bf->bf_state.bfs_ctsduration = ctsduration;
	
	/*
	 * Must disable multi-rate retry when using RTS/CTS.
	 */
	if (!sc->sc_mrrprot) {
		bf->bf_state.bfs_ismrr = 0;
		bf->bf_state.bfs_try0 =
		    bf->bf_state.bfs_rc[0].tries = ATH_TXMGTTRY; /* XXX ew */
	}
}

/*
 * Setup the descriptor chain for a normal or fast-frame
 * frame.
 *
 * XXX TODO: extend to include the destination hardware QCU ID.
 * Make sure that is correct.  Make sure that when being added
 * to the mcastq, the CABQ QCUID is set or things will get a bit
 * odd.
 */
static void
ath_tx_setds(struct ath_softc *sc, struct ath_buf *bf)
{
	struct ath_desc *ds = bf->bf_desc;
	struct ath_hal *ah = sc->sc_ah;

	if (bf->bf_state.bfs_txrate0 == 0)
		DPRINTF(sc, ATH_DEBUG_XMIT, 
		    "%s: bf=%p, txrate0=%d\n", __func__, bf, 0);

	ath_hal_setuptxdesc(ah, ds
		, bf->bf_state.bfs_pktlen	/* packet length */
		, bf->bf_state.bfs_hdrlen	/* header length */
		, bf->bf_state.bfs_atype	/* Atheros packet type */
		, bf->bf_state.bfs_txpower	/* txpower */
		, bf->bf_state.bfs_txrate0
		, bf->bf_state.bfs_try0		/* series 0 rate/tries */
		, bf->bf_state.bfs_keyix	/* key cache index */
		, bf->bf_state.bfs_txantenna	/* antenna mode */
		, bf->bf_state.bfs_txflags	/* flags */
		, bf->bf_state.bfs_ctsrate	/* rts/cts rate */
		, bf->bf_state.bfs_ctsduration	/* rts/cts duration */
	);

	/*
	 * This will be overriden when the descriptor chain is written.
	 */
	bf->bf_lastds = ds;
	bf->bf_last = bf;

	/* Set rate control and descriptor chain for this frame */
	ath_tx_set_ratectrl(sc, bf->bf_node, bf);
	ath_tx_chaindesclist(sc, ds, bf, 0, 0, 0);
}

/*
 * Do a rate lookup.
 *
 * This performs a rate lookup for the given ath_buf only if it's required.
 * Non-data frames and raw frames don't require it.
 *
 * This populates the primary and MRR entries; MRR values are
 * then disabled later on if something requires it (eg RTS/CTS on
 * pre-11n chipsets.
 *
 * This needs to be done before the RTS/CTS fields are calculated
 * as they may depend upon the rate chosen.
 */
static void
ath_tx_do_ratelookup(struct ath_softc *sc, struct ath_buf *bf)
{
	uint8_t rate, rix;
	int try0;

	if (! bf->bf_state.bfs_doratelookup)
		return;

	/* Get rid of any previous state */
	bzero(bf->bf_state.bfs_rc, sizeof(bf->bf_state.bfs_rc));

	ATH_NODE_LOCK(ATH_NODE(bf->bf_node));
	ath_rate_findrate(sc, ATH_NODE(bf->bf_node), bf->bf_state.bfs_shpream,
	    bf->bf_state.bfs_pktlen, &rix, &try0, &rate);

	/* In case MRR is disabled, make sure rc[0] is setup correctly */
	bf->bf_state.bfs_rc[0].rix = rix;
	bf->bf_state.bfs_rc[0].ratecode = rate;
	bf->bf_state.bfs_rc[0].tries = try0;

	if (bf->bf_state.bfs_ismrr && try0 != ATH_TXMAXTRY)
		ath_rate_getxtxrates(sc, ATH_NODE(bf->bf_node), rix,
		    bf->bf_state.bfs_rc);
	ATH_NODE_UNLOCK(ATH_NODE(bf->bf_node));

	sc->sc_txrix = rix;	/* for LED blinking */
	sc->sc_lastdatarix = rix;	/* for fast frames */
	bf->bf_state.bfs_try0 = try0;
	bf->bf_state.bfs_txrate0 = rate;
}

/*
 * Update the CLRDMASK bit in the ath_buf if it needs to be set.
 */
static void
ath_tx_update_clrdmask(struct ath_softc *sc, struct ath_tid *tid,
    struct ath_buf *bf)
{
	struct ath_node *an = ATH_NODE(bf->bf_node);

	ATH_TX_LOCK_ASSERT(sc);

	if (an->clrdmask == 1) {
		bf->bf_state.bfs_txflags |= HAL_TXDESC_CLRDMASK;
		an->clrdmask = 0;
	}
}

/*
 * Return whether this frame should be software queued or
 * direct dispatched.
 *
 * When doing powersave, BAR frames should be queued but other management
 * frames should be directly sent.
 *
 * When not doing powersave, stick BAR frames into the hardware queue
 * so it goes out even though the queue is paused.
 *
 * For now, management frames are also software queued by default.
 */
static int
ath_tx_should_swq_frame(struct ath_softc *sc, struct ath_node *an,
    struct mbuf *m0, int *queue_to_head)
{
	struct ieee80211_node *ni = &an->an_node;
	struct ieee80211_frame *wh;
	uint8_t type, subtype;

	wh = mtod(m0, struct ieee80211_frame *);
	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
	subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;

	(*queue_to_head) = 0;

	/* If it's not in powersave - direct-dispatch BAR */
	if ((ATH_NODE(ni)->an_is_powersave == 0)
	    && type == IEEE80211_FC0_TYPE_CTL &&
	    subtype == IEEE80211_FC0_SUBTYPE_BAR) {
		DPRINTF(sc, ATH_DEBUG_SW_TX,
		    "%s: BAR: TX'ing direct\n", __func__);
		return (0);
	} else if ((ATH_NODE(ni)->an_is_powersave == 1)
	    && type == IEEE80211_FC0_TYPE_CTL &&
	    subtype == IEEE80211_FC0_SUBTYPE_BAR) {
		/* BAR TX whilst asleep; queue */
		DPRINTF(sc, ATH_DEBUG_SW_TX,
		    "%s: swq: TX'ing\n", __func__);
		(*queue_to_head) = 1;
		return (1);
	} else if ((ATH_NODE(ni)->an_is_powersave == 1)
	    && (type == IEEE80211_FC0_TYPE_MGT ||
	        type == IEEE80211_FC0_TYPE_CTL)) {
		/*
		 * Other control/mgmt frame; bypass software queuing
		 * for now!
		 */
		DPRINTF(sc, ATH_DEBUG_XMIT, 
		    "%s: %6D: Node is asleep; sending mgmt "
		    "(type=%d, subtype=%d)\n",
		    __func__, ni->ni_macaddr, ":", type, subtype);
		return (0);
	} else {
		return (1);
	}
}


/*
 * Transmit the given frame to the hardware.
 *
 * The frame must already be setup; rate control must already have
 * been done.
 *
 * XXX since the TXQ lock is being held here (and I dislike holding
 * it for this long when not doing software aggregation), later on
 * break this function into "setup_normal" and "xmit_normal". The
 * lock only needs to be held for the ath_tx_handoff call.
 *
 * XXX we don't update the leak count here - if we're doing
 * direct frame dispatch, we need to be able to do it without
 * decrementing the leak count (eg multicast queue frames.)
 */
static void
ath_tx_xmit_normal(struct ath_softc *sc, struct ath_txq *txq,
    struct ath_buf *bf)
{
	struct ath_node *an = ATH_NODE(bf->bf_node);
	struct ath_tid *tid = &an->an_tid[bf->bf_state.bfs_tid];

	ATH_TX_LOCK_ASSERT(sc);

	/*
	 * For now, just enable CLRDMASK. ath_tx_xmit_normal() does
	 * set a completion handler however it doesn't (yet) properly
	 * handle the strict ordering requirements needed for normal,
	 * non-aggregate session frames.
	 *
	 * Once this is implemented, only set CLRDMASK like this for
	 * frames that must go out - eg management/raw frames.
	 */
	bf->bf_state.bfs_txflags |= HAL_TXDESC_CLRDMASK;

	/* Setup the descriptor before handoff */
	ath_tx_do_ratelookup(sc, bf);
	ath_tx_calc_duration(sc, bf);
	ath_tx_calc_protection(sc, bf);
	ath_tx_set_rtscts(sc, bf);
	ath_tx_rate_fill_rcflags(sc, bf);
	ath_tx_setds(sc, bf);

	/* Track per-TID hardware queue depth correctly */
	tid->hwq_depth++;

	/* Assign the completion handler */
	bf->bf_comp = ath_tx_normal_comp;

	/* Hand off to hardware */
	ath_tx_handoff(sc, txq, bf);
}

/*
 * Do the basic frame setup stuff that's required before the frame
 * is added to a software queue.
 *
 * All frames get mostly the same treatment and it's done once.
 * Retransmits fiddle with things like the rate control setup,
 * setting the retransmit bit in the packet; doing relevant DMA/bus
 * syncing and relinking it (back) into the hardware TX queue.
 *
 * Note that this may cause the mbuf to be reallocated, so
 * m0 may not be valid.
 */
static int
ath_tx_normal_setup(struct ath_softc *sc, struct ieee80211_node *ni,
    struct ath_buf *bf, struct mbuf *m0, struct ath_txq *txq)
{
	struct ieee80211vap *vap = ni->ni_vap;
	struct ath_hal *ah = sc->sc_ah;
	struct ifnet *ifp = sc->sc_ifp;
	struct ieee80211com *ic = ifp->if_l2com;
	const struct chanAccParams *cap = &ic->ic_wme.wme_chanParams;
	int error, iswep, ismcast, isfrag, ismrr;
	int keyix, hdrlen, pktlen, try0 = 0;
	u_int8_t rix = 0, txrate = 0;
	struct ath_desc *ds;
	struct ieee80211_frame *wh;
	u_int subtype, flags;
	HAL_PKT_TYPE atype;
	const HAL_RATE_TABLE *rt;
	HAL_BOOL shortPreamble;
	struct ath_node *an;
	u_int pri;

	/*
	 * To ensure that both sequence numbers and the CCMP PN handling
	 * is "correct", make sure that the relevant TID queue is locked.
	 * Otherwise the CCMP PN and seqno may appear out of order, causing
	 * re-ordered frames to have out of order CCMP PN's, resulting
	 * in many, many frame drops.
	 */
	ATH_TX_LOCK_ASSERT(sc);

	wh = mtod(m0, struct ieee80211_frame *);
	iswep = wh->i_fc[1] & IEEE80211_FC1_PROTECTED;
	ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
	isfrag = m0->m_flags & M_FRAG;
	hdrlen = ieee80211_anyhdrsize(wh);
	/*
	 * Packet length must not include any
	 * pad bytes; deduct them here.
	 */
	pktlen = m0->m_pkthdr.len - (hdrlen & 3);

	/* Handle encryption twiddling if needed */
	if (! ath_tx_tag_crypto(sc, ni, m0, iswep, isfrag, &hdrlen,
	    &pktlen, &keyix)) {
		ath_freetx(m0);
		return EIO;
	}

	/* packet header may have moved, reset our local pointer */
	wh = mtod(m0, struct ieee80211_frame *);

	pktlen += IEEE80211_CRC_LEN;

	/*
	 * Load the DMA map so any coalescing is done.  This
	 * also calculates the number of descriptors we need.
	 */
	error = ath_tx_dmasetup(sc, bf, m0);
	if (error != 0)
		return error;
	bf->bf_node = ni;			/* NB: held reference */
	m0 = bf->bf_m;				/* NB: may have changed */
	wh = mtod(m0, struct ieee80211_frame *);

	/* setup descriptors */
	ds = bf->bf_desc;
	rt = sc->sc_currates;
	KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));

	/*
	 * NB: the 802.11 layer marks whether or not we should
	 * use short preamble based on the current mode and
	 * negotiated parameters.
	 */
	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
	    (ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE)) {
		shortPreamble = AH_TRUE;
		sc->sc_stats.ast_tx_shortpre++;
	} else {
		shortPreamble = AH_FALSE;
	}

	an = ATH_NODE(ni);
	//flags = HAL_TXDESC_CLRDMASK;		/* XXX needed for crypto errs */
	flags = 0;
	ismrr = 0;				/* default no multi-rate retry*/
	pri = M_WME_GETAC(m0);			/* honor classification */
	/* XXX use txparams instead of fixed values */
	/*
	 * Calculate Atheros packet type from IEEE80211 packet header,
	 * setup for rate calculations, and select h/w transmit queue.
	 */
	switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
	case IEEE80211_FC0_TYPE_MGT:
		subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
		if (subtype == IEEE80211_FC0_SUBTYPE_BEACON)
			atype = HAL_PKT_TYPE_BEACON;
		else if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
			atype = HAL_PKT_TYPE_PROBE_RESP;
		else if (subtype == IEEE80211_FC0_SUBTYPE_ATIM)
			atype = HAL_PKT_TYPE_ATIM;
		else
			atype = HAL_PKT_TYPE_NORMAL;	/* XXX */
		rix = an->an_mgmtrix;
		txrate = rt->info[rix].rateCode;
		if (shortPreamble)
			txrate |= rt->info[rix].shortPreamble;
		try0 = ATH_TXMGTTRY;
		flags |= HAL_TXDESC_INTREQ;	/* force interrupt */
		break;
	case IEEE80211_FC0_TYPE_CTL:
		atype = HAL_PKT_TYPE_PSPOLL;	/* stop setting of duration */
		rix = an->an_mgmtrix;
		txrate = rt->info[rix].rateCode;
		if (shortPreamble)
			txrate |= rt->info[rix].shortPreamble;
		try0 = ATH_TXMGTTRY;
		flags |= HAL_TXDESC_INTREQ;	/* force interrupt */
		break;
	case IEEE80211_FC0_TYPE_DATA:
		atype = HAL_PKT_TYPE_NORMAL;		/* default */
		/*
		 * Data frames: multicast frames go out at a fixed rate,
		 * EAPOL frames use the mgmt frame rate; otherwise consult
		 * the rate control module for the rate to use.
		 */
		if (ismcast) {
			rix = an->an_mcastrix;
			txrate = rt->info[rix].rateCode;
			if (shortPreamble)
				txrate |= rt->info[rix].shortPreamble;
			try0 = 1;
		} else if (m0->m_flags & M_EAPOL) {
			/* XXX? maybe always use long preamble? */
			rix = an->an_mgmtrix;
			txrate = rt->info[rix].rateCode;
			if (shortPreamble)
				txrate |= rt->info[rix].shortPreamble;
			try0 = ATH_TXMAXTRY;	/* XXX?too many? */
		} else {
			/*
			 * Do rate lookup on each TX, rather than using
			 * the hard-coded TX information decided here.
			 */
			ismrr = 1;
			bf->bf_state.bfs_doratelookup = 1;
		}
		if (cap->cap_wmeParams[pri].wmep_noackPolicy)
			flags |= HAL_TXDESC_NOACK;
		break;
	default:
		if_printf(ifp, "bogus frame type 0x%x (%s)\n",
			wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK, __func__);
		/* XXX statistic */
		/* XXX free tx dmamap */
		ath_freetx(m0);
		return EIO;
	}

	/*
	 * There are two known scenarios where the frame AC doesn't match
	 * what the destination TXQ is.
	 *
	 * + non-QoS frames (eg management?) that the net80211 stack has
	 *   assigned a higher AC to, but since it's a non-QoS TID, it's
	 *   being thrown into TID 16.  TID 16 gets the AC_BE queue.
	 *   It's quite possible that management frames should just be
	 *   direct dispatched to hardware rather than go via the software
	 *   queue; that should be investigated in the future.  There are
	 *   some specific scenarios where this doesn't make sense, mostly
	 *   surrounding ADDBA request/response - hence why that is special
	 *   cased.
	 *
	 * + Multicast frames going into the VAP mcast queue.  That shows up
	 *   as "TXQ 11".
	 *
	 * This driver should eventually support separate TID and TXQ locking,
	 * allowing for arbitrary AC frames to appear on arbitrary software
	 * queues, being queued to the "correct" hardware queue when needed.
	 */
#if 0
	if (txq != sc->sc_ac2q[pri]) {
		DPRINTF(sc, ATH_DEBUG_XMIT, 
		    "%s: txq=%p (%d), pri=%d, pri txq=%p (%d)\n",
		    __func__,
		    txq,
		    txq->axq_qnum,
		    pri,
		    sc->sc_ac2q[pri],
		    sc->sc_ac2q[pri]->axq_qnum);
	}
#endif

	/*
	 * Calculate miscellaneous flags.
	 */
	if (ismcast) {
		flags |= HAL_TXDESC_NOACK;	/* no ack on broad/multicast */
	} else if (pktlen > vap->iv_rtsthreshold &&
	    (ni->ni_ath_flags & IEEE80211_NODE_FF) == 0) {
		flags |= HAL_TXDESC_RTSENA;	/* RTS based on frame length */
		sc->sc_stats.ast_tx_rts++;
	}
	if (flags & HAL_TXDESC_NOACK)		/* NB: avoid double counting */
		sc->sc_stats.ast_tx_noack++;
#ifdef IEEE80211_SUPPORT_TDMA
	if (sc->sc_tdma && (flags & HAL_TXDESC_NOACK) == 0) {
		DPRINTF(sc, ATH_DEBUG_TDMA,
		    "%s: discard frame, ACK required w/ TDMA\n", __func__);
		sc->sc_stats.ast_tdma_ack++;
		/* XXX free tx dmamap */
		ath_freetx(m0);
		return EIO;
	}
#endif

	/*
	 * Determine if a tx interrupt should be generated for
	 * this descriptor.  We take a tx interrupt to reap
	 * descriptors when the h/w hits an EOL condition or
	 * when the descriptor is specifically marked to generate
	 * an interrupt.  We periodically mark descriptors in this
	 * way to insure timely replenishing of the supply needed
	 * for sending frames.  Defering interrupts reduces system
	 * load and potentially allows more concurrent work to be
	 * done but if done to aggressively can cause senders to
	 * backup.
	 *
	 * NB: use >= to deal with sc_txintrperiod changing
	 *     dynamically through sysctl.
	 */
	if (flags & HAL_TXDESC_INTREQ) {
		txq->axq_intrcnt = 0;
	} else if (++txq->axq_intrcnt >= sc->sc_txintrperiod) {
		flags |= HAL_TXDESC_INTREQ;
		txq->axq_intrcnt = 0;
	}

	/* This point forward is actual TX bits */

	/*
	 * At this point we are committed to sending the frame
	 * and we don't need to look at m_nextpkt; clear it in
	 * case this frame is part of frag chain.
	 */
	m0->m_nextpkt = NULL;

	if (IFF_DUMPPKTS(sc, ATH_DEBUG_XMIT))
		ieee80211_dump_pkt(ic, mtod(m0, const uint8_t *), m0->m_len,
		    sc->sc_hwmap[rix].ieeerate, -1);

	if (ieee80211_radiotap_active_vap(vap)) {
		u_int64_t tsf = ath_hal_gettsf64(ah);

		sc->sc_tx_th.wt_tsf = htole64(tsf);
		sc->sc_tx_th.wt_flags = sc->sc_hwmap[rix].txflags;
		if (iswep)
			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_WEP;
		if (isfrag)
			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_FRAG;
		sc->sc_tx_th.wt_rate = sc->sc_hwmap[rix].ieeerate;
		sc->sc_tx_th.wt_txpower = ieee80211_get_node_txpower(ni);
		sc->sc_tx_th.wt_antenna = sc->sc_txantenna;

		ieee80211_radiotap_tx(vap, m0);
	}

	/* Blank the legacy rate array */
	bzero(&bf->bf_state.bfs_rc, sizeof(bf->bf_state.bfs_rc));

	/*
	 * ath_buf_set_rate needs at least one rate/try to setup
	 * the rate scenario.
	 */
	bf->bf_state.bfs_rc[0].rix = rix;
	bf->bf_state.bfs_rc[0].tries = try0;
	bf->bf_state.bfs_rc[0].ratecode = txrate;

	/* Store the decided rate index values away */
	bf->bf_state.bfs_pktlen = pktlen;
	bf->bf_state.bfs_hdrlen = hdrlen;
	bf->bf_state.bfs_atype = atype;
	bf->bf_state.bfs_txpower = ieee80211_get_node_txpower(ni);
	bf->bf_state.bfs_txrate0 = txrate;
	bf->bf_state.bfs_try0 = try0;
	bf->bf_state.bfs_keyix = keyix;
	bf->bf_state.bfs_txantenna = sc->sc_txantenna;
	bf->bf_state.bfs_txflags = flags;
	bf->bf_state.bfs_shpream = shortPreamble;

	/* XXX this should be done in ath_tx_setrate() */
	bf->bf_state.bfs_ctsrate0 = 0;	/* ie, no hard-coded ctsrate */
	bf->bf_state.bfs_ctsrate = 0;	/* calculated later */
	bf->bf_state.bfs_ctsduration = 0;
	bf->bf_state.bfs_ismrr = ismrr;

	return 0;
}

/*
 * Queue a frame to the hardware or software queue.
 *
 * This can be called by the net80211 code.
 *
 * XXX what about locking? Or, push the seqno assign into the
 * XXX aggregate scheduler so its serialised?
 *
 * XXX When sending management frames via ath_raw_xmit(),
 *     should CLRDMASK be set unconditionally?
 */
int
ath_tx_start(struct ath_softc *sc, struct ieee80211_node *ni,
    struct ath_buf *bf, struct mbuf *m0)
{
	struct ieee80211vap *vap = ni->ni_vap;
	struct ath_vap *avp = ATH_VAP(vap);
	int r = 0;
	u_int pri;
	int tid;
	struct ath_txq *txq;
	int ismcast;
	const struct ieee80211_frame *wh;
	int is_ampdu, is_ampdu_tx, is_ampdu_pending;
	ieee80211_seq seqno;
	uint8_t type, subtype;
	int queue_to_head;

	ATH_TX_LOCK_ASSERT(sc);

	/*
	 * Determine the target hardware queue.
	 *
	 * For multicast frames, the txq gets overridden appropriately
	 * depending upon the state of PS.
	 *
	 * For any other frame, we do a TID/QoS lookup inside the frame
	 * to see what the TID should be. If it's a non-QoS frame, the
	 * AC and TID are overridden. The TID/TXQ code assumes the
	 * TID is on a predictable hardware TXQ, so we don't support
	 * having a node TID queued to multiple hardware TXQs.
	 * This may change in the future but would require some locking
	 * fudgery.
	 */
	pri = ath_tx_getac(sc, m0);
	tid = ath_tx_gettid(sc, m0);

	txq = sc->sc_ac2q[pri];
	wh = mtod(m0, struct ieee80211_frame *);
	ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
	subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;

	/*
	 * Enforce how deep the multicast queue can grow.
	 *
	 * XXX duplicated in ath_raw_xmit().
	 */
	if (IEEE80211_IS_MULTICAST(wh->i_addr1)) {
		if (sc->sc_cabq->axq_depth + sc->sc_cabq->fifo.axq_depth
		    > sc->sc_txq_mcastq_maxdepth) {
			sc->sc_stats.ast_tx_mcastq_overflow++;
			m_freem(m0);
			return (ENOBUFS);
		}
	}

	/*
	 * Enforce how deep the unicast queue can grow.
	 *
	 * If the node is in power save then we don't want
	 * the software queue to grow too deep, or a node may
	 * end up consuming all of the ath_buf entries.
	 *
	 * For now, only do this for DATA frames.
	 *
	 * We will want to cap how many management/control
	 * frames get punted to the software queue so it doesn't
	 * fill up.  But the correct solution isn't yet obvious.
	 * In any case, this check should at least let frames pass
	 * that we are direct-dispatching.
	 *
	 * XXX TODO: duplicate this to the raw xmit path!
	 */
	if (type == IEEE80211_FC0_TYPE_DATA &&
	    ATH_NODE(ni)->an_is_powersave &&
	    ATH_NODE(ni)->an_swq_depth >
	     sc->sc_txq_node_psq_maxdepth) {
		sc->sc_stats.ast_tx_node_psq_overflow++;
		m_freem(m0);
		return (ENOBUFS);
	}

	/* A-MPDU TX */
	is_ampdu_tx = ath_tx_ampdu_running(sc, ATH_NODE(ni), tid);
	is_ampdu_pending = ath_tx_ampdu_pending(sc, ATH_NODE(ni), tid);
	is_ampdu = is_ampdu_tx | is_ampdu_pending;

	DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: tid=%d, ac=%d, is_ampdu=%d\n",
	    __func__, tid, pri, is_ampdu);

	/* Set local packet state, used to queue packets to hardware */
	bf->bf_state.bfs_tid = tid;
	bf->bf_state.bfs_tx_queue = txq->axq_qnum;
	bf->bf_state.bfs_pri = pri;

#if 1
	/*
	 * When servicing one or more stations in power-save mode
	 * (or) if there is some mcast data waiting on the mcast
	 * queue (to prevent out of order delivery) multicast frames
	 * must be bufferd until after the beacon.
	 *
	 * TODO: we should lock the mcastq before we check the length.
	 */
	if (sc->sc_cabq_enable && ismcast && (vap->iv_ps_sta || avp->av_mcastq.axq_depth)) {
		txq = &avp->av_mcastq;
		/*
		 * Mark the frame as eventually belonging on the CAB
		 * queue, so the descriptor setup functions will
		 * correctly initialise the descriptor 'qcuId' field.
		 */
		bf->bf_state.bfs_tx_queue = sc->sc_cabq->axq_qnum;
	}
#endif

	/* Do the generic frame setup */
	/* XXX should just bzero the bf_state? */
	bf->bf_state.bfs_dobaw = 0;

	/* A-MPDU TX? Manually set sequence number */
	/*
	 * Don't do it whilst pending; the net80211 layer still
	 * assigns them.
	 */
	if (is_ampdu_tx) {
		/*
		 * Always call; this function will
		 * handle making sure that null data frames
		 * don't get a sequence number from the current
		 * TID and thus mess with the BAW.
		 */
		seqno = ath_tx_tid_seqno_assign(sc, ni, bf, m0);

		/*
		 * Don't add QoS NULL frames to the BAW.
		 */
		if (IEEE80211_QOS_HAS_SEQ(wh) &&
		    subtype != IEEE80211_FC0_SUBTYPE_QOS_NULL) {
			bf->bf_state.bfs_dobaw = 1;
		}
	}

	/*
	 * If needed, the sequence number has been assigned.
	 * Squirrel it away somewhere easy to get to.
	 */
	bf->bf_state.bfs_seqno = M_SEQNO_GET(m0) << IEEE80211_SEQ_SEQ_SHIFT;

	/* Is ampdu pending? fetch the seqno and print it out */
	if (is_ampdu_pending)
		DPRINTF(sc, ATH_DEBUG_SW_TX,
		    "%s: tid %d: ampdu pending, seqno %d\n",
		    __func__, tid, M_SEQNO_GET(m0));

	/* This also sets up the DMA map */
	r = ath_tx_normal_setup(sc, ni, bf, m0, txq);

	if (r != 0)
		goto done;

	/* At this point m0 could have changed! */
	m0 = bf->bf_m;

#if 1
	/*
	 * If it's a multicast frame, do a direct-dispatch to the
	 * destination hardware queue. Don't bother software
	 * queuing it.
	 */
	/*
	 * If it's a BAR frame, do a direct dispatch to the
	 * destination hardware queue. Don't bother software
	 * queuing it, as the TID will now be paused.
	 * Sending a BAR frame can occur from the net80211 txa timer
	 * (ie, retries) or from the ath txtask (completion call.)
	 * It queues directly to hardware because the TID is paused
	 * at this point (and won't be unpaused until the BAR has
	 * either been TXed successfully or max retries has been
	 * reached.)
	 */
	/*
	 * Until things are better debugged - if this node is asleep
	 * and we're sending it a non-BAR frame, direct dispatch it.
	 * Why? Because we need to figure out what's actually being
	 * sent - eg, during reassociation/reauthentication after
	 * the node (last) disappeared whilst asleep, the driver should
	 * have unpaused/unsleep'ed the node.  So until that is
	 * sorted out, use this workaround.
	 */
	if (txq == &avp->av_mcastq) {
		DPRINTF(sc, ATH_DEBUG_SW_TX,
		    "%s: bf=%p: mcastq: TX'ing\n", __func__, bf);
		bf->bf_state.bfs_txflags |= HAL_TXDESC_CLRDMASK;
		ath_tx_xmit_normal(sc, txq, bf);
	} else if (ath_tx_should_swq_frame(sc, ATH_NODE(ni), m0,
	    &queue_to_head)) {
		ath_tx_swq(sc, ni, txq, queue_to_head, bf);
	} else {
		bf->bf_state.bfs_txflags |= HAL_TXDESC_CLRDMASK;
		ath_tx_xmit_normal(sc, txq, bf);
	}
#else
	/*
	 * For now, since there's no software queue,
	 * direct-dispatch to the hardware.
	 */
	bf->bf_state.bfs_txflags |= HAL_TXDESC_CLRDMASK;
	/*
	 * Update the current leak count if
	 * we're leaking frames; and set the
	 * MORE flag as appropriate.
	 */
	ath_tx_leak_count_update(sc, tid, bf);
	ath_tx_xmit_normal(sc, txq, bf);
#endif
done:
	return 0;
}

static int
ath_tx_raw_start(struct ath_softc *sc, struct ieee80211_node *ni,
	struct ath_buf *bf, struct mbuf *m0,
	const struct ieee80211_bpf_params *params)
{
	struct ifnet *ifp = sc->sc_ifp;
	struct ieee80211com *ic = ifp->if_l2com;
	struct ath_hal *ah = sc->sc_ah;
	struct ieee80211vap *vap = ni->ni_vap;
	int error, ismcast, ismrr;
	int keyix, hdrlen, pktlen, try0, txantenna;
	u_int8_t rix, txrate;
	struct ieee80211_frame *wh;
	u_int flags;
	HAL_PKT_TYPE atype;
	const HAL_RATE_TABLE *rt;
	struct ath_desc *ds;
	u_int pri;
	int o_tid = -1;
	int do_override;
	uint8_t type, subtype;
	int queue_to_head;

	ATH_TX_LOCK_ASSERT(sc);

	wh = mtod(m0, struct ieee80211_frame *);
	ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
	hdrlen = ieee80211_anyhdrsize(wh);
	/*
	 * Packet length must not include any
	 * pad bytes; deduct them here.
	 */
	/* XXX honor IEEE80211_BPF_DATAPAD */
	pktlen = m0->m_pkthdr.len - (hdrlen & 3) + IEEE80211_CRC_LEN;

	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
	subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;

	ATH_KTR(sc, ATH_KTR_TX, 2,
	     "ath_tx_raw_start: ni=%p, bf=%p, raw", ni, bf);

	DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: ismcast=%d\n",
	    __func__, ismcast);

	pri = params->ibp_pri & 3;
	/* Override pri if the frame isn't a QoS one */
	if (! IEEE80211_QOS_HAS_SEQ(wh))
		pri = ath_tx_getac(sc, m0);

	/* XXX If it's an ADDBA, override the correct queue */
	do_override = ath_tx_action_frame_override_queue(sc, ni, m0, &o_tid);

	/* Map ADDBA to the correct priority */
	if (do_override) {
#if 0
		DPRINTF(sc, ATH_DEBUG_XMIT, 
		    "%s: overriding tid %d pri %d -> %d\n",
		    __func__, o_tid, pri, TID_TO_WME_AC(o_tid));
#endif
		pri = TID_TO_WME_AC(o_tid);
	}

	/* Handle encryption twiddling if needed */
	if (! ath_tx_tag_crypto(sc, ni,
	    m0, params->ibp_flags & IEEE80211_BPF_CRYPTO, 0,
	    &hdrlen, &pktlen, &keyix)) {
		ath_freetx(m0);
		return EIO;
	}
	/* packet header may have moved, reset our local pointer */
	wh = mtod(m0, struct ieee80211_frame *);

	/* Do the generic frame setup */
	/* XXX should just bzero the bf_state? */
	bf->bf_state.bfs_dobaw = 0;

	error = ath_tx_dmasetup(sc, bf, m0);
	if (error != 0)
		return error;
	m0 = bf->bf_m;				/* NB: may have changed */
	wh = mtod(m0, struct ieee80211_frame *);
	bf->bf_node = ni;			/* NB: held reference */

	/* Always enable CLRDMASK for raw frames for now.. */
	flags = HAL_TXDESC_CLRDMASK;		/* XXX needed for crypto errs */
	flags |= HAL_TXDESC_INTREQ;		/* force interrupt */
	if (params->ibp_flags & IEEE80211_BPF_RTS)
		flags |= HAL_TXDESC_RTSENA;
	else if (params->ibp_flags & IEEE80211_BPF_CTS) {
		/* XXX assume 11g/11n protection? */
		bf->bf_state.bfs_doprot = 1;
		flags |= HAL_TXDESC_CTSENA;
	}
	/* XXX leave ismcast to injector? */
	if ((params->ibp_flags & IEEE80211_BPF_NOACK) || ismcast)
		flags |= HAL_TXDESC_NOACK;

	rt = sc->sc_currates;
	KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
	rix = ath_tx_findrix(sc, params->ibp_rate0);
	txrate = rt->info[rix].rateCode;
	if (params->ibp_flags & IEEE80211_BPF_SHORTPRE)
		txrate |= rt->info[rix].shortPreamble;
	sc->sc_txrix = rix;
	try0 = params->ibp_try0;
	ismrr = (params->ibp_try1 != 0);
	txantenna = params->ibp_pri >> 2;
	if (txantenna == 0)			/* XXX? */
		txantenna = sc->sc_txantenna;

	/*
	 * Since ctsrate is fixed, store it away for later
	 * use when the descriptor fields are being set.
	 */
	if (flags & (HAL_TXDESC_RTSENA|HAL_TXDESC_CTSENA))
		bf->bf_state.bfs_ctsrate0 = params->ibp_ctsrate;

	/*
	 * NB: we mark all packets as type PSPOLL so the h/w won't
	 * set the sequence number, duration, etc.
	 */
	atype = HAL_PKT_TYPE_PSPOLL;

	if (IFF_DUMPPKTS(sc, ATH_DEBUG_XMIT))
		ieee80211_dump_pkt(ic, mtod(m0, caddr_t), m0->m_len,
		    sc->sc_hwmap[rix].ieeerate, -1);

	if (ieee80211_radiotap_active_vap(vap)) {
		u_int64_t tsf = ath_hal_gettsf64(ah);

		sc->sc_tx_th.wt_tsf = htole64(tsf);
		sc->sc_tx_th.wt_flags = sc->sc_hwmap[rix].txflags;
		if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED)
			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_WEP;
		if (m0->m_flags & M_FRAG)
			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_FRAG;
		sc->sc_tx_th.wt_rate = sc->sc_hwmap[rix].ieeerate;
		sc->sc_tx_th.wt_txpower = MIN(params->ibp_power,
		    ieee80211_get_node_txpower(ni));
		sc->sc_tx_th.wt_antenna = sc->sc_txantenna;

		ieee80211_radiotap_tx(vap, m0);
	}

	/*
	 * Formulate first tx descriptor with tx controls.
	 */
	ds = bf->bf_desc;
	/* XXX check return value? */

	/* Store the decided rate index values away */
	bf->bf_state.bfs_pktlen = pktlen;
	bf->bf_state.bfs_hdrlen = hdrlen;
	bf->bf_state.bfs_atype = atype;
	bf->bf_state.bfs_txpower = MIN(params->ibp_power,
	    ieee80211_get_node_txpower(ni));
	bf->bf_state.bfs_txrate0 = txrate;
	bf->bf_state.bfs_try0 = try0;
	bf->bf_state.bfs_keyix = keyix;
	bf->bf_state.bfs_txantenna = txantenna;
	bf->bf_state.bfs_txflags = flags;
	bf->bf_state.bfs_shpream =
	    !! (params->ibp_flags & IEEE80211_BPF_SHORTPRE);

	/* Set local packet state, used to queue packets to hardware */
	bf->bf_state.bfs_tid = WME_AC_TO_TID(pri);
	bf->bf_state.bfs_tx_queue = sc->sc_ac2q[pri]->axq_qnum;
	bf->bf_state.bfs_pri = pri;

	/* XXX this should be done in ath_tx_setrate() */
	bf->bf_state.bfs_ctsrate = 0;
	bf->bf_state.bfs_ctsduration = 0;
	bf->bf_state.bfs_ismrr = ismrr;

	/* Blank the legacy rate array */
	bzero(&bf->bf_state.bfs_rc, sizeof(bf->bf_state.bfs_rc));

	bf->bf_state.bfs_rc[0].rix =
	    ath_tx_findrix(sc, params->ibp_rate0);
	bf->bf_state.bfs_rc[0].tries = try0;
	bf->bf_state.bfs_rc[0].ratecode = txrate;

	if (ismrr) {
		int rix;

		rix = ath_tx_findrix(sc, params->ibp_rate1);
		bf->bf_state.bfs_rc[1].rix = rix;
		bf->bf_state.bfs_rc[1].tries = params->ibp_try1;

		rix = ath_tx_findrix(sc, params->ibp_rate2);
		bf->bf_state.bfs_rc[2].rix = rix;
		bf->bf_state.bfs_rc[2].tries = params->ibp_try2;

		rix = ath_tx_findrix(sc, params->ibp_rate3);
		bf->bf_state.bfs_rc[3].rix = rix;
		bf->bf_state.bfs_rc[3].tries = params->ibp_try3;
	}
	/*
	 * All the required rate control decisions have been made;
	 * fill in the rc flags.
	 */
	ath_tx_rate_fill_rcflags(sc, bf);

	/* NB: no buffered multicast in power save support */

	/*
	 * If we're overiding the ADDBA destination, dump directly
	 * into the hardware queue, right after any pending
	 * frames to that node are.
	 */
	DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: dooverride=%d\n",
	    __func__, do_override);

#if 1
	/*
	 * Put addba frames in the right place in the right TID/HWQ.
	 */
	if (do_override) {
		bf->bf_state.bfs_txflags |= HAL_TXDESC_CLRDMASK;
		/*
		 * XXX if it's addba frames, should we be leaking
		 * them out via the frame leak method?
		 * XXX for now let's not risk it; but we may wish
		 * to investigate this later.
		 */
		ath_tx_xmit_normal(sc, sc->sc_ac2q[pri], bf);
	} else if (ath_tx_should_swq_frame(sc, ATH_NODE(ni), m0,
	    &queue_to_head)) {
		/* Queue to software queue */
		ath_tx_swq(sc, ni, sc->sc_ac2q[pri], queue_to_head, bf);
	} else {
		bf->bf_state.bfs_txflags |= HAL_TXDESC_CLRDMASK;
		ath_tx_xmit_normal(sc, sc->sc_ac2q[pri], bf);
	}
#else
	/* Direct-dispatch to the hardware */
	bf->bf_state.bfs_txflags |= HAL_TXDESC_CLRDMASK;
	/*
	 * Update the current leak count if
	 * we're leaking frames; and set the
	 * MORE flag as appropriate.
	 */
	ath_tx_leak_count_update(sc, tid, bf);
	ath_tx_xmit_normal(sc, sc->sc_ac2q[pri], bf);
#endif
	return 0;
}

/*
 * Send a raw frame.
 *
 * This can be called by net80211.
 */
int
ath_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
	const struct ieee80211_bpf_params *params)
{
	struct ieee80211com *ic = ni->ni_ic;
	struct ifnet *ifp = ic->ic_ifp;
	struct ath_softc *sc = ifp->if_softc;
	struct ath_buf *bf;
	struct ieee80211_frame *wh = mtod(m, struct ieee80211_frame *);
	int error = 0;

	ATH_PCU_LOCK(sc);
	if (sc->sc_inreset_cnt > 0) {
		DPRINTF(sc, ATH_DEBUG_XMIT, 
		    "%s: sc_inreset_cnt > 0; bailing\n", __func__);
		error = EIO;
		ATH_PCU_UNLOCK(sc);
		goto bad0;
	}
	sc->sc_txstart_cnt++;
	ATH_PCU_UNLOCK(sc);

	ATH_TX_LOCK(sc);

	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || sc->sc_invalid) {
		DPRINTF(sc, ATH_DEBUG_XMIT, "%s: discard frame, %s", __func__,
		    (ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 ?
			"!running" : "invalid");
		m_freem(m);
		error = ENETDOWN;
		goto bad;
	}

	/*
	 * Enforce how deep the multicast queue can grow.
	 *
	 * XXX duplicated in ath_tx_start().
	 */
	if (IEEE80211_IS_MULTICAST(wh->i_addr1)) {
		if (sc->sc_cabq->axq_depth + sc->sc_cabq->fifo.axq_depth
		    > sc->sc_txq_mcastq_maxdepth) {
			sc->sc_stats.ast_tx_mcastq_overflow++;
			error = ENOBUFS;
		}

		if (error != 0) {
			m_freem(m);
			goto bad;
		}
	}

	/*
	 * Grab a TX buffer and associated resources.
	 */
	bf = ath_getbuf(sc, ATH_BUFTYPE_MGMT);
	if (bf == NULL) {
		sc->sc_stats.ast_tx_nobuf++;
		m_freem(m);
		error = ENOBUFS;
		goto bad;
	}
	ATH_KTR(sc, ATH_KTR_TX, 3, "ath_raw_xmit: m=%p, params=%p, bf=%p\n",
	    m, params,  bf);

	if (params == NULL) {
		/*
		 * Legacy path; interpret frame contents to decide
		 * precisely how to send the frame.
		 */
		if (ath_tx_start(sc, ni, bf, m)) {
			error = EIO;		/* XXX */
			goto bad2;
		}
	} else {
		/*
		 * Caller supplied explicit parameters to use in
		 * sending the frame.
		 */
		if (ath_tx_raw_start(sc, ni, bf, m, params)) {
			error = EIO;		/* XXX */
			goto bad2;
		}
	}
	sc->sc_wd_timer = 5;
	ifp->if_opackets++;
	sc->sc_stats.ast_tx_raw++;

	/*
	 * Update the TIM - if there's anything queued to the
	 * software queue and power save is enabled, we should
	 * set the TIM.
	 */
	ath_tx_update_tim(sc, ni, 1);

	ATH_TX_UNLOCK(sc);

	ATH_PCU_LOCK(sc);
	sc->sc_txstart_cnt--;
	ATH_PCU_UNLOCK(sc);

	return 0;
bad2:
	ATH_KTR(sc, ATH_KTR_TX, 3, "ath_raw_xmit: bad2: m=%p, params=%p, "
	    "bf=%p",
	    m,
	    params,
	    bf);
	ATH_TXBUF_LOCK(sc);
	ath_returnbuf_head(sc, bf);
	ATH_TXBUF_UNLOCK(sc);
bad:

	ATH_TX_UNLOCK(sc);

	ATH_PCU_LOCK(sc);
	sc->sc_txstart_cnt--;
	ATH_PCU_UNLOCK(sc);
bad0:
	ATH_KTR(sc, ATH_KTR_TX, 2, "ath_raw_xmit: bad0: m=%p, params=%p",
	    m, params);
	ifp->if_oerrors++;
	sc->sc_stats.ast_tx_raw_fail++;
	ieee80211_free_node(ni);

	return error;
}

/* Some helper functions */

/*
 * ADDBA (and potentially others) need to be placed in the same
 * hardware queue as the TID/node it's relating to. This is so
 * it goes out after any pending non-aggregate frames to the
 * same node/TID.
 *
 * If this isn't done, the ADDBA can go out before the frames
 * queued in hardware. Even though these frames have a sequence
 * number -earlier- than the ADDBA can be transmitted (but
 * no frames whose sequence numbers are after the ADDBA should
 * be!) they'll arrive after the ADDBA - and the receiving end
 * will simply drop them as being out of the BAW.
 *
 * The frames can't be appended to the TID software queue - it'll
 * never be sent out. So these frames have to be directly
 * dispatched to the hardware, rather than queued in software.
 * So if this function returns true, the TXQ has to be
 * overridden and it has to be directly dispatched.
 *
 * It's a dirty hack, but someone's gotta do it.
 */

/*
 * XXX doesn't belong here!
 */
static int
ieee80211_is_action(struct ieee80211_frame *wh)
{
	/* Type: Management frame? */
	if ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) !=
	    IEEE80211_FC0_TYPE_MGT)
		return 0;

	/* Subtype: Action frame? */
	if ((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) !=
	    IEEE80211_FC0_SUBTYPE_ACTION)
		return 0;

	return 1;
}

#define	MS(_v, _f)	(((_v) & _f) >> _f##_S)
/*
 * Return an alternate TID for ADDBA request frames.
 *
 * Yes, this likely should be done in the net80211 layer.
 */
static int
ath_tx_action_frame_override_queue(struct ath_softc *sc,
    struct ieee80211_node *ni,
    struct mbuf *m0, int *tid)
{
	struct ieee80211_frame *wh = mtod(m0, struct ieee80211_frame *);
	struct ieee80211_action_ba_addbarequest *ia;
	uint8_t *frm;
	uint16_t baparamset;

	/* Not action frame? Bail */
	if (! ieee80211_is_action(wh))
		return 0;

	/* XXX Not needed for frames we send? */
#if 0
	/* Correct length? */
	if (! ieee80211_parse_action(ni, m))
		return 0;
#endif

	/* Extract out action frame */
	frm = (u_int8_t *)&wh[1];
	ia = (struct ieee80211_action_ba_addbarequest *) frm;

	/* Not ADDBA? Bail */
	if (ia->rq_header.ia_category != IEEE80211_ACTION_CAT_BA)
		return 0;
	if (ia->rq_header.ia_action != IEEE80211_ACTION_BA_ADDBA_REQUEST)
		return 0;

	/* Extract TID, return it */
	baparamset = le16toh(ia->rq_baparamset);
	*tid = (int) MS(baparamset, IEEE80211_BAPS_TID);

	return 1;
}
#undef	MS

/* Per-node software queue operations */

/*
 * Add the current packet to the given BAW.
 * It is assumed that the current packet
 *
 * + fits inside the BAW;
 * + already has had a sequence number allocated.
 *
 * Since the BAW status may be modified by both the ath task and
 * the net80211/ifnet contexts, the TID must be locked.
 */
void
ath_tx_addto_baw(struct ath_softc *sc, struct ath_node *an,
    struct ath_tid *tid, struct ath_buf *bf)
{
	int index, cindex;
	struct ieee80211_tx_ampdu *tap;

	ATH_TX_LOCK_ASSERT(sc);

	if (bf->bf_state.bfs_isretried)
		return;

	tap = ath_tx_get_tx_tid(an, tid->tid);

	if (! bf->bf_state.bfs_dobaw) {
		DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
		    "%s: dobaw=0, seqno=%d, window %d:%d\n",
		    __func__, SEQNO(bf->bf_state.bfs_seqno),
		    tap->txa_start, tap->txa_wnd);
	}

	if (bf->bf_state.bfs_addedbaw)
		DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
		    "%s: re-added? tid=%d, seqno %d; window %d:%d; "
		    "baw head=%d tail=%d\n",
		    __func__, tid->tid, SEQNO(bf->bf_state.bfs_seqno),
		    tap->txa_start, tap->txa_wnd, tid->baw_head,
		    tid->baw_tail);

	/*
	 * Verify that the given sequence number is not outside of the
	 * BAW.  Complain loudly if that's the case.
	 */
	if (! BAW_WITHIN(tap->txa_start, tap->txa_wnd,
	    SEQNO(bf->bf_state.bfs_seqno))) {
		DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
		    "%s: bf=%p: outside of BAW?? tid=%d, seqno %d; window %d:%d; "
		    "baw head=%d tail=%d\n",
		    __func__, bf, tid->tid, SEQNO(bf->bf_state.bfs_seqno),
		    tap->txa_start, tap->txa_wnd, tid->baw_head,
		    tid->baw_tail);
	}

	/*
	 * ni->ni_txseqs[] is the currently allocated seqno.
	 * the txa state contains the current baw start.
	 */
	index  = ATH_BA_INDEX(tap->txa_start, SEQNO(bf->bf_state.bfs_seqno));
	cindex = (tid->baw_head + index) & (ATH_TID_MAX_BUFS - 1);
	DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
	    "%s: tid=%d, seqno %d; window %d:%d; index=%d cindex=%d "
	    "baw head=%d tail=%d\n",
	    __func__, tid->tid, SEQNO(bf->bf_state.bfs_seqno),
	    tap->txa_start, tap->txa_wnd, index, cindex, tid->baw_head,
	    tid->baw_tail);


#if 0
	assert(tid->tx_buf[cindex] == NULL);
#endif
	if (tid->tx_buf[cindex] != NULL) {
		DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
		    "%s: ba packet dup (index=%d, cindex=%d, "
		    "head=%d, tail=%d)\n",
		    __func__, index, cindex, tid->baw_head, tid->baw_tail);
		DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
		    "%s: BA bf: %p; seqno=%d ; new bf: %p; seqno=%d\n",
		    __func__,
		    tid->tx_buf[cindex],
		    SEQNO(tid->tx_buf[cindex]->bf_state.bfs_seqno),
		    bf,
		    SEQNO(bf->bf_state.bfs_seqno)
		);
	}
	tid->tx_buf[cindex] = bf;

	if (index >= ((tid->baw_tail - tid->baw_head) &
	    (ATH_TID_MAX_BUFS - 1))) {
		tid->baw_tail = cindex;
		INCR(tid->baw_tail, ATH_TID_MAX_BUFS);
	}
}

/*
 * Flip the BAW buffer entry over from the existing one to the new one.
 *
 * When software retransmitting a (sub-)frame, it is entirely possible that
 * the frame ath_buf is marked as BUSY and can't be immediately reused.
 * In that instance the buffer is cloned and the new buffer is used for
 * retransmit. We thus need to update the ath_buf slot in the BAW buf
 * tracking array to maintain consistency.
 */
static void
ath_tx_switch_baw_buf(struct ath_softc *sc, struct ath_node *an,
    struct ath_tid *tid, struct ath_buf *old_bf, struct ath_buf *new_bf)
{
	int index, cindex;
	struct ieee80211_tx_ampdu *tap;
	int seqno = SEQNO(old_bf->bf_state.bfs_seqno);

	ATH_TX_LOCK_ASSERT(sc);

	tap = ath_tx_get_tx_tid(an, tid->tid);
	index  = ATH_BA_INDEX(tap->txa_start, seqno);
	cindex = (tid->baw_head + index) & (ATH_TID_MAX_BUFS - 1);

	/*
	 * Just warn for now; if it happens then we should find out
	 * about it. It's highly likely the aggregation session will
	 * soon hang.
	 */
	if (old_bf->bf_state.bfs_seqno != new_bf->bf_state.bfs_seqno) {
		DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
		    "%s: retransmitted buffer"
		    " has mismatching seqno's, BA session may hang.\n",
		    __func__);
		DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
		    "%s: old seqno=%d, new_seqno=%d\n", __func__,
		    old_bf->bf_state.bfs_seqno, new_bf->bf_state.bfs_seqno);
	}

	if (tid->tx_buf[cindex] != old_bf) {
		DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
		    "%s: ath_buf pointer incorrect; "
		    " has m BA session may hang.\n", __func__);
		DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
		    "%s: old bf=%p, new bf=%p\n", __func__, old_bf, new_bf);
	}

	tid->tx_buf[cindex] = new_bf;
}

/*
 * seq_start - left edge of BAW
 * seq_next - current/next sequence number to allocate
 *
 * Since the BAW status may be modified by both the ath task and
 * the net80211/ifnet contexts, the TID must be locked.
 */
static void
ath_tx_update_baw(struct ath_softc *sc, struct ath_node *an,
    struct ath_tid *tid, const struct ath_buf *bf)
{
	int index, cindex;
	struct ieee80211_tx_ampdu *tap;
	int seqno = SEQNO(bf->bf_state.bfs_seqno);

	ATH_TX_LOCK_ASSERT(sc);

	tap = ath_tx_get_tx_tid(an, tid->tid);
	index  = ATH_BA_INDEX(tap->txa_start, seqno);
	cindex = (tid->baw_head + index) & (ATH_TID_MAX_BUFS - 1);

	DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
	    "%s: tid=%d, baw=%d:%d, seqno=%d, index=%d, cindex=%d, "
	    "baw head=%d, tail=%d\n",
	    __func__, tid->tid, tap->txa_start, tap->txa_wnd, seqno, index,
	    cindex, tid->baw_head, tid->baw_tail);

	/*
	 * If this occurs then we have a big problem - something else
	 * has slid tap->txa_start along without updating the BAW
	 * tracking start/end pointers. Thus the TX BAW state is now
	 * completely busted.
	 *
	 * But for now, since I haven't yet fixed TDMA and buffer cloning,
	 * it's quite possible that a cloned buffer is making its way
	 * here and causing it to fire off. Disable TDMA for now.
	 */
	if (tid->tx_buf[cindex] != bf) {
		DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
		    "%s: comp bf=%p, seq=%d; slot bf=%p, seqno=%d\n",
		    __func__, bf, SEQNO(bf->bf_state.bfs_seqno),
		    tid->tx_buf[cindex],
		    (tid->tx_buf[cindex] != NULL) ?
		      SEQNO(tid->tx_buf[cindex]->bf_state.bfs_seqno) : -1);
	}

	tid->tx_buf[cindex] = NULL;

	while (tid->baw_head != tid->baw_tail &&
	    !tid->tx_buf[tid->baw_head]) {
		INCR(tap->txa_start, IEEE80211_SEQ_RANGE);
		INCR(tid->baw_head, ATH_TID_MAX_BUFS);
	}
	DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
	    "%s: baw is now %d:%d, baw head=%d\n",
	    __func__, tap->txa_start, tap->txa_wnd, tid->baw_head);
}

static void
ath_tx_leak_count_update(struct ath_softc *sc, struct ath_tid *tid,
    struct ath_buf *bf)
{
	struct ieee80211_frame *wh;

	ATH_TX_LOCK_ASSERT(sc);

	if (tid->an->an_leak_count > 0) {
		wh = mtod(bf->bf_m, struct ieee80211_frame *);

		/*
		 * Update MORE based on the software/net80211 queue states.
		 */
		if ((tid->an->an_stack_psq > 0)
		    || (tid->an->an_swq_depth > 0))
			wh->i_fc[1] |= IEEE80211_FC1_MORE_DATA;
		else
			wh->i_fc[1] &= ~IEEE80211_FC1_MORE_DATA;

		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
		    "%s: %6D: leak count = %d, psq=%d, swq=%d, MORE=%d\n",
		    __func__,
		    tid->an->an_node.ni_macaddr,
		    ":",
		    tid->an->an_leak_count,
		    tid->an->an_stack_psq,
		    tid->an->an_swq_depth,
		    !! (wh->i_fc[1] & IEEE80211_FC1_MORE_DATA));

		/*
		 * Re-sync the underlying buffer.
		 */
		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
		    BUS_DMASYNC_PREWRITE);

		tid->an->an_leak_count --;
	}
}

static int
ath_tx_tid_can_tx_or_sched(struct ath_softc *sc, struct ath_tid *tid)
{

	ATH_TX_LOCK_ASSERT(sc);

	if (tid->an->an_leak_count > 0) {
		return (1);
	}
	if (tid->paused)
		return (0);
	return (1);
}

/*
 * Mark the current node/TID as ready to TX.
 *
 * This is done to make it easy for the software scheduler to
 * find which nodes have data to send.
 *
 * The TXQ lock must be held.
 */
void
ath_tx_tid_sched(struct ath_softc *sc, struct ath_tid *tid)
{
	struct ath_txq *txq = sc->sc_ac2q[tid->ac];

	ATH_TX_LOCK_ASSERT(sc);

	/*
	 * If we are leaking out a frame to this destination
	 * for PS-POLL, ensure that we allow scheduling to
	 * occur.
	 */
	if (! ath_tx_tid_can_tx_or_sched(sc, tid))
		return;		/* paused, can't schedule yet */

	if (tid->sched)
		return;		/* already scheduled */

	tid->sched = 1;

#if 0
	/*
	 * If this is a sleeping node we're leaking to, given
	 * it a higher priority.  This is so bad for QoS it hurts.
	 */
	if (tid->an->an_leak_count) {
		TAILQ_INSERT_HEAD(&txq->axq_tidq, tid, axq_qelem);
	} else {
		TAILQ_INSERT_TAIL(&txq->axq_tidq, tid, axq_qelem);
	}
#endif

	/*
	 * We can't do the above - it'll confuse the TXQ software
	 * scheduler which will keep checking the _head_ TID
	 * in the list to see if it has traffic.  If we queue
	 * a TID to the head of the list and it doesn't transmit,
	 * we'll check it again.
	 *
	 * So, get the rest of this leaking frames support working
	 * and reliable first and _then_ optimise it so they're
	 * pushed out in front of any other pending software
	 * queued nodes.
	 */
	TAILQ_INSERT_TAIL(&txq->axq_tidq, tid, axq_qelem);
}

/*
 * Mark the current node as no longer needing to be polled for
 * TX packets.
 *
 * The TXQ lock must be held.
 */
static void
ath_tx_tid_unsched(struct ath_softc *sc, struct ath_tid *tid)
{
	struct ath_txq *txq = sc->sc_ac2q[tid->ac];

	ATH_TX_LOCK_ASSERT(sc);

	if (tid->sched == 0)
		return;

	tid->sched = 0;
	TAILQ_REMOVE(&txq->axq_tidq, tid, axq_qelem);
}

/*
 * Assign a sequence number manually to the given frame.
 *
 * This should only be called for A-MPDU TX frames.
 */
static ieee80211_seq
ath_tx_tid_seqno_assign(struct ath_softc *sc, struct ieee80211_node *ni,
    struct ath_buf *bf, struct mbuf *m0)
{
	struct ieee80211_frame *wh;
	int tid, pri;
	ieee80211_seq seqno;
	uint8_t subtype;

	/* TID lookup */
	wh = mtod(m0, struct ieee80211_frame *);
	pri = M_WME_GETAC(m0);			/* honor classification */
	tid = WME_AC_TO_TID(pri);
	DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: pri=%d, tid=%d, qos has seq=%d\n",
	    __func__, pri, tid, IEEE80211_QOS_HAS_SEQ(wh));

	/* XXX Is it a control frame? Ignore */

	/* Does the packet require a sequence number? */
	if (! IEEE80211_QOS_HAS_SEQ(wh))
		return -1;

	ATH_TX_LOCK_ASSERT(sc);

	/*
	 * Is it a QOS NULL Data frame? Give it a sequence number from
	 * the default TID (IEEE80211_NONQOS_TID.)
	 *
	 * The RX path of everything I've looked at doesn't include the NULL
	 * data frame sequence number in the aggregation state updates, so
	 * assigning it a sequence number there will cause a BAW hole on the
	 * RX side.
	 */
	subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
	if (subtype == IEEE80211_FC0_SUBTYPE_QOS_NULL) {
		/* XXX no locking for this TID? This is a bit of a problem. */
		seqno = ni->ni_txseqs[IEEE80211_NONQOS_TID];
		INCR(ni->ni_txseqs[IEEE80211_NONQOS_TID], IEEE80211_SEQ_RANGE);
	} else {
		/* Manually assign sequence number */
		seqno = ni->ni_txseqs[tid];
		INCR(ni->ni_txseqs[tid], IEEE80211_SEQ_RANGE);
	}
	*(uint16_t *)&wh->i_seq[0] = htole16(seqno << IEEE80211_SEQ_SEQ_SHIFT);
	M_SEQNO_SET(m0, seqno);

	/* Return so caller can do something with it if needed */
	DPRINTF(sc, ATH_DEBUG_SW_TX, "%s:  -> seqno=%d\n", __func__, seqno);
	return seqno;
}

/*
 * Attempt to direct dispatch an aggregate frame to hardware.
 * If the frame is out of BAW, queue.
 * Otherwise, schedule it as a single frame.
 */
static void
ath_tx_xmit_aggr(struct ath_softc *sc, struct ath_node *an,
    struct ath_txq *txq, struct ath_buf *bf)
{
	struct ath_tid *tid = &an->an_tid[bf->bf_state.bfs_tid];
	struct ieee80211_tx_ampdu *tap;

	ATH_TX_LOCK_ASSERT(sc);

	tap = ath_tx_get_tx_tid(an, tid->tid);

	/* paused? queue */
	if (! ath_tx_tid_can_tx_or_sched(sc, tid)) {
		ATH_TID_INSERT_HEAD(tid, bf, bf_list);
		/* XXX don't sched - we're paused! */
		return;
	}

	/* outside baw? queue */
	if (bf->bf_state.bfs_dobaw &&
	    (! BAW_WITHIN(tap->txa_start, tap->txa_wnd,
	    SEQNO(bf->bf_state.bfs_seqno)))) {
		ATH_TID_INSERT_HEAD(tid, bf, bf_list);
		ath_tx_tid_sched(sc, tid);
		return;
	}

	/*
	 * This is a temporary check and should be removed once
	 * all the relevant code paths have been fixed.
	 *
	 * During aggregate retries, it's possible that the head
	 * frame will fail (which has the bfs_aggr and bfs_nframes
	 * fields set for said aggregate) and will be retried as
	 * a single frame.  In this instance, the values should
	 * be reset or the completion code will get upset with you.
	 */
	if (bf->bf_state.bfs_aggr != 0 || bf->bf_state.bfs_nframes > 1) {
		DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR,
		    "%s: bfs_aggr=%d, bfs_nframes=%d\n", __func__,
		    bf->bf_state.bfs_aggr, bf->bf_state.bfs_nframes);
		bf->bf_state.bfs_aggr = 0;
		bf->bf_state.bfs_nframes = 1;
	}

	/* Update CLRDMASK just before this frame is queued */
	ath_tx_update_clrdmask(sc, tid, bf);

	/* Direct dispatch to hardware */
	ath_tx_do_ratelookup(sc, bf);
	ath_tx_calc_duration(sc, bf);
	ath_tx_calc_protection(sc, bf);
	ath_tx_set_rtscts(sc, bf);
	ath_tx_rate_fill_rcflags(sc, bf);
	ath_tx_setds(sc, bf);

	/* Statistics */
	sc->sc_aggr_stats.aggr_low_hwq_single_pkt++;

	/* Track per-TID hardware queue depth correctly */
	tid->hwq_depth++;

	/* Add to BAW */
	if (bf->bf_state.bfs_dobaw) {
		ath_tx_addto_baw(sc, an, tid, bf);
		bf->bf_state.bfs_addedbaw = 1;
	}

	/* Set completion handler, multi-frame aggregate or not */
	bf->bf_comp = ath_tx_aggr_comp;

	/*
	 * Update the current leak count if
	 * we're leaking frames; and set the
	 * MORE flag as appropriate.
	 */
	ath_tx_leak_count_update(sc, tid, bf);

	/* Hand off to hardware */
	ath_tx_handoff(sc, txq, bf);
}

/*
 * Attempt to send the packet.
 * If the queue isn't busy, direct-dispatch.
 * If the queue is busy enough, queue the given packet on the
 *  relevant software queue.
 */
void
ath_tx_swq(struct ath_softc *sc, struct ieee80211_node *ni,
    struct ath_txq *txq, int queue_to_head, struct ath_buf *bf)
{
	struct ath_node *an = ATH_NODE(ni);
	struct ieee80211_frame *wh;
	struct ath_tid *atid;
	int pri, tid;
	struct mbuf *m0 = bf->bf_m;

	ATH_TX_LOCK_ASSERT(sc);

	/* Fetch the TID - non-QoS frames get assigned to TID 16 */
	wh = mtod(m0, struct ieee80211_frame *);
	pri = ath_tx_getac(sc, m0);
	tid = ath_tx_gettid(sc, m0);
	atid = &an->an_tid[tid];

	DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: bf=%p, pri=%d, tid=%d, qos=%d\n",
	    __func__, bf, pri, tid, IEEE80211_QOS_HAS_SEQ(wh));

	/* Set local packet state, used to queue packets to hardware */
	/* XXX potentially duplicate info, re-check */
	bf->bf_state.bfs_tid = tid;
	bf->bf_state.bfs_tx_queue = txq->axq_qnum;
	bf->bf_state.bfs_pri = pri;

	/*
	 * If the hardware queue isn't busy, queue it directly.
	 * If the hardware queue is busy, queue it.
	 * If the TID is paused or the traffic it outside BAW, software
	 * queue it.
	 *
	 * If the node is in power-save and we're leaking a frame,
	 * leak a single frame.
	 */
	if (! ath_tx_tid_can_tx_or_sched(sc, atid)) {
		/* TID is paused, queue */
		DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: paused\n", __func__);
		/*
		 * If the caller requested that it be sent at a high
		 * priority, queue it at the head of the list.
		 */
		if (queue_to_head)
			ATH_TID_INSERT_HEAD(atid, bf, bf_list);
		else
			ATH_TID_INSERT_TAIL(atid, bf, bf_list);
	} else if (ath_tx_ampdu_pending(sc, an, tid)) {
		/* AMPDU pending; queue */
		DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: pending\n", __func__);
		ATH_TID_INSERT_TAIL(atid, bf, bf_list);
		/* XXX sched? */
	} else if (ath_tx_ampdu_running(sc, an, tid)) {
		/* AMPDU running, attempt direct dispatch if possible */

		/*
		 * Always queue the frame to the tail of the list.
		 */
		ATH_TID_INSERT_TAIL(atid, bf, bf_list);

		/*
		 * If the hardware queue isn't busy, direct dispatch
		 * the head frame in the list.  Don't schedule the
		 * TID - let it build some more frames first?
		 *
		 * When running A-MPDU, always just check the hardware
		 * queue depth against the aggregate frame limit.
		 * We don't want to burst a large number of single frames
		 * out to the hardware; we want to aggressively hold back.
		 *
		 * Otherwise, schedule the TID.
		 */
		/* XXX TXQ locking */
		if (txq->axq_depth + txq->fifo.axq_depth < sc->sc_hwq_limit_aggr) {
			bf = ATH_TID_FIRST(atid);
			ATH_TID_REMOVE(atid, bf, bf_list);

			/*
			 * Ensure it's definitely treated as a non-AMPDU
			 * frame - this information may have been left
			 * over from a previous attempt.
			 */
			bf->bf_state.bfs_aggr = 0;
			bf->bf_state.bfs_nframes = 1;

			/* Queue to the hardware */
			ath_tx_xmit_aggr(sc, an, txq, bf);
			DPRINTF(sc, ATH_DEBUG_SW_TX,
			    "%s: xmit_aggr\n",
			    __func__);
		} else {
			DPRINTF(sc, ATH_DEBUG_SW_TX,
			    "%s: ampdu; swq'ing\n",
			    __func__);

			ath_tx_tid_sched(sc, atid);
		}
	/*
	 * If we're not doing A-MPDU, be prepared to direct dispatch
	 * up to both limits if possible.  This particular corner
	 * case may end up with packet starvation between aggregate
	 * traffic and non-aggregate traffic: we wnat to ensure
	 * that non-aggregate stations get a few frames queued to the
	 * hardware before the aggregate station(s) get their chance.
	 *
	 * So if you only ever see a couple of frames direct dispatched
	 * to the hardware from a non-AMPDU client, check both here
	 * and in the software queue dispatcher to ensure that those
	 * non-AMPDU stations get a fair chance to transmit.
	 */
	/* XXX TXQ locking */
	} else if ((txq->axq_depth + txq->fifo.axq_depth < sc->sc_hwq_limit_nonaggr) &&
		    (txq->axq_aggr_depth < sc->sc_hwq_limit_aggr)) {
		/* AMPDU not running, attempt direct dispatch */
		DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: xmit_normal\n", __func__);
		/* See if clrdmask needs to be set */
		ath_tx_update_clrdmask(sc, atid, bf);

		/*
		 * Update the current leak count if
		 * we're leaking frames; and set the
		 * MORE flag as appropriate.
		 */
		ath_tx_leak_count_update(sc, atid, bf);

		/*
		 * Dispatch the frame.
		 */
		ath_tx_xmit_normal(sc, txq, bf);
	} else {
		/* Busy; queue */
		DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: swq'ing\n", __func__);
		ATH_TID_INSERT_TAIL(atid, bf, bf_list);
		ath_tx_tid_sched(sc, atid);
	}
}

/*
 * Only set the clrdmask bit if none of the nodes are currently
 * filtered.
 *
 * XXX TODO: go through all the callers and check to see
 * which are being called in the context of looping over all
 * TIDs (eg, if all tids are being paused, resumed, etc.)
 * That'll avoid O(n^2) complexity here.
 */
static void
ath_tx_set_clrdmask(struct ath_softc *sc, struct ath_node *an)
{
	int i;

	ATH_TX_LOCK_ASSERT(sc);

	for (i = 0; i < IEEE80211_TID_SIZE; i++) {
		if (an->an_tid[i].isfiltered == 1)
			return;
	}
	an->clrdmask = 1;
}

/*
 * Configure the per-TID node state.
 *
 * This likely belongs in if_ath_node.c but I can't think of anywhere
 * else to put it just yet.
 *
 * This sets up the SLISTs and the mutex as appropriate.
 */
void
ath_tx_tid_init(struct ath_softc *sc, struct ath_node *an)
{
	int i, j;
	struct ath_tid *atid;

	for (i = 0; i < IEEE80211_TID_SIZE; i++) {
		atid = &an->an_tid[i];

		/* XXX now with this bzer(), is the field 0'ing needed? */
		bzero(atid, sizeof(*atid));

		TAILQ_INIT(&atid->tid_q);
		TAILQ_INIT(&atid->filtq.tid_q);
		atid->tid = i;
		atid->an = an;
		for (j = 0; j < ATH_TID_MAX_BUFS; j++)
			atid->tx_buf[j] = NULL;
		atid->baw_head = atid->baw_tail = 0;
		atid->paused = 0;
		atid->sched = 0;
		atid->hwq_depth = 0;
		atid->cleanup_inprogress = 0;
		if (i == IEEE80211_NONQOS_TID)
			atid->ac = ATH_NONQOS_TID_AC;
		else
			atid->ac = TID_TO_WME_AC(i);
	}
	an->clrdmask = 1;	/* Always start by setting this bit */
}

/*
 * Pause the current TID. This stops packets from being transmitted
 * on it.
 *
 * Since this is also called from upper layers as well as the driver,
 * it will get the TID lock.
 */
static void
ath_tx_tid_pause(struct ath_softc *sc, struct ath_tid *tid)
{

	ATH_TX_LOCK_ASSERT(sc);
	tid->paused++;
	DPRINTF(sc, ATH_DEBUG_SW_TX_CTRL, "%s: paused = %d\n",
	    __func__, tid->paused);
}

/*
 * Unpause the current TID, and schedule it if needed.
 */
static void
ath_tx_tid_resume(struct ath_softc *sc, struct ath_tid *tid)
{
	ATH_TX_LOCK_ASSERT(sc);

	/*
	 * There's some odd places where ath_tx_tid_resume() is called
	 * when it shouldn't be; this works around that particular issue
	 * until it's actually resolved.
	 */
	if (tid->paused == 0) {
		DPRINTF(sc, ATH_DEBUG_SW_TX_CTRL,
		    "%s: %6D: paused=0?\n", __func__,
		    tid->an->an_node.ni_macaddr, ":");
	} else {
		tid->paused--;
	}

	DPRINTF(sc, ATH_DEBUG_SW_TX_CTRL, "%s: unpaused = %d\n",
	    __func__, tid->paused);

	if (tid->paused)
		return;

	/*
	 * Override the clrdmask configuration for the next frame
	 * from this TID, just to get the ball rolling.
	 */
	ath_tx_set_clrdmask(sc, tid->an);

	if (tid->axq_depth == 0)
		return;

	/* XXX isfiltered shouldn't ever be 0 at this point */
	if (tid->isfiltered == 1) {
		DPRINTF(sc, ATH_DEBUG_SW_TX_CTRL, "%s: filtered?!\n",
		    __func__);
		return;
	}

	ath_tx_tid_sched(sc, tid);

	/*
	 * Queue the software TX scheduler.
	 */
	ath_tx_swq_kick(sc);
}

/*
 * Add the given ath_buf to the TID filtered frame list.
 * This requires the TID be filtered.
 */
static void
ath_tx_tid_filt_addbuf(struct ath_softc *sc, struct ath_tid *tid,
    struct ath_buf *bf)
{

	ATH_TX_LOCK_ASSERT(sc);

	if (!tid->isfiltered)
		DPRINTF(sc, ATH_DEBUG_SW_TX_FILT, "%s: not filtered?!\n",
		    __func__);

	DPRINTF(sc, ATH_DEBUG_SW_TX_FILT, "%s: bf=%p\n", __func__, bf);

	/* Set the retry bit and bump the retry counter */
	ath_tx_set_retry(sc, bf);
	sc->sc_stats.ast_tx_swfiltered++;

	ATH_TID_FILT_INSERT_TAIL(tid, bf, bf_list);
}

/*
 * Handle a completed filtered frame from the given TID.
 * This just enables/pauses the filtered frame state if required
 * and appends the filtered frame to the filtered queue.
 */
static void
ath_tx_tid_filt_comp_buf(struct ath_softc *sc, struct ath_tid *tid,
    struct ath_buf *bf)
{

	ATH_TX_LOCK_ASSERT(sc);

	if (! tid->isfiltered) {
		DPRINTF(sc, ATH_DEBUG_SW_TX_FILT, "%s: filter transition\n",
		    __func__);
		tid->isfiltered = 1;
		ath_tx_tid_pause(sc, tid);
	}

	/* Add the frame to the filter queue */
	ath_tx_tid_filt_addbuf(sc, tid, bf);
}

/*
 * Complete the filtered frame TX completion.
 *
 * If there are no more frames in the hardware queue, unpause/unfilter
 * the TID if applicable.  Otherwise we will wait for a node PS transition
 * to unfilter.
 */
static void
ath_tx_tid_filt_comp_complete(struct ath_softc *sc, struct ath_tid *tid)
{
	struct ath_buf *bf;

	ATH_TX_LOCK_ASSERT(sc);

	if (tid->hwq_depth != 0)
		return;

	DPRINTF(sc, ATH_DEBUG_SW_TX_FILT, "%s: hwq=0, transition back\n",
	    __func__);
	tid->isfiltered = 0;
	/* XXX ath_tx_tid_resume() also calls ath_tx_set_clrdmask()! */
	ath_tx_set_clrdmask(sc, tid->an);

	/* XXX this is really quite inefficient */
	while ((bf = ATH_TID_FILT_LAST(tid, ath_bufhead_s)) != NULL) {
		ATH_TID_FILT_REMOVE(tid, bf, bf_list);
		ATH_TID_INSERT_HEAD(tid, bf, bf_list);
	}

	ath_tx_tid_resume(sc, tid);
}

/*
 * Called when a single (aggregate or otherwise) frame is completed.
 *
 * Returns 1 if the buffer could be added to the filtered list
 * (cloned or otherwise), 0 if the buffer couldn't be added to the
 * filtered list (failed clone; expired retry) and the caller should
 * free it and handle it like a failure (eg by sending a BAR.)
 */
static int
ath_tx_tid_filt_comp_single(struct ath_softc *sc, struct ath_tid *tid,
    struct ath_buf *bf)
{
	struct ath_buf *nbf;
	int retval;

	ATH_TX_LOCK_ASSERT(sc);

	/*
	 * Don't allow a filtered frame to live forever.
	 */
	if (bf->bf_state.bfs_retries > SWMAX_RETRIES) {
		sc->sc_stats.ast_tx_swretrymax++;
		DPRINTF(sc, ATH_DEBUG_SW_TX_FILT,
		    "%s: bf=%p, seqno=%d, exceeded retries\n",
		    __func__,
		    bf,
		    bf->bf_state.bfs_seqno);
		return (0);
	}

	/*
	 * A busy buffer can't be added to the retry list.
	 * It needs to be cloned.
	 */
	if (bf->bf_flags & ATH_BUF_BUSY) {
		nbf = ath_tx_retry_clone(sc, tid->an, tid, bf);
		DPRINTF(sc, ATH_DEBUG_SW_TX_FILT,
		    "%s: busy buffer clone: %p -> %p\n",
		    __func__, bf, nbf);
	} else {
		nbf = bf;
	}

	if (nbf == NULL) {
		DPRINTF(sc, ATH_DEBUG_SW_TX_FILT,
		    "%s: busy buffer couldn't be cloned (%p)!\n",
		    __func__, bf);
		retval = 1;
	} else {
		ath_tx_tid_filt_comp_buf(sc, tid, nbf);
		retval = 0;
	}
	ath_tx_tid_filt_comp_complete(sc, tid);

	return (retval);
}

static void
ath_tx_tid_filt_comp_aggr(struct ath_softc *sc, struct ath_tid *tid,
    struct ath_buf *bf_first, ath_bufhead *bf_q)
{
	struct ath_buf *bf, *bf_next, *nbf;

	ATH_TX_LOCK_ASSERT(sc);

	bf = bf_first;
	while (bf) {
		bf_next = bf->bf_next;
		bf->bf_next = NULL;	/* Remove it from the aggr list */

		/*
		 * Don't allow a filtered frame to live forever.
		 */
		if (bf->bf_state.bfs_retries > SWMAX_RETRIES) {
			sc->sc_stats.ast_tx_swretrymax++;
			DPRINTF(sc, ATH_DEBUG_SW_TX_FILT,
			    "%s: bf=%p, seqno=%d, exceeded retries\n",
			    __func__,
			    bf,
			    bf->bf_state.bfs_seqno);
			TAILQ_INSERT_TAIL(bf_q, bf, bf_list);
			goto next;
		}

		if (bf->bf_flags & ATH_BUF_BUSY) {
			nbf = ath_tx_retry_clone(sc, tid->an, tid, bf);
			DPRINTF(sc, ATH_DEBUG_SW_TX_FILT,
			    "%s: busy buffer cloned: %p -> %p",
			    __func__, bf, nbf);
		} else {
			nbf = bf;
		}

		/*
		 * If the buffer couldn't be cloned, add it to bf_q;
		 * the caller will free the buffer(s) as required.
		 */
		if (nbf == NULL) {
			DPRINTF(sc, ATH_DEBUG_SW_TX_FILT,
			    "%s: buffer couldn't be cloned! (%p)\n",
			    __func__, bf);
			TAILQ_INSERT_TAIL(bf_q, bf, bf_list);
		} else {
			ath_tx_tid_filt_comp_buf(sc, tid, nbf);
		}
next:
		bf = bf_next;
	}

	ath_tx_tid_filt_comp_complete(sc, tid);
}

/*
 * Suspend the queue because we need to TX a BAR.
 */
static void
ath_tx_tid_bar_suspend(struct ath_softc *sc, struct ath_tid *tid)
{

	ATH_TX_LOCK_ASSERT(sc);

	DPRINTF(sc, ATH_DEBUG_SW_TX_BAR,
	    "%s: tid=%d, bar_wait=%d, bar_tx=%d, called\n",
	    __func__,
	    tid->tid,
	    tid->bar_wait,
	    tid->bar_tx);

	/* We shouldn't be called when bar_tx is 1 */
	if (tid->bar_tx) {
		DPRINTF(sc, ATH_DEBUG_SW_TX_BAR,
		    "%s: bar_tx is 1?!\n", __func__);
	}

	/* If we've already been called, just be patient. */
	if (tid->bar_wait)
		return;

	/* Wait! */
	tid->bar_wait = 1;

	/* Only one pause, no matter how many frames fail */
	ath_tx_tid_pause(sc, tid);
}

/*
 * We've finished with BAR handling - either we succeeded or
 * failed. Either way, unsuspend TX.
 */
static void
ath_tx_tid_bar_unsuspend(struct ath_softc *sc, struct ath_tid *tid)
{

	ATH_TX_LOCK_ASSERT(sc);

	DPRINTF(sc, ATH_DEBUG_SW_TX_BAR,
	    "%s: %6D: TID=%d, called\n",
	    __func__,
	    tid->an->an_node.ni_macaddr,
	    ":",
	    tid->tid);

	if (tid->bar_tx == 0 || tid->bar_wait == 0) {
		DPRINTF(sc, ATH_DEBUG_SW_TX_BAR,
		    "%s: %6D: TID=%d, bar_tx=%d, bar_wait=%d: ?\n",
		    __func__, tid->an->an_node.ni_macaddr, ":",
		    tid->tid, tid->bar_tx, tid->bar_wait);
	}

	tid->bar_tx = tid->bar_wait = 0;
	ath_tx_tid_resume(sc, tid);
}

/*
 * Return whether we're ready to TX a BAR frame.
 *
 * Requires the TID lock be held.
 */
static int
ath_tx_tid_bar_tx_ready(struct ath_softc *sc, struct ath_tid *tid)
{

	ATH_TX_LOCK_ASSERT(sc);

	if (tid->bar_wait == 0 || tid->hwq_depth > 0)
		return (0);

	DPRINTF(sc, ATH_DEBUG_SW_TX_BAR,
	    "%s: %6D: TID=%d, bar ready\n",
	    __func__,
	    tid->an->an_node.ni_macaddr,
	    ":",
	    tid->tid);

	return (1);
}

/*
 * Check whether the current TID is ready to have a BAR
 * TXed and if so, do the TX.
 *
 * Since the TID/TXQ lock can't be held during a call to
 * ieee80211_send_bar(), we have to do the dirty thing of unlocking it,
 * sending the BAR and locking it again.
 *
 * Eventually, the code to send the BAR should be broken out
 * from this routine so the lock doesn't have to be reacquired
 * just to be immediately dropped by the caller.
 */
static void
ath_tx_tid_bar_tx(struct ath_softc *sc, struct ath_tid *tid)
{
	struct ieee80211_tx_ampdu *tap;

	ATH_TX_LOCK_ASSERT(sc);

	DPRINTF(sc, ATH_DEBUG_SW_TX_BAR,
	    "%s: %6D: TID=%d, called\n",
	    __func__,
	    tid->an->an_node.ni_macaddr,
	    ":",
	    tid->tid);

	tap = ath_tx_get_tx_tid(tid->an, tid->tid);

	/*
	 * This is an error condition!
	 */
	if (tid->bar_wait == 0 || tid->bar_tx == 1) {
		DPRINTF(sc, ATH_DEBUG_SW_TX_BAR,
		    "%s: %6D: TID=%d, bar_tx=%d, bar_wait=%d: ?\n",
		    __func__, tid->an->an_node.ni_macaddr, ":",
		    tid->tid, tid->bar_tx, tid->bar_wait);
		return;
	}

	/* Don't do anything if we still have pending frames */
	if (tid->hwq_depth > 0) {
		DPRINTF(sc, ATH_DEBUG_SW_TX_BAR,
		    "%s: %6D: TID=%d, hwq_depth=%d, waiting\n",
		    __func__,
		    tid->an->an_node.ni_macaddr,
		    ":",
		    tid->tid,
		    tid->hwq_depth);
		return;
	}

	/* We're now about to TX */
	tid->bar_tx = 1;

	/*
	 * Override the clrdmask configuration for the next frame,
	 * just to get the ball rolling.
	 */
	ath_tx_set_clrdmask(sc, tid->an);

	/*
	 * Calculate new BAW left edge, now that all frames have either
	 * succeeded or failed.
	 *
	 * XXX verify this is _actually_ the valid value to begin at!
	 */
	DPRINTF(sc, ATH_DEBUG_SW_TX_BAR,
	    "%s: %6D: TID=%d, new BAW left edge=%d\n",
	    __func__,
	    tid->an->an_node.ni_macaddr,
	    ":",
	    tid->tid,
	    tap->txa_start);

	/* Try sending the BAR frame */
	/* We can't hold the lock here! */

	ATH_TX_UNLOCK(sc);
	if (ieee80211_send_bar(&tid->an->an_node, tap, tap->txa_start) == 0) {
		/* Success? Now we wait for notification that it's done */
		ATH_TX_LOCK(sc);
		return;
	}

	/* Failure? For now, warn loudly and continue */
	ATH_TX_LOCK(sc);
	DPRINTF(sc, ATH_DEBUG_SW_TX_BAR,
	    "%s: %6D: TID=%d, failed to TX BAR, continue!\n",
	    __func__, tid->an->an_node.ni_macaddr, ":",
	    tid->tid);
	ath_tx_tid_bar_unsuspend(sc, tid);
}

static void
ath_tx_tid_drain_pkt(struct ath_softc *sc, struct ath_node *an,
    struct ath_tid *tid, ath_bufhead *bf_cq, struct ath_buf *bf)
{

	ATH_TX_LOCK_ASSERT(sc);

	/*
	 * If the current TID is running AMPDU, update
	 * the BAW.
	 */
	if (ath_tx_ampdu_running(sc, an, tid->tid) &&
	    bf->bf_state.bfs_dobaw) {
		/*
		 * Only remove the frame from the BAW if it's
		 * been transmitted at least once; this means
		 * the frame was in the BAW to begin with.
		 */
		if (bf->bf_state.bfs_retries > 0) {
			ath_tx_update_baw(sc, an, tid, bf);
			bf->bf_state.bfs_dobaw = 0;
		}
#if 0
		/*
		 * This has become a non-fatal error now
		 */
		if (! bf->bf_state.bfs_addedbaw)
			DPRINTF(sc, ATH_DEBUG_SW_TX_BAW
			    "%s: wasn't added: seqno %d\n",
			    __func__, SEQNO(bf->bf_state.bfs_seqno));
#endif
	}

	/* Strip it out of an aggregate list if it was in one */
	bf->bf_next = NULL;

	/* Insert on the free queue to be freed by the caller */
	TAILQ_INSERT_TAIL(bf_cq, bf, bf_list);
}

static void
ath_tx_tid_drain_print(struct ath_softc *sc, struct ath_node *an,
    const char *pfx, struct ath_tid *tid, struct ath_buf *bf)
{
	struct ieee80211_node *ni = &an->an_node;
	struct ath_txq *txq;
	struct ieee80211_tx_ampdu *tap;

	txq = sc->sc_ac2q[tid->ac];
	tap = ath_tx_get_tx_tid(an, tid->tid);

	DPRINTF(sc, ATH_DEBUG_SW_TX,
	    "%s: %s: %6D: bf=%p: addbaw=%d, dobaw=%d, "
	    "seqno=%d, retry=%d\n",
	    __func__,
	    pfx,
	    ni->ni_macaddr,
	    ":",
	    bf,
	    bf->bf_state.bfs_addedbaw,
	    bf->bf_state.bfs_dobaw,
	    SEQNO(bf->bf_state.bfs_seqno),
	    bf->bf_state.bfs_retries);
	DPRINTF(sc, ATH_DEBUG_SW_TX,
	    "%s: %s: %6D: bf=%p: txq[%d] axq_depth=%d, axq_aggr_depth=%d\n",
	    __func__,
	    pfx,
	    ni->ni_macaddr,
	    ":",
	    bf,
	    txq->axq_qnum,
	    txq->axq_depth,
	    txq->axq_aggr_depth);
	DPRINTF(sc, ATH_DEBUG_SW_TX,
	    "%s: %s: %6D: bf=%p: tid txq_depth=%d hwq_depth=%d, bar_wait=%d, "
	      "isfiltered=%d\n",
	    __func__,
	    pfx,
	    ni->ni_macaddr,
	    ":",
	    bf,
	    tid->axq_depth,
	    tid->hwq_depth,
	    tid->bar_wait,
	    tid->isfiltered);
	DPRINTF(sc, ATH_DEBUG_SW_TX,
	    "%s: %s: %6D: tid %d: "
	    "sched=%d, paused=%d, "
	    "incomp=%d, baw_head=%d, "
	    "baw_tail=%d txa_start=%d, ni_txseqs=%d\n",
	     __func__,
	     pfx,
	     ni->ni_macaddr,
	     ":",
	     tid->tid,
	     tid->sched, tid->paused,
	     tid->incomp, tid->baw_head,
	     tid->baw_tail, tap == NULL ? -1 : tap->txa_start,
	     ni->ni_txseqs[tid->tid]);

	/* XXX Dump the frame, see what it is? */
	if (IFF_DUMPPKTS(sc, ATH_DEBUG_XMIT))
		ieee80211_dump_pkt(ni->ni_ic,
		    mtod(bf->bf_m, const uint8_t *),
		    bf->bf_m->m_len, 0, -1);
}

/*
 * Free any packets currently pending in the software TX queue.
 *
 * This will be called when a node is being deleted.
 *
 * It can also be called on an active node during an interface
 * reset or state transition.
 *
 * (From Linux/reference):
 *
 * TODO: For frame(s) that are in the retry state, we will reuse the
 * sequence number(s) without setting the retry bit. The
 * alternative is to give up on these and BAR the receiver's window
 * forward.
 */
static void
ath_tx_tid_drain(struct ath_softc *sc, struct ath_node *an,
    struct ath_tid *tid, ath_bufhead *bf_cq)
{
	struct ath_buf *bf;
	struct ieee80211_tx_ampdu *tap;
	struct ieee80211_node *ni = &an->an_node;
	int t;

	tap = ath_tx_get_tx_tid(an, tid->tid);

	ATH_TX_LOCK_ASSERT(sc);

	/* Walk the queue, free frames */
	t = 0;
	for (;;) {
		bf = ATH_TID_FIRST(tid);
		if (bf == NULL) {
			break;
		}

		if (t == 0) {
			ath_tx_tid_drain_print(sc, an, "norm", tid, bf);
			t = 1;
		}

		ATH_TID_REMOVE(tid, bf, bf_list);
		ath_tx_tid_drain_pkt(sc, an, tid, bf_cq, bf);
	}

	/* And now, drain the filtered frame queue */
	t = 0;
	for (;;) {
		bf = ATH_TID_FILT_FIRST(tid);
		if (bf == NULL)
			break;

		if (t == 0) {
			ath_tx_tid_drain_print(sc, an, "filt", tid, bf);
			t = 1;
		}

		ATH_TID_FILT_REMOVE(tid, bf, bf_list);
		ath_tx_tid_drain_pkt(sc, an, tid, bf_cq, bf);
	}

	/*
	 * Override the clrdmask configuration for the next frame
	 * in case there is some future transmission, just to get
	 * the ball rolling.
	 *
	 * This won't hurt things if the TID is about to be freed.
	 */
	ath_tx_set_clrdmask(sc, tid->an);

	/*
	 * Now that it's completed, grab the TID lock and update
	 * the sequence number and BAW window.
	 * Because sequence numbers have been assigned to frames
	 * that haven't been sent yet, it's entirely possible
	 * we'll be called with some pending frames that have not
	 * been transmitted.
	 *
	 * The cleaner solution is to do the sequence number allocation
	 * when the packet is first transmitted - and thus the "retries"
	 * check above would be enough to update the BAW/seqno.
	 */

	/* But don't do it for non-QoS TIDs */
	if (tap) {
#if 1
		DPRINTF(sc, ATH_DEBUG_SW_TX_CTRL,
		    "%s: %6D: node %p: TID %d: sliding BAW left edge to %d\n",
		    __func__,
		    ni->ni_macaddr,
		    ":",
		    an,
		    tid->tid,
		    tap->txa_start);
#endif
		ni->ni_txseqs[tid->tid] = tap->txa_start;
		tid->baw_tail = tid->baw_head;
	}
}

/*
 * Reset the TID state.  This must be only called once the node has
 * had its frames flushed from this TID, to ensure that no other
 * pause / unpause logic can kick in.
 */
static void
ath_tx_tid_reset(struct ath_softc *sc, struct ath_tid *tid)
{

#if 0
	tid->bar_wait = tid->bar_tx = tid->isfiltered = 0;
	tid->paused = tid->sched = tid->addba_tx_pending = 0;
	tid->incomp = tid->cleanup_inprogress = 0;
#endif

	/*
	 * If we have a bar_wait set, we need to unpause the TID
	 * here.  Otherwise once cleanup has finished, the TID won't
	 * have the right paused counter.
	 *
	 * XXX I'm not going through resume here - I don't want the
	 * node to be rescheuled just yet.  This however should be
	 * methodized!
	 */
	if (tid->bar_wait) {
		if (tid->paused > 0) {
			tid->paused --;
		}
	}

	/*
	 * XXX same with a currently filtered TID.
	 *
	 * Since this is being called during a flush, we assume that
	 * the filtered frame list is actually empty.
	 *
	 * XXX TODO: add in a check to ensure that the filtered queue
	 * depth is actually 0!
	 */
	if (tid->isfiltered) {
		if (tid->paused > 0) {
			tid->paused --;
		}
	}

	/*
	 * Clear BAR, filtered frames, scheduled and ADDBA pending.
	 * The TID may be going through cleanup from the last association
	 * where things in the BAW are still in the hardware queue.
	 */
	tid->bar_wait = 0;
	tid->bar_tx = 0;
	tid->isfiltered = 0;
	tid->sched = 0;
	tid->addba_tx_pending = 0;

	/*
	 * XXX TODO: it may just be enough to walk the HWQs and mark
	 * frames for that node as non-aggregate; or mark the ath_node
	 * with something that indicates that aggregation is no longer
	 * occuring.  Then we can just toss the BAW complaints and
	 * do a complete hard reset of state here - no pause, no
	 * complete counter, etc.
	 */

}

/*
 * Flush all software queued packets for the given node.
 *
 * This occurs when a completion handler frees the last buffer
 * for a node, and the node is thus freed. This causes the node
 * to be cleaned up, which ends up calling ath_tx_node_flush.
 */
void
ath_tx_node_flush(struct ath_softc *sc, struct ath_node *an)
{
	int tid;
	ath_bufhead bf_cq;
	struct ath_buf *bf;

	TAILQ_INIT(&bf_cq);

	ATH_KTR(sc, ATH_KTR_NODE, 1, "ath_tx_node_flush: flush node; ni=%p",
	    &an->an_node);

	ATH_TX_LOCK(sc);
	DPRINTF(sc, ATH_DEBUG_NODE,
	    "%s: %6D: flush; is_powersave=%d, stack_psq=%d, tim=%d, "
	    "swq_depth=%d, clrdmask=%d, leak_count=%d\n",
	    __func__,
	    an->an_node.ni_macaddr,
	    ":",
	    an->an_is_powersave,
	    an->an_stack_psq,
	    an->an_tim_set,
	    an->an_swq_depth,
	    an->clrdmask,
	    an->an_leak_count);

	for (tid = 0; tid < IEEE80211_TID_SIZE; tid++) {
		struct ath_tid *atid = &an->an_tid[tid];

		/* Free packets */
		ath_tx_tid_drain(sc, an, atid, &bf_cq);

		/* Remove this tid from the list of active tids */
		ath_tx_tid_unsched(sc, atid);

		/* Reset the per-TID pause, BAR, etc state */
		ath_tx_tid_reset(sc, atid);
	}

	/*
	 * Clear global leak count
	 */
	an->an_leak_count = 0;
	ATH_TX_UNLOCK(sc);

	/* Handle completed frames */
	while ((bf = TAILQ_FIRST(&bf_cq)) != NULL) {
		TAILQ_REMOVE(&bf_cq, bf, bf_list);
		ath_tx_default_comp(sc, bf, 0);
	}
}

/*
 * Drain all the software TXQs currently with traffic queued.
 */
void
ath_tx_txq_drain(struct ath_softc *sc, struct ath_txq *txq)
{
	struct ath_tid *tid;
	ath_bufhead bf_cq;
	struct ath_buf *bf;

	TAILQ_INIT(&bf_cq);
	ATH_TX_LOCK(sc);

	/*
	 * Iterate over all active tids for the given txq,
	 * flushing and unsched'ing them
	 */
	while (! TAILQ_EMPTY(&txq->axq_tidq)) {
		tid = TAILQ_FIRST(&txq->axq_tidq);
		ath_tx_tid_drain(sc, tid->an, tid, &bf_cq);
		ath_tx_tid_unsched(sc, tid);
	}

	ATH_TX_UNLOCK(sc);

	while ((bf = TAILQ_FIRST(&bf_cq)) != NULL) {
		TAILQ_REMOVE(&bf_cq, bf, bf_list);
		ath_tx_default_comp(sc, bf, 0);
	}
}

/*
 * Handle completion of non-aggregate session frames.
 *
 * This (currently) doesn't implement software retransmission of
 * non-aggregate frames!
 *
 * Software retransmission of non-aggregate frames needs to obey
 * the strict sequence number ordering, and drop any frames that
 * will fail this.
 *
 * For now, filtered frames and frame transmission will cause
 * all kinds of issues.  So we don't support them.
 *
 * So anyone queuing frames via ath_tx_normal_xmit() or
 * ath_tx_hw_queue_norm() must override and set CLRDMASK.
 */
void
ath_tx_normal_comp(struct ath_softc *sc, struct ath_buf *bf, int fail)
{
	struct ieee80211_node *ni = bf->bf_node;
	struct ath_node *an = ATH_NODE(ni);
	int tid = bf->bf_state.bfs_tid;
	struct ath_tid *atid = &an->an_tid[tid];
	struct ath_tx_status *ts = &bf->bf_status.ds_txstat;

	/* The TID state is protected behind the TXQ lock */
	ATH_TX_LOCK(sc);

	DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: bf=%p: fail=%d, hwq_depth now %d\n",
	    __func__, bf, fail, atid->hwq_depth - 1);

	atid->hwq_depth--;

#if 0
	/*
	 * If the frame was filtered, stick it on the filter frame
	 * queue and complain about it.  It shouldn't happen!
	 */
	if ((ts->ts_status & HAL_TXERR_FILT) ||
	    (ts->ts_status != 0 && atid->isfiltered)) {
		DPRINTF(sc, ATH_DEBUG_SW_TX,
		    "%s: isfiltered=%d, ts_status=%d: huh?\n",
		    __func__,
		    atid->isfiltered,
		    ts->ts_status);
		ath_tx_tid_filt_comp_buf(sc, atid, bf);
	}
#endif
	if (atid->isfiltered)
		DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: filtered?!\n", __func__);
	if (atid->hwq_depth < 0)
		DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: hwq_depth < 0: %d\n",
		    __func__, atid->hwq_depth);

	/*
	 * If the queue is filtered, potentially mark it as complete
	 * and reschedule it as needed.
	 *
	 * This is required as there may be a subsequent TX descriptor
	 * for this end-node that has CLRDMASK set, so it's quite possible
	 * that a filtered frame will be followed by a non-filtered
	 * (complete or otherwise) frame.
	 *
	 * XXX should we do this before we complete the frame?
	 */
	if (atid->isfiltered)
		ath_tx_tid_filt_comp_complete(sc, atid);
	ATH_TX_UNLOCK(sc);

	/*
	 * punt to rate control if we're not being cleaned up
	 * during a hw queue drain and the frame wanted an ACK.
	 */
	if (fail == 0 && ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0))
		ath_tx_update_ratectrl(sc, ni, bf->bf_state.bfs_rc,
		    ts, bf->bf_state.bfs_pktlen,
		    1, (ts->ts_status == 0) ? 0 : 1);

	ath_tx_default_comp(sc, bf, fail);
}

/*
 * Handle cleanup of aggregate session packets that aren't
 * an A-MPDU.
 *
 * There's no need to update the BAW here - the session is being
 * torn down.
 */
static void
ath_tx_comp_cleanup_unaggr(struct ath_softc *sc, struct ath_buf *bf)
{
	struct ieee80211_node *ni = bf->bf_node;
	struct ath_node *an = ATH_NODE(ni);
	int tid = bf->bf_state.bfs_tid;
	struct ath_tid *atid = &an->an_tid[tid];

	DPRINTF(sc, ATH_DEBUG_SW_TX_CTRL, "%s: TID %d: incomp=%d\n",
	    __func__, tid, atid->incomp);

	ATH_TX_LOCK(sc);
	atid->incomp--;
	if (atid->incomp == 0) {
		DPRINTF(sc, ATH_DEBUG_SW_TX_CTRL,
		    "%s: TID %d: cleaned up! resume!\n",
		    __func__, tid);
		atid->cleanup_inprogress = 0;
		ath_tx_tid_resume(sc, atid);
	}
	ATH_TX_UNLOCK(sc);

	ath_tx_default_comp(sc, bf, 0);
}

/*
 * Performs transmit side cleanup when TID changes from aggregated to
 * unaggregated.
 *
 * - Discard all retry frames from the s/w queue.
 * - Fix the tx completion function for all buffers in s/w queue.
 * - Count the number of unacked frames, and let transmit completion
 *   handle it later.
 *
 * The caller is responsible for pausing the TID and unpausing the
 * TID if no cleanup was required. Otherwise the cleanup path will
 * unpause the TID once the last hardware queued frame is completed.
 */
static void
ath_tx_tid_cleanup(struct ath_softc *sc, struct ath_node *an, int tid,
    ath_bufhead *bf_cq)
{
	struct ath_tid *atid = &an->an_tid[tid];
	struct ieee80211_tx_ampdu *tap;
	struct ath_buf *bf, *bf_next;

	ATH_TX_LOCK_ASSERT(sc);

	DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
	    "%s: TID %d: called\n", __func__, tid);

	/*
	 * Move the filtered frames to the TX queue, before
	 * we run off and discard/process things.
	 */
	/* XXX this is really quite inefficient */
	while ((bf = ATH_TID_FILT_LAST(atid, ath_bufhead_s)) != NULL) {
		ATH_TID_FILT_REMOVE(atid, bf, bf_list);
		ATH_TID_INSERT_HEAD(atid, bf, bf_list);
	}

	/*
	 * Update the frames in the software TX queue:
	 *
	 * + Discard retry frames in the queue
	 * + Fix the completion function to be non-aggregate
	 */
	bf = ATH_TID_FIRST(atid);
	while (bf) {
		if (bf->bf_state.bfs_isretried) {
			bf_next = TAILQ_NEXT(bf, bf_list);
			ATH_TID_REMOVE(atid, bf, bf_list);
			if (bf->bf_state.bfs_dobaw) {
				ath_tx_update_baw(sc, an, atid, bf);
				if (!bf->bf_state.bfs_addedbaw)
					DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
					    "%s: wasn't added: seqno %d\n",
					    __func__,
					    SEQNO(bf->bf_state.bfs_seqno));
			}
			bf->bf_state.bfs_dobaw = 0;
			/*
			 * Call the default completion handler with "fail" just
			 * so upper levels are suitably notified about this.
			 */
			TAILQ_INSERT_TAIL(bf_cq, bf, bf_list);
			bf = bf_next;
			continue;
		}
		/* Give these the default completion handler */
		bf->bf_comp = ath_tx_normal_comp;
		bf = TAILQ_NEXT(bf, bf_list);
	}

	/*
	 * Calculate what hardware-queued frames exist based
	 * on the current BAW size. Ie, what frames have been
	 * added to the TX hardware queue for this TID but
	 * not yet ACKed.
	 */
	tap = ath_tx_get_tx_tid(an, tid);
	/* Need the lock - fiddling with BAW */
	while (atid->baw_head != atid->baw_tail) {
		if (atid->tx_buf[atid->baw_head]) {
			atid->incomp++;
			atid->cleanup_inprogress = 1;
			atid->tx_buf[atid->baw_head] = NULL;
		}
		INCR(atid->baw_head, ATH_TID_MAX_BUFS);
		INCR(tap->txa_start, IEEE80211_SEQ_RANGE);
	}

	if (atid->cleanup_inprogress)
		DPRINTF(sc, ATH_DEBUG_SW_TX_CTRL,
		    "%s: TID %d: cleanup needed: %d packets\n",
		    __func__, tid, atid->incomp);

	/* Owner now must free completed frames */
}

static struct ath_buf *
ath_tx_retry_clone(struct ath_softc *sc, struct ath_node *an,
    struct ath_tid *tid, struct ath_buf *bf)
{
	struct ath_buf *nbf;
	int error;

	/*
	 * Clone the buffer.  This will handle the dma unmap and
	 * copy the node reference to the new buffer.  If this
	 * works out, 'bf' will have no DMA mapping, no mbuf
	 * pointer and no node reference.
	 */
	nbf = ath_buf_clone(sc, bf);

#if 0
	DPRINTF(sc, ATH_DEBUG_XMIT, "%s: ATH_BUF_BUSY; cloning\n",
	    __func__);
#endif

	if (nbf == NULL) {
		/* Failed to clone */
		DPRINTF(sc, ATH_DEBUG_XMIT,
		    "%s: failed to clone a busy buffer\n",
		    __func__);
		return NULL;
	}

	/* Setup the dma for the new buffer */
	error = ath_tx_dmasetup(sc, nbf, nbf->bf_m);
	if (error != 0) {
		DPRINTF(sc, ATH_DEBUG_XMIT,
		    "%s: failed to setup dma for clone\n",
		    __func__);
		/*
		 * Put this at the head of the list, not tail;
		 * that way it doesn't interfere with the
		 * busy buffer logic (which uses the tail of
		 * the list.)
		 */
		ATH_TXBUF_LOCK(sc);
		ath_returnbuf_head(sc, nbf);
		ATH_TXBUF_UNLOCK(sc);
		return NULL;
	}

	/* Update BAW if required, before we free the original buf */
	if (bf->bf_state.bfs_dobaw)
		ath_tx_switch_baw_buf(sc, an, tid, bf, nbf);

	/* Free original buffer; return new buffer */
	ath_freebuf(sc, bf);

	return nbf;
}

/*
 * Handle retrying an unaggregate frame in an aggregate
 * session.
 *
 * If too many retries occur, pause the TID, wait for
 * any further retransmits (as there's no reason why
 * non-aggregate frames in an aggregate session are
 * transmitted in-order; they just have to be in-BAW)
 * and then queue a BAR.
 */
static void
ath_tx_aggr_retry_unaggr(struct ath_softc *sc, struct ath_buf *bf)
{
	struct ieee80211_node *ni = bf->bf_node;
	struct ath_node *an = ATH_NODE(ni);
	int tid = bf->bf_state.bfs_tid;
	struct ath_tid *atid = &an->an_tid[tid];
	struct ieee80211_tx_ampdu *tap;

	ATH_TX_LOCK(sc);

	tap = ath_tx_get_tx_tid(an, tid);

	/*
	 * If the buffer is marked as busy, we can't directly
	 * reuse it. Instead, try to clone the buffer.
	 * If the clone is successful, recycle the old buffer.
	 * If the clone is unsuccessful, set bfs_retries to max
	 * to force the next bit of code to free the buffer
	 * for us.
	 */
	if ((bf->bf_state.bfs_retries < SWMAX_RETRIES) &&
	    (bf->bf_flags & ATH_BUF_BUSY)) {
		struct ath_buf *nbf;
		nbf = ath_tx_retry_clone(sc, an, atid, bf);
		if (nbf)
			/* bf has been freed at this point */
			bf = nbf;
		else
			bf->bf_state.bfs_retries = SWMAX_RETRIES + 1;
	}

	if (bf->bf_state.bfs_retries >= SWMAX_RETRIES) {
		DPRINTF(sc, ATH_DEBUG_SW_TX_RETRIES,
		    "%s: exceeded retries; seqno %d\n",
		    __func__, SEQNO(bf->bf_state.bfs_seqno));
		sc->sc_stats.ast_tx_swretrymax++;

		/* Update BAW anyway */
		if (bf->bf_state.bfs_dobaw) {
			ath_tx_update_baw(sc, an, atid, bf);
			if (! bf->bf_state.bfs_addedbaw)
				DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
				    "%s: wasn't added: seqno %d\n",
				    __func__, SEQNO(bf->bf_state.bfs_seqno));
		}
		bf->bf_state.bfs_dobaw = 0;

		/* Suspend the TX queue and get ready to send the BAR */
		ath_tx_tid_bar_suspend(sc, atid);

		/* Send the BAR if there are no other frames waiting */
		if (ath_tx_tid_bar_tx_ready(sc, atid))
			ath_tx_tid_bar_tx(sc, atid);

		ATH_TX_UNLOCK(sc);

		/* Free buffer, bf is free after this call */
		ath_tx_default_comp(sc, bf, 0);
		return;
	}

	/*
	 * This increments the retry counter as well as
	 * sets the retry flag in the ath_buf and packet
	 * body.
	 */
	ath_tx_set_retry(sc, bf);
	sc->sc_stats.ast_tx_swretries++;

	/*
	 * Insert this at the head of the queue, so it's
	 * retried before any current/subsequent frames.
	 */
	ATH_TID_INSERT_HEAD(atid, bf, bf_list);
	ath_tx_tid_sched(sc, atid);
	/* Send the BAR if there are no other frames waiting */
	if (ath_tx_tid_bar_tx_ready(sc, atid))
		ath_tx_tid_bar_tx(sc, atid);

	ATH_TX_UNLOCK(sc);
}

/*
 * Common code for aggregate excessive retry/subframe retry.
 * If retrying, queues buffers to bf_q. If not, frees the
 * buffers.
 *
 * XXX should unify this with ath_tx_aggr_retry_unaggr()
 */
static int
ath_tx_retry_subframe(struct ath_softc *sc, struct ath_buf *bf,
    ath_bufhead *bf_q)
{
	struct ieee80211_node *ni = bf->bf_node;
	struct ath_node *an = ATH_NODE(ni);
	int tid = bf->bf_state.bfs_tid;
	struct ath_tid *atid = &an->an_tid[tid];

	ATH_TX_LOCK_ASSERT(sc);

	/* XXX clr11naggr should be done for all subframes */
	ath_hal_clr11n_aggr(sc->sc_ah, bf->bf_desc);
	ath_hal_set11nburstduration(sc->sc_ah, bf->bf_desc, 0);

	/* ath_hal_set11n_virtualmorefrag(sc->sc_ah, bf->bf_desc, 0); */

	/*
	 * If the buffer is marked as busy, we can't directly
	 * reuse it. Instead, try to clone the buffer.
	 * If the clone is successful, recycle the old buffer.
	 * If the clone is unsuccessful, set bfs_retries to max
	 * to force the next bit of code to free the buffer
	 * for us.
	 */
	if ((bf->bf_state.bfs_retries < SWMAX_RETRIES) &&
	    (bf->bf_flags & ATH_BUF_BUSY)) {
		struct ath_buf *nbf;
		nbf = ath_tx_retry_clone(sc, an, atid, bf);
		if (nbf)
			/* bf has been freed at this point */
			bf = nbf;
		else
			bf->bf_state.bfs_retries = SWMAX_RETRIES + 1;
	}

	if (bf->bf_state.bfs_retries >= SWMAX_RETRIES) {
		sc->sc_stats.ast_tx_swretrymax++;
		DPRINTF(sc, ATH_DEBUG_SW_TX_RETRIES,
		    "%s: max retries: seqno %d\n",
		    __func__, SEQNO(bf->bf_state.bfs_seqno));
		ath_tx_update_baw(sc, an, atid, bf);
		if (!bf->bf_state.bfs_addedbaw)
			DPRINTF(sc, ATH_DEBUG_SW_TX_BAW,
			    "%s: wasn't added: seqno %d\n",
			    __func__, SEQNO(bf->bf_state.bfs_seqno));
		bf->bf_state.bfs_dobaw = 0;
		return 1;
	}

	ath_tx_set_retry(sc, bf);
	sc->sc_stats.ast_tx_swretries++;
	bf->bf_next = NULL;		/* Just to make sure */

	/* Clear the aggregate state */
	bf->bf_state.bfs_aggr = 0;
	bf->bf_state.bfs_ndelim = 0;	/* ??? needed? */
	bf->bf_state.bfs_nframes = 1;

	TAILQ_INSERT_TAIL(bf_q, bf, bf_list);
	return 0;
}

/*
 * error pkt completion for an aggregate destination
 */
static void
ath_tx_comp_aggr_error(struct ath_softc *sc, struct ath_buf *bf_first,
    struct ath_tid *tid)
{
	struct ieee80211_node *ni = bf_first->bf_node;
	struct ath_node *an = ATH_NODE(ni);
	struct ath_buf *bf_next, *bf;
	ath_bufhead bf_q;
	int drops = 0;
	struct ieee80211_tx_ampdu *tap;
	ath_bufhead bf_cq;

	TAILQ_INIT(&bf_q);
	TAILQ_INIT(&bf_cq);

	/*
	 * Update rate control - all frames have failed.
	 *
	 * XXX use the length in the first frame in the series;
	 * XXX just so things are consistent for now.
	 */
	ath_tx_update_ratectrl(sc, ni, bf_first->bf_state.bfs_rc,
	    &bf_first->bf_status.ds_txstat,
	    bf_first->bf_state.bfs_pktlen,
	    bf_first->bf_state.bfs_nframes, bf_first->bf_state.bfs_nframes);

	ATH_TX_LOCK(sc);
	tap = ath_tx_get_tx_tid(an, tid->tid);
	sc->sc_stats.ast_tx_aggr_failall++;

	/* Retry all subframes */
	bf = bf_first;
	while (bf) {
		bf_next = bf->bf_next;
		bf->bf_next = NULL;	/* Remove it from the aggr list */
		sc->sc_stats.ast_tx_aggr_fail++;
		if (ath_tx_retry_subframe(sc, bf, &bf_q)) {
			drops++;
			bf->bf_next = NULL;
			TAILQ_INSERT_TAIL(&bf_cq, bf, bf_list);
		}
		bf = bf_next;
	}

	/* Prepend all frames to the beginning of the queue */
	while ((bf = TAILQ_LAST(&bf_q, ath_bufhead_s)) != NULL) {
		TAILQ_REMOVE(&bf_q, bf, bf_list);
		ATH_TID_INSERT_HEAD(tid, bf, bf_list);
	}

	/*
	 * Schedule the TID to be re-tried.
	 */
	ath_tx_tid_sched(sc, tid);

	/*
	 * send bar if we dropped any frames
	 *
	 * Keep the txq lock held for now, as we need to ensure
	 * that ni_txseqs[] is consistent (as it's being updated
	 * in the ifnet TX context or raw TX context.)
	 */
	if (drops) {
		/* Suspend the TX queue and get ready to send the BAR */
		ath_tx_tid_bar_suspend(sc, tid);
	}

	/*
	 * Send BAR if required
	 */
	if (ath_tx_tid_bar_tx_ready(sc, tid))
		ath_tx_tid_bar_tx(sc, tid);

	ATH_TX_UNLOCK(sc);

	/* Complete frames which errored out */
	while ((bf = TAILQ_FIRST(&bf_cq)) != NULL) {
		TAILQ_REMOVE(&bf_cq, bf, bf_list);
		ath_tx_default_comp(sc, bf, 0);
	}
}

/*
 * Handle clean-up of packets from an aggregate list.
 *
 * There's no need to update the BAW here - the session is being
 * torn down.
 */
static void
ath_tx_comp_cleanup_aggr(struct ath_softc *sc, struct ath_buf *bf_first)
{
	struct ath_buf *bf, *bf_next;
	struct ieee80211_node *ni = bf_first->bf_node;
	struct ath_node *an = ATH_NODE(ni);
	int tid = bf_first->bf_state.bfs_tid;
	struct ath_tid *atid = &an->an_tid[tid];

	ATH_TX_LOCK(sc);

	/* update incomp */
	bf = bf_first;
	while (bf) {
		atid->incomp--;
		bf = bf->bf_next;
	}

	if (atid->incomp == 0) {
		DPRINTF(sc, ATH_DEBUG_SW_TX_CTRL,
		    "%s: TID %d: cleaned up! resume!\n",
		    __func__, tid);
		atid->cleanup_inprogress = 0;
		ath_tx_tid_resume(sc, atid);
	}

	/* Send BAR if required */
	/* XXX why would we send a BAR when transitioning to non-aggregation? */
	/*
	 * XXX TODO: we should likely just tear down the BAR state here,
	 * rather than sending a BAR.
	 */
	if (ath_tx_tid_bar_tx_ready(sc, atid))
		ath_tx_tid_bar_tx(sc, atid);

	ATH_TX_UNLOCK(sc);

	/* Handle frame completion */
	bf = bf_first;
	while (bf) {
		bf_next = bf->bf_next;
		ath_tx_default_comp(sc, bf, 1);
		bf = bf_next;
	}
}

/*
 * Handle completion of an set of aggregate frames.
 *
 * Note: the completion handler is the last descriptor in the aggregate,
 * not the last descriptor in the first frame.
 */
static void
ath_tx_aggr_comp_aggr(struct ath_softc *sc, struct ath_buf *bf_first,
    int fail)
{
	//struct ath_desc *ds = bf->bf_lastds;
	struct ieee80211_node *ni = bf_first->bf_node;
	struct ath_node *an = ATH_NODE(ni);
	int tid = bf_first->bf_state.bfs_tid;
	struct ath_tid *atid = &an->an_tid[tid];
	struct ath_tx_status ts;
	struct ieee80211_tx_ampdu *tap;
	ath_bufhead bf_q;
	ath_bufhead bf_cq;
	int seq_st, tx_ok;
	int hasba, isaggr;
	uint32_t ba[2];
	struct ath_buf *bf, *bf_next;
	int ba_index;
	int drops = 0;
	int nframes = 0, nbad = 0, nf;
	int pktlen;
	/* XXX there's too much on the stack? */
	struct ath_rc_series rc[ATH_RC_NUM];
	int txseq;

	DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR, "%s: called; hwq_depth=%d\n",
	    __func__, atid->hwq_depth);

	/*
	 * Take a copy; this may be needed -after- bf_first
	 * has been completed and freed.
	 */
	ts = bf_first->bf_status.ds_txstat;

	TAILQ_INIT(&bf_q);
	TAILQ_INIT(&bf_cq);

	/* The TID state is kept behind the TXQ lock */
	ATH_TX_LOCK(sc);

	atid->hwq_depth--;
	if (atid->hwq_depth < 0)
		DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR, "%s: hwq_depth < 0: %d\n",
		    __func__, atid->hwq_depth);

	/*
	 * If the TID is filtered, handle completing the filter
	 * transition before potentially kicking it to the cleanup
	 * function.
	 *
	 * XXX this is duplicate work, ew.
	 */
	if (atid->isfiltered)
		ath_tx_tid_filt_comp_complete(sc, atid);

	/*
	 * Punt cleanup to the relevant function, not our problem now
	 */
	if (atid->cleanup_inprogress) {
		if (atid->isfiltered)
			DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR,
			    "%s: isfiltered=1, normal_comp?\n",
			    __func__);
		ATH_TX_UNLOCK(sc);
		ath_tx_comp_cleanup_aggr(sc, bf_first);
		return;
	}

	/*
	 * If the frame is filtered, transition to filtered frame
	 * mode and add this to the filtered frame list.
	 *
	 * XXX TODO: figure out how this interoperates with
	 * BAR, pause and cleanup states.
	 */
	if ((ts.ts_status & HAL_TXERR_FILT) ||
	    (ts.ts_status != 0 && atid->isfiltered)) {
		if (fail != 0)
			DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR,
			    "%s: isfiltered=1, fail=%d\n", __func__, fail);
		ath_tx_tid_filt_comp_aggr(sc, atid, bf_first, &bf_cq);

		/* Remove from BAW */
		TAILQ_FOREACH_SAFE(bf, &bf_cq, bf_list, bf_next) {
			if (bf->bf_state.bfs_addedbaw)
				drops++;
			if (bf->bf_state.bfs_dobaw) {
				ath_tx_update_baw(sc, an, atid, bf);
				if (!bf->bf_state.bfs_addedbaw)
					DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR,
					    "%s: wasn't added: seqno %d\n",
					    __func__,
					    SEQNO(bf->bf_state.bfs_seqno));
			}
			bf->bf_state.bfs_dobaw = 0;
		}
		/*
		 * If any intermediate frames in the BAW were dropped when
		 * handling filtering things, send a BAR.
		 */
		if (drops)
			ath_tx_tid_bar_suspend(sc, atid);

		/*
		 * Finish up by sending a BAR if required and freeing
		 * the frames outside of the TX lock.
		 */
		goto finish_send_bar;
	}

	/*
	 * XXX for now, use the first frame in the aggregate for
	 * XXX rate control completion; it's at least consistent.
	 */
	pktlen = bf_first->bf_state.bfs_pktlen;

	/*
	 * Handle errors first!
	 *
	 * Here, handle _any_ error as a "exceeded retries" error.
	 * Later on (when filtered frames are to be specially handled)
	 * it'll have to be expanded.
	 */
#if 0
	if (ts.ts_status & HAL_TXERR_XRETRY) {
#endif
	if (ts.ts_status != 0) {
		ATH_TX_UNLOCK(sc);
		ath_tx_comp_aggr_error(sc, bf_first, atid);
		return;
	}

	tap = ath_tx_get_tx_tid(an, tid);

	/*
	 * extract starting sequence and block-ack bitmap
	 */
	/* XXX endian-ness of seq_st, ba? */
	seq_st = ts.ts_seqnum;
	hasba = !! (ts.ts_flags & HAL_TX_BA);
	tx_ok = (ts.ts_status == 0);
	isaggr = bf_first->bf_state.bfs_aggr;
	ba[0] = ts.ts_ba_low;
	ba[1] = ts.ts_ba_high;

	/*
	 * Copy the TX completion status and the rate control
	 * series from the first descriptor, as it may be freed
	 * before the rate control code can get its grubby fingers
	 * into things.
	 */
	memcpy(rc, bf_first->bf_state.bfs_rc, sizeof(rc));

	DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR,
	    "%s: txa_start=%d, tx_ok=%d, status=%.8x, flags=%.8x, "
	    "isaggr=%d, seq_st=%d, hasba=%d, ba=%.8x, %.8x\n",
	    __func__, tap->txa_start, tx_ok, ts.ts_status, ts.ts_flags,
	    isaggr, seq_st, hasba, ba[0], ba[1]);

	/*
	 * The reference driver doesn't do this; it simply ignores
	 * this check in its entirety.
	 *
	 * I've seen this occur when using iperf to send traffic
	 * out tid 1 - the aggregate frames are all marked as TID 1,
	 * but the TXSTATUS has TID=0.  So, let's just ignore this
	 * check.
	 */
#if 0
	/* Occasionally, the MAC sends a tx status for the wrong TID. */
	if (tid != ts.ts_tid) {
		DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR, "%s: tid %d != hw tid %d\n",
		    __func__, tid, ts.ts_tid);
		tx_ok = 0;
	}
#endif

	/* AR5416 BA bug; this requires an interface reset */
	if (isaggr && tx_ok && (! hasba)) {
		DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR,
		    "%s: AR5416 bug: hasba=%d; txok=%d, isaggr=%d, "
		    "seq_st=%d\n",
		    __func__, hasba, tx_ok, isaggr, seq_st);
		/* XXX TODO: schedule an interface reset */
#ifdef ATH_DEBUG
		ath_printtxbuf(sc, bf_first,
		    sc->sc_ac2q[atid->ac]->axq_qnum, 0, 0);
#endif
	}

	/*
	 * Walk the list of frames, figure out which ones were correctly
	 * sent and which weren't.
	 */
	bf = bf_first;
	nf = bf_first->bf_state.bfs_nframes;

	/* bf_first is going to be invalid once this list is walked */
	bf_first = NULL;

	/*
	 * Walk the list of completed frames and determine
	 * which need to be completed and which need to be
	 * retransmitted.
	 *
	 * For completed frames, the completion functions need
	 * to be called at the end of this function as the last
	 * node reference may free the node.
	 *
	 * Finally, since the TXQ lock can't be held during the
	 * completion callback (to avoid lock recursion),
	 * the completion calls have to be done outside of the
	 * lock.
	 */
	while (bf) {
		nframes++;
		ba_index = ATH_BA_INDEX(seq_st,
		    SEQNO(bf->bf_state.bfs_seqno));
		bf_next = bf->bf_next;
		bf->bf_next = NULL;	/* Remove it from the aggr list */

		DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR,
		    "%s: checking bf=%p seqno=%d; ack=%d\n",
		    __func__, bf, SEQNO(bf->bf_state.bfs_seqno),
		    ATH_BA_ISSET(ba, ba_index));

		if (tx_ok && ATH_BA_ISSET(ba, ba_index)) {
			sc->sc_stats.ast_tx_aggr_ok++;
			ath_tx_update_baw(sc, an, atid, bf);
			bf->bf_state.bfs_dobaw = 0;
			if (!bf->bf_state.bfs_addedbaw)
				DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR,
				    "%s: wasn't added: seqno %d\n",
				    __func__, SEQNO(bf->bf_state.bfs_seqno));
			bf->bf_next = NULL;
			TAILQ_INSERT_TAIL(&bf_cq, bf, bf_list);
		} else {
			sc->sc_stats.ast_tx_aggr_fail++;
			if (ath_tx_retry_subframe(sc, bf, &bf_q)) {
				drops++;
				bf->bf_next = NULL;
				TAILQ_INSERT_TAIL(&bf_cq, bf, bf_list);
			}
			nbad++;
		}
		bf = bf_next;
	}

	/*
	 * Now that the BAW updates have been done, unlock
	 *
	 * txseq is grabbed before the lock is released so we
	 * have a consistent view of what -was- in the BAW.
	 * Anything after this point will not yet have been
	 * TXed.
	 */
	txseq = tap->txa_start;
	ATH_TX_UNLOCK(sc);

	if (nframes != nf)
		DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR,
		    "%s: num frames seen=%d; bf nframes=%d\n",
		    __func__, nframes, nf);

	/*
	 * Now we know how many frames were bad, call the rate
	 * control code.
	 */
	if (fail == 0)
		ath_tx_update_ratectrl(sc, ni, rc, &ts, pktlen, nframes,
		    nbad);

	/*
	 * send bar if we dropped any frames
	 */
	if (drops) {
		/* Suspend the TX queue and get ready to send the BAR */
		ATH_TX_LOCK(sc);
		ath_tx_tid_bar_suspend(sc, atid);
		ATH_TX_UNLOCK(sc);
	}

	DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR,
	    "%s: txa_start now %d\n", __func__, tap->txa_start);

	ATH_TX_LOCK(sc);

	/* Prepend all frames to the beginning of the queue */
	while ((bf = TAILQ_LAST(&bf_q, ath_bufhead_s)) != NULL) {
		TAILQ_REMOVE(&bf_q, bf, bf_list);
		ATH_TID_INSERT_HEAD(atid, bf, bf_list);
	}

	/*
	 * Reschedule to grab some further frames.
	 */
	ath_tx_tid_sched(sc, atid);

	/*
	 * If the queue is filtered, re-schedule as required.
	 *
	 * This is required as there may be a subsequent TX descriptor
	 * for this end-node that has CLRDMASK set, so it's quite possible
	 * that a filtered frame will be followed by a non-filtered
	 * (complete or otherwise) frame.
	 *
	 * XXX should we do this before we complete the frame?
	 */
	if (atid->isfiltered)
		ath_tx_tid_filt_comp_complete(sc, atid);

finish_send_bar:

	/*
	 * Send BAR if required
	 */
	if (ath_tx_tid_bar_tx_ready(sc, atid))
		ath_tx_tid_bar_tx(sc, atid);

	ATH_TX_UNLOCK(sc);

	/* Do deferred completion */
	while ((bf = TAILQ_FIRST(&bf_cq)) != NULL) {
		TAILQ_REMOVE(&bf_cq, bf, bf_list);
		ath_tx_default_comp(sc, bf, 0);
	}
}

/*
 * Handle completion of unaggregated frames in an ADDBA
 * session.
 *
 * Fail is set to 1 if the entry is being freed via a call to
 * ath_tx_draintxq().
 */
static void
ath_tx_aggr_comp_unaggr(struct ath_softc *sc, struct ath_buf *bf, int fail)
{
	struct ieee80211_node *ni = bf->bf_node;
	struct ath_node *an = ATH_NODE(ni);
	int tid = bf->bf_state.bfs_tid;
	struct ath_tid *atid = &an->an_tid[tid];
	struct ath_tx_status ts;
	int drops = 0;

	/*
	 * Take a copy of this; filtering/cloning the frame may free the
	 * bf pointer.
	 */
	ts = bf->bf_status.ds_txstat;

	/*
	 * Update rate control status here, before we possibly
	 * punt to retry or cleanup.
	 *
	 * Do it outside of the TXQ lock.
	 */
	if (fail == 0 && ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0))
		ath_tx_update_ratectrl(sc, ni, bf->bf_state.bfs_rc,
		    &bf->bf_status.ds_txstat,
		    bf->bf_state.bfs_pktlen,
		    1, (ts.ts_status == 0) ? 0 : 1);

	/*
	 * This is called early so atid->hwq_depth can be tracked.
	 * This unfortunately means that it's released and regrabbed
	 * during retry and cleanup. That's rather inefficient.
	 */
	ATH_TX_LOCK(sc);

	if (tid == IEEE80211_NONQOS_TID)
		DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: TID=16!\n", __func__);

	DPRINTF(sc, ATH_DEBUG_SW_TX,
	    "%s: bf=%p: tid=%d, hwq_depth=%d, seqno=%d\n",
	    __func__, bf, bf->bf_state.bfs_tid, atid->hwq_depth,
	    SEQNO(bf->bf_state.bfs_seqno));

	atid->hwq_depth--;
	if (atid->hwq_depth < 0)
		DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: hwq_depth < 0: %d\n",
		    __func__, atid->hwq_depth);

	/*
	 * If the TID is filtered, handle completing the filter
	 * transition before potentially kicking it to the cleanup
	 * function.
	 */
	if (atid->isfiltered)
		ath_tx_tid_filt_comp_complete(sc, atid);

	/*
	 * If a cleanup is in progress, punt to comp_cleanup;
	 * rather than handling it here. It's thus their
	 * responsibility to clean up, call the completion
	 * function in net80211, etc.
	 */
	if (atid->cleanup_inprogress) {
		if (atid->isfiltered)
			DPRINTF(sc, ATH_DEBUG_SW_TX,
			    "%s: isfiltered=1, normal_comp?\n",
			    __func__);
		ATH_TX_UNLOCK(sc);
		DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: cleanup_unaggr\n",
		    __func__);
		ath_tx_comp_cleanup_unaggr(sc, bf);
		return;
	}

	/*
	 * XXX TODO: how does cleanup, BAR and filtered frame handling
	 * overlap?
	 *
	 * If the frame is filtered OR if it's any failure but
	 * the TID is filtered, the frame must be added to the
	 * filtered frame list.
	 *
	 * However - a busy buffer can't be added to the filtered
	 * list as it will end up being recycled without having
	 * been made available for the hardware.
	 */
	if ((ts.ts_status & HAL_TXERR_FILT) ||
	    (ts.ts_status != 0 && atid->isfiltered)) {
		int freeframe;

		if (fail != 0)
			DPRINTF(sc, ATH_DEBUG_SW_TX,
			    "%s: isfiltered=1, fail=%d\n",
			    __func__, fail);
		freeframe = ath_tx_tid_filt_comp_single(sc, atid, bf);
		if (freeframe) {
			/* Remove from BAW */
			if (bf->bf_state.bfs_addedbaw)
				drops++;
			if (bf->bf_state.bfs_dobaw) {
				ath_tx_update_baw(sc, an, atid, bf);
				if (!bf->bf_state.bfs_addedbaw)
					DPRINTF(sc, ATH_DEBUG_SW_TX,
					    "%s: wasn't added: seqno %d\n",
					    __func__, SEQNO(bf->bf_state.bfs_seqno));
			}
			bf->bf_state.bfs_dobaw = 0;
		}

		/*
		 * If the frame couldn't be filtered, treat it as a drop and
		 * prepare to send a BAR.
		 */
		if (freeframe && drops)
			ath_tx_tid_bar_suspend(sc, atid);

		/*
		 * Send BAR if required
		 */
		if (ath_tx_tid_bar_tx_ready(sc, atid))
			ath_tx_tid_bar_tx(sc, atid);

		ATH_TX_UNLOCK(sc);
		/*
		 * If freeframe is set, then the frame couldn't be
		 * cloned and bf is still valid.  Just complete/free it.
		 */
		if (freeframe)
			ath_tx_default_comp(sc, bf, fail);


		return;
	}
	/*
	 * Don't bother with the retry check if all frames
	 * are being failed (eg during queue deletion.)
	 */
#if 0
	if (fail == 0 && ts->ts_status & HAL_TXERR_XRETRY) {
#endif
	if (fail == 0 && ts.ts_status != 0) {
		ATH_TX_UNLOCK(sc);
		DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: retry_unaggr\n",
		    __func__);
		ath_tx_aggr_retry_unaggr(sc, bf);
		return;
	}

	/* Success? Complete */
	DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: TID=%d, seqno %d\n",
	    __func__, tid, SEQNO(bf->bf_state.bfs_seqno));
	if (bf->bf_state.bfs_dobaw) {
		ath_tx_update_baw(sc, an, atid, bf);
		bf->bf_state.bfs_dobaw = 0;
		if (!bf->bf_state.bfs_addedbaw)
			DPRINTF(sc, ATH_DEBUG_SW_TX,
			    "%s: wasn't added: seqno %d\n",
			    __func__, SEQNO(bf->bf_state.bfs_seqno));
	}

	/*
	 * If the queue is filtered, re-schedule as required.
	 *
	 * This is required as there may be a subsequent TX descriptor
	 * for this end-node that has CLRDMASK set, so it's quite possible
	 * that a filtered frame will be followed by a non-filtered
	 * (complete or otherwise) frame.
	 *
	 * XXX should we do this before we complete the frame?
	 */
	if (atid->isfiltered)
		ath_tx_tid_filt_comp_complete(sc, atid);

	/*
	 * Send BAR if required
	 */
	if (ath_tx_tid_bar_tx_ready(sc, atid))
		ath_tx_tid_bar_tx(sc, atid);

	ATH_TX_UNLOCK(sc);

	ath_tx_default_comp(sc, bf, fail);
	/* bf is freed at this point */
}

void
ath_tx_aggr_comp(struct ath_softc *sc, struct ath_buf *bf, int fail)
{
	if (bf->bf_state.bfs_aggr)
		ath_tx_aggr_comp_aggr(sc, bf, fail);
	else
		ath_tx_aggr_comp_unaggr(sc, bf, fail);
}

/*
 * Schedule some packets from the given node/TID to the hardware.
 *
 * This is the aggregate version.
 */
void
ath_tx_tid_hw_queue_aggr(struct ath_softc *sc, struct ath_node *an,
    struct ath_tid *tid)
{
	struct ath_buf *bf;
	struct ath_txq *txq = sc->sc_ac2q[tid->ac];
	struct ieee80211_tx_ampdu *tap;
	ATH_AGGR_STATUS status;
	ath_bufhead bf_q;

	DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: tid=%d\n", __func__, tid->tid);
	ATH_TX_LOCK_ASSERT(sc);

	/*
	 * XXX TODO: If we're called for a queue that we're leaking frames to,
	 * ensure we only leak one.
	 */

	tap = ath_tx_get_tx_tid(an, tid->tid);

	if (tid->tid == IEEE80211_NONQOS_TID)
		DPRINTF(sc, ATH_DEBUG_SW_TX, 
		    "%s: called for TID=NONQOS_TID?\n", __func__);

	for (;;) {
		status = ATH_AGGR_DONE;

		/*
		 * If the upper layer has paused the TID, don't
		 * queue any further packets.
		 *
		 * This can also occur from the completion task because
		 * of packet loss; but as its serialised with this code,
		 * it won't "appear" half way through queuing packets.
		 */
		if (! ath_tx_tid_can_tx_or_sched(sc, tid))
			break;

		bf = ATH_TID_FIRST(tid);
		if (bf == NULL) {
			break;
		}

		/*
		 * If the packet doesn't fall within the BAW (eg a NULL
		 * data frame), schedule it directly; continue.
		 */
		if (! bf->bf_state.bfs_dobaw) {
			DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR,
			    "%s: non-baw packet\n",
			    __func__);
			ATH_TID_REMOVE(tid, bf, bf_list);

			if (bf->bf_state.bfs_nframes > 1)
				DPRINTF(sc, ATH_DEBUG_SW_TX, 
				    "%s: aggr=%d, nframes=%d\n",
				    __func__,
				    bf->bf_state.bfs_aggr,
				    bf->bf_state.bfs_nframes);

			/*
			 * This shouldn't happen - such frames shouldn't
			 * ever have been queued as an aggregate in the
			 * first place.  However, make sure the fields
			 * are correctly setup just to be totally sure.
			 */
			bf->bf_state.bfs_aggr = 0;
			bf->bf_state.bfs_nframes = 1;

			/* Update CLRDMASK just before this frame is queued */
			ath_tx_update_clrdmask(sc, tid, bf);

			ath_tx_do_ratelookup(sc, bf);
			ath_tx_calc_duration(sc, bf);
			ath_tx_calc_protection(sc, bf);
			ath_tx_set_rtscts(sc, bf);
			ath_tx_rate_fill_rcflags(sc, bf);
			ath_tx_setds(sc, bf);
			ath_hal_clr11n_aggr(sc->sc_ah, bf->bf_desc);

			sc->sc_aggr_stats.aggr_nonbaw_pkt++;

			/* Queue the packet; continue */
			goto queuepkt;
		}

		TAILQ_INIT(&bf_q);

		/*
		 * Do a rate control lookup on the first frame in the
		 * list. The rate control code needs that to occur
		 * before it can determine whether to TX.
		 * It's inaccurate because the rate control code doesn't
		 * really "do" aggregate lookups, so it only considers
		 * the size of the first frame.
		 */
		ath_tx_do_ratelookup(sc, bf);
		bf->bf_state.bfs_rc[3].rix = 0;
		bf->bf_state.bfs_rc[3].tries = 0;

		ath_tx_calc_duration(sc, bf);
		ath_tx_calc_protection(sc, bf);

		ath_tx_set_rtscts(sc, bf);
		ath_tx_rate_fill_rcflags(sc, bf);

		status = ath_tx_form_aggr(sc, an, tid, &bf_q);

		DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR,
		    "%s: ath_tx_form_aggr() status=%d\n", __func__, status);

		/*
		 * No frames to be picked up - out of BAW
		 */
		if (TAILQ_EMPTY(&bf_q))
			break;

		/*
		 * This assumes that the descriptor list in the ath_bufhead
		 * are already linked together via bf_next pointers.
		 */
		bf = TAILQ_FIRST(&bf_q);

		if (status == ATH_AGGR_8K_LIMITED)
			sc->sc_aggr_stats.aggr_rts_aggr_limited++;

		/*
		 * If it's the only frame send as non-aggregate
		 * assume that ath_tx_form_aggr() has checked
		 * whether it's in the BAW and added it appropriately.
		 */
		if (bf->bf_state.bfs_nframes == 1) {
			DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR,
			    "%s: single-frame aggregate\n", __func__);

			/* Update CLRDMASK just before this frame is queued */
			ath_tx_update_clrdmask(sc, tid, bf);

			bf->bf_state.bfs_aggr = 0;
			bf->bf_state.bfs_ndelim = 0;
			ath_tx_setds(sc, bf);
			ath_hal_clr11n_aggr(sc->sc_ah, bf->bf_desc);
			if (status == ATH_AGGR_BAW_CLOSED)
				sc->sc_aggr_stats.aggr_baw_closed_single_pkt++;
			else
				sc->sc_aggr_stats.aggr_single_pkt++;
		} else {
			DPRINTF(sc, ATH_DEBUG_SW_TX_AGGR,
			    "%s: multi-frame aggregate: %d frames, "
			    "length %d\n",
			     __func__, bf->bf_state.bfs_nframes,
			    bf->bf_state.bfs_al);
			bf->bf_state.bfs_aggr = 1;
			sc->sc_aggr_stats.aggr_pkts[bf->bf_state.bfs_nframes]++;
			sc->sc_aggr_stats.aggr_aggr_pkt++;

			/* Update CLRDMASK just before this frame is queued */
			ath_tx_update_clrdmask(sc, tid, bf);

			/*
			 * Calculate the duration/protection as required.
			 */
			ath_tx_calc_duration(sc, bf);
			ath_tx_calc_protection(sc, bf);

			/*
			 * Update the rate and rtscts information based on the
			 * rate decision made by the rate control code;
			 * the first frame in the aggregate needs it.
			 */
			ath_tx_set_rtscts(sc, bf);

			/*
			 * Setup the relevant descriptor fields
			 * for aggregation. The first descriptor
			 * already points to the rest in the chain.
			 */
			ath_tx_setds_11n(sc, bf);

		}
	queuepkt:
		/* Set completion handler, multi-frame aggregate or not */
		bf->bf_comp = ath_tx_aggr_comp;

		if (bf->bf_state.bfs_tid == IEEE80211_NONQOS_TID)
			DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: TID=16?\n", __func__);

		/*
		 * Update leak count and frame config if were leaking frames.
		 *
		 * XXX TODO: it should update all frames in an aggregate
		 * correctly!
		 */
		ath_tx_leak_count_update(sc, tid, bf);

		/* Punt to txq */
		ath_tx_handoff(sc, txq, bf);

		/* Track outstanding buffer count to hardware */
		/* aggregates are "one" buffer */
		tid->hwq_depth++;

		/*
		 * Break out if ath_tx_form_aggr() indicated
		 * there can't be any further progress (eg BAW is full.)
		 * Checking for an empty txq is done above.
		 *
		 * XXX locking on txq here?
		 */
		/* XXX TXQ locking */
		if (txq->axq_aggr_depth >= sc->sc_hwq_limit_aggr ||
		    (status == ATH_AGGR_BAW_CLOSED ||
		     status == ATH_AGGR_LEAK_CLOSED))
			break;
	}
}

/*
 * Schedule some packets from the given node/TID to the hardware.
 *
 * XXX TODO: this routine doesn't enforce the maximum TXQ depth.
 * It just dumps frames into the TXQ.  We should limit how deep
 * the transmit queue can grow for frames dispatched to the given
 * TXQ.
 *
 * To avoid locking issues, either we need to own the TXQ lock
 * at this point, or we need to pass in the maximum frame count
 * from the caller.
 */
void
ath_tx_tid_hw_queue_norm(struct ath_softc *sc, struct ath_node *an,
    struct ath_tid *tid)
{
	struct ath_buf *bf;
	struct ath_txq *txq = sc->sc_ac2q[tid->ac];

	DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: node %p: TID %d: called\n",
	    __func__, an, tid->tid);

	ATH_TX_LOCK_ASSERT(sc);

	/* Check - is AMPDU pending or running? then print out something */
	if (ath_tx_ampdu_pending(sc, an, tid->tid))
		DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: tid=%d, ampdu pending?\n",
		    __func__, tid->tid);
	if (ath_tx_ampdu_running(sc, an, tid->tid))
		DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: tid=%d, ampdu running?\n",
		    __func__, tid->tid);

	for (;;) {

		/*
		 * If the upper layers have paused the TID, don't
		 * queue any further packets.
		 *
		 * XXX if we are leaking frames, make sure we decrement
		 * that counter _and_ we continue here.
		 */
		if (! ath_tx_tid_can_tx_or_sched(sc, tid))
			break;

		bf = ATH_TID_FIRST(tid);
		if (bf == NULL) {
			break;
		}

		ATH_TID_REMOVE(tid, bf, bf_list);

		/* Sanity check! */
		if (tid->tid != bf->bf_state.bfs_tid) {
			DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: bfs_tid %d !="
			    " tid %d\n", __func__, bf->bf_state.bfs_tid,
			    tid->tid);
		}
		/* Normal completion handler */
		bf->bf_comp = ath_tx_normal_comp;

		/*
		 * Override this for now, until the non-aggregate
		 * completion handler correctly handles software retransmits.
		 */
		bf->bf_state.bfs_txflags |= HAL_TXDESC_CLRDMASK;

		/* Update CLRDMASK just before this frame is queued */
		ath_tx_update_clrdmask(sc, tid, bf);

		/* Program descriptors + rate control */
		ath_tx_do_ratelookup(sc, bf);
		ath_tx_calc_duration(sc, bf);
		ath_tx_calc_protection(sc, bf);
		ath_tx_set_rtscts(sc, bf);
		ath_tx_rate_fill_rcflags(sc, bf);
		ath_tx_setds(sc, bf);

		/*
		 * Update the current leak count if
		 * we're leaking frames; and set the
		 * MORE flag as appropriate.
		 */
		ath_tx_leak_count_update(sc, tid, bf);

		/* Track outstanding buffer count to hardware */
		/* aggregates are "one" buffer */
		tid->hwq_depth++;

		/* Punt to hardware or software txq */
		ath_tx_handoff(sc, txq, bf);
	}
}

/*
 * Schedule some packets to the given hardware queue.
 *
 * This function walks the list of TIDs (ie, ath_node TIDs
 * with queued traffic) and attempts to schedule traffic
 * from them.
 *
 * TID scheduling is implemented as a FIFO, with TIDs being
 * added to the end of the queue after some frames have been
 * scheduled.
 */
void
ath_txq_sched(struct ath_softc *sc, struct ath_txq *txq)
{
	struct ath_tid *tid, *next, *last;

	ATH_TX_LOCK_ASSERT(sc);

	/*
	 * Don't schedule if the hardware queue is busy.
	 * This (hopefully) gives some more time to aggregate
	 * some packets in the aggregation queue.
	 *
	 * XXX It doesn't stop a parallel sender from sneaking
	 * in transmitting a frame!
	 */
	/* XXX TXQ locking */
	if (txq->axq_aggr_depth + txq->fifo.axq_depth >= sc->sc_hwq_limit_aggr) {
		sc->sc_aggr_stats.aggr_sched_nopkt++;
		return;
	}
	if (txq->axq_depth >= sc->sc_hwq_limit_nonaggr) {
		sc->sc_aggr_stats.aggr_sched_nopkt++;
		return;
	}

	last = TAILQ_LAST(&txq->axq_tidq, axq_t_s);

	TAILQ_FOREACH_SAFE(tid, &txq->axq_tidq, axq_qelem, next) {
		/*
		 * Suspend paused queues here; they'll be resumed
		 * once the addba completes or times out.
		 */
		DPRINTF(sc, ATH_DEBUG_SW_TX, "%s: tid=%d, paused=%d\n",
		    __func__, tid->tid, tid->paused);
		ath_tx_tid_unsched(sc, tid);
		/*
		 * This node may be in power-save and we're leaking
		 * a frame; be careful.
		 */
		if (! ath_tx_tid_can_tx_or_sched(sc, tid)) {
			continue;
		}
		if (ath_tx_ampdu_running(sc, tid->an, tid->tid))
			ath_tx_tid_hw_queue_aggr(sc, tid->an, tid);
		else
			ath_tx_tid_hw_queue_norm(sc, tid->an, tid);

		/* Not empty? Re-schedule */
		if (tid->axq_depth != 0)
			ath_tx_tid_sched(sc, tid);

		/*
		 * Give the software queue time to aggregate more
		 * packets.  If we aren't running aggregation then
		 * we should still limit the hardware queue depth.
		 */
		/* XXX TXQ locking */
		if (txq->axq_aggr_depth + txq->fifo.axq_depth >= sc->sc_hwq_limit_aggr) {
			break;
		}
		if (txq->axq_depth >= sc->sc_hwq_limit_nonaggr) {
			break;
		}

		/*
		 * If this was the last entry on the original list, stop.
		 * Otherwise nodes that have been rescheduled onto the end
		 * of the TID FIFO list will just keep being rescheduled.
		 *
		 * XXX What should we do about nodes that were paused
		 * but are pending a leaking frame in response to a ps-poll?
		 * They'll be put at the front of the list; so they'll
		 * prematurely trigger this condition! Ew.
		 */
		if (tid == last)
			break;
	}
}

/*
 * TX addba handling
 */

/*
 * Return net80211 TID struct pointer, or NULL for none
 */
struct ieee80211_tx_ampdu *
ath_tx_get_tx_tid(struct ath_node *an, int tid)
{
	struct ieee80211_node *ni = &an->an_node;
	struct ieee80211_tx_ampdu *tap;

	if (tid == IEEE80211_NONQOS_TID)
		return NULL;

	tap = &ni->ni_tx_ampdu[tid];
	return tap;
}

/*
 * Is AMPDU-TX running?
 */
static int
ath_tx_ampdu_running(struct ath_softc *sc, struct ath_node *an, int tid)
{
	struct ieee80211_tx_ampdu *tap;

	if (tid == IEEE80211_NONQOS_TID)
		return 0;

	tap = ath_tx_get_tx_tid(an, tid);
	if (tap == NULL)
		return 0;	/* Not valid; default to not running */

	return !! (tap->txa_flags & IEEE80211_AGGR_RUNNING);
}

/*
 * Is AMPDU-TX negotiation pending?
 */
static int
ath_tx_ampdu_pending(struct ath_softc *sc, struct ath_node *an, int tid)
{
	struct ieee80211_tx_ampdu *tap;

	if (tid == IEEE80211_NONQOS_TID)
		return 0;

	tap = ath_tx_get_tx_tid(an, tid);
	if (tap == NULL)
		return 0;	/* Not valid; default to not pending */

	return !! (tap->txa_flags & IEEE80211_AGGR_XCHGPEND);
}

/*
 * Is AMPDU-TX pending for the given TID?
 */


/*
 * Method to handle sending an ADDBA request.
 *
 * We tap this so the relevant flags can be set to pause the TID
 * whilst waiting for the response.
 *
 * XXX there's no timeout handler we can override?
 */
int
ath_addba_request(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap,
    int dialogtoken, int baparamset, int batimeout)
{
	struct ath_softc *sc = ni->ni_ic->ic_ifp->if_softc;
	int tid = tap->txa_tid;
	struct ath_node *an = ATH_NODE(ni);
	struct ath_tid *atid = &an->an_tid[tid];

	/*
	 * XXX danger Will Robinson!
	 *
	 * Although the taskqueue may be running and scheduling some more
	 * packets, these should all be _before_ the addba sequence number.
	 * However, net80211 will keep self-assigning sequence numbers
	 * until addba has been negotiated.
	 *
	 * In the past, these packets would be "paused" (which still works
	 * fine, as they're being scheduled to the driver in the same
	 * serialised method which is calling the addba request routine)
	 * and when the aggregation session begins, they'll be dequeued
	 * as aggregate packets and added to the BAW. However, now there's
	 * a "bf->bf_state.bfs_dobaw" flag, and this isn't set for these
	 * packets. Thus they never get included in the BAW tracking and
	 * this can cause the initial burst of packets after the addba
	 * negotiation to "hang", as they quickly fall outside the BAW.
	 *
	 * The "eventual" solution should be to tag these packets with
	 * dobaw. Although net80211 has given us a sequence number,
	 * it'll be "after" the left edge of the BAW and thus it'll
	 * fall within it.
	 */
	ATH_TX_LOCK(sc);
	/*
	 * This is a bit annoying.  Until net80211 HT code inherits some
	 * (any) locking, we may have this called in parallel BUT only
	 * one response/timeout will be called.  Grr.
	 */
	if (atid->addba_tx_pending == 0) {
		ath_tx_tid_pause(sc, atid);
		atid->addba_tx_pending = 1;
	}
	ATH_TX_UNLOCK(sc);

	DPRINTF(sc, ATH_DEBUG_SW_TX_CTRL,
	    "%s: %6D: called; dialogtoken=%d, baparamset=%d, batimeout=%d\n",
	    __func__,
	    ni->ni_macaddr,
	    ":",
	    dialogtoken, baparamset, batimeout);
	DPRINTF(sc, ATH_DEBUG_SW_TX_CTRL,
	    "%s: txa_start=%d, ni_txseqs=%d\n",
	    __func__, tap->txa_start, ni->ni_txseqs[tid]);

	return sc->sc_addba_request(ni, tap, dialogtoken, baparamset,
	    batimeout);
}

/*
 * Handle an ADDBA response.
 *
 * We unpause the queue so TX'ing can resume.
 *
 * Any packets TX'ed from this point should be "aggregate" (whether
 * aggregate or not) so the BAW is updated.
 *
 * Note! net80211 keeps self-assigning sequence numbers until
 * ampdu is negotiated. This means the initially-negotiated BAW left
 * edge won't match the ni->ni_txseq.
 *
 * So, being very dirty, the BAW left edge is "slid" here to match
 * ni->ni_txseq.
 *
 * What likely SHOULD happen is that all packets subsequent to the
 * addba request should be tagged as aggregate and queued as non-aggregate
 * frames; thus updating the BAW. For now though, I'll just slide the
 * window.
 */
int
ath_addba_response(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap,
    int status, int code, int batimeout)
{
	struct ath_softc *sc = ni->ni_ic->ic_ifp->if_softc;
	int tid = tap->txa_tid;
	struct ath_node *an = ATH_NODE(ni);
	struct ath_tid *atid = &an->an_tid[tid];
	int r;

	DPRINTF(sc, ATH_DEBUG_SW_TX_CTRL,
	    "%s: %6D: called; status=%d, code=%d, batimeout=%d\n", __func__,
	    ni->ni_macaddr,
	    ":",
	    status, code, batimeout);

	DPRINTF(sc, ATH_DEBUG_SW_TX_CTRL,
	    "%s: txa_start=%d, ni_txseqs=%d\n",
	    __func__, tap->txa_start, ni->ni_txseqs[tid]);

	/*
	 * Call this first, so the interface flags get updated
	 * before the TID is unpaused. Otherwise a race condition
	 * exists where the unpaused TID still doesn't yet have
	 * IEEE80211_AGGR_RUNNING set.
	 */
	r = sc->sc_addba_response(ni, tap, status, code, batimeout);

	ATH_TX_LOCK(sc);
	atid->addba_tx_pending = 0;
	/*
	 * XXX dirty!
	 * Slide the BAW left edge to wherever net80211 left it for us.
	 * Read above for more information.
	 */
	tap->txa_start = ni->ni_txseqs[tid];
	ath_tx_tid_resume(sc, atid);
	ATH_TX_UNLOCK(sc);
	return r;
}


/*
 * Stop ADDBA on a queue.
 *
 * This can be called whilst BAR TX is currently active on the queue,
 * so make sure this is unblocked before continuing.
 */
void
ath_addba_stop(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap)
{
	struct ath_softc *sc = ni->ni_ic->ic_ifp->if_softc;
	int tid = tap->txa_tid;
	struct ath_node *an = ATH_NODE(ni);
	struct ath_tid *atid = &an->an_tid[tid];
	ath_bufhead bf_cq;
	struct ath_buf *bf;

	DPRINTF(sc, ATH_DEBUG_SW_TX_CTRL, "%s: %6D: called\n",
	    __func__,
	    ni->ni_macaddr,
	    ":");

	/*
	 * Pause TID traffic early, so there aren't any races
	 * Unblock the pending BAR held traffic, if it's currently paused.
	 */
	ATH_TX_LOCK(sc);
	ath_tx_tid_pause(sc, atid);
	if (atid->bar_wait) {
		/*
		 * bar_unsuspend() expects bar_tx == 1, as it should be
		 * called from the TX completion path.  This quietens
		 * the warning.  It's cleared for us anyway.
		 */
		atid->bar_tx = 1;
		ath_tx_tid_bar_unsuspend(sc, atid);
	}
	ATH_TX_UNLOCK(sc);

	/* There's no need to hold the TXQ lock here */
	sc->sc_addba_stop(ni, tap);

	/*
	 * ath_tx_tid_cleanup will resume the TID if possible, otherwise
	 * it'll set the cleanup flag, and it'll be unpaused once
	 * things have been cleaned up.
	 */
	TAILQ_INIT(&bf_cq);
	ATH_TX_LOCK(sc);
	ath_tx_tid_cleanup(sc, an, tid, &bf_cq);
	/*
	 * Unpause the TID if no cleanup is required.
	 */
	if (! atid->cleanup_inprogress)
		ath_tx_tid_resume(sc, atid);
	ATH_TX_UNLOCK(sc);

	/* Handle completing frames and fail them */
	while ((bf = TAILQ_FIRST(&bf_cq)) != NULL) {
		TAILQ_REMOVE(&bf_cq, bf, bf_list);
		ath_tx_default_comp(sc, bf, 1);
	}

}

/*
 * Handle a node reassociation.
 *
 * We may have a bunch of frames queued to the hardware; those need
 * to be marked as cleanup.
 */
void
ath_tx_node_reassoc(struct ath_softc *sc, struct ath_node *an)
{
	struct ath_tid *tid;
	int i;
	ath_bufhead bf_cq;
	struct ath_buf *bf;

	TAILQ_INIT(&bf_cq);

	ATH_TX_UNLOCK_ASSERT(sc);

	ATH_TX_LOCK(sc);
	for (i = 0; i < IEEE80211_TID_SIZE; i++) {
		tid = &an->an_tid[i];
		if (tid->hwq_depth == 0)
			continue;
		ath_tx_tid_pause(sc, tid);
		DPRINTF(sc, ATH_DEBUG_NODE,
		    "%s: %6D: TID %d: cleaning up TID\n",
		    __func__,
		    an->an_node.ni_macaddr,
		    ":",
		    i);
		ath_tx_tid_cleanup(sc, an, i, &bf_cq);
		/*
		 * Unpause the TID if no cleanup is required.
		 */
		if (! tid->cleanup_inprogress)
			ath_tx_tid_resume(sc, tid);
	}
	ATH_TX_UNLOCK(sc);

	/* Handle completing frames and fail them */
	while ((bf = TAILQ_FIRST(&bf_cq)) != NULL) {
		TAILQ_REMOVE(&bf_cq, bf, bf_list);
		ath_tx_default_comp(sc, bf, 1);
	}
}

/*
 * Note: net80211 bar_timeout() doesn't call this function on BAR failure;
 * it simply tears down the aggregation session. Ew.
 *
 * It however will call ieee80211_ampdu_stop() which will call
 * ic->ic_addba_stop().
 *
 * XXX This uses a hard-coded max BAR count value; the whole
 * XXX BAR TX success or failure should be better handled!
 */
void
ath_bar_response(struct ieee80211_node *ni, struct ieee80211_tx_ampdu *tap,
    int status)
{
	struct ath_softc *sc = ni->ni_ic->ic_ifp->if_softc;
	int tid = tap->txa_tid;
	struct ath_node *an = ATH_NODE(ni);
	struct ath_tid *atid = &an->an_tid[tid];
	int attempts = tap->txa_attempts;

	DPRINTF(sc, ATH_DEBUG_SW_TX_BAR,
	    "%s: %6D: called; txa_tid=%d, atid->tid=%d, status=%d, attempts=%d\n",
	    __func__,
	    ni->ni_macaddr,
	    ":",
	    tap->txa_tid,
	    atid->tid,
	    status,
	    attempts);

	/* Note: This may update the BAW details */
	sc->sc_bar_response(ni, tap, status);

	/* Unpause the TID */
	/*
	 * XXX if this is attempt=50, the TID will be downgraded
	 * XXX to a non-aggregate session. So we must unpause the
	 * XXX TID here or it'll never be done.
	 *
	 * Also, don't call it if bar_tx/bar_wait are 0; something
	 * has beaten us to the punch? (XXX figure out what?)
	 */
	if (status == 0 || attempts == 50) {
		ATH_TX_LOCK(sc);
		if (atid->bar_tx == 0 || atid->bar_wait == 0)
			DPRINTF(sc, ATH_DEBUG_SW_TX_BAR,
			    "%s: huh? bar_tx=%d, bar_wait=%d\n",
			    __func__,
			    atid->bar_tx, atid->bar_wait);
		else
			ath_tx_tid_bar_unsuspend(sc, atid);
		ATH_TX_UNLOCK(sc);
	}
}

/*
 * This is called whenever the pending ADDBA request times out.
 * Unpause and reschedule the TID.
 */
void
ath_addba_response_timeout(struct ieee80211_node *ni,
    struct ieee80211_tx_ampdu *tap)
{
	struct ath_softc *sc = ni->ni_ic->ic_ifp->if_softc;
	int tid = tap->txa_tid;
	struct ath_node *an = ATH_NODE(ni);
	struct ath_tid *atid = &an->an_tid[tid];

	DPRINTF(sc, ATH_DEBUG_SW_TX_CTRL,
	    "%s: %6D: TID=%d, called; resuming\n",
	    __func__,
	    ni->ni_macaddr,
	    ":",
	    tid);

	ATH_TX_LOCK(sc);
	atid->addba_tx_pending = 0;
	ATH_TX_UNLOCK(sc);

	/* Note: This updates the aggregate state to (again) pending */
	sc->sc_addba_response_timeout(ni, tap);

	/* Unpause the TID; which reschedules it */
	ATH_TX_LOCK(sc);
	ath_tx_tid_resume(sc, atid);
	ATH_TX_UNLOCK(sc);
}

/*
 * Check if a node is asleep or not.
 */
int
ath_tx_node_is_asleep(struct ath_softc *sc, struct ath_node *an)
{

	ATH_TX_LOCK_ASSERT(sc);

	return (an->an_is_powersave);
}

/*
 * Mark a node as currently "in powersaving."
 * This suspends all traffic on the node.
 *
 * This must be called with the node/tx locks free.
 *
 * XXX TODO: the locking silliness below is due to how the node
 * locking currently works.  Right now, the node lock is grabbed
 * to do rate control lookups and these are done with the TX
 * queue lock held.  This means the node lock can't be grabbed
 * first here or a LOR will occur.
 *
 * Eventually (hopefully!) the TX path code will only grab
 * the TXQ lock when transmitting and the ath_node lock when
 * doing node/TID operations.  There are other complications -
 * the sched/unsched operations involve walking the per-txq
 * 'active tid' list and this requires both locks to be held.
 */
void
ath_tx_node_sleep(struct ath_softc *sc, struct ath_node *an)
{
	struct ath_tid *atid;
	struct ath_txq *txq;
	int tid;

	ATH_TX_UNLOCK_ASSERT(sc);

	/* Suspend all traffic on the node */
	ATH_TX_LOCK(sc);

	if (an->an_is_powersave) {
		DPRINTF(sc, ATH_DEBUG_XMIT,
		    "%s: %6D: node was already asleep!\n",
		    __func__, an->an_node.ni_macaddr, ":");
		ATH_TX_UNLOCK(sc);
		return;
	}

	for (tid = 0; tid < IEEE80211_TID_SIZE; tid++) {
		atid = &an->an_tid[tid];
		txq = sc->sc_ac2q[atid->ac];

		ath_tx_tid_pause(sc, atid);
	}

	/* Mark node as in powersaving */
	an->an_is_powersave = 1;

	ATH_TX_UNLOCK(sc);
}

/*
 * Mark a node as currently "awake."
 * This resumes all traffic to the node.
 */
void
ath_tx_node_wakeup(struct ath_softc *sc, struct ath_node *an)
{
	struct ath_tid *atid;
	struct ath_txq *txq;
	int tid;

	ATH_TX_UNLOCK_ASSERT(sc);

	ATH_TX_LOCK(sc);

	/* !? */
	if (an->an_is_powersave == 0) {
		ATH_TX_UNLOCK(sc);
		DPRINTF(sc, ATH_DEBUG_XMIT,
		    "%s: an=%p: node was already awake\n",
		    __func__, an);
		return;
	}

	/* Mark node as awake */
	an->an_is_powersave = 0;
	/*
	 * Clear any pending leaked frame requests
	 */
	an->an_leak_count = 0;

	for (tid = 0; tid < IEEE80211_TID_SIZE; tid++) {
		atid = &an->an_tid[tid];
		txq = sc->sc_ac2q[atid->ac];

		ath_tx_tid_resume(sc, atid);
	}
	ATH_TX_UNLOCK(sc);
}

static int
ath_legacy_dma_txsetup(struct ath_softc *sc)
{

	/* nothing new needed */
	return (0);
}

static int
ath_legacy_dma_txteardown(struct ath_softc *sc)
{

	/* nothing new needed */
	return (0);
}

void
ath_xmit_setup_legacy(struct ath_softc *sc)
{
	/*
	 * For now, just set the descriptor length to sizeof(ath_desc);
	 * worry about extracting the real length out of the HAL later.
	 */
	sc->sc_tx_desclen = sizeof(struct ath_desc);
	sc->sc_tx_statuslen = sizeof(struct ath_desc);
	sc->sc_tx_nmaps = 1;	/* only one buffer per TX desc */

	sc->sc_tx.xmit_setup = ath_legacy_dma_txsetup;
	sc->sc_tx.xmit_teardown = ath_legacy_dma_txteardown;
	sc->sc_tx.xmit_attach_comp_func = ath_legacy_attach_comp_func;

	sc->sc_tx.xmit_dma_restart = ath_legacy_tx_dma_restart;
	sc->sc_tx.xmit_handoff = ath_legacy_xmit_handoff;

	sc->sc_tx.xmit_drain = ath_legacy_tx_drain;
}
OpenPOWER on IntegriCloud