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

#include <machine/bus.h>

#include <net/if.h>
#include <net/if_var.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 <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>
#include <dev/ath/if_ath_misc.h>
#include <dev/ath/if_ath_tsf.h>
#include <dev/ath/if_ath_tx.h>
#include <dev/ath/if_ath_sysctl.h>
#include <dev/ath/if_ath_led.h>
#include <dev/ath/if_ath_keycache.h>
#include <dev/ath/if_ath_rx.h>
#include <dev/ath/if_ath_rx_edma.h>
#include <dev/ath/if_ath_tx_edma.h>
#include <dev/ath/if_ath_beacon.h>
#include <dev/ath/if_ath_btcoex.h>
#include <dev/ath/if_ath_btcoex_mci.h>
#include <dev/ath/if_ath_spectral.h>
#include <dev/ath/if_ath_lna_div.h>
#include <dev/ath/if_athdfs.h>
#include <dev/ath/if_ath_ioctl.h>
#include <dev/ath/if_ath_descdma.h>

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

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

/*
 * Only enable this if you're working on PS-POLL support.
 */
#define	ATH_SW_PSQ

/*
 * ATH_BCBUF determines the number of vap's that can transmit
 * beacons and also (currently) the number of vap's that can
 * have unique mac addresses/bssid.  When staggering beacons
 * 4 is probably a good max as otherwise the beacons become
 * very closely spaced and there is limited time for cab q traffic
 * to go out.  You can burst beacons instead but that is not good
 * for stations in power save and at some point you really want
 * another radio (and channel).
 *
 * The limit on the number of mac addresses is tied to our use of
 * the U/L bit and tracking addresses in a byte; it would be
 * worthwhile to allow more for applications like proxy sta.
 */
CTASSERT(ATH_BCBUF <= 8);

static struct ieee80211vap *ath_vap_create(struct ieee80211com *,
		    const char [IFNAMSIZ], int, enum ieee80211_opmode, int,
		    const uint8_t [IEEE80211_ADDR_LEN],
		    const uint8_t [IEEE80211_ADDR_LEN]);
static void	ath_vap_delete(struct ieee80211vap *);
static int	ath_init(struct ath_softc *);
static void	ath_stop(struct ath_softc *);
static int	ath_reset_vap(struct ieee80211vap *, u_long);
static int	ath_transmit(struct ieee80211com *, struct mbuf *);
static int	ath_media_change(struct ifnet *);
static void	ath_watchdog(void *);
static void	ath_parent(struct ieee80211com *);
static void	ath_fatal_proc(void *, int);
static void	ath_bmiss_vap(struct ieee80211vap *);
static void	ath_bmiss_proc(void *, int);
static void	ath_key_update_begin(struct ieee80211vap *);
static void	ath_key_update_end(struct ieee80211vap *);
static void	ath_update_mcast_hw(struct ath_softc *);
static void	ath_update_mcast(struct ieee80211com *);
static void	ath_update_promisc(struct ieee80211com *);
static void	ath_updateslot(struct ieee80211com *);
static void	ath_bstuck_proc(void *, int);
static void	ath_reset_proc(void *, int);
static int	ath_desc_alloc(struct ath_softc *);
static void	ath_desc_free(struct ath_softc *);
static struct ieee80211_node *ath_node_alloc(struct ieee80211vap *,
			const uint8_t [IEEE80211_ADDR_LEN]);
static void	ath_node_cleanup(struct ieee80211_node *);
static void	ath_node_free(struct ieee80211_node *);
static void	ath_node_getsignal(const struct ieee80211_node *,
			int8_t *, int8_t *);
static void	ath_txq_init(struct ath_softc *sc, struct ath_txq *, int);
static struct ath_txq *ath_txq_setup(struct ath_softc*, int qtype, int subtype);
static int	ath_tx_setup(struct ath_softc *, int, int);
static void	ath_tx_cleanupq(struct ath_softc *, struct ath_txq *);
static void	ath_tx_cleanup(struct ath_softc *);
static int	ath_tx_processq(struct ath_softc *sc, struct ath_txq *txq,
		    int dosched);
static void	ath_tx_proc_q0(void *, int);
static void	ath_tx_proc_q0123(void *, int);
static void	ath_tx_proc(void *, int);
static void	ath_txq_sched_tasklet(void *, int);
static int	ath_chan_set(struct ath_softc *, struct ieee80211_channel *);
static void	ath_chan_change(struct ath_softc *, struct ieee80211_channel *);
static void	ath_scan_start(struct ieee80211com *);
static void	ath_scan_end(struct ieee80211com *);
static void	ath_set_channel(struct ieee80211com *);
#ifdef	ATH_ENABLE_11N
static void	ath_update_chw(struct ieee80211com *);
#endif	/* ATH_ENABLE_11N */
static int	ath_set_quiet_ie(struct ieee80211_node *, uint8_t *);
static void	ath_calibrate(void *);
static int	ath_newstate(struct ieee80211vap *, enum ieee80211_state, int);
static void	ath_setup_stationkey(struct ieee80211_node *);
static void	ath_newassoc(struct ieee80211_node *, int);
static int	ath_setregdomain(struct ieee80211com *,
		    struct ieee80211_regdomain *, int,
		    struct ieee80211_channel []);
static void	ath_getradiocaps(struct ieee80211com *, int, int *,
		    struct ieee80211_channel []);
static int	ath_getchannels(struct ath_softc *);

static int	ath_rate_setup(struct ath_softc *, u_int mode);
static void	ath_setcurmode(struct ath_softc *, enum ieee80211_phymode);

static void	ath_announce(struct ath_softc *);

static void	ath_dfs_tasklet(void *, int);
static void	ath_node_powersave(struct ieee80211_node *, int);
static int	ath_node_set_tim(struct ieee80211_node *, int);
static void	ath_node_recv_pspoll(struct ieee80211_node *, struct mbuf *);

#ifdef IEEE80211_SUPPORT_TDMA
#include <dev/ath/if_ath_tdma.h>
#endif

SYSCTL_DECL(_hw_ath);

/* XXX validate sysctl values */
static	int ath_longcalinterval = 30;		/* long cals every 30 secs */
SYSCTL_INT(_hw_ath, OID_AUTO, longcal, CTLFLAG_RW, &ath_longcalinterval,
	    0, "long chip calibration interval (secs)");
static	int ath_shortcalinterval = 100;		/* short cals every 100 ms */
SYSCTL_INT(_hw_ath, OID_AUTO, shortcal, CTLFLAG_RW, &ath_shortcalinterval,
	    0, "short chip calibration interval (msecs)");
static	int ath_resetcalinterval = 20*60;	/* reset cal state 20 mins */
SYSCTL_INT(_hw_ath, OID_AUTO, resetcal, CTLFLAG_RW, &ath_resetcalinterval,
	    0, "reset chip calibration results (secs)");
static	int ath_anicalinterval = 100;		/* ANI calibration - 100 msec */
SYSCTL_INT(_hw_ath, OID_AUTO, anical, CTLFLAG_RW, &ath_anicalinterval,
	    0, "ANI calibration (msecs)");

int ath_rxbuf = ATH_RXBUF;		/* # rx buffers to allocate */
SYSCTL_INT(_hw_ath, OID_AUTO, rxbuf, CTLFLAG_RWTUN, &ath_rxbuf,
	    0, "rx buffers allocated");
int ath_txbuf = ATH_TXBUF;		/* # tx buffers to allocate */
SYSCTL_INT(_hw_ath, OID_AUTO, txbuf, CTLFLAG_RWTUN, &ath_txbuf,
	    0, "tx buffers allocated");
int ath_txbuf_mgmt = ATH_MGMT_TXBUF;	/* # mgmt tx buffers to allocate */
SYSCTL_INT(_hw_ath, OID_AUTO, txbuf_mgmt, CTLFLAG_RWTUN, &ath_txbuf_mgmt,
	    0, "tx (mgmt) buffers allocated");

int ath_bstuck_threshold = 4;		/* max missed beacons */
SYSCTL_INT(_hw_ath, OID_AUTO, bstuck, CTLFLAG_RW, &ath_bstuck_threshold,
	    0, "max missed beacon xmits before chip reset");

MALLOC_DEFINE(M_ATHDEV, "athdev", "ath driver dma buffers");

void
ath_legacy_attach_comp_func(struct ath_softc *sc)
{

	/*
	 * Special case certain configurations.  Note the
	 * CAB queue is handled by these specially so don't
	 * include them when checking the txq setup mask.
	 */
	switch (sc->sc_txqsetup &~ (1<<sc->sc_cabq->axq_qnum)) {
	case 0x01:
		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc_q0, sc);
		break;
	case 0x0f:
		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc_q0123, sc);
		break;
	default:
		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc, sc);
		break;
	}
}

/*
 * Set the target power mode.
 *
 * If this is called during a point in time where
 * the hardware is being programmed elsewhere, it will
 * simply store it away and update it when all current
 * uses of the hardware are completed.
 *
 * If the chip is going into network sleep or power off, then
 * we will wait until all uses of the chip are done before
 * going into network sleep or power off.
 *
 * If the chip is being programmed full-awake, then immediately
 * program it full-awake so we can actually stay awake rather than
 * the chip potentially going to sleep underneath us.
 */
void
_ath_power_setpower(struct ath_softc *sc, int power_state, int selfgen,
    const char *file, int line)
{
	ATH_LOCK_ASSERT(sc);

	DPRINTF(sc, ATH_DEBUG_PWRSAVE, "%s: (%s:%d) state=%d, refcnt=%d, target=%d, cur=%d\n",
	    __func__,
	    file,
	    line,
	    power_state,
	    sc->sc_powersave_refcnt,
	    sc->sc_target_powerstate,
	    sc->sc_cur_powerstate);

	sc->sc_target_powerstate = power_state;

	/*
	 * Don't program the chip into network sleep if the chip
	 * is being programmed elsewhere.
	 *
	 * However, if the chip is being programmed /awake/, force
	 * the chip awake so we stay awake.
	 */
	if ((sc->sc_powersave_refcnt == 0 || power_state == HAL_PM_AWAKE) &&
	    power_state != sc->sc_cur_powerstate) {
		sc->sc_cur_powerstate = power_state;
		ath_hal_setpower(sc->sc_ah, power_state);

		/*
		 * If the NIC is force-awake, then set the
		 * self-gen frame state appropriately.
		 *
		 * If the nic is in network sleep or full-sleep,
		 * we let the above call leave the self-gen
		 * state as "sleep".
		 */
		if (selfgen &&
		    sc->sc_cur_powerstate == HAL_PM_AWAKE &&
		    sc->sc_target_selfgen_state != HAL_PM_AWAKE) {
			ath_hal_setselfgenpower(sc->sc_ah,
			    sc->sc_target_selfgen_state);
		}
	}
}

/*
 * Set the current self-generated frames state.
 *
 * This is separate from the target power mode.  The chip may be
 * awake but the desired state is "sleep", so frames sent to the
 * destination has PWRMGT=1 in the 802.11 header.  The NIC also
 * needs to know to set PWRMGT=1 in self-generated frames.
 */
void
_ath_power_set_selfgen(struct ath_softc *sc, int power_state, const char *file, int line)
{

	ATH_LOCK_ASSERT(sc);

	DPRINTF(sc, ATH_DEBUG_PWRSAVE, "%s: (%s:%d) state=%d, refcnt=%d\n",
	    __func__,
	    file,
	    line,
	    power_state,
	    sc->sc_target_selfgen_state);

	sc->sc_target_selfgen_state = power_state;

	/*
	 * If the NIC is force-awake, then set the power state.
	 * Network-state and full-sleep will already transition it to
	 * mark self-gen frames as sleeping - and we can't
	 * guarantee the NIC is awake to program the self-gen frame
	 * setting anyway.
	 */
	if (sc->sc_cur_powerstate == HAL_PM_AWAKE) {
		ath_hal_setselfgenpower(sc->sc_ah, power_state);
	}
}

/*
 * Set the hardware power mode and take a reference.
 *
 * This doesn't update the target power mode in the driver;
 * it just updates the hardware power state.
 *
 * XXX it should only ever force the hardware awake; it should
 * never be called to set it asleep.
 */
void
_ath_power_set_power_state(struct ath_softc *sc, int power_state, const char *file, int line)
{
	ATH_LOCK_ASSERT(sc);

	DPRINTF(sc, ATH_DEBUG_PWRSAVE, "%s: (%s:%d) state=%d, refcnt=%d\n",
	    __func__,
	    file,
	    line,
	    power_state,
	    sc->sc_powersave_refcnt);

	sc->sc_powersave_refcnt++;

	/*
	 * Only do the power state change if we're not programming
	 * it elsewhere.
	 */
	if (power_state != sc->sc_cur_powerstate) {
		ath_hal_setpower(sc->sc_ah, power_state);
		sc->sc_cur_powerstate = power_state;
		/*
		 * Adjust the self-gen powerstate if appropriate.
		 */
		if (sc->sc_cur_powerstate == HAL_PM_AWAKE &&
		    sc->sc_target_selfgen_state != HAL_PM_AWAKE) {
			ath_hal_setselfgenpower(sc->sc_ah,
			    sc->sc_target_selfgen_state);
		}
	}
}

/*
 * Restore the power save mode to what it once was.
 *
 * This will decrement the reference counter and once it hits
 * zero, it'll restore the powersave state.
 */
void
_ath_power_restore_power_state(struct ath_softc *sc, const char *file, int line)
{

	ATH_LOCK_ASSERT(sc);

	DPRINTF(sc, ATH_DEBUG_PWRSAVE, "%s: (%s:%d) refcnt=%d, target state=%d\n",
	    __func__,
	    file,
	    line,
	    sc->sc_powersave_refcnt,
	    sc->sc_target_powerstate);

	if (sc->sc_powersave_refcnt == 0)
		device_printf(sc->sc_dev, "%s: refcnt=0?\n", __func__);
	else
		sc->sc_powersave_refcnt--;

	if (sc->sc_powersave_refcnt == 0 &&
	    sc->sc_target_powerstate != sc->sc_cur_powerstate) {
		sc->sc_cur_powerstate = sc->sc_target_powerstate;
		ath_hal_setpower(sc->sc_ah, sc->sc_target_powerstate);
	}

	/*
	 * Adjust the self-gen powerstate if appropriate.
	 */
	if (sc->sc_cur_powerstate == HAL_PM_AWAKE &&
	    sc->sc_target_selfgen_state != HAL_PM_AWAKE) {
		ath_hal_setselfgenpower(sc->sc_ah,
		    sc->sc_target_selfgen_state);
	}

}

/*
 * Configure the initial HAL configuration values based on bus
 * specific parameters.
 *
 * Some PCI IDs and other information may need tweaking.
 *
 * XXX TODO: ath9k and the Atheros HAL only program comm2g_switch_enable
 * if BT antenna diversity isn't enabled.
 *
 * So, let's also figure out how to enable BT diversity for AR9485.
 */
static void
ath_setup_hal_config(struct ath_softc *sc, HAL_OPS_CONFIG *ah_config)
{
	/* XXX TODO: only for PCI devices? */

	if (sc->sc_pci_devinfo & (ATH_PCI_CUS198 | ATH_PCI_CUS230)) {
		ah_config->ath_hal_ext_lna_ctl_gpio = 0x200; /* bit 9 */
		ah_config->ath_hal_ext_atten_margin_cfg = AH_TRUE;
		ah_config->ath_hal_min_gainidx = AH_TRUE;
		ah_config->ath_hal_ant_ctrl_comm2g_switch_enable = 0x000bbb88;
		/* XXX low_rssi_thresh */
		/* XXX fast_div_bias */
		device_printf(sc->sc_dev, "configuring for %s\n",
		    (sc->sc_pci_devinfo & ATH_PCI_CUS198) ?
		    "CUS198" : "CUS230");
	}

	if (sc->sc_pci_devinfo & ATH_PCI_CUS217)
		device_printf(sc->sc_dev, "CUS217 card detected\n");

	if (sc->sc_pci_devinfo & ATH_PCI_CUS252)
		device_printf(sc->sc_dev, "CUS252 card detected\n");

	if (sc->sc_pci_devinfo & ATH_PCI_AR9565_1ANT)
		device_printf(sc->sc_dev, "WB335 1-ANT card detected\n");

	if (sc->sc_pci_devinfo & ATH_PCI_AR9565_2ANT)
		device_printf(sc->sc_dev, "WB335 2-ANT card detected\n");

	if (sc->sc_pci_devinfo & ATH_PCI_BT_ANT_DIV)
		device_printf(sc->sc_dev,
		    "Bluetooth Antenna Diversity card detected\n");

	if (sc->sc_pci_devinfo & ATH_PCI_KILLER)
		device_printf(sc->sc_dev, "Killer Wireless card detected\n");

#if 0
        /*
         * Some WB335 cards do not support antenna diversity. Since
         * we use a hardcoded value for AR9565 instead of using the
         * EEPROM/OTP data, remove the combining feature from
         * the HW capabilities bitmap.
         */
        if (sc->sc_pci_devinfo & (ATH9K_PCI_AR9565_1ANT | ATH9K_PCI_AR9565_2ANT)) {
                if (!(sc->sc_pci_devinfo & ATH9K_PCI_BT_ANT_DIV))
                        pCap->hw_caps &= ~ATH9K_HW_CAP_ANT_DIV_COMB;
        }

        if (sc->sc_pci_devinfo & ATH9K_PCI_BT_ANT_DIV) {
                pCap->hw_caps |= ATH9K_HW_CAP_BT_ANT_DIV;
                device_printf(sc->sc_dev, "Set BT/WLAN RX diversity capability\n");
        }
#endif

        if (sc->sc_pci_devinfo & ATH_PCI_D3_L1_WAR) {
                ah_config->ath_hal_pcie_waen = 0x0040473b;
                device_printf(sc->sc_dev, "Enable WAR for ASPM D3/L1\n");
        }

#if 0
        if (sc->sc_pci_devinfo & ATH9K_PCI_NO_PLL_PWRSAVE) {
                ah->config.no_pll_pwrsave = true;
                device_printf(sc->sc_dev, "Disable PLL PowerSave\n");
        }
#endif

}

/*
 * Attempt to fetch the MAC address from the kernel environment.
 *
 * Returns 0, macaddr in macaddr if successful; -1 otherwise.
 */
static int
ath_fetch_mac_kenv(struct ath_softc *sc, uint8_t *macaddr)
{
	char devid_str[32];
	int local_mac = 0;
	char *local_macstr;

	/*
	 * Fetch from the kenv rather than using hints.
	 *
	 * Hints would be nice but the transition to dynamic
	 * hints/kenv doesn't happen early enough for this
	 * to work reliably (eg on anything embedded.)
	 */
	snprintf(devid_str, 32, "hint.%s.%d.macaddr",
	    device_get_name(sc->sc_dev),
	    device_get_unit(sc->sc_dev));

	if ((local_macstr = kern_getenv(devid_str)) != NULL) {
		uint32_t tmpmac[ETHER_ADDR_LEN];
		int count;
		int i;

		/* Have a MAC address; should use it */
		device_printf(sc->sc_dev,
		    "Overriding MAC address from environment: '%s'\n",
		    local_macstr);

		/* Extract out the MAC address */
		count = sscanf(local_macstr, "%x%*c%x%*c%x%*c%x%*c%x%*c%x",
		    &tmpmac[0], &tmpmac[1],
		    &tmpmac[2], &tmpmac[3],
		    &tmpmac[4], &tmpmac[5]);
		if (count == 6) {
			/* Valid! */
			local_mac = 1;
			for (i = 0; i < ETHER_ADDR_LEN; i++)
				macaddr[i] = tmpmac[i];
		}
		/* Done! */
		freeenv(local_macstr);
		local_macstr = NULL;
	}

	if (local_mac)
		return (0);
	return (-1);
}

#define	HAL_MODE_HT20 (HAL_MODE_11NG_HT20 | HAL_MODE_11NA_HT20)
#define	HAL_MODE_HT40 \
	(HAL_MODE_11NG_HT40PLUS | HAL_MODE_11NG_HT40MINUS | \
	HAL_MODE_11NA_HT40PLUS | HAL_MODE_11NA_HT40MINUS)
int
ath_attach(u_int16_t devid, struct ath_softc *sc)
{
	struct ieee80211com *ic = &sc->sc_ic;
	struct ath_hal *ah = NULL;
	HAL_STATUS status;
	int error = 0, i;
	u_int wmodes;
	int rx_chainmask, tx_chainmask;
	HAL_OPS_CONFIG ah_config;

	DPRINTF(sc, ATH_DEBUG_ANY, "%s: devid 0x%x\n", __func__, devid);

	ic->ic_softc = sc;
	ic->ic_name = device_get_nameunit(sc->sc_dev);

	/*
	 * Configure the initial configuration data.
	 *
	 * This is stuff that may be needed early during attach
	 * rather than done via configuration calls later.
	 */
	bzero(&ah_config, sizeof(ah_config));
	ath_setup_hal_config(sc, &ah_config);

	ah = ath_hal_attach(devid, sc, sc->sc_st, sc->sc_sh,
	    sc->sc_eepromdata, &ah_config, &status);
	if (ah == NULL) {
		device_printf(sc->sc_dev,
		    "unable to attach hardware; HAL status %u\n", status);
		error = ENXIO;
		goto bad;
	}
	sc->sc_ah = ah;
	sc->sc_invalid = 0;	/* ready to go, enable interrupt handling */
#ifdef	ATH_DEBUG
	sc->sc_debug = ath_debug;
#endif

	/*
	 * Force the chip awake during setup, just to keep
	 * the HAL/driver power tracking happy.
	 *
	 * There are some methods (eg ath_hal_setmac())
	 * that poke the hardware.
	 */
	ATH_LOCK(sc);
	ath_power_setpower(sc, HAL_PM_AWAKE, 1);
	ATH_UNLOCK(sc);

	/*
	 * Setup the DMA/EDMA functions based on the current
	 * hardware support.
	 *
	 * This is required before the descriptors are allocated.
	 */
	if (ath_hal_hasedma(sc->sc_ah)) {
		sc->sc_isedma = 1;
		ath_recv_setup_edma(sc);
		ath_xmit_setup_edma(sc);
	} else {
		ath_recv_setup_legacy(sc);
		ath_xmit_setup_legacy(sc);
	}

	if (ath_hal_hasmybeacon(sc->sc_ah)) {
		sc->sc_do_mybeacon = 1;
	}

	/*
	 * Check if the MAC has multi-rate retry support.
	 * We do this by trying to setup a fake extended
	 * descriptor.  MAC's that don't have support will
	 * return false w/o doing anything.  MAC's that do
	 * support it will return true w/o doing anything.
	 */
	sc->sc_mrretry = ath_hal_setupxtxdesc(ah, NULL, 0,0, 0,0, 0,0);

	/*
	 * Check if the device has hardware counters for PHY
	 * errors.  If so we need to enable the MIB interrupt
	 * so we can act on stat triggers.
	 */
	if (ath_hal_hwphycounters(ah))
		sc->sc_needmib = 1;

	/*
	 * Get the hardware key cache size.
	 */
	sc->sc_keymax = ath_hal_keycachesize(ah);
	if (sc->sc_keymax > ATH_KEYMAX) {
		device_printf(sc->sc_dev,
		    "Warning, using only %u of %u key cache slots\n",
		    ATH_KEYMAX, sc->sc_keymax);
		sc->sc_keymax = ATH_KEYMAX;
	}
	/*
	 * Reset the key cache since some parts do not
	 * reset the contents on initial power up.
	 */
	for (i = 0; i < sc->sc_keymax; i++)
		ath_hal_keyreset(ah, i);

	/*
	 * Collect the default channel list.
	 */
	error = ath_getchannels(sc);
	if (error != 0)
		goto bad;

	/*
	 * Setup rate tables for all potential media types.
	 */
	ath_rate_setup(sc, IEEE80211_MODE_11A);
	ath_rate_setup(sc, IEEE80211_MODE_11B);
	ath_rate_setup(sc, IEEE80211_MODE_11G);
	ath_rate_setup(sc, IEEE80211_MODE_TURBO_A);
	ath_rate_setup(sc, IEEE80211_MODE_TURBO_G);
	ath_rate_setup(sc, IEEE80211_MODE_STURBO_A);
	ath_rate_setup(sc, IEEE80211_MODE_11NA);
	ath_rate_setup(sc, IEEE80211_MODE_11NG);
	ath_rate_setup(sc, IEEE80211_MODE_HALF);
	ath_rate_setup(sc, IEEE80211_MODE_QUARTER);

	/* NB: setup here so ath_rate_update is happy */
	ath_setcurmode(sc, IEEE80211_MODE_11A);

	/*
	 * Allocate TX descriptors and populate the lists.
	 */
	error = ath_desc_alloc(sc);
	if (error != 0) {
		device_printf(sc->sc_dev,
		    "failed to allocate TX descriptors: %d\n", error);
		goto bad;
	}
	error = ath_txdma_setup(sc);
	if (error != 0) {
		device_printf(sc->sc_dev,
		    "failed to allocate TX descriptors: %d\n", error);
		goto bad;
	}

	/*
	 * Allocate RX descriptors and populate the lists.
	 */
	error = ath_rxdma_setup(sc);
	if (error != 0) {
		device_printf(sc->sc_dev,
		     "failed to allocate RX descriptors: %d\n", error);
		goto bad;
	}

	callout_init_mtx(&sc->sc_cal_ch, &sc->sc_mtx, 0);
	callout_init_mtx(&sc->sc_wd_ch, &sc->sc_mtx, 0);

	ATH_TXBUF_LOCK_INIT(sc);

	sc->sc_tq = taskqueue_create("ath_taskq", M_NOWAIT,
		taskqueue_thread_enqueue, &sc->sc_tq);
	taskqueue_start_threads(&sc->sc_tq, 1, PI_NET, "%s taskq",
	    device_get_nameunit(sc->sc_dev));

	TASK_INIT(&sc->sc_rxtask, 0, sc->sc_rx.recv_tasklet, sc);
	TASK_INIT(&sc->sc_bmisstask, 0, ath_bmiss_proc, sc);
	TASK_INIT(&sc->sc_bstucktask,0, ath_bstuck_proc, sc);
	TASK_INIT(&sc->sc_resettask,0, ath_reset_proc, sc);
	TASK_INIT(&sc->sc_txqtask, 0, ath_txq_sched_tasklet, sc);
	TASK_INIT(&sc->sc_fataltask, 0, ath_fatal_proc, sc);

	/*
	 * Allocate hardware transmit queues: one queue for
	 * beacon frames and one data queue for each QoS
	 * priority.  Note that the hal handles resetting
	 * these queues at the needed time.
	 *
	 * XXX PS-Poll
	 */
	sc->sc_bhalq = ath_beaconq_setup(sc);
	if (sc->sc_bhalq == (u_int) -1) {
		device_printf(sc->sc_dev,
		    "unable to setup a beacon xmit queue!\n");
		error = EIO;
		goto bad2;
	}
	sc->sc_cabq = ath_txq_setup(sc, HAL_TX_QUEUE_CAB, 0);
	if (sc->sc_cabq == NULL) {
		device_printf(sc->sc_dev, "unable to setup CAB xmit queue!\n");
		error = EIO;
		goto bad2;
	}
	/* NB: insure BK queue is the lowest priority h/w queue */
	if (!ath_tx_setup(sc, WME_AC_BK, HAL_WME_AC_BK)) {
		device_printf(sc->sc_dev,
		    "unable to setup xmit queue for %s traffic!\n",
		    ieee80211_wme_acnames[WME_AC_BK]);
		error = EIO;
		goto bad2;
	}
	if (!ath_tx_setup(sc, WME_AC_BE, HAL_WME_AC_BE) ||
	    !ath_tx_setup(sc, WME_AC_VI, HAL_WME_AC_VI) ||
	    !ath_tx_setup(sc, WME_AC_VO, HAL_WME_AC_VO)) {
		/*
		 * Not enough hardware tx queues to properly do WME;
		 * just punt and assign them all to the same h/w queue.
		 * We could do a better job of this if, for example,
		 * we allocate queues when we switch from station to
		 * AP mode.
		 */
		if (sc->sc_ac2q[WME_AC_VI] != NULL)
			ath_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_VI]);
		if (sc->sc_ac2q[WME_AC_BE] != NULL)
			ath_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_BE]);
		sc->sc_ac2q[WME_AC_BE] = sc->sc_ac2q[WME_AC_BK];
		sc->sc_ac2q[WME_AC_VI] = sc->sc_ac2q[WME_AC_BK];
		sc->sc_ac2q[WME_AC_VO] = sc->sc_ac2q[WME_AC_BK];
	}

	/*
	 * Attach the TX completion function.
	 *
	 * The non-EDMA chips may have some special case optimisations;
	 * this method gives everyone a chance to attach cleanly.
	 */
	sc->sc_tx.xmit_attach_comp_func(sc);

	/*
	 * Setup rate control.  Some rate control modules
	 * call back to change the anntena state so expose
	 * the necessary entry points.
	 * XXX maybe belongs in struct ath_ratectrl?
	 */
	sc->sc_setdefantenna = ath_setdefantenna;
	sc->sc_rc = ath_rate_attach(sc);
	if (sc->sc_rc == NULL) {
		error = EIO;
		goto bad2;
	}

	/* Attach DFS module */
	if (! ath_dfs_attach(sc)) {
		device_printf(sc->sc_dev,
		    "%s: unable to attach DFS\n", __func__);
		error = EIO;
		goto bad2;
	}

	/* Attach spectral module */
	if (ath_spectral_attach(sc) < 0) {
		device_printf(sc->sc_dev,
		    "%s: unable to attach spectral\n", __func__);
		error = EIO;
		goto bad2;
	}

	/* Attach bluetooth coexistence module */
	if (ath_btcoex_attach(sc) < 0) {
		device_printf(sc->sc_dev,
		    "%s: unable to attach bluetooth coexistence\n", __func__);
		error = EIO;
		goto bad2;
	}

	/* Attach LNA diversity module */
	if (ath_lna_div_attach(sc) < 0) {
		device_printf(sc->sc_dev,
		    "%s: unable to attach LNA diversity\n", __func__);
		error = EIO;
		goto bad2;
	}

	/* Start DFS processing tasklet */
	TASK_INIT(&sc->sc_dfstask, 0, ath_dfs_tasklet, sc);

	/* Configure LED state */
	sc->sc_blinking = 0;
	sc->sc_ledstate = 1;
	sc->sc_ledon = 0;			/* low true */
	sc->sc_ledidle = (2700*hz)/1000;	/* 2.7sec */
	callout_init(&sc->sc_ledtimer, 1);

	/*
	 * Don't setup hardware-based blinking.
	 *
	 * Although some NICs may have this configured in the
	 * default reset register values, the user may wish
	 * to alter which pins have which function.
	 *
	 * The reference driver attaches the MAC network LED to GPIO1 and
	 * the MAC power LED to GPIO2.  However, the DWA-552 cardbus
	 * NIC has these reversed.
	 */
	sc->sc_hardled = (1 == 0);
	sc->sc_led_net_pin = -1;
	sc->sc_led_pwr_pin = -1;
	/*
	 * Auto-enable soft led processing for IBM cards and for
	 * 5211 minipci cards.  Users can also manually enable/disable
	 * support with a sysctl.
	 */
	sc->sc_softled = (devid == AR5212_DEVID_IBM || devid == AR5211_DEVID);
	ath_led_config(sc);
	ath_hal_setledstate(ah, HAL_LED_INIT);

	/* XXX not right but it's not used anywhere important */
	ic->ic_phytype = IEEE80211_T_OFDM;
	ic->ic_opmode = IEEE80211_M_STA;
	ic->ic_caps =
		  IEEE80211_C_STA		/* station mode */
		| IEEE80211_C_IBSS		/* ibss, nee adhoc, mode */
		| IEEE80211_C_HOSTAP		/* hostap mode */
		| IEEE80211_C_MONITOR		/* monitor mode */
		| IEEE80211_C_AHDEMO		/* adhoc demo mode */
		| IEEE80211_C_WDS		/* 4-address traffic works */
		| IEEE80211_C_MBSS		/* mesh point link mode */
		| IEEE80211_C_SHPREAMBLE	/* short preamble supported */
		| IEEE80211_C_SHSLOT		/* short slot time supported */
		| IEEE80211_C_WPA		/* capable of WPA1+WPA2 */
#ifndef	ATH_ENABLE_11N
		| IEEE80211_C_BGSCAN		/* capable of bg scanning */
#endif
		| IEEE80211_C_TXFRAG		/* handle tx frags */
#ifdef	ATH_ENABLE_DFS
		| IEEE80211_C_DFS		/* Enable radar detection */
#endif
		| IEEE80211_C_PMGT		/* Station side power mgmt */
		| IEEE80211_C_SWSLEEP
		;
	/*
	 * Query the hal to figure out h/w crypto support.
	 */
	if (ath_hal_ciphersupported(ah, HAL_CIPHER_WEP))
		ic->ic_cryptocaps |= IEEE80211_CRYPTO_WEP;
	if (ath_hal_ciphersupported(ah, HAL_CIPHER_AES_OCB))
		ic->ic_cryptocaps |= IEEE80211_CRYPTO_AES_OCB;
	if (ath_hal_ciphersupported(ah, HAL_CIPHER_AES_CCM))
		ic->ic_cryptocaps |= IEEE80211_CRYPTO_AES_CCM;
	if (ath_hal_ciphersupported(ah, HAL_CIPHER_CKIP))
		ic->ic_cryptocaps |= IEEE80211_CRYPTO_CKIP;
	if (ath_hal_ciphersupported(ah, HAL_CIPHER_TKIP)) {
		ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIP;
		/*
		 * Check if h/w does the MIC and/or whether the
		 * separate key cache entries are required to
		 * handle both tx+rx MIC keys.
		 */
		if (ath_hal_ciphersupported(ah, HAL_CIPHER_MIC))
			ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIPMIC;
		/*
		 * If the h/w supports storing tx+rx MIC keys
		 * in one cache slot automatically enable use.
		 */
		if (ath_hal_hastkipsplit(ah) ||
		    !ath_hal_settkipsplit(ah, AH_FALSE))
			sc->sc_splitmic = 1;
		/*
		 * If the h/w can do TKIP MIC together with WME then
		 * we use it; otherwise we force the MIC to be done
		 * in software by the net80211 layer.
		 */
		if (ath_hal_haswmetkipmic(ah))
			sc->sc_wmetkipmic = 1;
	}
	sc->sc_hasclrkey = ath_hal_ciphersupported(ah, HAL_CIPHER_CLR);
	/*
	 * Check for multicast key search support.
	 */
	if (ath_hal_hasmcastkeysearch(sc->sc_ah) &&
	    !ath_hal_getmcastkeysearch(sc->sc_ah)) {
		ath_hal_setmcastkeysearch(sc->sc_ah, 1);
	}
	sc->sc_mcastkey = ath_hal_getmcastkeysearch(ah);
	/*
	 * Mark key cache slots associated with global keys
	 * as in use.  If we knew TKIP was not to be used we
	 * could leave the +32, +64, and +32+64 slots free.
	 */
	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
		setbit(sc->sc_keymap, i);
		setbit(sc->sc_keymap, i+64);
		if (sc->sc_splitmic) {
			setbit(sc->sc_keymap, i+32);
			setbit(sc->sc_keymap, i+32+64);
		}
	}
	/*
	 * TPC support can be done either with a global cap or
	 * per-packet support.  The latter is not available on
	 * all parts.  We're a bit pedantic here as all parts
	 * support a global cap.
	 */
	if (ath_hal_hastpc(ah) || ath_hal_hastxpowlimit(ah))
		ic->ic_caps |= IEEE80211_C_TXPMGT;

	/*
	 * Mark WME capability only if we have sufficient
	 * hardware queues to do proper priority scheduling.
	 */
	if (sc->sc_ac2q[WME_AC_BE] != sc->sc_ac2q[WME_AC_BK])
		ic->ic_caps |= IEEE80211_C_WME;
	/*
	 * Check for misc other capabilities.
	 */
	if (ath_hal_hasbursting(ah))
		ic->ic_caps |= IEEE80211_C_BURST;
	sc->sc_hasbmask = ath_hal_hasbssidmask(ah);
	sc->sc_hasbmatch = ath_hal_hasbssidmatch(ah);
	sc->sc_hastsfadd = ath_hal_hastsfadjust(ah);
	sc->sc_rxslink = ath_hal_self_linked_final_rxdesc(ah);

	/* XXX TODO: just make this a "store tx/rx timestamp length" operation */
	if (ath_hal_get_rx_tsf_prec(ah, &i)) {
		if (i == 32) {
			sc->sc_rxtsf32 = 1;
		}
		if (bootverbose)
			device_printf(sc->sc_dev, "RX timestamp: %d bits\n", i);
	}
	if (ath_hal_get_tx_tsf_prec(ah, &i)) {
		if (bootverbose)
			device_printf(sc->sc_dev, "TX timestamp: %d bits\n", i);
	}

	sc->sc_hasenforcetxop = ath_hal_hasenforcetxop(ah);
	sc->sc_rx_lnamixer = ath_hal_hasrxlnamixer(ah);
	sc->sc_hasdivcomb = ath_hal_hasdivantcomb(ah);

	/*
	 * Some WB335 cards do not support antenna diversity. Since
	 * we use a hardcoded value for AR9565 instead of using the
	 * EEPROM/OTP data, remove the combining feature from
	 * the HW capabilities bitmap.
	 */
	/*
	 * XXX TODO: check reference driver and ath9k for what to do
	 * here for WB335.  I think we have to actually disable the
	 * LNA div processing in the HAL and instead use the hard
	 * coded values; and then use BT diversity.
	 *
	 * .. but also need to setup MCI too for WB335..
	 */
#if 0
	if (sc->sc_pci_devinfo & (ATH9K_PCI_AR9565_1ANT | ATH9K_PCI_AR9565_2ANT)) {
		device_printf(sc->sc_dev, "%s: WB335: disabling LNA mixer diversity\n",
		    __func__);
		sc->sc_dolnadiv = 0;
	}
#endif

	if (ath_hal_hasfastframes(ah))
		ic->ic_caps |= IEEE80211_C_FF;
	wmodes = ath_hal_getwirelessmodes(ah);
	if (wmodes & (HAL_MODE_108G|HAL_MODE_TURBO))
		ic->ic_caps |= IEEE80211_C_TURBOP;
#ifdef IEEE80211_SUPPORT_TDMA
	if (ath_hal_macversion(ah) > 0x78) {
		ic->ic_caps |= IEEE80211_C_TDMA; /* capable of TDMA */
		ic->ic_tdma_update = ath_tdma_update;
	}
#endif

	/*
	 * TODO: enforce that at least this many frames are available
	 * in the txbuf list before allowing data frames (raw or
	 * otherwise) to be transmitted.
	 */
	sc->sc_txq_data_minfree = 10;

	/*
	 * Shorten this to 64 packets, or 1/4 ath_txbuf, whichever
	 * is smaller.
	 *
	 * Anything bigger can potentially see the cabq consume
	 * almost all buffers, starving everything else, only to
	 * see most fail to transmit in the given beacon interval.
	 */
	sc->sc_txq_mcastq_maxdepth = MIN(64, ath_txbuf / 4);

	/*
	 * How deep can the node software TX queue get whilst it's asleep.
	 */
	sc->sc_txq_node_psq_maxdepth = 16;

	/*
	 * Default the maximum queue to to 1/4'th the TX buffers, or
	 * 64, whichever is smaller.
	 */
	sc->sc_txq_node_maxdepth = MIN(64, ath_txbuf / 4);

	/* Enable CABQ by default */
	sc->sc_cabq_enable = 1;

	/*
	 * Allow the TX and RX chainmasks to be overridden by
	 * environment variables and/or device.hints.
	 *
	 * This must be done early - before the hardware is
	 * calibrated or before the 802.11n stream calculation
	 * is done.
	 */
	if (resource_int_value(device_get_name(sc->sc_dev),
	    device_get_unit(sc->sc_dev), "rx_chainmask",
	    &rx_chainmask) == 0) {
		device_printf(sc->sc_dev, "Setting RX chainmask to 0x%x\n",
		    rx_chainmask);
		(void) ath_hal_setrxchainmask(sc->sc_ah, rx_chainmask);
	}
	if (resource_int_value(device_get_name(sc->sc_dev),
	    device_get_unit(sc->sc_dev), "tx_chainmask",
	    &tx_chainmask) == 0) {
		device_printf(sc->sc_dev, "Setting TX chainmask to 0x%x\n",
		    tx_chainmask);
		(void) ath_hal_settxchainmask(sc->sc_ah, tx_chainmask);
	}

	/*
	 * Query the TX/RX chainmask configuration.
	 *
	 * This is only relevant for 11n devices.
	 */
	ath_hal_getrxchainmask(ah, &sc->sc_rxchainmask);
	ath_hal_gettxchainmask(ah, &sc->sc_txchainmask);

	/*
	 * Disable MRR with protected frames by default.
	 * Only 802.11n series NICs can handle this.
	 */
	sc->sc_mrrprot = 0;	/* XXX should be a capability */

	/*
	 * Query the enterprise mode information the HAL.
	 */
	if (ath_hal_getcapability(ah, HAL_CAP_ENTERPRISE_MODE, 0,
	    &sc->sc_ent_cfg) == HAL_OK)
		sc->sc_use_ent = 1;

#ifdef	ATH_ENABLE_11N
	/*
	 * Query HT capabilities
	 */
	if (ath_hal_getcapability(ah, HAL_CAP_HT, 0, NULL) == HAL_OK &&
	    (wmodes & (HAL_MODE_HT20 | HAL_MODE_HT40))) {
		uint32_t rxs, txs;
		uint32_t ldpc;

		device_printf(sc->sc_dev, "[HT] enabling HT modes\n");

		sc->sc_mrrprot = 1;	/* XXX should be a capability */

		ic->ic_htcaps = IEEE80211_HTC_HT	/* HT operation */
			    | IEEE80211_HTC_AMPDU	/* A-MPDU tx/rx */
			    | IEEE80211_HTC_AMSDU	/* A-MSDU tx/rx */
			    | IEEE80211_HTCAP_MAXAMSDU_3839
			    				/* max A-MSDU length */
			    | IEEE80211_HTCAP_SMPS_OFF;	/* SM power save off */

		/*
		 * Enable short-GI for HT20 only if the hardware
		 * advertises support.
		 * Notably, anything earlier than the AR9287 doesn't.
		 */
		if ((ath_hal_getcapability(ah,
		    HAL_CAP_HT20_SGI, 0, NULL) == HAL_OK) &&
		    (wmodes & HAL_MODE_HT20)) {
			device_printf(sc->sc_dev,
			    "[HT] enabling short-GI in 20MHz mode\n");
			ic->ic_htcaps |= IEEE80211_HTCAP_SHORTGI20;
		}

		if (wmodes & HAL_MODE_HT40)
			ic->ic_htcaps |= IEEE80211_HTCAP_CHWIDTH40
			    |  IEEE80211_HTCAP_SHORTGI40;

		/*
		 * TX/RX streams need to be taken into account when
		 * negotiating which MCS rates it'll receive and
		 * what MCS rates are available for TX.
		 */
		(void) ath_hal_getcapability(ah, HAL_CAP_STREAMS, 0, &txs);
		(void) ath_hal_getcapability(ah, HAL_CAP_STREAMS, 1, &rxs);
		ic->ic_txstream = txs;
		ic->ic_rxstream = rxs;

		/*
		 * Setup TX and RX STBC based on what the HAL allows and
		 * the currently configured chainmask set.
		 * Ie - don't enable STBC TX if only one chain is enabled.
		 * STBC RX is fine on a single RX chain; it just won't
		 * provide any real benefit.
		 */
		if (ath_hal_getcapability(ah, HAL_CAP_RX_STBC, 0,
		    NULL) == HAL_OK) {
			sc->sc_rx_stbc = 1;
			device_printf(sc->sc_dev,
			    "[HT] 1 stream STBC receive enabled\n");
			ic->ic_htcaps |= IEEE80211_HTCAP_RXSTBC_1STREAM;
		}
		if (txs > 1 && ath_hal_getcapability(ah, HAL_CAP_TX_STBC, 0,
		    NULL) == HAL_OK) {
			sc->sc_tx_stbc = 1;
			device_printf(sc->sc_dev,
			    "[HT] 1 stream STBC transmit enabled\n");
			ic->ic_htcaps |= IEEE80211_HTCAP_TXSTBC;
		}

		(void) ath_hal_getcapability(ah, HAL_CAP_RTS_AGGR_LIMIT, 1,
		    &sc->sc_rts_aggr_limit);
		if (sc->sc_rts_aggr_limit != (64 * 1024))
			device_printf(sc->sc_dev,
			    "[HT] RTS aggregates limited to %d KiB\n",
			    sc->sc_rts_aggr_limit / 1024);

		/*
		 * LDPC
		 */
		if ((ath_hal_getcapability(ah, HAL_CAP_LDPC, 0, &ldpc))
		    == HAL_OK && (ldpc == 1)) {
			sc->sc_has_ldpc = 1;
			device_printf(sc->sc_dev,
			    "[HT] LDPC transmit/receive enabled\n");
			ic->ic_htcaps |= IEEE80211_HTCAP_LDPC |
					 IEEE80211_HTC_TXLDPC;
		}


		device_printf(sc->sc_dev,
		    "[HT] %d RX streams; %d TX streams\n", rxs, txs);
	}
#endif

	/*
	 * Initial aggregation settings.
	 */
	sc->sc_hwq_limit_aggr = ATH_AGGR_MIN_QDEPTH;
	sc->sc_hwq_limit_nonaggr = ATH_NONAGGR_MIN_QDEPTH;
	sc->sc_tid_hwq_lo = ATH_AGGR_SCHED_LOW;
	sc->sc_tid_hwq_hi = ATH_AGGR_SCHED_HIGH;
	sc->sc_aggr_limit = ATH_AGGR_MAXSIZE;
	sc->sc_delim_min_pad = 0;

	/*
	 * Check if the hardware requires PCI register serialisation.
	 * Some of the Owl based MACs require this.
	 */
	if (mp_ncpus > 1 &&
	    ath_hal_getcapability(ah, HAL_CAP_SERIALISE_WAR,
	     0, NULL) == HAL_OK) {
		sc->sc_ah->ah_config.ah_serialise_reg_war = 1;
		device_printf(sc->sc_dev,
		    "Enabling register serialisation\n");
	}

	/*
	 * Initialise the deferred completed RX buffer list.
	 */
	TAILQ_INIT(&sc->sc_rx_rxlist[HAL_RX_QUEUE_HP]);
	TAILQ_INIT(&sc->sc_rx_rxlist[HAL_RX_QUEUE_LP]);

	/*
	 * Indicate we need the 802.11 header padded to a
	 * 32-bit boundary for 4-address and QoS frames.
	 */
	ic->ic_flags |= IEEE80211_F_DATAPAD;

	/*
	 * Query the hal about antenna support.
	 */
	sc->sc_defant = ath_hal_getdefantenna(ah);

	/*
	 * Not all chips have the VEOL support we want to
	 * use with IBSS beacons; check here for it.
	 */
	sc->sc_hasveol = ath_hal_hasveol(ah);

	/* get mac address from kenv first, then hardware */
	if (ath_fetch_mac_kenv(sc, ic->ic_macaddr) == 0) {
		/* Tell the HAL now about the new MAC */
		ath_hal_setmac(ah, ic->ic_macaddr);
	} else {
		ath_hal_getmac(ah, ic->ic_macaddr);
	}

	if (sc->sc_hasbmask)
		ath_hal_getbssidmask(ah, sc->sc_hwbssidmask);

	/* NB: used to size node table key mapping array */
	ic->ic_max_keyix = sc->sc_keymax;
	/* call MI attach routine. */
	ieee80211_ifattach(ic);
	ic->ic_setregdomain = ath_setregdomain;
	ic->ic_getradiocaps = ath_getradiocaps;
	sc->sc_opmode = HAL_M_STA;

	/* override default methods */
	ic->ic_ioctl = ath_ioctl;
	ic->ic_parent = ath_parent;
	ic->ic_transmit = ath_transmit;
	ic->ic_newassoc = ath_newassoc;
	ic->ic_updateslot = ath_updateslot;
	ic->ic_wme.wme_update = ath_wme_update;
	ic->ic_vap_create = ath_vap_create;
	ic->ic_vap_delete = ath_vap_delete;
	ic->ic_raw_xmit = ath_raw_xmit;
	ic->ic_update_mcast = ath_update_mcast;
	ic->ic_update_promisc = ath_update_promisc;
	ic->ic_node_alloc = ath_node_alloc;
	sc->sc_node_free = ic->ic_node_free;
	ic->ic_node_free = ath_node_free;
	sc->sc_node_cleanup = ic->ic_node_cleanup;
	ic->ic_node_cleanup = ath_node_cleanup;
	ic->ic_node_getsignal = ath_node_getsignal;
	ic->ic_scan_start = ath_scan_start;
	ic->ic_scan_end = ath_scan_end;
	ic->ic_set_channel = ath_set_channel;
#ifdef	ATH_ENABLE_11N
	/* 802.11n specific - but just override anyway */
	sc->sc_addba_request = ic->ic_addba_request;
	sc->sc_addba_response = ic->ic_addba_response;
	sc->sc_addba_stop = ic->ic_addba_stop;
	sc->sc_bar_response = ic->ic_bar_response;
	sc->sc_addba_response_timeout = ic->ic_addba_response_timeout;

	ic->ic_addba_request = ath_addba_request;
	ic->ic_addba_response = ath_addba_response;
	ic->ic_addba_response_timeout = ath_addba_response_timeout;
	ic->ic_addba_stop = ath_addba_stop;
	ic->ic_bar_response = ath_bar_response;

	ic->ic_update_chw = ath_update_chw;
#endif	/* ATH_ENABLE_11N */
	ic->ic_set_quiet = ath_set_quiet_ie;

#ifdef	ATH_ENABLE_RADIOTAP_VENDOR_EXT
	/*
	 * There's one vendor bitmap entry in the RX radiotap
	 * header; make sure that's taken into account.
	 */
	ieee80211_radiotap_attachv(ic,
	    &sc->sc_tx_th.wt_ihdr, sizeof(sc->sc_tx_th), 0,
		ATH_TX_RADIOTAP_PRESENT,
	    &sc->sc_rx_th.wr_ihdr, sizeof(sc->sc_rx_th), 1,
		ATH_RX_RADIOTAP_PRESENT);
#else
	/*
	 * No vendor bitmap/extensions are present.
	 */
	ieee80211_radiotap_attach(ic,
	    &sc->sc_tx_th.wt_ihdr, sizeof(sc->sc_tx_th),
		ATH_TX_RADIOTAP_PRESENT,
	    &sc->sc_rx_th.wr_ihdr, sizeof(sc->sc_rx_th),
		ATH_RX_RADIOTAP_PRESENT);
#endif	/* ATH_ENABLE_RADIOTAP_VENDOR_EXT */

	/*
	 * Setup the ALQ logging if required
	 */
#ifdef	ATH_DEBUG_ALQ
	if_ath_alq_init(&sc->sc_alq, device_get_nameunit(sc->sc_dev));
	if_ath_alq_setcfg(&sc->sc_alq,
	    sc->sc_ah->ah_macVersion,
	    sc->sc_ah->ah_macRev,
	    sc->sc_ah->ah_phyRev,
	    sc->sc_ah->ah_magic);
#endif

	/*
	 * Setup dynamic sysctl's now that country code and
	 * regdomain are available from the hal.
	 */
	ath_sysctlattach(sc);
	ath_sysctl_stats_attach(sc);
	ath_sysctl_hal_attach(sc);

	if (bootverbose)
		ieee80211_announce(ic);
	ath_announce(sc);

	/*
	 * Put it to sleep for now.
	 */
	ATH_LOCK(sc);
	ath_power_setpower(sc, HAL_PM_FULL_SLEEP, 1);
	ATH_UNLOCK(sc);

	return 0;
bad2:
	ath_tx_cleanup(sc);
	ath_desc_free(sc);
	ath_txdma_teardown(sc);
	ath_rxdma_teardown(sc);

bad:
	if (ah)
		ath_hal_detach(ah);
	sc->sc_invalid = 1;
	return error;
}

int
ath_detach(struct ath_softc *sc)
{

	/*
	 * NB: the order of these is important:
	 * o stop the chip so no more interrupts will fire
	 * o call the 802.11 layer before detaching the hal to
	 *   insure callbacks into the driver to delete global
	 *   key cache entries can be handled
	 * o free the taskqueue which drains any pending tasks
	 * o reclaim the tx queue data structures after calling
	 *   the 802.11 layer as we'll get called back to reclaim
	 *   node state and potentially want to use them
	 * o to cleanup the tx queues the hal is called, so detach
	 *   it last
	 * Other than that, it's straightforward...
	 */

	/*
	 * XXX Wake the hardware up first.  ath_stop() will still
	 * wake it up first, but I'd rather do it here just to
	 * ensure it's awake.
	 */
	ATH_LOCK(sc);
	ath_power_set_power_state(sc, HAL_PM_AWAKE);
	ath_power_setpower(sc, HAL_PM_AWAKE, 1);

	/*
	 * Stop things cleanly.
	 */
	ath_stop(sc);
	ATH_UNLOCK(sc);

	ieee80211_ifdetach(&sc->sc_ic);
	taskqueue_free(sc->sc_tq);
#ifdef ATH_TX99_DIAG
	if (sc->sc_tx99 != NULL)
		sc->sc_tx99->detach(sc->sc_tx99);
#endif
	ath_rate_detach(sc->sc_rc);
#ifdef	ATH_DEBUG_ALQ
	if_ath_alq_tidyup(&sc->sc_alq);
#endif
	ath_lna_div_detach(sc);
	ath_btcoex_detach(sc);
	ath_spectral_detach(sc);
	ath_dfs_detach(sc);
	ath_desc_free(sc);
	ath_txdma_teardown(sc);
	ath_rxdma_teardown(sc);
	ath_tx_cleanup(sc);
	ath_hal_detach(sc->sc_ah);	/* NB: sets chip in full sleep */

	return 0;
}

/*
 * MAC address handling for multiple BSS on the same radio.
 * The first vap uses the MAC address from the EEPROM.  For
 * subsequent vap's we set the U/L bit (bit 1) in the MAC
 * address and use the next six bits as an index.
 */
static void
assign_address(struct ath_softc *sc, uint8_t mac[IEEE80211_ADDR_LEN], int clone)
{
	int i;

	if (clone && sc->sc_hasbmask) {
		/* NB: we only do this if h/w supports multiple bssid */
		for (i = 0; i < 8; i++)
			if ((sc->sc_bssidmask & (1<<i)) == 0)
				break;
		if (i != 0)
			mac[0] |= (i << 2)|0x2;
	} else
		i = 0;
	sc->sc_bssidmask |= 1<<i;
	sc->sc_hwbssidmask[0] &= ~mac[0];
	if (i == 0)
		sc->sc_nbssid0++;
}

static void
reclaim_address(struct ath_softc *sc, const uint8_t mac[IEEE80211_ADDR_LEN])
{
	int i = mac[0] >> 2;
	uint8_t mask;

	if (i != 0 || --sc->sc_nbssid0 == 0) {
		sc->sc_bssidmask &= ~(1<<i);
		/* recalculate bssid mask from remaining addresses */
		mask = 0xff;
		for (i = 1; i < 8; i++)
			if (sc->sc_bssidmask & (1<<i))
				mask &= ~((i<<2)|0x2);
		sc->sc_hwbssidmask[0] |= mask;
	}
}

/*
 * Assign a beacon xmit slot.  We try to space out
 * assignments so when beacons are staggered the
 * traffic coming out of the cab q has maximal time
 * to go out before the next beacon is scheduled.
 */
static int
assign_bslot(struct ath_softc *sc)
{
	u_int slot, free;

	free = 0;
	for (slot = 0; slot < ATH_BCBUF; slot++)
		if (sc->sc_bslot[slot] == NULL) {
			if (sc->sc_bslot[(slot+1)%ATH_BCBUF] == NULL &&
			    sc->sc_bslot[(slot-1)%ATH_BCBUF] == NULL)
				return slot;
			free = slot;
			/* NB: keep looking for a double slot */
		}
	return free;
}

static struct ieee80211vap *
ath_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
    enum ieee80211_opmode opmode, int flags,
    const uint8_t bssid[IEEE80211_ADDR_LEN],
    const uint8_t mac0[IEEE80211_ADDR_LEN])
{
	struct ath_softc *sc = ic->ic_softc;
	struct ath_vap *avp;
	struct ieee80211vap *vap;
	uint8_t mac[IEEE80211_ADDR_LEN];
	int needbeacon, error;
	enum ieee80211_opmode ic_opmode;

	avp = malloc(sizeof(struct ath_vap), M_80211_VAP, M_WAITOK | M_ZERO);
	needbeacon = 0;
	IEEE80211_ADDR_COPY(mac, mac0);

	ATH_LOCK(sc);
	ic_opmode = opmode;		/* default to opmode of new vap */
	switch (opmode) {
	case IEEE80211_M_STA:
		if (sc->sc_nstavaps != 0) {	/* XXX only 1 for now */
			device_printf(sc->sc_dev, "only 1 sta vap supported\n");
			goto bad;
		}
		if (sc->sc_nvaps) {
			/*
			 * With multiple vaps we must fall back
			 * to s/w beacon miss handling.
			 */
			flags |= IEEE80211_CLONE_NOBEACONS;
		}
		if (flags & IEEE80211_CLONE_NOBEACONS) {
			/*
			 * Station mode w/o beacons are implemented w/ AP mode.
			 */
			ic_opmode = IEEE80211_M_HOSTAP;
		}
		break;
	case IEEE80211_M_IBSS:
		if (sc->sc_nvaps != 0) {	/* XXX only 1 for now */
			device_printf(sc->sc_dev,
			    "only 1 ibss vap supported\n");
			goto bad;
		}
		needbeacon = 1;
		break;
	case IEEE80211_M_AHDEMO:
#ifdef IEEE80211_SUPPORT_TDMA
		if (flags & IEEE80211_CLONE_TDMA) {
			if (sc->sc_nvaps != 0) {
				device_printf(sc->sc_dev,
				    "only 1 tdma vap supported\n");
				goto bad;
			}
			needbeacon = 1;
			flags |= IEEE80211_CLONE_NOBEACONS;
		}
		/* fall thru... */
#endif
	case IEEE80211_M_MONITOR:
		if (sc->sc_nvaps != 0 && ic->ic_opmode != opmode) {
			/*
			 * Adopt existing mode.  Adding a monitor or ahdemo
			 * vap to an existing configuration is of dubious
			 * value but should be ok.
			 */
			/* XXX not right for monitor mode */
			ic_opmode = ic->ic_opmode;
		}
		break;
	case IEEE80211_M_HOSTAP:
	case IEEE80211_M_MBSS:
		needbeacon = 1;
		break;
	case IEEE80211_M_WDS:
		if (sc->sc_nvaps != 0 && ic->ic_opmode == IEEE80211_M_STA) {
			device_printf(sc->sc_dev,
			    "wds not supported in sta mode\n");
			goto bad;
		}
		/*
		 * Silently remove any request for a unique
		 * bssid; WDS vap's always share the local
		 * mac address.
		 */
		flags &= ~IEEE80211_CLONE_BSSID;
		if (sc->sc_nvaps == 0)
			ic_opmode = IEEE80211_M_HOSTAP;
		else
			ic_opmode = ic->ic_opmode;
		break;
	default:
		device_printf(sc->sc_dev, "unknown opmode %d\n", opmode);
		goto bad;
	}
	/*
	 * Check that a beacon buffer is available; the code below assumes it.
	 */
	if (needbeacon & TAILQ_EMPTY(&sc->sc_bbuf)) {
		device_printf(sc->sc_dev, "no beacon buffer available\n");
		goto bad;
	}

	/* STA, AHDEMO? */
	if (opmode == IEEE80211_M_HOSTAP || opmode == IEEE80211_M_MBSS) {
		assign_address(sc, mac, flags & IEEE80211_CLONE_BSSID);
		ath_hal_setbssidmask(sc->sc_ah, sc->sc_hwbssidmask);
	}

	vap = &avp->av_vap;
	/* XXX can't hold mutex across if_alloc */
	ATH_UNLOCK(sc);
	error = ieee80211_vap_setup(ic, vap, name, unit, opmode, flags, bssid);
	ATH_LOCK(sc);
	if (error != 0) {
		device_printf(sc->sc_dev, "%s: error %d creating vap\n",
		    __func__, error);
		goto bad2;
	}

	/* h/w crypto support */
	vap->iv_key_alloc = ath_key_alloc;
	vap->iv_key_delete = ath_key_delete;
	vap->iv_key_set = ath_key_set;
	vap->iv_key_update_begin = ath_key_update_begin;
	vap->iv_key_update_end = ath_key_update_end;

	/* override various methods */
	avp->av_recv_mgmt = vap->iv_recv_mgmt;
	vap->iv_recv_mgmt = ath_recv_mgmt;
	vap->iv_reset = ath_reset_vap;
	vap->iv_update_beacon = ath_beacon_update;
	avp->av_newstate = vap->iv_newstate;
	vap->iv_newstate = ath_newstate;
	avp->av_bmiss = vap->iv_bmiss;
	vap->iv_bmiss = ath_bmiss_vap;

	avp->av_node_ps = vap->iv_node_ps;
	vap->iv_node_ps = ath_node_powersave;

	avp->av_set_tim = vap->iv_set_tim;
	vap->iv_set_tim = ath_node_set_tim;

	avp->av_recv_pspoll = vap->iv_recv_pspoll;
	vap->iv_recv_pspoll = ath_node_recv_pspoll;

	/* Set default parameters */

	/*
	 * Anything earlier than some AR9300 series MACs don't
	 * support a smaller MPDU density.
	 */
	vap->iv_ampdu_density = IEEE80211_HTCAP_MPDUDENSITY_8;
	/*
	 * All NICs can handle the maximum size, however
	 * AR5416 based MACs can only TX aggregates w/ RTS
	 * protection when the total aggregate size is <= 8k.
	 * However, for now that's enforced by the TX path.
	 */
	vap->iv_ampdu_rxmax = IEEE80211_HTCAP_MAXRXAMPDU_64K;
	vap->iv_ampdu_limit = IEEE80211_HTCAP_MAXRXAMPDU_64K;

	avp->av_bslot = -1;
	if (needbeacon) {
		/*
		 * Allocate beacon state and setup the q for buffered
		 * multicast frames.  We know a beacon buffer is
		 * available because we checked above.
		 */
		avp->av_bcbuf = TAILQ_FIRST(&sc->sc_bbuf);
		TAILQ_REMOVE(&sc->sc_bbuf, avp->av_bcbuf, bf_list);
		if (opmode != IEEE80211_M_IBSS || !sc->sc_hasveol) {
			/*
			 * Assign the vap to a beacon xmit slot.  As above
			 * this cannot fail to find a free one.
			 */
			avp->av_bslot = assign_bslot(sc);
			KASSERT(sc->sc_bslot[avp->av_bslot] == NULL,
			    ("beacon slot %u not empty", avp->av_bslot));
			sc->sc_bslot[avp->av_bslot] = vap;
			sc->sc_nbcnvaps++;
		}
		if (sc->sc_hastsfadd && sc->sc_nbcnvaps > 0) {
			/*
			 * Multple vaps are to transmit beacons and we
			 * have h/w support for TSF adjusting; enable
			 * use of staggered beacons.
			 */
			sc->sc_stagbeacons = 1;
		}
		ath_txq_init(sc, &avp->av_mcastq, ATH_TXQ_SWQ);
	}

	ic->ic_opmode = ic_opmode;
	if (opmode != IEEE80211_M_WDS) {
		sc->sc_nvaps++;
		if (opmode == IEEE80211_M_STA)
			sc->sc_nstavaps++;
		if (opmode == IEEE80211_M_MBSS)
			sc->sc_nmeshvaps++;
	}
	switch (ic_opmode) {
	case IEEE80211_M_IBSS:
		sc->sc_opmode = HAL_M_IBSS;
		break;
	case IEEE80211_M_STA:
		sc->sc_opmode = HAL_M_STA;
		break;
	case IEEE80211_M_AHDEMO:
#ifdef IEEE80211_SUPPORT_TDMA
		if (vap->iv_caps & IEEE80211_C_TDMA) {
			sc->sc_tdma = 1;
			/* NB: disable tsf adjust */
			sc->sc_stagbeacons = 0;
		}
		/*
		 * NB: adhoc demo mode is a pseudo mode; to the hal it's
		 * just ap mode.
		 */
		/* fall thru... */
#endif
	case IEEE80211_M_HOSTAP:
	case IEEE80211_M_MBSS:
		sc->sc_opmode = HAL_M_HOSTAP;
		break;
	case IEEE80211_M_MONITOR:
		sc->sc_opmode = HAL_M_MONITOR;
		break;
	default:
		/* XXX should not happen */
		break;
	}
	if (sc->sc_hastsfadd) {
		/*
		 * Configure whether or not TSF adjust should be done.
		 */
		ath_hal_settsfadjust(sc->sc_ah, sc->sc_stagbeacons);
	}
	if (flags & IEEE80211_CLONE_NOBEACONS) {
		/*
		 * Enable s/w beacon miss handling.
		 */
		sc->sc_swbmiss = 1;
	}
	ATH_UNLOCK(sc);

	/* complete setup */
	ieee80211_vap_attach(vap, ath_media_change, ieee80211_media_status,
	    mac);
	return vap;
bad2:
	reclaim_address(sc, mac);
	ath_hal_setbssidmask(sc->sc_ah, sc->sc_hwbssidmask);
bad:
	free(avp, M_80211_VAP);
	ATH_UNLOCK(sc);
	return NULL;
}

static void
ath_vap_delete(struct ieee80211vap *vap)
{
	struct ieee80211com *ic = vap->iv_ic;
	struct ath_softc *sc = ic->ic_softc;
	struct ath_hal *ah = sc->sc_ah;
	struct ath_vap *avp = ATH_VAP(vap);

	ATH_LOCK(sc);
	ath_power_set_power_state(sc, HAL_PM_AWAKE);
	ATH_UNLOCK(sc);

	DPRINTF(sc, ATH_DEBUG_RESET, "%s: called\n", __func__);
	if (sc->sc_running) {
		/*
		 * Quiesce the hardware while we remove the vap.  In
		 * particular we need to reclaim all references to
		 * the vap state by any frames pending on the tx queues.
		 */
		ath_hal_intrset(ah, 0);		/* disable interrupts */
		/* XXX Do all frames from all vaps/nodes need draining here? */
		ath_stoprecv(sc, 1);		/* stop recv side */
		ath_draintxq(sc, ATH_RESET_DEFAULT);		/* stop hw xmit side */
	}

	/* .. leave the hardware awake for now. */

	ieee80211_vap_detach(vap);

	/*
	 * XXX Danger Will Robinson! Danger!
	 *
	 * Because ieee80211_vap_detach() can queue a frame (the station
	 * diassociate message?) after we've drained the TXQ and
	 * flushed the software TXQ, we will end up with a frame queued
	 * to a node whose vap is about to be freed.
	 *
	 * To work around this, flush the hardware/software again.
	 * This may be racy - the ath task may be running and the packet
	 * may be being scheduled between sw->hw txq. Tsk.
	 *
	 * TODO: figure out why a new node gets allocated somewhere around
	 * here (after the ath_tx_swq() call; and after an ath_stop()
	 * call!)
	 */

	ath_draintxq(sc, ATH_RESET_DEFAULT);

	ATH_LOCK(sc);
	/*
	 * Reclaim beacon state.  Note this must be done before
	 * the vap instance is reclaimed as we may have a reference
	 * to it in the buffer for the beacon frame.
	 */
	if (avp->av_bcbuf != NULL) {
		if (avp->av_bslot != -1) {
			sc->sc_bslot[avp->av_bslot] = NULL;
			sc->sc_nbcnvaps--;
		}
		ath_beacon_return(sc, avp->av_bcbuf);
		avp->av_bcbuf = NULL;
		if (sc->sc_nbcnvaps == 0) {
			sc->sc_stagbeacons = 0;
			if (sc->sc_hastsfadd)
				ath_hal_settsfadjust(sc->sc_ah, 0);
		}
		/*
		 * Reclaim any pending mcast frames for the vap.
		 */
		ath_tx_draintxq(sc, &avp->av_mcastq);
	}
	/*
	 * Update bookkeeping.
	 */
	if (vap->iv_opmode == IEEE80211_M_STA) {
		sc->sc_nstavaps--;
		if (sc->sc_nstavaps == 0 && sc->sc_swbmiss)
			sc->sc_swbmiss = 0;
	} else if (vap->iv_opmode == IEEE80211_M_HOSTAP ||
	    vap->iv_opmode == IEEE80211_M_MBSS) {
		reclaim_address(sc, vap->iv_myaddr);
		ath_hal_setbssidmask(ah, sc->sc_hwbssidmask);
		if (vap->iv_opmode == IEEE80211_M_MBSS)
			sc->sc_nmeshvaps--;
	}
	if (vap->iv_opmode != IEEE80211_M_WDS)
		sc->sc_nvaps--;
#ifdef IEEE80211_SUPPORT_TDMA
	/* TDMA operation ceases when the last vap is destroyed */
	if (sc->sc_tdma && sc->sc_nvaps == 0) {
		sc->sc_tdma = 0;
		sc->sc_swbmiss = 0;
	}
#endif
	free(avp, M_80211_VAP);

	if (sc->sc_running) {
		/*
		 * Restart rx+tx machines if still running (RUNNING will
		 * be reset if we just destroyed the last vap).
		 */
		if (ath_startrecv(sc) != 0)
			device_printf(sc->sc_dev,
			    "%s: unable to restart recv logic\n", __func__);
		if (sc->sc_beacons) {		/* restart beacons */
#ifdef IEEE80211_SUPPORT_TDMA
			if (sc->sc_tdma)
				ath_tdma_config(sc, NULL);
			else
#endif
				ath_beacon_config(sc, NULL);
		}
		ath_hal_intrset(ah, sc->sc_imask);
	}

	/* Ok, let the hardware asleep. */
	ath_power_restore_power_state(sc);
	ATH_UNLOCK(sc);
}

void
ath_suspend(struct ath_softc *sc)
{
	struct ieee80211com *ic = &sc->sc_ic;

	sc->sc_resume_up = ic->ic_nrunning != 0;

	ieee80211_suspend_all(ic);
	/*
	 * NB: don't worry about putting the chip in low power
	 * mode; pci will power off our socket on suspend and
	 * CardBus detaches the device.
	 *
	 * XXX TODO: well, that's great, except for non-cardbus
	 * devices!
	 */

	/*
	 * XXX This doesn't wait until all pending taskqueue
	 * items and parallel transmit/receive/other threads
	 * are running!
	 */
	ath_hal_intrset(sc->sc_ah, 0);
	taskqueue_block(sc->sc_tq);

	ATH_LOCK(sc);
	callout_stop(&sc->sc_cal_ch);
	ATH_UNLOCK(sc);

	/*
	 * XXX ensure sc_invalid is 1
	 */

	/* Disable the PCIe PHY, complete with workarounds */
	ath_hal_enablepcie(sc->sc_ah, 1, 1);
}

/*
 * Reset the key cache since some parts do not reset the
 * contents on resume.  First we clear all entries, then
 * re-load keys that the 802.11 layer assumes are setup
 * in h/w.
 */
static void
ath_reset_keycache(struct ath_softc *sc)
{
	struct ieee80211com *ic = &sc->sc_ic;
	struct ath_hal *ah = sc->sc_ah;
	int i;

	ATH_LOCK(sc);
	ath_power_set_power_state(sc, HAL_PM_AWAKE);
	for (i = 0; i < sc->sc_keymax; i++)
		ath_hal_keyreset(ah, i);
	ath_power_restore_power_state(sc);
	ATH_UNLOCK(sc);
	ieee80211_crypto_reload_keys(ic);
}

/*
 * Fetch the current chainmask configuration based on the current
 * operating channel and options.
 */
static void
ath_update_chainmasks(struct ath_softc *sc, struct ieee80211_channel *chan)
{

	/*
	 * Set TX chainmask to the currently configured chainmask;
	 * the TX chainmask depends upon the current operating mode.
	 */
	sc->sc_cur_rxchainmask = sc->sc_rxchainmask;
	if (IEEE80211_IS_CHAN_HT(chan)) {
		sc->sc_cur_txchainmask = sc->sc_txchainmask;
	} else {
		sc->sc_cur_txchainmask = 1;
	}

	DPRINTF(sc, ATH_DEBUG_RESET,
	    "%s: TX chainmask is now 0x%x, RX is now 0x%x\n",
	    __func__,
	    sc->sc_cur_txchainmask,
	    sc->sc_cur_rxchainmask);
}

void
ath_resume(struct ath_softc *sc)
{
	struct ieee80211com *ic = &sc->sc_ic;
	struct ath_hal *ah = sc->sc_ah;
	HAL_STATUS status;

	ath_hal_enablepcie(ah, 0, 0);

	/*
	 * Must reset the chip before we reload the
	 * keycache as we were powered down on suspend.
	 */
	ath_update_chainmasks(sc,
	    sc->sc_curchan != NULL ? sc->sc_curchan : ic->ic_curchan);
	ath_hal_setchainmasks(sc->sc_ah, sc->sc_cur_txchainmask,
	    sc->sc_cur_rxchainmask);

	/* Ensure we set the current power state to on */
	ATH_LOCK(sc);
	ath_power_setselfgen(sc, HAL_PM_AWAKE);
	ath_power_set_power_state(sc, HAL_PM_AWAKE);
	ath_power_setpower(sc, HAL_PM_AWAKE, 1);
	ATH_UNLOCK(sc);

	ath_hal_reset(ah, sc->sc_opmode,
	    sc->sc_curchan != NULL ? sc->sc_curchan : ic->ic_curchan,
	    AH_FALSE, HAL_RESET_NORMAL, &status);
	ath_reset_keycache(sc);

	ATH_RX_LOCK(sc);
	sc->sc_rx_stopped = 1;
	sc->sc_rx_resetted = 1;
	ATH_RX_UNLOCK(sc);

	/* Let DFS at it in case it's a DFS channel */
	ath_dfs_radar_enable(sc, ic->ic_curchan);

	/* Let spectral at in case spectral is enabled */
	ath_spectral_enable(sc, ic->ic_curchan);

	/*
	 * Let bluetooth coexistence at in case it's needed for this channel
	 */
	ath_btcoex_enable(sc, ic->ic_curchan);

	/*
	 * If we're doing TDMA, enforce the TXOP limitation for chips that
	 * support it.
	 */
	if (sc->sc_hasenforcetxop && sc->sc_tdma)
		ath_hal_setenforcetxop(sc->sc_ah, 1);
	else
		ath_hal_setenforcetxop(sc->sc_ah, 0);

	/* Restore the LED configuration */
	ath_led_config(sc);
	ath_hal_setledstate(ah, HAL_LED_INIT);

	if (sc->sc_resume_up)
		ieee80211_resume_all(ic);

	ATH_LOCK(sc);
	ath_power_restore_power_state(sc);
	ATH_UNLOCK(sc);

	/* XXX beacons ? */
}

void
ath_shutdown(struct ath_softc *sc)
{

	ATH_LOCK(sc);
	ath_stop(sc);
	ATH_UNLOCK(sc);
	/* NB: no point powering down chip as we're about to reboot */
}

/*
 * Interrupt handler.  Most of the actual processing is deferred.
 */
void
ath_intr(void *arg)
{
	struct ath_softc *sc = arg;
	struct ath_hal *ah = sc->sc_ah;
	HAL_INT status = 0;
	uint32_t txqs;

	/*
	 * If we're inside a reset path, just print a warning and
	 * clear the ISR. The reset routine will finish it for us.
	 */
	ATH_PCU_LOCK(sc);
	if (sc->sc_inreset_cnt) {
		HAL_INT status;
		ath_hal_getisr(ah, &status);	/* clear ISR */
		ath_hal_intrset(ah, 0);		/* disable further intr's */
		DPRINTF(sc, ATH_DEBUG_ANY,
		    "%s: in reset, ignoring: status=0x%x\n",
		    __func__, status);
		ATH_PCU_UNLOCK(sc);
		return;
	}

	if (sc->sc_invalid) {
		/*
		 * The hardware is not ready/present, don't touch anything.
		 * Note this can happen early on if the IRQ is shared.
		 */
		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid; ignored\n", __func__);
		ATH_PCU_UNLOCK(sc);
		return;
	}
	if (!ath_hal_intrpend(ah)) {		/* shared irq, not for us */
		ATH_PCU_UNLOCK(sc);
		return;
	}

	ATH_LOCK(sc);
	ath_power_set_power_state(sc, HAL_PM_AWAKE);
	ATH_UNLOCK(sc);

	if (sc->sc_ic.ic_nrunning == 0 && sc->sc_running == 0) {
		HAL_INT status;

		DPRINTF(sc, ATH_DEBUG_ANY, "%s: ic_nrunning %d sc_running %d\n",
		    __func__, sc->sc_ic.ic_nrunning, sc->sc_running);
		ath_hal_getisr(ah, &status);	/* clear ISR */
		ath_hal_intrset(ah, 0);		/* disable further intr's */
		ATH_PCU_UNLOCK(sc);

		ATH_LOCK(sc);
		ath_power_restore_power_state(sc);
		ATH_UNLOCK(sc);
		return;
	}

	/*
	 * Figure out the reason(s) for the interrupt.  Note
	 * that the hal returns a pseudo-ISR that may include
	 * bits we haven't explicitly enabled so we mask the
	 * value to insure we only process bits we requested.
	 */
	ath_hal_getisr(ah, &status);		/* NB: clears ISR too */
	DPRINTF(sc, ATH_DEBUG_INTR, "%s: status 0x%x\n", __func__, status);
	ATH_KTR(sc, ATH_KTR_INTERRUPTS, 1, "ath_intr: mask=0x%.8x", status);
#ifdef	ATH_DEBUG_ALQ
	if_ath_alq_post_intr(&sc->sc_alq, status, ah->ah_intrstate,
	    ah->ah_syncstate);
#endif	/* ATH_DEBUG_ALQ */
#ifdef	ATH_KTR_INTR_DEBUG
	ATH_KTR(sc, ATH_KTR_INTERRUPTS, 5,
	    "ath_intr: ISR=0x%.8x, ISR_S0=0x%.8x, ISR_S1=0x%.8x, ISR_S2=0x%.8x, ISR_S5=0x%.8x",
	    ah->ah_intrstate[0],
	    ah->ah_intrstate[1],
	    ah->ah_intrstate[2],
	    ah->ah_intrstate[3],
	    ah->ah_intrstate[6]);
#endif

	/* Squirrel away SYNC interrupt debugging */
	if (ah->ah_syncstate != 0) {
		int i;
		for (i = 0; i < 32; i++)
			if (ah->ah_syncstate & (i << i))
				sc->sc_intr_stats.sync_intr[i]++;
	}

	status &= sc->sc_imask;			/* discard unasked for bits */

	/* Short-circuit un-handled interrupts */
	if (status == 0x0) {
		ATH_PCU_UNLOCK(sc);

		ATH_LOCK(sc);
		ath_power_restore_power_state(sc);
		ATH_UNLOCK(sc);

		return;
	}

	/*
	 * Take a note that we're inside the interrupt handler, so
	 * the reset routines know to wait.
	 */
	sc->sc_intr_cnt++;
	ATH_PCU_UNLOCK(sc);

	/*
	 * Handle the interrupt. We won't run concurrent with the reset
	 * or channel change routines as they'll wait for sc_intr_cnt
	 * to be 0 before continuing.
	 */
	if (status & HAL_INT_FATAL) {
		sc->sc_stats.ast_hardware++;
		ath_hal_intrset(ah, 0);		/* disable intr's until reset */
		taskqueue_enqueue(sc->sc_tq, &sc->sc_fataltask);
	} else {
		if (status & HAL_INT_SWBA) {
			/*
			 * Software beacon alert--time to send a beacon.
			 * Handle beacon transmission directly; deferring
			 * this is too slow to meet timing constraints
			 * under load.
			 */
#ifdef IEEE80211_SUPPORT_TDMA
			if (sc->sc_tdma) {
				if (sc->sc_tdmaswba == 0) {
					struct ieee80211com *ic = &sc->sc_ic;
					struct ieee80211vap *vap =
					    TAILQ_FIRST(&ic->ic_vaps);
					ath_tdma_beacon_send(sc, vap);
					sc->sc_tdmaswba =
					    vap->iv_tdma->tdma_bintval;
				} else
					sc->sc_tdmaswba--;
			} else
#endif
			{
				ath_beacon_proc(sc, 0);
#ifdef IEEE80211_SUPPORT_SUPERG
				/*
				 * Schedule the rx taskq in case there's no
				 * traffic so any frames held on the staging
				 * queue are aged and potentially flushed.
				 */
				sc->sc_rx.recv_sched(sc, 1);
#endif
			}
		}
		if (status & HAL_INT_RXEOL) {
			int imask;
			ATH_KTR(sc, ATH_KTR_ERROR, 0, "ath_intr: RXEOL");
			if (! sc->sc_isedma) {
				ATH_PCU_LOCK(sc);
				/*
				 * NB: the hardware should re-read the link when
				 *     RXE bit is written, but it doesn't work at
				 *     least on older hardware revs.
				 */
				sc->sc_stats.ast_rxeol++;
				/*
				 * Disable RXEOL/RXORN - prevent an interrupt
				 * storm until the PCU logic can be reset.
				 * In case the interface is reset some other
				 * way before "sc_kickpcu" is called, don't
				 * modify sc_imask - that way if it is reset
				 * by a call to ath_reset() somehow, the
				 * interrupt mask will be correctly reprogrammed.
				 */
				imask = sc->sc_imask;
				imask &= ~(HAL_INT_RXEOL | HAL_INT_RXORN);
				ath_hal_intrset(ah, imask);
				/*
				 * Only blank sc_rxlink if we've not yet kicked
				 * the PCU.
				 *
				 * This isn't entirely correct - the correct solution
				 * would be to have a PCU lock and engage that for
				 * the duration of the PCU fiddling; which would include
				 * running the RX process. Otherwise we could end up
				 * messing up the RX descriptor chain and making the
				 * RX desc list much shorter.
				 */
				if (! sc->sc_kickpcu)
					sc->sc_rxlink = NULL;
				sc->sc_kickpcu = 1;
				ATH_PCU_UNLOCK(sc);
			}
			/*
			 * Enqueue an RX proc to handle whatever
			 * is in the RX queue.
			 * This will then kick the PCU if required.
			 */
			sc->sc_rx.recv_sched(sc, 1);
		}
		if (status & HAL_INT_TXURN) {
			sc->sc_stats.ast_txurn++;
			/* bump tx trigger level */
			ath_hal_updatetxtriglevel(ah, AH_TRUE);
		}
		/*
		 * Handle both the legacy and RX EDMA interrupt bits.
		 * Note that HAL_INT_RXLP is also HAL_INT_RXDESC.
		 */
		if (status & (HAL_INT_RX | HAL_INT_RXHP | HAL_INT_RXLP)) {
			sc->sc_stats.ast_rx_intr++;
			sc->sc_rx.recv_sched(sc, 1);
		}
		if (status & HAL_INT_TX) {
			sc->sc_stats.ast_tx_intr++;
			/*
			 * Grab all the currently set bits in the HAL txq bitmap
			 * and blank them. This is the only place we should be
			 * doing this.
			 */
			if (! sc->sc_isedma) {
				ATH_PCU_LOCK(sc);
				txqs = 0xffffffff;
				ath_hal_gettxintrtxqs(sc->sc_ah, &txqs);
				ATH_KTR(sc, ATH_KTR_INTERRUPTS, 3,
				    "ath_intr: TX; txqs=0x%08x, txq_active was 0x%08x, now 0x%08x",
				    txqs,
				    sc->sc_txq_active,
				    sc->sc_txq_active | txqs);
				sc->sc_txq_active |= txqs;
				ATH_PCU_UNLOCK(sc);
			}
			taskqueue_enqueue(sc->sc_tq, &sc->sc_txtask);
		}
		if (status & HAL_INT_BMISS) {
			sc->sc_stats.ast_bmiss++;
			taskqueue_enqueue(sc->sc_tq, &sc->sc_bmisstask);
		}
		if (status & HAL_INT_GTT)
			sc->sc_stats.ast_tx_timeout++;
		if (status & HAL_INT_CST)
			sc->sc_stats.ast_tx_cst++;
		if (status & HAL_INT_MIB) {
			sc->sc_stats.ast_mib++;
			ATH_PCU_LOCK(sc);
			/*
			 * Disable interrupts until we service the MIB
			 * interrupt; otherwise it will continue to fire.
			 */
			ath_hal_intrset(ah, 0);
			/*
			 * Let the hal handle the event.  We assume it will
			 * clear whatever condition caused the interrupt.
			 */
			ath_hal_mibevent(ah, &sc->sc_halstats);
			/*
			 * Don't reset the interrupt if we've just
			 * kicked the PCU, or we may get a nested
			 * RXEOL before the rxproc has had a chance
			 * to run.
			 */
			if (sc->sc_kickpcu == 0)
				ath_hal_intrset(ah, sc->sc_imask);
			ATH_PCU_UNLOCK(sc);
		}
		if (status & HAL_INT_RXORN) {
			/* NB: hal marks HAL_INT_FATAL when RXORN is fatal */
			ATH_KTR(sc, ATH_KTR_ERROR, 0, "ath_intr: RXORN");
			sc->sc_stats.ast_rxorn++;
		}
		if (status & HAL_INT_TSFOOR) {
			/* out of range beacon - wake the chip up,
			 * but don't modify self-gen frame config */
			device_printf(sc->sc_dev, "%s: TSFOOR\n", __func__);
			sc->sc_syncbeacon = 1;
			ATH_LOCK(sc);
			ath_power_setpower(sc, HAL_PM_AWAKE, 0);
			ATH_UNLOCK(sc);
		}
		if (status & HAL_INT_MCI) {
			ath_btcoex_mci_intr(sc);
		}
	}
	ATH_PCU_LOCK(sc);
	sc->sc_intr_cnt--;
	ATH_PCU_UNLOCK(sc);

	ATH_LOCK(sc);
	ath_power_restore_power_state(sc);
	ATH_UNLOCK(sc);
}

static void
ath_fatal_proc(void *arg, int pending)
{
	struct ath_softc *sc = arg;
	u_int32_t *state;
	u_int32_t len;
	void *sp;

	if (sc->sc_invalid)
		return;

	device_printf(sc->sc_dev, "hardware error; resetting\n");
	/*
	 * Fatal errors are unrecoverable.  Typically these
	 * are caused by DMA errors.  Collect h/w state from
	 * the hal so we can diagnose what's going on.
	 */
	if (ath_hal_getfatalstate(sc->sc_ah, &sp, &len)) {
		KASSERT(len >= 6*sizeof(u_int32_t), ("len %u bytes", len));
		state = sp;
		device_printf(sc->sc_dev,
		    "0x%08x 0x%08x 0x%08x, 0x%08x 0x%08x 0x%08x\n", state[0],
		    state[1] , state[2], state[3], state[4], state[5]);
	}
	ath_reset(sc, ATH_RESET_NOLOSS);
}

static void
ath_bmiss_vap(struct ieee80211vap *vap)
{
	struct ath_softc *sc = vap->iv_ic->ic_softc;

	/*
	 * Workaround phantom bmiss interrupts by sanity-checking
	 * the time of our last rx'd frame.  If it is within the
	 * beacon miss interval then ignore the interrupt.  If it's
	 * truly a bmiss we'll get another interrupt soon and that'll
	 * be dispatched up for processing.  Note this applies only
	 * for h/w beacon miss events.
	 */

	/*
	 * XXX TODO: Just read the TSF during the interrupt path;
	 * that way we don't have to wake up again just to read it
	 * again.
	 */
	ATH_LOCK(sc);
	ath_power_set_power_state(sc, HAL_PM_AWAKE);
	ATH_UNLOCK(sc);

	if ((vap->iv_flags_ext & IEEE80211_FEXT_SWBMISS) == 0) {
		u_int64_t lastrx = sc->sc_lastrx;
		u_int64_t tsf = ath_hal_gettsf64(sc->sc_ah);
		/* XXX should take a locked ref to iv_bss */
		u_int bmisstimeout =
			vap->iv_bmissthreshold * vap->iv_bss->ni_intval * 1024;

		DPRINTF(sc, ATH_DEBUG_BEACON,
		    "%s: tsf %llu lastrx %lld (%llu) bmiss %u\n",
		    __func__, (unsigned long long) tsf,
		    (unsigned long long)(tsf - lastrx),
		    (unsigned long long) lastrx, bmisstimeout);

		if (tsf - lastrx <= bmisstimeout) {
			sc->sc_stats.ast_bmiss_phantom++;

			ATH_LOCK(sc);
			ath_power_restore_power_state(sc);
			ATH_UNLOCK(sc);

			return;
		}
	}

	/*
	 * Keep the hardware awake if it's asleep (and leave self-gen
	 * frame config alone) until the next beacon, so we can resync
	 * against the next beacon.
	 *
	 * This handles three common beacon miss cases in STA powersave mode -
	 * (a) the beacon TBTT isnt a multiple of bintval;
	 * (b) the beacon was missed; and
	 * (c) the beacons are being delayed because the AP is busy and
	 *     isn't reliably able to meet its TBTT.
	 */
	ATH_LOCK(sc);
	ath_power_setpower(sc, HAL_PM_AWAKE, 0);
	ath_power_restore_power_state(sc);
	ATH_UNLOCK(sc);
	DPRINTF(sc, ATH_DEBUG_BEACON,
	    "%s: forced awake; force syncbeacon=1\n", __func__);

	/*
	 * Attempt to force a beacon resync.
	 */
	sc->sc_syncbeacon = 1;

	ATH_VAP(vap)->av_bmiss(vap);
}

/* XXX this needs a force wakeup! */
int
ath_hal_gethangstate(struct ath_hal *ah, uint32_t mask, uint32_t *hangs)
{
	uint32_t rsize;
	void *sp;

	if (!ath_hal_getdiagstate(ah, HAL_DIAG_CHECK_HANGS, &mask, sizeof(mask), &sp, &rsize))
		return 0;
	KASSERT(rsize == sizeof(uint32_t), ("resultsize %u", rsize));
	*hangs = *(uint32_t *)sp;
	return 1;
}

static void
ath_bmiss_proc(void *arg, int pending)
{
	struct ath_softc *sc = arg;
	uint32_t hangs;

	DPRINTF(sc, ATH_DEBUG_ANY, "%s: pending %u\n", __func__, pending);

	ATH_LOCK(sc);
	ath_power_set_power_state(sc, HAL_PM_AWAKE);
	ATH_UNLOCK(sc);

	ath_beacon_miss(sc);

	/*
	 * Do a reset upon any becaon miss event.
	 *
	 * It may be a non-recognised RX clear hang which needs a reset
	 * to clear.
	 */
	if (ath_hal_gethangstate(sc->sc_ah, 0xff, &hangs) && hangs != 0) {
		ath_reset(sc, ATH_RESET_NOLOSS);
		device_printf(sc->sc_dev,
		    "bb hang detected (0x%x), resetting\n", hangs);
	} else {
		ath_reset(sc, ATH_RESET_NOLOSS);
		ieee80211_beacon_miss(&sc->sc_ic);
	}

	/* Force a beacon resync, in case they've drifted */
	sc->sc_syncbeacon = 1;

	ATH_LOCK(sc);
	ath_power_restore_power_state(sc);
	ATH_UNLOCK(sc);
}

/*
 * Handle TKIP MIC setup to deal hardware that doesn't do MIC
 * calcs together with WME.  If necessary disable the crypto
 * hardware and mark the 802.11 state so keys will be setup
 * with the MIC work done in software.
 */
static void
ath_settkipmic(struct ath_softc *sc)
{
	struct ieee80211com *ic = &sc->sc_ic;

	if ((ic->ic_cryptocaps & IEEE80211_CRYPTO_TKIP) && !sc->sc_wmetkipmic) {
		if (ic->ic_flags & IEEE80211_F_WME) {
			ath_hal_settkipmic(sc->sc_ah, AH_FALSE);
			ic->ic_cryptocaps &= ~IEEE80211_CRYPTO_TKIPMIC;
		} else {
			ath_hal_settkipmic(sc->sc_ah, AH_TRUE);
			ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIPMIC;
		}
	}
}

static void
ath_vap_clear_quiet_ie(struct ath_softc *sc)
{
	struct ieee80211com *ic = &sc->sc_ic;
	struct ieee80211vap *vap;
	struct ath_vap *avp;

	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
		avp = ATH_VAP(vap);
		/* Quiet time handling - ensure we resync */
		memset(&avp->quiet_ie, 0, sizeof(avp->quiet_ie));
	}
}

static int
ath_init(struct ath_softc *sc)
{
	struct ieee80211com *ic = &sc->sc_ic;
	struct ath_hal *ah = sc->sc_ah;
	HAL_STATUS status;

	ATH_LOCK_ASSERT(sc);

	/*
	 * Force the sleep state awake.
	 */
	ath_power_setselfgen(sc, HAL_PM_AWAKE);
	ath_power_set_power_state(sc, HAL_PM_AWAKE);
	ath_power_setpower(sc, HAL_PM_AWAKE, 1);

	/*
	 * Stop anything previously setup.  This is safe
	 * whether this is the first time through or not.
	 */
	ath_stop(sc);

	/*
	 * The basic interface to setting the hardware in a good
	 * state is ``reset''.  On return the hardware is known to
	 * be powered up and with interrupts disabled.  This must
	 * be followed by initialization of the appropriate bits
	 * and then setup of the interrupt mask.
	 */
	ath_settkipmic(sc);
	ath_update_chainmasks(sc, ic->ic_curchan);
	ath_hal_setchainmasks(sc->sc_ah, sc->sc_cur_txchainmask,
	    sc->sc_cur_rxchainmask);

	if (!ath_hal_reset(ah, sc->sc_opmode, ic->ic_curchan, AH_FALSE,
	    HAL_RESET_NORMAL, &status)) {
		device_printf(sc->sc_dev,
		    "unable to reset hardware; hal status %u\n", status);
		return (ENODEV);
	}

	ATH_RX_LOCK(sc);
	sc->sc_rx_stopped = 1;
	sc->sc_rx_resetted = 1;
	ATH_RX_UNLOCK(sc);

	/* Clear quiet IE state for each VAP */
	ath_vap_clear_quiet_ie(sc);

	ath_chan_change(sc, ic->ic_curchan);

	/* Let DFS at it in case it's a DFS channel */
	ath_dfs_radar_enable(sc, ic->ic_curchan);

	/* Let spectral at in case spectral is enabled */
	ath_spectral_enable(sc, ic->ic_curchan);

	/*
	 * Let bluetooth coexistence at in case it's needed for this channel
	 */
	ath_btcoex_enable(sc, ic->ic_curchan);

	/*
	 * If we're doing TDMA, enforce the TXOP limitation for chips that
	 * support it.
	 */
	if (sc->sc_hasenforcetxop && sc->sc_tdma)
		ath_hal_setenforcetxop(sc->sc_ah, 1);
	else
		ath_hal_setenforcetxop(sc->sc_ah, 0);

	/*
	 * Likewise this is set during reset so update
	 * state cached in the driver.
	 */
	sc->sc_diversity = ath_hal_getdiversity(ah);
	sc->sc_lastlongcal = ticks;
	sc->sc_resetcal = 1;
	sc->sc_lastcalreset = 0;
	sc->sc_lastani = ticks;
	sc->sc_lastshortcal = ticks;
	sc->sc_doresetcal = AH_FALSE;
	/*
	 * Beacon timers were cleared here; give ath_newstate()
	 * a hint that the beacon timers should be poked when
	 * things transition to the RUN state.
	 */
	sc->sc_beacons = 0;

	/*
	 * Setup the hardware after reset: the key cache
	 * is filled as needed and the receive engine is
	 * set going.  Frame transmit is handled entirely
	 * in the frame output path; there's nothing to do
	 * here except setup the interrupt mask.
	 */
	if (ath_startrecv(sc) != 0) {
		device_printf(sc->sc_dev, "unable to start recv logic\n");
		ath_power_restore_power_state(sc);
		return (ENODEV);
	}

	/*
	 * Enable interrupts.
	 */
	sc->sc_imask = HAL_INT_RX | HAL_INT_TX
		  | HAL_INT_RXORN | HAL_INT_TXURN
		  | HAL_INT_FATAL | HAL_INT_GLOBAL;

	/*
	 * Enable RX EDMA bits.  Note these overlap with
	 * HAL_INT_RX and HAL_INT_RXDESC respectively.
	 */
	if (sc->sc_isedma)
		sc->sc_imask |= (HAL_INT_RXHP | HAL_INT_RXLP);

	/*
	 * If we're an EDMA NIC, we don't care about RXEOL.
	 * Writing a new descriptor in will simply restart
	 * RX DMA.
	 */
	if (! sc->sc_isedma)
		sc->sc_imask |= HAL_INT_RXEOL;

	/*
	 * Enable MCI interrupt for MCI devices.
	 */
	if (sc->sc_btcoex_mci)
		sc->sc_imask |= HAL_INT_MCI;

	/*
	 * Enable MIB interrupts when there are hardware phy counters.
	 * Note we only do this (at the moment) for station mode.
	 */
	if (sc->sc_needmib && ic->ic_opmode == IEEE80211_M_STA)
		sc->sc_imask |= HAL_INT_MIB;

	/*
	 * XXX add capability for this.
	 *
	 * If we're in STA mode (and maybe IBSS?) then register for
	 * TSFOOR interrupts.
	 */
	if (ic->ic_opmode == IEEE80211_M_STA)
		sc->sc_imask |= HAL_INT_TSFOOR;

	/* Enable global TX timeout and carrier sense timeout if available */
	if (ath_hal_gtxto_supported(ah))
		sc->sc_imask |= HAL_INT_GTT;

	DPRINTF(sc, ATH_DEBUG_RESET, "%s: imask=0x%x\n",
		__func__, sc->sc_imask);

	sc->sc_running = 1;
	callout_reset(&sc->sc_wd_ch, hz, ath_watchdog, sc);
	ath_hal_intrset(ah, sc->sc_imask);

	ath_power_restore_power_state(sc);

	return (0);
}

static void
ath_stop(struct ath_softc *sc)
{
	struct ath_hal *ah = sc->sc_ah;

	ATH_LOCK_ASSERT(sc);

	/*
	 * Wake the hardware up before fiddling with it.
	 */
	ath_power_set_power_state(sc, HAL_PM_AWAKE);

	if (sc->sc_running) {
		/*
		 * Shutdown the hardware and driver:
		 *    reset 802.11 state machine
		 *    turn off timers
		 *    disable interrupts
		 *    turn off the radio
		 *    clear transmit machinery
		 *    clear receive machinery
		 *    drain and release tx queues
		 *    reclaim beacon resources
		 *    power down hardware
		 *
		 * Note that some of this work is not possible if the
		 * hardware is gone (invalid).
		 */
#ifdef ATH_TX99_DIAG
		if (sc->sc_tx99 != NULL)
			sc->sc_tx99->stop(sc->sc_tx99);
#endif
		callout_stop(&sc->sc_wd_ch);
		sc->sc_wd_timer = 0;
		sc->sc_running = 0;
		if (!sc->sc_invalid) {
			if (sc->sc_softled) {
				callout_stop(&sc->sc_ledtimer);
				ath_hal_gpioset(ah, sc->sc_ledpin,
					!sc->sc_ledon);
				sc->sc_blinking = 0;
			}
			ath_hal_intrset(ah, 0);
		}
		/* XXX we should stop RX regardless of whether it's valid */
		if (!sc->sc_invalid) {
			ath_stoprecv(sc, 1);
			ath_hal_phydisable(ah);
		} else
			sc->sc_rxlink = NULL;
		ath_draintxq(sc, ATH_RESET_DEFAULT);
		ath_beacon_free(sc);	/* XXX not needed */
	}

	/* And now, restore the current power state */
	ath_power_restore_power_state(sc);
}

/*
 * Wait until all pending TX/RX has completed.
 *
 * This waits until all existing transmit, receive and interrupts
 * have completed.  It's assumed that the caller has first
 * grabbed the reset lock so it doesn't try to do overlapping
 * chip resets.
 */
#define	MAX_TXRX_ITERATIONS	100
static void
ath_txrx_stop_locked(struct ath_softc *sc)
{
	int i = MAX_TXRX_ITERATIONS;

	ATH_UNLOCK_ASSERT(sc);
	ATH_PCU_LOCK_ASSERT(sc);

	/*
	 * Sleep until all the pending operations have completed.
	 *
	 * The caller must ensure that reset has been incremented
	 * or the pending operations may continue being queued.
	 */
	while (sc->sc_rxproc_cnt || sc->sc_txproc_cnt ||
	    sc->sc_txstart_cnt || sc->sc_intr_cnt) {
		if (i <= 0)
			break;
		msleep(sc, &sc->sc_pcu_mtx, 0, "ath_txrx_stop",
		    msecs_to_ticks(10));
		i--;
	}

	if (i <= 0)
		device_printf(sc->sc_dev,
		    "%s: didn't finish after %d iterations\n",
		    __func__, MAX_TXRX_ITERATIONS);
}
#undef	MAX_TXRX_ITERATIONS

#if 0
static void
ath_txrx_stop(struct ath_softc *sc)
{
	ATH_UNLOCK_ASSERT(sc);
	ATH_PCU_UNLOCK_ASSERT(sc);

	ATH_PCU_LOCK(sc);
	ath_txrx_stop_locked(sc);
	ATH_PCU_UNLOCK(sc);
}
#endif

static void
ath_txrx_start(struct ath_softc *sc)
{

	taskqueue_unblock(sc->sc_tq);
}

/*
 * Grab the reset lock, and wait around until no one else
 * is trying to do anything with it.
 *
 * This is totally horrible but we can't hold this lock for
 * long enough to do TX/RX or we end up with net80211/ip stack
 * LORs and eventual deadlock.
 *
 * "dowait" signals whether to spin, waiting for the reset
 * lock count to reach 0. This should (for now) only be used
 * during the reset path, as the rest of the code may not
 * be locking-reentrant enough to behave correctly.
 *
 * Another, cleaner way should be found to serialise all of
 * these operations.
 */
#define	MAX_RESET_ITERATIONS	25
static int
ath_reset_grablock(struct ath_softc *sc, int dowait)
{
	int w = 0;
	int i = MAX_RESET_ITERATIONS;

	ATH_PCU_LOCK_ASSERT(sc);
	do {
		if (sc->sc_inreset_cnt == 0) {
			w = 1;
			break;
		}
		if (dowait == 0) {
			w = 0;
			break;
		}
		ATH_PCU_UNLOCK(sc);
		/*
		 * 1 tick is likely not enough time for long calibrations
		 * to complete.  So we should wait quite a while.
		 */
		pause("ath_reset_grablock", msecs_to_ticks(100));
		i--;
		ATH_PCU_LOCK(sc);
	} while (i > 0);

	/*
	 * We always increment the refcounter, regardless
	 * of whether we succeeded to get it in an exclusive
	 * way.
	 */
	sc->sc_inreset_cnt++;

	if (i <= 0)
		device_printf(sc->sc_dev,
		    "%s: didn't finish after %d iterations\n",
		    __func__, MAX_RESET_ITERATIONS);

	if (w == 0)
		device_printf(sc->sc_dev,
		    "%s: warning, recursive reset path!\n",
		    __func__);

	return w;
}
#undef MAX_RESET_ITERATIONS

/*
 * Reset the hardware w/o losing operational state.  This is
 * basically a more efficient way of doing ath_stop, ath_init,
 * followed by state transitions to the current 802.11
 * operational state.  Used to recover from various errors and
 * to reset or reload hardware state.
 */
int
ath_reset(struct ath_softc *sc, ATH_RESET_TYPE reset_type)
{
	struct ieee80211com *ic = &sc->sc_ic;
	struct ath_hal *ah = sc->sc_ah;
	HAL_STATUS status;
	int i;

	DPRINTF(sc, ATH_DEBUG_RESET, "%s: called\n", __func__);

	/* Ensure ATH_LOCK isn't held; ath_rx_proc can't be locked */
	ATH_PCU_UNLOCK_ASSERT(sc);
	ATH_UNLOCK_ASSERT(sc);

	/* Try to (stop any further TX/RX from occurring */
	taskqueue_block(sc->sc_tq);

	/*
	 * Wake the hardware up.
	 */
	ATH_LOCK(sc);
	ath_power_set_power_state(sc, HAL_PM_AWAKE);
	ATH_UNLOCK(sc);

	ATH_PCU_LOCK(sc);

	/*
	 * Grab the reset lock before TX/RX is stopped.
	 *
	 * This is needed to ensure that when the TX/RX actually does finish,
	 * no further TX/RX/reset runs in parallel with this.
	 */
	if (ath_reset_grablock(sc, 1) == 0) {
		device_printf(sc->sc_dev, "%s: concurrent reset! Danger!\n",
		    __func__);
	}

	/* disable interrupts */
	ath_hal_intrset(ah, 0);

	/*
	 * Now, ensure that any in progress TX/RX completes before we
	 * continue.
	 */
	ath_txrx_stop_locked(sc);

	ATH_PCU_UNLOCK(sc);

	/*
	 * Regardless of whether we're doing a no-loss flush or
	 * not, stop the PCU and handle what's in the RX queue.
	 * That way frames aren't dropped which shouldn't be.
	 */
	ath_stoprecv(sc, (reset_type != ATH_RESET_NOLOSS));
	ath_rx_flush(sc);

	/*
	 * Should now wait for pending TX/RX to complete
	 * and block future ones from occurring. This needs to be
	 * done before the TX queue is drained.
	 */
	ath_draintxq(sc, reset_type);	/* stop xmit side */

	ath_settkipmic(sc);		/* configure TKIP MIC handling */
	/* NB: indicate channel change so we do a full reset */
	ath_update_chainmasks(sc, ic->ic_curchan);
	ath_hal_setchainmasks(sc->sc_ah, sc->sc_cur_txchainmask,
	    sc->sc_cur_rxchainmask);
	if (!ath_hal_reset(ah, sc->sc_opmode, ic->ic_curchan, AH_TRUE,
	    HAL_RESET_NORMAL, &status))
		device_printf(sc->sc_dev,
		    "%s: unable to reset hardware; hal status %u\n",
		    __func__, status);
	sc->sc_diversity = ath_hal_getdiversity(ah);

	ATH_RX_LOCK(sc);
	sc->sc_rx_stopped = 1;
	sc->sc_rx_resetted = 1;
	ATH_RX_UNLOCK(sc);

	/* Quiet time handling - ensure we resync */
	ath_vap_clear_quiet_ie(sc);

	/* Let DFS at it in case it's a DFS channel */
	ath_dfs_radar_enable(sc, ic->ic_curchan);

	/* Let spectral at in case spectral is enabled */
	ath_spectral_enable(sc, ic->ic_curchan);

	/*
	 * Let bluetooth coexistence at in case it's needed for this channel
	 */
	ath_btcoex_enable(sc, ic->ic_curchan);

	/*
	 * If we're doing TDMA, enforce the TXOP limitation for chips that
	 * support it.
	 */
	if (sc->sc_hasenforcetxop && sc->sc_tdma)
		ath_hal_setenforcetxop(sc->sc_ah, 1);
	else
		ath_hal_setenforcetxop(sc->sc_ah, 0);

	if (ath_startrecv(sc) != 0)	/* restart recv */
		device_printf(sc->sc_dev,
		    "%s: unable to start recv logic\n", __func__);
	/*
	 * We may be doing a reset in response to an ioctl
	 * that changes the channel so update any state that
	 * might change as a result.
	 */
	ath_chan_change(sc, ic->ic_curchan);
	if (sc->sc_beacons) {		/* restart beacons */
#ifdef IEEE80211_SUPPORT_TDMA
		if (sc->sc_tdma)
			ath_tdma_config(sc, NULL);
		else
#endif
			ath_beacon_config(sc, NULL);
	}

	/*
	 * Release the reset lock and re-enable interrupts here.
	 * If an interrupt was being processed in ath_intr(),
	 * it would disable interrupts at this point. So we have
	 * to atomically enable interrupts and decrement the
	 * reset counter - this way ath_intr() doesn't end up
	 * disabling interrupts without a corresponding enable
	 * in the rest or channel change path.
	 *
	 * Grab the TX reference in case we need to transmit.
	 * That way a parallel transmit doesn't.
	 */
	ATH_PCU_LOCK(sc);
	sc->sc_inreset_cnt--;
	sc->sc_txstart_cnt++;
	/* XXX only do this if sc_inreset_cnt == 0? */
	ath_hal_intrset(ah, sc->sc_imask);
	ATH_PCU_UNLOCK(sc);

	/*
	 * TX and RX can be started here. If it were started with
	 * sc_inreset_cnt > 0, the TX and RX path would abort.
	 * Thus if this is a nested call through the reset or
	 * channel change code, TX completion will occur but
	 * RX completion and ath_start / ath_tx_start will not
	 * run.
	 */

	/* Restart TX/RX as needed */
	ath_txrx_start(sc);

	/* XXX TODO: we need to hold the tx refcount here! */

	/* Restart TX completion and pending TX */
	if (reset_type == ATH_RESET_NOLOSS) {
		for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
			if (ATH_TXQ_SETUP(sc, i)) {
				ATH_TXQ_LOCK(&sc->sc_txq[i]);
				ath_txq_restart_dma(sc, &sc->sc_txq[i]);
				ATH_TXQ_UNLOCK(&sc->sc_txq[i]);

				ATH_TX_LOCK(sc);
				ath_txq_sched(sc, &sc->sc_txq[i]);
				ATH_TX_UNLOCK(sc);
			}
		}
	}

	ATH_LOCK(sc);
	ath_power_restore_power_state(sc);
	ATH_UNLOCK(sc);

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

	/* Handle any frames in the TX queue */
	/*
	 * XXX should this be done by the caller, rather than
	 * ath_reset() ?
	 */
	ath_tx_kick(sc);		/* restart xmit */
	return 0;
}

static int
ath_reset_vap(struct ieee80211vap *vap, u_long cmd)
{
	struct ieee80211com *ic = vap->iv_ic;
	struct ath_softc *sc = ic->ic_softc;
	struct ath_hal *ah = sc->sc_ah;

	switch (cmd) {
	case IEEE80211_IOC_TXPOWER:
		/*
		 * If per-packet TPC is enabled, then we have nothing
		 * to do; otherwise we need to force the global limit.
		 * All this can happen directly; no need to reset.
		 */
		if (!ath_hal_gettpc(ah))
			ath_hal_settxpowlimit(ah, ic->ic_txpowlimit);
		return 0;
	}
	/* XXX? Full or NOLOSS? */
	return ath_reset(sc, ATH_RESET_FULL);
}

struct ath_buf *
_ath_getbuf_locked(struct ath_softc *sc, ath_buf_type_t btype)
{
	struct ath_buf *bf;

	ATH_TXBUF_LOCK_ASSERT(sc);

	if (btype == ATH_BUFTYPE_MGMT)
		bf = TAILQ_FIRST(&sc->sc_txbuf_mgmt);
	else
		bf = TAILQ_FIRST(&sc->sc_txbuf);

	if (bf == NULL) {
		sc->sc_stats.ast_tx_getnobuf++;
	} else {
		if (bf->bf_flags & ATH_BUF_BUSY) {
			sc->sc_stats.ast_tx_getbusybuf++;
			bf = NULL;
		}
	}

	if (bf != NULL && (bf->bf_flags & ATH_BUF_BUSY) == 0) {
		if (btype == ATH_BUFTYPE_MGMT)
			TAILQ_REMOVE(&sc->sc_txbuf_mgmt, bf, bf_list);
		else {
			TAILQ_REMOVE(&sc->sc_txbuf, bf, bf_list);
			sc->sc_txbuf_cnt--;

			/*
			 * This shuldn't happen; however just to be
			 * safe print a warning and fudge the txbuf
			 * count.
			 */
			if (sc->sc_txbuf_cnt < 0) {
				device_printf(sc->sc_dev,
				    "%s: sc_txbuf_cnt < 0?\n",
				    __func__);
				sc->sc_txbuf_cnt = 0;
			}
		}
	} else
		bf = NULL;

	if (bf == NULL) {
		/* XXX should check which list, mgmt or otherwise */
		DPRINTF(sc, ATH_DEBUG_XMIT, "%s: %s\n", __func__,
		    TAILQ_FIRST(&sc->sc_txbuf) == NULL ?
			"out of xmit buffers" : "xmit buffer busy");
		return NULL;
	}

	/* XXX TODO: should do this at buffer list initialisation */
	/* XXX (then, ensure the buffer has the right flag set) */
	bf->bf_flags = 0;
	if (btype == ATH_BUFTYPE_MGMT)
		bf->bf_flags |= ATH_BUF_MGMT;
	else
		bf->bf_flags &= (~ATH_BUF_MGMT);

	/* Valid bf here; clear some basic fields */
	bf->bf_next = NULL;	/* XXX just to be sure */
	bf->bf_last = NULL;	/* XXX again, just to be sure */
	bf->bf_comp = NULL;	/* XXX again, just to be sure */
	bzero(&bf->bf_state, sizeof(bf->bf_state));

	/*
	 * Track the descriptor ID only if doing EDMA
	 */
	if (sc->sc_isedma) {
		bf->bf_descid = sc->sc_txbuf_descid;
		sc->sc_txbuf_descid++;
	}

	return bf;
}

/*
 * When retrying a software frame, buffers marked ATH_BUF_BUSY
 * can't be thrown back on the queue as they could still be
 * in use by the hardware.
 *
 * This duplicates the buffer, or returns NULL.
 *
 * The descriptor is also copied but the link pointers and
 * the DMA segments aren't copied; this frame should thus
 * be again passed through the descriptor setup/chain routines
 * so the link is correct.
 *
 * The caller must free the buffer using ath_freebuf().
 */
struct ath_buf *
ath_buf_clone(struct ath_softc *sc, struct ath_buf *bf)
{
	struct ath_buf *tbf;

	tbf = ath_getbuf(sc,
	    (bf->bf_flags & ATH_BUF_MGMT) ?
	     ATH_BUFTYPE_MGMT : ATH_BUFTYPE_NORMAL);
	if (tbf == NULL)
		return NULL;	/* XXX failure? Why? */

	/* Copy basics */
	tbf->bf_next = NULL;
	tbf->bf_nseg = bf->bf_nseg;
	tbf->bf_flags = bf->bf_flags & ATH_BUF_FLAGS_CLONE;
	tbf->bf_status = bf->bf_status;
	tbf->bf_m = bf->bf_m;
	tbf->bf_node = bf->bf_node;
	KASSERT((bf->bf_node != NULL), ("%s: bf_node=NULL!", __func__));
	/* will be setup by the chain/setup function */
	tbf->bf_lastds = NULL;
	/* for now, last == self */
	tbf->bf_last = tbf;
	tbf->bf_comp = bf->bf_comp;

	/* NOTE: DMA segments will be setup by the setup/chain functions */

	/* The caller has to re-init the descriptor + links */

	/*
	 * Free the DMA mapping here, before we NULL the mbuf.
	 * We must only call bus_dmamap_unload() once per mbuf chain
	 * or behaviour is undefined.
	 */
	if (bf->bf_m != NULL) {
		/*
		 * XXX is this POSTWRITE call required?
		 */
		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
		    BUS_DMASYNC_POSTWRITE);
		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
	}

	bf->bf_m = NULL;
	bf->bf_node = NULL;

	/* Copy state */
	memcpy(&tbf->bf_state, &bf->bf_state, sizeof(bf->bf_state));

	return tbf;
}

struct ath_buf *
ath_getbuf(struct ath_softc *sc, ath_buf_type_t btype)
{
	struct ath_buf *bf;

	ATH_TXBUF_LOCK(sc);
	bf = _ath_getbuf_locked(sc, btype);
	/*
	 * If a mgmt buffer was requested but we're out of those,
	 * try requesting a normal one.
	 */
	if (bf == NULL && btype == ATH_BUFTYPE_MGMT)
		bf = _ath_getbuf_locked(sc, ATH_BUFTYPE_NORMAL);
	ATH_TXBUF_UNLOCK(sc);
	if (bf == NULL) {
		DPRINTF(sc, ATH_DEBUG_XMIT, "%s: stop queue\n", __func__);
		sc->sc_stats.ast_tx_qstop++;
	}
	return bf;
}

/*
 * Transmit a single frame.
 *
 * net80211 will free the node reference if the transmit
 * fails, so don't free the node reference here.
 */
static int
ath_transmit(struct ieee80211com *ic, struct mbuf *m)
{
	struct ath_softc *sc = ic->ic_softc;
	struct ieee80211_node *ni;
	struct mbuf *next;
	struct ath_buf *bf;
	ath_bufhead frags;
	int retval = 0;

	/*
	 * Tell the reset path that we're currently transmitting.
	 */
	ATH_PCU_LOCK(sc);
	if (sc->sc_inreset_cnt > 0) {
		DPRINTF(sc, ATH_DEBUG_XMIT,
		    "%s: sc_inreset_cnt > 0; bailing\n", __func__);
		ATH_PCU_UNLOCK(sc);
		sc->sc_stats.ast_tx_qstop++;
		ATH_KTR(sc, ATH_KTR_TX, 0, "ath_start_task: OACTIVE, finish");
		return (ENOBUFS);	/* XXX should be EINVAL or? */
	}
	sc->sc_txstart_cnt++;
	ATH_PCU_UNLOCK(sc);

	/* Wake the hardware up already */
	ATH_LOCK(sc);
	ath_power_set_power_state(sc, HAL_PM_AWAKE);
	ATH_UNLOCK(sc);

	ATH_KTR(sc, ATH_KTR_TX, 0, "ath_transmit: start");
	/*
	 * Grab the TX lock - it's ok to do this here; we haven't
	 * yet started transmitting.
	 */
	ATH_TX_LOCK(sc);

	/*
	 * Node reference, if there's one.
	 */
	ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;

	/*
	 * Enforce how deep a node queue can get.
	 *
	 * XXX it would be nicer if we kept an mbuf queue per
	 * node and only whacked them into ath_bufs when we
	 * are ready to schedule some traffic from them.
	 * .. that may come later.
	 *
	 * XXX we should also track the per-node hardware queue
	 * depth so it is easy to limit the _SUM_ of the swq and
	 * hwq frames.  Since we only schedule two HWQ frames
	 * at a time, this should be OK for now.
	 */
	if ((!(m->m_flags & M_EAPOL)) &&
	    (ATH_NODE(ni)->an_swq_depth > sc->sc_txq_node_maxdepth)) {
		sc->sc_stats.ast_tx_nodeq_overflow++;
		retval = ENOBUFS;
		goto finish;
	}

	/*
	 * Check how many TX buffers are available.
	 *
	 * If this is for non-EAPOL traffic, just leave some
	 * space free in order for buffer cloning and raw
	 * frame transmission to occur.
	 *
	 * If it's for EAPOL traffic, ignore this for now.
	 * Management traffic will be sent via the raw transmit
	 * method which bypasses this check.
	 *
	 * This is needed to ensure that EAPOL frames during
	 * (re) keying have a chance to go out.
	 *
	 * See kern/138379 for more information.
	 */
	if ((!(m->m_flags & M_EAPOL)) &&
	    (sc->sc_txbuf_cnt <= sc->sc_txq_data_minfree)) {
		sc->sc_stats.ast_tx_nobuf++;
		retval = ENOBUFS;
		goto finish;
	}

	/*
	 * Grab a TX buffer and associated resources.
	 *
	 * If it's an EAPOL frame, allocate a MGMT ath_buf.
	 * That way even with temporary buffer exhaustion due to
	 * the data path doesn't leave us without the ability
	 * to transmit management frames.
	 *
	 * Otherwise allocate a normal buffer.
	 */
	if (m->m_flags & M_EAPOL)
		bf = ath_getbuf(sc, ATH_BUFTYPE_MGMT);
	else
		bf = ath_getbuf(sc, ATH_BUFTYPE_NORMAL);

	if (bf == NULL) {
		/*
		 * If we failed to allocate a buffer, fail.
		 *
		 * We shouldn't fail normally, due to the check
		 * above.
		 */
		sc->sc_stats.ast_tx_nobuf++;
		retval = ENOBUFS;
		goto finish;
	}

	/*
	 * At this point we have a buffer; so we need to free it
	 * if we hit any error conditions.
	 */

	/*
	 * Check for fragmentation.  If this frame
	 * has been broken up verify we have enough
	 * buffers to send all the fragments so all
	 * go out or none...
	 */
	TAILQ_INIT(&frags);
	if ((m->m_flags & M_FRAG) &&
	    !ath_txfrag_setup(sc, &frags, m, ni)) {
		DPRINTF(sc, ATH_DEBUG_XMIT,
		    "%s: out of txfrag buffers\n", __func__);
		sc->sc_stats.ast_tx_nofrag++;
		if_inc_counter(ni->ni_vap->iv_ifp, IFCOUNTER_OERRORS, 1);
		/*
		 * XXXGL: is mbuf valid after ath_txfrag_setup? If yes,
		 * we shouldn't free it but return back.
		 */
		ieee80211_free_mbuf(m);
		m = NULL;
		goto bad;
	}

	/*
	 * At this point if we have any TX fragments, then we will
	 * have bumped the node reference once for each of those.
	 */

	/*
	 * XXX Is there anything actually _enforcing_ that the
	 * fragments are being transmitted in one hit, rather than
	 * being interleaved with other transmissions on that
	 * hardware queue?
	 *
	 * The ATH TX output lock is the only thing serialising this
	 * right now.
	 */

	/*
	 * Calculate the "next fragment" length field in ath_buf
	 * in order to let the transmit path know enough about
	 * what to next write to the hardware.
	 */
	if (m->m_flags & M_FRAG) {
		struct ath_buf *fbf = bf;
		struct ath_buf *n_fbf = NULL;
		struct mbuf *fm = m->m_nextpkt;

		/*
		 * We need to walk the list of fragments and set
		 * the next size to the following buffer.
		 * However, the first buffer isn't in the frag
		 * list, so we have to do some gymnastics here.
		 */
		TAILQ_FOREACH(n_fbf, &frags, bf_list) {
			fbf->bf_nextfraglen = fm->m_pkthdr.len;
			fbf = n_fbf;
			fm = fm->m_nextpkt;
		}
	}

nextfrag:
	/*
	 * Pass the frame to the h/w for transmission.
	 * Fragmented frames have each frag chained together
	 * with m_nextpkt.  We know there are sufficient ath_buf's
	 * to send all the frags because of work done by
	 * ath_txfrag_setup.  We leave m_nextpkt set while
	 * calling ath_tx_start so it can use it to extend the
	 * the tx duration to cover the subsequent frag and
	 * so it can reclaim all the mbufs in case of an error;
	 * ath_tx_start clears m_nextpkt once it commits to
	 * handing the frame to the hardware.
	 *
	 * Note: if this fails, then the mbufs are freed but
	 * not the node reference.
	 *
	 * So, we now have to free the node reference ourselves here
	 * and return OK up to the stack.
	 */
	next = m->m_nextpkt;
	if (ath_tx_start(sc, ni, bf, m)) {
bad:
		if_inc_counter(ni->ni_vap->iv_ifp, IFCOUNTER_OERRORS, 1);
reclaim:
		bf->bf_m = NULL;
		bf->bf_node = NULL;
		ATH_TXBUF_LOCK(sc);
		ath_returnbuf_head(sc, bf);
		/*
		 * Free the rest of the node references and
		 * buffers for the fragment list.
		 */
		ath_txfrag_cleanup(sc, &frags, ni);
		ATH_TXBUF_UNLOCK(sc);

		/*
		 * XXX: And free the node/return OK; ath_tx_start() may have
		 *      modified the buffer.  We currently have no way to
		 *      signify that the mbuf was freed but there was an error.
		 */
		ieee80211_free_node(ni);
		retval = 0;
		goto finish;
	}

	/*
	 * Check here if the node is in power save state.
	 */
	ath_tx_update_tim(sc, ni, 1);

	if (next != NULL) {
		/*
		 * Beware of state changing between frags.
		 * XXX check sta power-save state?
		 */
		if (ni->ni_vap->iv_state != IEEE80211_S_RUN) {
			DPRINTF(sc, ATH_DEBUG_XMIT,
			    "%s: flush fragmented packet, state %s\n",
			    __func__,
			    ieee80211_state_name[ni->ni_vap->iv_state]);
			/* XXX dmamap */
			ieee80211_free_mbuf(next);
			goto reclaim;
		}
		m = next;
		bf = TAILQ_FIRST(&frags);
		KASSERT(bf != NULL, ("no buf for txfrag"));
		TAILQ_REMOVE(&frags, bf, bf_list);
		goto nextfrag;
	}

	/*
	 * Bump watchdog timer.
	 */
	sc->sc_wd_timer = 5;

finish:
	ATH_TX_UNLOCK(sc);

	/*
	 * Finished transmitting!
	 */
	ATH_PCU_LOCK(sc);
	sc->sc_txstart_cnt--;
	ATH_PCU_UNLOCK(sc);

	/* Sleep the hardware if required */
	ATH_LOCK(sc);
	ath_power_restore_power_state(sc);
	ATH_UNLOCK(sc);

	ATH_KTR(sc, ATH_KTR_TX, 0, "ath_transmit: finished");
	
	return (retval);
}

static int
ath_media_change(struct ifnet *ifp)
{
	int error = ieee80211_media_change(ifp);
	/* NB: only the fixed rate can change and that doesn't need a reset */
	return (error == ENETRESET ? 0 : error);
}

/*
 * Block/unblock tx+rx processing while a key change is done.
 * We assume the caller serializes key management operations
 * so we only need to worry about synchronization with other
 * uses that originate in the driver.
 */
static void
ath_key_update_begin(struct ieee80211vap *vap)
{
	struct ath_softc *sc = vap->iv_ic->ic_softc;

	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
	taskqueue_block(sc->sc_tq);
}

static void
ath_key_update_end(struct ieee80211vap *vap)
{
	struct ath_softc *sc = vap->iv_ic->ic_softc;

	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
	taskqueue_unblock(sc->sc_tq);
}

static void
ath_update_promisc(struct ieee80211com *ic)
{
	struct ath_softc *sc = ic->ic_softc;
	u_int32_t rfilt;

	/* configure rx filter */
	ATH_LOCK(sc);
	ath_power_set_power_state(sc, HAL_PM_AWAKE);
	rfilt = ath_calcrxfilter(sc);
	ath_hal_setrxfilter(sc->sc_ah, rfilt);
	ath_power_restore_power_state(sc);
	ATH_UNLOCK(sc);

	DPRINTF(sc, ATH_DEBUG_MODE, "%s: RX filter 0x%x\n", __func__, rfilt);
}

/*
 * Driver-internal mcast update call.
 *
 * Assumes the hardware is already awake.
 */
static void
ath_update_mcast_hw(struct ath_softc *sc)
{
	struct ieee80211com *ic = &sc->sc_ic;
	u_int32_t mfilt[2];

	/* calculate and install multicast filter */
	if (ic->ic_allmulti == 0) {
		struct ieee80211vap *vap;
		struct ifnet *ifp;
		struct ifmultiaddr *ifma;

		/*
		 * Merge multicast addresses to form the hardware filter.
		 */
		mfilt[0] = mfilt[1] = 0;
		TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
			ifp = vap->iv_ifp;
			if_maddr_rlock(ifp);
			TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
				caddr_t dl;
				uint32_t val;
				uint8_t pos;

				/* calculate XOR of eight 6bit values */
				dl = LLADDR((struct sockaddr_dl *)
				    ifma->ifma_addr);
				val = le32dec(dl + 0);
				pos = (val >> 18) ^ (val >> 12) ^ (val >> 6) ^
				    val;
				val = le32dec(dl + 3);
				pos ^= (val >> 18) ^ (val >> 12) ^ (val >> 6) ^
				    val;
				pos &= 0x3f;
				mfilt[pos / 32] |= (1 << (pos % 32));
			}
			if_maddr_runlock(ifp);
		}
	} else
		mfilt[0] = mfilt[1] = ~0;

	ath_hal_setmcastfilter(sc->sc_ah, mfilt[0], mfilt[1]);

	DPRINTF(sc, ATH_DEBUG_MODE, "%s: MC filter %08x:%08x\n",
		__func__, mfilt[0], mfilt[1]);
}

/*
 * Called from the net80211 layer - force the hardware
 * awake before operating.
 */
static void
ath_update_mcast(struct ieee80211com *ic)
{
	struct ath_softc *sc = ic->ic_softc;

	ATH_LOCK(sc);
	ath_power_set_power_state(sc, HAL_PM_AWAKE);
	ATH_UNLOCK(sc);

	ath_update_mcast_hw(sc);

	ATH_LOCK(sc);
	ath_power_restore_power_state(sc);
	ATH_UNLOCK(sc);
}

void
ath_mode_init(struct ath_softc *sc)
{
	struct ieee80211com *ic = &sc->sc_ic;
	struct ath_hal *ah = sc->sc_ah;
	u_int32_t rfilt;

	/* XXX power state? */

	/* configure rx filter */
	rfilt = ath_calcrxfilter(sc);
	ath_hal_setrxfilter(ah, rfilt);

	/* configure operational mode */
	ath_hal_setopmode(ah);

	/* handle any link-level address change */
	ath_hal_setmac(ah, ic->ic_macaddr);

	/* calculate and install multicast filter */
	ath_update_mcast_hw(sc);
}

/*
 * Set the slot time based on the current setting.
 */
void
ath_setslottime(struct ath_softc *sc)
{
	struct ieee80211com *ic = &sc->sc_ic;
	struct ath_hal *ah = sc->sc_ah;
	u_int usec;

	if (IEEE80211_IS_CHAN_HALF(ic->ic_curchan))
		usec = 13;
	else if (IEEE80211_IS_CHAN_QUARTER(ic->ic_curchan))
		usec = 21;
	else if (IEEE80211_IS_CHAN_ANYG(ic->ic_curchan)) {
		/* honor short/long slot time only in 11g */
		/* XXX shouldn't honor on pure g or turbo g channel */
		if (ic->ic_flags & IEEE80211_F_SHSLOT)
			usec = HAL_SLOT_TIME_9;
		else
			usec = HAL_SLOT_TIME_20;
	} else
		usec = HAL_SLOT_TIME_9;

	DPRINTF(sc, ATH_DEBUG_RESET,
	    "%s: chan %u MHz flags 0x%x %s slot, %u usec\n",
	    __func__, ic->ic_curchan->ic_freq, ic->ic_curchan->ic_flags,
	    ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long", usec);

	/* Wake up the hardware first before updating the slot time */
	ATH_LOCK(sc);
	ath_power_set_power_state(sc, HAL_PM_AWAKE);
	ath_hal_setslottime(ah, usec);
	ath_power_restore_power_state(sc);
	sc->sc_updateslot = OK;
	ATH_UNLOCK(sc);
}

/*
 * Callback from the 802.11 layer to update the
 * slot time based on the current setting.
 */
static void
ath_updateslot(struct ieee80211com *ic)
{
	struct ath_softc *sc = ic->ic_softc;

	/*
	 * When not coordinating the BSS, change the hardware
	 * immediately.  For other operation we defer the change
	 * until beacon updates have propagated to the stations.
	 *
	 * XXX sc_updateslot isn't changed behind a lock?
	 */
	if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
	    ic->ic_opmode == IEEE80211_M_MBSS)
		sc->sc_updateslot = UPDATE;
	else
		ath_setslottime(sc);
}

/*
 * Append the contents of src to dst; both queues
 * are assumed to be locked.
 */
void
ath_txqmove(struct ath_txq *dst, struct ath_txq *src)
{

	ATH_TXQ_LOCK_ASSERT(src);
	ATH_TXQ_LOCK_ASSERT(dst);

	TAILQ_CONCAT(&dst->axq_q, &src->axq_q, bf_list);
	dst->axq_link = src->axq_link;
	src->axq_link = NULL;
	dst->axq_depth += src->axq_depth;
	dst->axq_aggr_depth += src->axq_aggr_depth;
	src->axq_depth = 0;
	src->axq_aggr_depth = 0;
}

/*
 * Reset the hardware, with no loss.
 *
 * This can't be used for a general case reset.
 */
static void
ath_reset_proc(void *arg, int pending)
{
	struct ath_softc *sc = arg;

#if 0
	device_printf(sc->sc_dev, "%s: resetting\n", __func__);
#endif
	ath_reset(sc, ATH_RESET_NOLOSS);
}

/*
 * Reset the hardware after detecting beacons have stopped.
 */
static void
ath_bstuck_proc(void *arg, int pending)
{
	struct ath_softc *sc = arg;
	uint32_t hangs = 0;

	if (ath_hal_gethangstate(sc->sc_ah, 0xff, &hangs) && hangs != 0)
		device_printf(sc->sc_dev, "bb hang detected (0x%x)\n", hangs);

#ifdef	ATH_DEBUG_ALQ
	if (if_ath_alq_checkdebug(&sc->sc_alq, ATH_ALQ_STUCK_BEACON))
		if_ath_alq_post(&sc->sc_alq, ATH_ALQ_STUCK_BEACON, 0, NULL);
#endif

	device_printf(sc->sc_dev, "stuck beacon; resetting (bmiss count %u)\n",
	    sc->sc_bmisscount);
	sc->sc_stats.ast_bstuck++;
	/*
	 * This assumes that there's no simultaneous channel mode change
	 * occurring.
	 */
	ath_reset(sc, ATH_RESET_NOLOSS);
}

static int
ath_desc_alloc(struct ath_softc *sc)
{
	int error;

	error = ath_descdma_setup(sc, &sc->sc_txdma, &sc->sc_txbuf,
		    "tx", sc->sc_tx_desclen, ath_txbuf, ATH_MAX_SCATTER);
	if (error != 0) {
		return error;
	}
	sc->sc_txbuf_cnt = ath_txbuf;

	error = ath_descdma_setup(sc, &sc->sc_txdma_mgmt, &sc->sc_txbuf_mgmt,
		    "tx_mgmt", sc->sc_tx_desclen, ath_txbuf_mgmt,
		    ATH_TXDESC);
	if (error != 0) {
		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
		return error;
	}

	/*
	 * XXX mark txbuf_mgmt frames with ATH_BUF_MGMT, so the
	 * flag doesn't have to be set in ath_getbuf_locked().
	 */

	error = ath_descdma_setup(sc, &sc->sc_bdma, &sc->sc_bbuf,
			"beacon", sc->sc_tx_desclen, ATH_BCBUF, 1);
	if (error != 0) {
		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
		ath_descdma_cleanup(sc, &sc->sc_txdma_mgmt,
		    &sc->sc_txbuf_mgmt);
		return error;
	}
	return 0;
}

static void
ath_desc_free(struct ath_softc *sc)
{

	if (sc->sc_bdma.dd_desc_len != 0)
		ath_descdma_cleanup(sc, &sc->sc_bdma, &sc->sc_bbuf);
	if (sc->sc_txdma.dd_desc_len != 0)
		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
	if (sc->sc_txdma_mgmt.dd_desc_len != 0)
		ath_descdma_cleanup(sc, &sc->sc_txdma_mgmt,
		    &sc->sc_txbuf_mgmt);
}

static struct ieee80211_node *
ath_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
{
	struct ieee80211com *ic = vap->iv_ic;
	struct ath_softc *sc = ic->ic_softc;
	const size_t space = sizeof(struct ath_node) + sc->sc_rc->arc_space;
	struct ath_node *an;

	an = malloc(space, M_80211_NODE, M_NOWAIT|M_ZERO);
	if (an == NULL) {
		/* XXX stat+msg */
		return NULL;
	}
	ath_rate_node_init(sc, an);

	/* Setup the mutex - there's no associd yet so set the name to NULL */
	snprintf(an->an_name, sizeof(an->an_name), "%s: node %p",
	    device_get_nameunit(sc->sc_dev), an);
	mtx_init(&an->an_mtx, an->an_name, NULL, MTX_DEF);

	/* XXX setup ath_tid */
	ath_tx_tid_init(sc, an);

	DPRINTF(sc, ATH_DEBUG_NODE, "%s: %6D: an %p\n", __func__, mac, ":", an);
	return &an->an_node;
}

static void
ath_node_cleanup(struct ieee80211_node *ni)
{
	struct ieee80211com *ic = ni->ni_ic;
	struct ath_softc *sc = ic->ic_softc;

	DPRINTF(sc, ATH_DEBUG_NODE, "%s: %6D: an %p\n", __func__,
	    ni->ni_macaddr, ":", ATH_NODE(ni));

	/* Cleanup ath_tid, free unused bufs, unlink bufs in TXQ */
	ath_tx_node_flush(sc, ATH_NODE(ni));
	ath_rate_node_cleanup(sc, ATH_NODE(ni));
	sc->sc_node_cleanup(ni);
}

static void
ath_node_free(struct ieee80211_node *ni)
{
	struct ieee80211com *ic = ni->ni_ic;
	struct ath_softc *sc = ic->ic_softc;

	DPRINTF(sc, ATH_DEBUG_NODE, "%s: %6D: an %p\n", __func__,
	    ni->ni_macaddr, ":", ATH_NODE(ni));
	mtx_destroy(&ATH_NODE(ni)->an_mtx);
	sc->sc_node_free(ni);
}

static void
ath_node_getsignal(const struct ieee80211_node *ni, int8_t *rssi, int8_t *noise)
{
	struct ieee80211com *ic = ni->ni_ic;
	struct ath_softc *sc = ic->ic_softc;
	struct ath_hal *ah = sc->sc_ah;

	*rssi = ic->ic_node_getrssi(ni);
	if (ni->ni_chan != IEEE80211_CHAN_ANYC)
		*noise = ath_hal_getchannoise(ah, ni->ni_chan);
	else
		*noise = -95;		/* nominally correct */
}

/*
 * Set the default antenna.
 */
void
ath_setdefantenna(struct ath_softc *sc, u_int antenna)
{
	struct ath_hal *ah = sc->sc_ah;

	/* XXX block beacon interrupts */
	ath_hal_setdefantenna(ah, antenna);
	if (sc->sc_defant != antenna)
		sc->sc_stats.ast_ant_defswitch++;
	sc->sc_defant = antenna;
	sc->sc_rxotherant = 0;
}

static void
ath_txq_init(struct ath_softc *sc, struct ath_txq *txq, int qnum)
{
	txq->axq_qnum = qnum;
	txq->axq_ac = 0;
	txq->axq_depth = 0;
	txq->axq_aggr_depth = 0;
	txq->axq_intrcnt = 0;
	txq->axq_link = NULL;
	txq->axq_softc = sc;
	TAILQ_INIT(&txq->axq_q);
	TAILQ_INIT(&txq->axq_tidq);
	TAILQ_INIT(&txq->fifo.axq_q);
	ATH_TXQ_LOCK_INIT(sc, txq);
}

/*
 * Setup a h/w transmit queue.
 */
static struct ath_txq *
ath_txq_setup(struct ath_softc *sc, int qtype, int subtype)
{
	struct ath_hal *ah = sc->sc_ah;
	HAL_TXQ_INFO qi;
	int qnum;

	memset(&qi, 0, sizeof(qi));
	qi.tqi_subtype = subtype;
	qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
	qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
	qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
	/*
	 * Enable interrupts only for EOL and DESC conditions.
	 * We mark tx descriptors to receive a DESC interrupt
	 * when a tx queue gets deep; otherwise waiting for the
	 * EOL to reap descriptors.  Note that this is done to
	 * reduce interrupt load and this only defers reaping
	 * descriptors, never transmitting frames.  Aside from
	 * reducing interrupts this also permits more concurrency.
	 * The only potential downside is if the tx queue backs
	 * up in which case the top half of the kernel may backup
	 * due to a lack of tx descriptors.
	 */
	if (sc->sc_isedma)
		qi.tqi_qflags = HAL_TXQ_TXEOLINT_ENABLE |
		    HAL_TXQ_TXOKINT_ENABLE;
	else
		qi.tqi_qflags = HAL_TXQ_TXEOLINT_ENABLE |
		    HAL_TXQ_TXDESCINT_ENABLE;

	qnum = ath_hal_setuptxqueue(ah, qtype, &qi);
	if (qnum == -1) {
		/*
		 * NB: don't print a message, this happens
		 * normally on parts with too few tx queues
		 */
		return NULL;
	}
	if (qnum >= nitems(sc->sc_txq)) {
		device_printf(sc->sc_dev,
			"hal qnum %u out of range, max %zu!\n",
			qnum, nitems(sc->sc_txq));
		ath_hal_releasetxqueue(ah, qnum);
		return NULL;
	}
	if (!ATH_TXQ_SETUP(sc, qnum)) {
		ath_txq_init(sc, &sc->sc_txq[qnum], qnum);
		sc->sc_txqsetup |= 1<<qnum;
	}
	return &sc->sc_txq[qnum];
}

/*
 * Setup a hardware data transmit queue for the specified
 * access control.  The hal may not support all requested
 * queues in which case it will return a reference to a
 * previously setup queue.  We record the mapping from ac's
 * to h/w queues for use by ath_tx_start and also track
 * the set of h/w queues being used to optimize work in the
 * transmit interrupt handler and related routines.
 */
static int
ath_tx_setup(struct ath_softc *sc, int ac, int haltype)
{
	struct ath_txq *txq;

	if (ac >= nitems(sc->sc_ac2q)) {
		device_printf(sc->sc_dev, "AC %u out of range, max %zu!\n",
			ac, nitems(sc->sc_ac2q));
		return 0;
	}
	txq = ath_txq_setup(sc, HAL_TX_QUEUE_DATA, haltype);
	if (txq != NULL) {
		txq->axq_ac = ac;
		sc->sc_ac2q[ac] = txq;
		return 1;
	} else
		return 0;
}

/*
 * Update WME parameters for a transmit queue.
 */
static int
ath_txq_update(struct ath_softc *sc, int ac)
{
#define	ATH_EXPONENT_TO_VALUE(v)	((1<<v)-1)
	struct ieee80211com *ic = &sc->sc_ic;
	struct ath_txq *txq = sc->sc_ac2q[ac];
	struct chanAccParams chp;
	struct wmeParams *wmep;
	struct ath_hal *ah = sc->sc_ah;
	HAL_TXQ_INFO qi;

	ieee80211_wme_ic_getparams(ic, &chp);
	wmep = &chp.cap_wmeParams[ac];

	ath_hal_gettxqueueprops(ah, txq->axq_qnum, &qi);
#ifdef IEEE80211_SUPPORT_TDMA
	if (sc->sc_tdma) {
		/*
		 * AIFS is zero so there's no pre-transmit wait.  The
		 * burst time defines the slot duration and is configured
		 * through net80211.  The QCU is setup to not do post-xmit
		 * back off, lockout all lower-priority QCU's, and fire
		 * off the DMA beacon alert timer which is setup based
		 * on the slot configuration.
		 */
		qi.tqi_qflags = HAL_TXQ_TXOKINT_ENABLE
			      | HAL_TXQ_TXERRINT_ENABLE
			      | HAL_TXQ_TXURNINT_ENABLE
			      | HAL_TXQ_TXEOLINT_ENABLE
			      | HAL_TXQ_DBA_GATED
			      | HAL_TXQ_BACKOFF_DISABLE
			      | HAL_TXQ_ARB_LOCKOUT_GLOBAL
			      ;
		qi.tqi_aifs = 0;
		/* XXX +dbaprep? */
		qi.tqi_readyTime = sc->sc_tdmaslotlen;
		qi.tqi_burstTime = qi.tqi_readyTime;
	} else {
#endif
		/*
		 * XXX shouldn't this just use the default flags
		 * used in the previous queue setup?
		 */
		qi.tqi_qflags = HAL_TXQ_TXOKINT_ENABLE
			      | HAL_TXQ_TXERRINT_ENABLE
			      | HAL_TXQ_TXDESCINT_ENABLE
			      | HAL_TXQ_TXURNINT_ENABLE
			      | HAL_TXQ_TXEOLINT_ENABLE
			      ;
		qi.tqi_aifs = wmep->wmep_aifsn;
		qi.tqi_cwmin = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
		qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
		qi.tqi_readyTime = 0;
		qi.tqi_burstTime = IEEE80211_TXOP_TO_US(wmep->wmep_txopLimit);
#ifdef IEEE80211_SUPPORT_TDMA
	}
#endif

	DPRINTF(sc, ATH_DEBUG_RESET,
	    "%s: Q%u qflags 0x%x aifs %u cwmin %u cwmax %u burstTime %u\n",
	    __func__, txq->axq_qnum, qi.tqi_qflags,
	    qi.tqi_aifs, qi.tqi_cwmin, qi.tqi_cwmax, qi.tqi_burstTime);

	if (!ath_hal_settxqueueprops(ah, txq->axq_qnum, &qi)) {
		device_printf(sc->sc_dev, "unable to update hardware queue "
		    "parameters for %s traffic!\n", ieee80211_wme_acnames[ac]);
		return 0;
	} else {
		ath_hal_resettxqueue(ah, txq->axq_qnum); /* push to h/w */
		return 1;
	}
#undef ATH_EXPONENT_TO_VALUE
}

/*
 * Callback from the 802.11 layer to update WME parameters.
 */
int
ath_wme_update(struct ieee80211com *ic)
{
	struct ath_softc *sc = ic->ic_softc;

	return !ath_txq_update(sc, WME_AC_BE) ||
	    !ath_txq_update(sc, WME_AC_BK) ||
	    !ath_txq_update(sc, WME_AC_VI) ||
	    !ath_txq_update(sc, WME_AC_VO) ? EIO : 0;
}

/*
 * Reclaim resources for a setup queue.
 */
static void
ath_tx_cleanupq(struct ath_softc *sc, struct ath_txq *txq)
{

	ath_hal_releasetxqueue(sc->sc_ah, txq->axq_qnum);
	sc->sc_txqsetup &= ~(1<<txq->axq_qnum);
	ATH_TXQ_LOCK_DESTROY(txq);
}

/*
 * Reclaim all tx queue resources.
 */
static void
ath_tx_cleanup(struct ath_softc *sc)
{
	int i;

	ATH_TXBUF_LOCK_DESTROY(sc);
	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
		if (ATH_TXQ_SETUP(sc, i))
			ath_tx_cleanupq(sc, &sc->sc_txq[i]);
}

/*
 * Return h/w rate index for an IEEE rate (w/o basic rate bit)
 * using the current rates in sc_rixmap.
 */
int
ath_tx_findrix(const struct ath_softc *sc, uint8_t rate)
{
	int rix = sc->sc_rixmap[rate];
	/* NB: return lowest rix for invalid rate */
	return (rix == 0xff ? 0 : rix);
}

static void
ath_tx_update_stats(struct ath_softc *sc, struct ath_tx_status *ts,
    struct ath_buf *bf)
{
	struct ieee80211_node *ni = bf->bf_node;
	struct ieee80211com *ic = &sc->sc_ic;
	int sr, lr, pri;

	if (ts->ts_status == 0) {
		u_int8_t txant = ts->ts_antenna;
		sc->sc_stats.ast_ant_tx[txant]++;
		sc->sc_ant_tx[txant]++;
		if (ts->ts_finaltsi != 0)
			sc->sc_stats.ast_tx_altrate++;

		/* XXX TODO: should do per-pri conuters */
		pri = M_WME_GETAC(bf->bf_m);
		if (pri >= WME_AC_VO)
			ic->ic_wme.wme_hipri_traffic++;

		if ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0)
			ni->ni_inact = ni->ni_inact_reload;
	} else {
		if (ts->ts_status & HAL_TXERR_XRETRY)
			sc->sc_stats.ast_tx_xretries++;
		if (ts->ts_status & HAL_TXERR_FIFO)
			sc->sc_stats.ast_tx_fifoerr++;
		if (ts->ts_status & HAL_TXERR_FILT)
			sc->sc_stats.ast_tx_filtered++;
		if (ts->ts_status & HAL_TXERR_XTXOP)
			sc->sc_stats.ast_tx_xtxop++;
		if (ts->ts_status & HAL_TXERR_TIMER_EXPIRED)
			sc->sc_stats.ast_tx_timerexpired++;

		if (bf->bf_m->m_flags & M_FF)
			sc->sc_stats.ast_ff_txerr++;
	}
	/* XXX when is this valid? */
	if (ts->ts_flags & HAL_TX_DESC_CFG_ERR)
		sc->sc_stats.ast_tx_desccfgerr++;
	/*
	 * This can be valid for successful frame transmission!
	 * If there's a TX FIFO underrun during aggregate transmission,
	 * the MAC will pad the rest of the aggregate with delimiters.
	 * If a BA is returned, the frame is marked as "OK" and it's up
	 * to the TX completion code to notice which frames weren't
	 * successfully transmitted.
	 */
	if (ts->ts_flags & HAL_TX_DATA_UNDERRUN)
		sc->sc_stats.ast_tx_data_underrun++;
	if (ts->ts_flags & HAL_TX_DELIM_UNDERRUN)
		sc->sc_stats.ast_tx_delim_underrun++;

	sr = ts->ts_shortretry;
	lr = ts->ts_longretry;
	sc->sc_stats.ast_tx_shortretry += sr;
	sc->sc_stats.ast_tx_longretry += lr;

}

/*
 * The default completion. If fail is 1, this means
 * "please don't retry the frame, and just return -1 status
 * to the net80211 stack.
 */
void
ath_tx_default_comp(struct ath_softc *sc, struct ath_buf *bf, int fail)
{
	struct ath_tx_status *ts = &bf->bf_status.ds_txstat;
	int st;

	if (fail == 1)
		st = -1;
	else
		st = ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0) ?
		    ts->ts_status : HAL_TXERR_XRETRY;

#if 0
	if (bf->bf_state.bfs_dobaw)
		device_printf(sc->sc_dev,
		    "%s: bf %p: seqno %d: dobaw should've been cleared!\n",
		    __func__,
		    bf,
		    SEQNO(bf->bf_state.bfs_seqno));
#endif
	if (bf->bf_next != NULL)
		device_printf(sc->sc_dev,
		    "%s: bf %p: seqno %d: bf_next not NULL!\n",
		    __func__,
		    bf,
		    SEQNO(bf->bf_state.bfs_seqno));

	/*
	 * Check if the node software queue is empty; if so
	 * then clear the TIM.
	 *
	 * This needs to be done before the buffer is freed as
	 * otherwise the node reference will have been released
	 * and the node may not actually exist any longer.
	 *
	 * XXX I don't like this belonging here, but it's cleaner
	 * to do it here right now then all the other places
	 * where ath_tx_default_comp() is called.
	 *
	 * XXX TODO: during drain, ensure that the callback is
	 * being called so we get a chance to update the TIM.
	 */
	if (bf->bf_node) {
		ATH_TX_LOCK(sc);
		ath_tx_update_tim(sc, bf->bf_node, 0);
		ATH_TX_UNLOCK(sc);
	}

	/*
	 * Do any tx complete callback.  Note this must
	 * be done before releasing the node reference.
	 * This will free the mbuf, release the net80211
	 * node and recycle the ath_buf.
	 */
	ath_tx_freebuf(sc, bf, st);
}

/*
 * Update rate control with the given completion status.
 */
void
ath_tx_update_ratectrl(struct ath_softc *sc, struct ieee80211_node *ni,
    struct ath_rc_series *rc, struct ath_tx_status *ts, int frmlen,
    int nframes, int nbad)
{
	struct ath_node *an;

	/* Only for unicast frames */
	if (ni == NULL)
		return;

	an = ATH_NODE(ni);
	ATH_NODE_UNLOCK_ASSERT(an);

	if ((ts->ts_status & HAL_TXERR_FILT) == 0) {
		ATH_NODE_LOCK(an);
		ath_rate_tx_complete(sc, an, rc, ts, frmlen, nframes, nbad);
		ATH_NODE_UNLOCK(an);
	}
}

/*
 * Process the completion of the given buffer.
 *
 * This calls the rate control update and then the buffer completion.
 * This will either free the buffer or requeue it.  In any case, the
 * bf pointer should be treated as invalid after this function is called.
 */
void
ath_tx_process_buf_completion(struct ath_softc *sc, struct ath_txq *txq,
    struct ath_tx_status *ts, struct ath_buf *bf)
{
	struct ieee80211_node *ni = bf->bf_node;

	ATH_TX_UNLOCK_ASSERT(sc);
	ATH_TXQ_UNLOCK_ASSERT(txq);

	/* If unicast frame, update general statistics */
	if (ni != NULL) {
		/* update statistics */
		ath_tx_update_stats(sc, ts, bf);
	}

	/*
	 * Call the completion handler.
	 * The completion handler is responsible for
	 * calling the rate control code.
	 *
	 * Frames with no completion handler get the
	 * rate control code called here.
	 */
	if (bf->bf_comp == NULL) {
		if ((ts->ts_status & HAL_TXERR_FILT) == 0 &&
		    (bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0) {
			/*
			 * XXX assume this isn't an aggregate
			 * frame.
			 */
			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, 0);
	} else
		bf->bf_comp(sc, bf, 0);
}



/*
 * Process completed xmit descriptors from the specified queue.
 * Kick the packet scheduler if needed. This can occur from this
 * particular task.
 */
static int
ath_tx_processq(struct ath_softc *sc, struct ath_txq *txq, int dosched)
{
	struct ath_hal *ah = sc->sc_ah;
	struct ath_buf *bf;
	struct ath_desc *ds;
	struct ath_tx_status *ts;
	struct ieee80211_node *ni;
#ifdef	IEEE80211_SUPPORT_SUPERG
	struct ieee80211com *ic = &sc->sc_ic;
#endif	/* IEEE80211_SUPPORT_SUPERG */
	int nacked;
	HAL_STATUS status;

	DPRINTF(sc, ATH_DEBUG_TX_PROC, "%s: tx queue %u head %p link %p\n",
		__func__, txq->axq_qnum,
		(caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, txq->axq_qnum),
		txq->axq_link);

	ATH_KTR(sc, ATH_KTR_TXCOMP, 4,
	    "ath_tx_processq: txq=%u head %p link %p depth %p",
	    txq->axq_qnum,
	    (caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, txq->axq_qnum),
	    txq->axq_link,
	    txq->axq_depth);

	nacked = 0;
	for (;;) {
		ATH_TXQ_LOCK(txq);
		txq->axq_intrcnt = 0;	/* reset periodic desc intr count */
		bf = TAILQ_FIRST(&txq->axq_q);
		if (bf == NULL) {
			ATH_TXQ_UNLOCK(txq);
			break;
		}
		ds = bf->bf_lastds;	/* XXX must be setup correctly! */
		ts = &bf->bf_status.ds_txstat;

		status = ath_hal_txprocdesc(ah, ds, ts);
#ifdef ATH_DEBUG
		if (sc->sc_debug & ATH_DEBUG_XMIT_DESC)
			ath_printtxbuf(sc, bf, txq->axq_qnum, 0,
			    status == HAL_OK);
		else if ((sc->sc_debug & ATH_DEBUG_RESET) && (dosched == 0))
			ath_printtxbuf(sc, bf, txq->axq_qnum, 0,
			    status == HAL_OK);
#endif
#ifdef	ATH_DEBUG_ALQ
		if (if_ath_alq_checkdebug(&sc->sc_alq,
		    ATH_ALQ_EDMA_TXSTATUS)) {
			if_ath_alq_post(&sc->sc_alq, ATH_ALQ_EDMA_TXSTATUS,
			sc->sc_tx_statuslen,
			(char *) ds);
		}
#endif

		if (status == HAL_EINPROGRESS) {
			ATH_KTR(sc, ATH_KTR_TXCOMP, 3,
			    "ath_tx_processq: txq=%u, bf=%p ds=%p, HAL_EINPROGRESS",
			    txq->axq_qnum, bf, ds);
			ATH_TXQ_UNLOCK(txq);
			break;
		}
		ATH_TXQ_REMOVE(txq, bf, bf_list);

		/*
		 * Sanity check.
		 */
		if (txq->axq_qnum != bf->bf_state.bfs_tx_queue) {
			device_printf(sc->sc_dev,
			    "%s: TXQ=%d: bf=%p, bfs_tx_queue=%d\n",
			    __func__,
			    txq->axq_qnum,
			    bf,
			    bf->bf_state.bfs_tx_queue);
		}
		if (txq->axq_qnum != bf->bf_last->bf_state.bfs_tx_queue) {
			device_printf(sc->sc_dev,
			    "%s: TXQ=%d: bf_last=%p, bfs_tx_queue=%d\n",
			    __func__,
			    txq->axq_qnum,
			    bf->bf_last,
			    bf->bf_last->bf_state.bfs_tx_queue);
		}

#if 0
		if (txq->axq_depth > 0) {
			/*
			 * More frames follow.  Mark the buffer busy
			 * so it's not re-used while the hardware may
			 * still re-read the link field in the descriptor.
			 *
			 * Use the last buffer in an aggregate as that
			 * is where the hardware may be - intermediate
			 * descriptors won't be "busy".
			 */
			bf->bf_last->bf_flags |= ATH_BUF_BUSY;
		} else
			txq->axq_link = NULL;
#else
		bf->bf_last->bf_flags |= ATH_BUF_BUSY;
#endif
		if (bf->bf_state.bfs_aggr)
			txq->axq_aggr_depth--;

		ni = bf->bf_node;

		ATH_KTR(sc, ATH_KTR_TXCOMP, 5,
		    "ath_tx_processq: txq=%u, bf=%p, ds=%p, ni=%p, ts_status=0x%08x",
		    txq->axq_qnum, bf, ds, ni, ts->ts_status);
		/*
		 * If unicast frame was ack'd update RSSI,
		 * including the last rx time used to
		 * workaround phantom bmiss interrupts.
		 */
		if (ni != NULL && ts->ts_status == 0 &&
		    ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0)) {
			nacked++;
			sc->sc_stats.ast_tx_rssi = ts->ts_rssi;
			ATH_RSSI_LPF(sc->sc_halstats.ns_avgtxrssi,
				ts->ts_rssi);
		}
		ATH_TXQ_UNLOCK(txq);

		/*
		 * Update statistics and call completion
		 */
		ath_tx_process_buf_completion(sc, txq, ts, bf);

		/* XXX at this point, bf and ni may be totally invalid */
	}
#ifdef IEEE80211_SUPPORT_SUPERG
	/*
	 * Flush fast-frame staging queue when traffic slows.
	 */
	if (txq->axq_depth <= 1)
		ieee80211_ff_flush(ic, txq->axq_ac);
#endif

	/* Kick the software TXQ scheduler */
	if (dosched) {
		ATH_TX_LOCK(sc);
		ath_txq_sched(sc, txq);
		ATH_TX_UNLOCK(sc);
	}

	ATH_KTR(sc, ATH_KTR_TXCOMP, 1,
	    "ath_tx_processq: txq=%u: done",
	    txq->axq_qnum);

	return nacked;
}

#define	TXQACTIVE(t, q)		( (t) & (1 << (q)))

/*
 * Deferred processing of transmit interrupt; special-cased
 * for a single hardware transmit queue (e.g. 5210 and 5211).
 */
static void
ath_tx_proc_q0(void *arg, int npending)
{
	struct ath_softc *sc = arg;
	uint32_t txqs;

	ATH_PCU_LOCK(sc);
	sc->sc_txproc_cnt++;
	txqs = sc->sc_txq_active;
	sc->sc_txq_active &= ~txqs;
	ATH_PCU_UNLOCK(sc);

	ATH_LOCK(sc);
	ath_power_set_power_state(sc, HAL_PM_AWAKE);
	ATH_UNLOCK(sc);

	ATH_KTR(sc, ATH_KTR_TXCOMP, 1,
	    "ath_tx_proc_q0: txqs=0x%08x", txqs);

	if (TXQACTIVE(txqs, 0) && ath_tx_processq(sc, &sc->sc_txq[0], 1))
		/* XXX why is lastrx updated in tx code? */
		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
	if (TXQACTIVE(txqs, sc->sc_cabq->axq_qnum))
		ath_tx_processq(sc, sc->sc_cabq, 1);
	sc->sc_wd_timer = 0;

	if (sc->sc_softled)
		ath_led_event(sc, sc->sc_txrix);

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

	ATH_LOCK(sc);
	ath_power_restore_power_state(sc);
	ATH_UNLOCK(sc);

	ath_tx_kick(sc);
}

/*
 * Deferred processing of transmit interrupt; special-cased
 * for four hardware queues, 0-3 (e.g. 5212 w/ WME support).
 */
static void
ath_tx_proc_q0123(void *arg, int npending)
{
	struct ath_softc *sc = arg;
	int nacked;
	uint32_t txqs;

	ATH_PCU_LOCK(sc);
	sc->sc_txproc_cnt++;
	txqs = sc->sc_txq_active;
	sc->sc_txq_active &= ~txqs;
	ATH_PCU_UNLOCK(sc);

	ATH_LOCK(sc);
	ath_power_set_power_state(sc, HAL_PM_AWAKE);
	ATH_UNLOCK(sc);

	ATH_KTR(sc, ATH_KTR_TXCOMP, 1,
	    "ath_tx_proc_q0123: txqs=0x%08x", txqs);

	/*
	 * Process each active queue.
	 */
	nacked = 0;
	if (TXQACTIVE(txqs, 0))
		nacked += ath_tx_processq(sc, &sc->sc_txq[0], 1);
	if (TXQACTIVE(txqs, 1))
		nacked += ath_tx_processq(sc, &sc->sc_txq[1], 1);
	if (TXQACTIVE(txqs, 2))
		nacked += ath_tx_processq(sc, &sc->sc_txq[2], 1);
	if (TXQACTIVE(txqs, 3))
		nacked += ath_tx_processq(sc, &sc->sc_txq[3], 1);
	if (TXQACTIVE(txqs, sc->sc_cabq->axq_qnum))
		ath_tx_processq(sc, sc->sc_cabq, 1);
	if (nacked)
		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);

	sc->sc_wd_timer = 0;

	if (sc->sc_softled)
		ath_led_event(sc, sc->sc_txrix);

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

	ATH_LOCK(sc);
	ath_power_restore_power_state(sc);
	ATH_UNLOCK(sc);

	ath_tx_kick(sc);
}

/*
 * Deferred processing of transmit interrupt.
 */
static void
ath_tx_proc(void *arg, int npending)
{
	struct ath_softc *sc = arg;
	int i, nacked;
	uint32_t txqs;

	ATH_PCU_LOCK(sc);
	sc->sc_txproc_cnt++;
	txqs = sc->sc_txq_active;
	sc->sc_txq_active &= ~txqs;
	ATH_PCU_UNLOCK(sc);

	ATH_LOCK(sc);
	ath_power_set_power_state(sc, HAL_PM_AWAKE);
	ATH_UNLOCK(sc);

	ATH_KTR(sc, ATH_KTR_TXCOMP, 1, "ath_tx_proc: txqs=0x%08x", txqs);

	/*
	 * Process each active queue.
	 */
	nacked = 0;
	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
		if (ATH_TXQ_SETUP(sc, i) && TXQACTIVE(txqs, i))
			nacked += ath_tx_processq(sc, &sc->sc_txq[i], 1);
	if (nacked)
		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);

	sc->sc_wd_timer = 0;

	if (sc->sc_softled)
		ath_led_event(sc, sc->sc_txrix);

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

	ATH_LOCK(sc);
	ath_power_restore_power_state(sc);
	ATH_UNLOCK(sc);

	ath_tx_kick(sc);
}
#undef	TXQACTIVE

/*
 * Deferred processing of TXQ rescheduling.
 */
static void
ath_txq_sched_tasklet(void *arg, int npending)
{
	struct ath_softc *sc = arg;
	int i;

	/* XXX is skipping ok? */
	ATH_PCU_LOCK(sc);
#if 0
	if (sc->sc_inreset_cnt > 0) {
		device_printf(sc->sc_dev,
		    "%s: sc_inreset_cnt > 0; skipping\n", __func__);
		ATH_PCU_UNLOCK(sc);
		return;
	}
#endif
	sc->sc_txproc_cnt++;
	ATH_PCU_UNLOCK(sc);

	ATH_LOCK(sc);
	ath_power_set_power_state(sc, HAL_PM_AWAKE);
	ATH_UNLOCK(sc);

	ATH_TX_LOCK(sc);
	for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
		if (ATH_TXQ_SETUP(sc, i)) {
			ath_txq_sched(sc, &sc->sc_txq[i]);
		}
	}
	ATH_TX_UNLOCK(sc);

	ATH_LOCK(sc);
	ath_power_restore_power_state(sc);
	ATH_UNLOCK(sc);

	ATH_PCU_LOCK(sc);
	sc->sc_txproc_cnt--;
	ATH_PCU_UNLOCK(sc);
}

void
ath_returnbuf_tail(struct ath_softc *sc, struct ath_buf *bf)
{

	ATH_TXBUF_LOCK_ASSERT(sc);

	if (bf->bf_flags & ATH_BUF_MGMT)
		TAILQ_INSERT_TAIL(&sc->sc_txbuf_mgmt, bf, bf_list);
	else {
		TAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
		sc->sc_txbuf_cnt++;
		if (sc->sc_txbuf_cnt > ath_txbuf) {
			device_printf(sc->sc_dev,
			    "%s: sc_txbuf_cnt > %d?\n",
			    __func__,
			    ath_txbuf);
			sc->sc_txbuf_cnt = ath_txbuf;
		}
	}
}

void
ath_returnbuf_head(struct ath_softc *sc, struct ath_buf *bf)
{

	ATH_TXBUF_LOCK_ASSERT(sc);

	if (bf->bf_flags & ATH_BUF_MGMT)
		TAILQ_INSERT_HEAD(&sc->sc_txbuf_mgmt, bf, bf_list);
	else {
		TAILQ_INSERT_HEAD(&sc->sc_txbuf, bf, bf_list);
		sc->sc_txbuf_cnt++;
		if (sc->sc_txbuf_cnt > ATH_TXBUF) {
			device_printf(sc->sc_dev,
			    "%s: sc_txbuf_cnt > %d?\n",
			    __func__,
			    ATH_TXBUF);
			sc->sc_txbuf_cnt = ATH_TXBUF;
		}
	}
}

/*
 * Free the holding buffer if it exists
 */
void
ath_txq_freeholdingbuf(struct ath_softc *sc, struct ath_txq *txq)
{
	ATH_TXBUF_UNLOCK_ASSERT(sc);
	ATH_TXQ_LOCK_ASSERT(txq);

	if (txq->axq_holdingbf == NULL)
		return;

	txq->axq_holdingbf->bf_flags &= ~ATH_BUF_BUSY;

	ATH_TXBUF_LOCK(sc);
	ath_returnbuf_tail(sc, txq->axq_holdingbf);
	ATH_TXBUF_UNLOCK(sc);

	txq->axq_holdingbf = NULL;
}

/*
 * Add this buffer to the holding queue, freeing the previous
 * one if it exists.
 */
static void
ath_txq_addholdingbuf(struct ath_softc *sc, struct ath_buf *bf)
{
	struct ath_txq *txq;

	txq = &sc->sc_txq[bf->bf_state.bfs_tx_queue];

	ATH_TXBUF_UNLOCK_ASSERT(sc);
	ATH_TXQ_LOCK_ASSERT(txq);

	/* XXX assert ATH_BUF_BUSY is set */

	/* XXX assert the tx queue is under the max number */
	if (bf->bf_state.bfs_tx_queue > HAL_NUM_TX_QUEUES) {
		device_printf(sc->sc_dev, "%s: bf=%p: invalid tx queue (%d)\n",
		    __func__,
		    bf,
		    bf->bf_state.bfs_tx_queue);
		bf->bf_flags &= ~ATH_BUF_BUSY;
		ath_returnbuf_tail(sc, bf);
		return;
	}
	ath_txq_freeholdingbuf(sc, txq);
	txq->axq_holdingbf = bf;
}

/*
 * Return a buffer to the pool and update the 'busy' flag on the
 * previous 'tail' entry.
 *
 * This _must_ only be called when the buffer is involved in a completed
 * TX. The logic is that if it was part of an active TX, the previous
 * buffer on the list is now not involved in a halted TX DMA queue, waiting
 * for restart (eg for TDMA.)
 *
 * The caller must free the mbuf and recycle the node reference.
 *
 * XXX This method of handling busy / holding buffers is insanely stupid.
 * It requires bf_state.bfs_tx_queue to be correctly assigned.  It would
 * be much nicer if buffers in the processq() methods would instead be
 * always completed there (pushed onto a txq or ath_bufhead) so we knew
 * exactly what hardware queue they came from in the first place.
 */
void
ath_freebuf(struct ath_softc *sc, struct ath_buf *bf)
{
	struct ath_txq *txq;

	txq = &sc->sc_txq[bf->bf_state.bfs_tx_queue];

	KASSERT((bf->bf_node == NULL), ("%s: bf->bf_node != NULL\n", __func__));
	KASSERT((bf->bf_m == NULL), ("%s: bf->bf_m != NULL\n", __func__));

	/*
	 * If this buffer is busy, push it onto the holding queue.
	 */
	if (bf->bf_flags & ATH_BUF_BUSY) {
		ATH_TXQ_LOCK(txq);
		ath_txq_addholdingbuf(sc, bf);
		ATH_TXQ_UNLOCK(txq);
		return;
	}

	/*
	 * Not a busy buffer, so free normally
	 */
	ATH_TXBUF_LOCK(sc);
	ath_returnbuf_tail(sc, bf);
	ATH_TXBUF_UNLOCK(sc);
}

/*
 * This is currently used by ath_tx_draintxq() and
 * ath_tx_tid_free_pkts().
 *
 * It recycles a single ath_buf.
 */
void
ath_tx_freebuf(struct ath_softc *sc, struct ath_buf *bf, int status)
{
	struct ieee80211_node *ni = bf->bf_node;
	struct mbuf *m0 = bf->bf_m;

	/*
	 * Make sure that we only sync/unload if there's an mbuf.
	 * If not (eg we cloned a buffer), the unload will have already
	 * occurred.
	 */
	if (bf->bf_m != NULL) {
		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
		    BUS_DMASYNC_POSTWRITE);
		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
	}

	bf->bf_node = NULL;
	bf->bf_m = NULL;

	/* Free the buffer, it's not needed any longer */
	ath_freebuf(sc, bf);

	/* Pass the buffer back to net80211 - completing it */
	ieee80211_tx_complete(ni, m0, status);
}

static struct ath_buf *
ath_tx_draintxq_get_one(struct ath_softc *sc, struct ath_txq *txq)
{
	struct ath_buf *bf;

	ATH_TXQ_LOCK_ASSERT(txq);

	/*
	 * Drain the FIFO queue first, then if it's
	 * empty, move to the normal frame queue.
	 */
	bf = TAILQ_FIRST(&txq->fifo.axq_q);
	if (bf != NULL) {
		/*
		 * Is it the last buffer in this set?
		 * Decrement the FIFO counter.
		 */
		if (bf->bf_flags & ATH_BUF_FIFOEND) {
			if (txq->axq_fifo_depth == 0) {
				device_printf(sc->sc_dev,
				    "%s: Q%d: fifo_depth=0, fifo.axq_depth=%d?\n",
				    __func__,
				    txq->axq_qnum,
				    txq->fifo.axq_depth);
			} else
				txq->axq_fifo_depth--;
		}
		ATH_TXQ_REMOVE(&txq->fifo, bf, bf_list);
		return (bf);
	}

	/*
	 * Debugging!
	 */
	if (txq->axq_fifo_depth != 0 || txq->fifo.axq_depth != 0) {
		device_printf(sc->sc_dev,
		    "%s: Q%d: fifo_depth=%d, fifo.axq_depth=%d\n",
		    __func__,
		    txq->axq_qnum,
		    txq->axq_fifo_depth,
		    txq->fifo.axq_depth);
	}

	/*
	 * Now drain the pending queue.
	 */
	bf = TAILQ_FIRST(&txq->axq_q);
	if (bf == NULL) {
		txq->axq_link = NULL;
		return (NULL);
	}
	ATH_TXQ_REMOVE(txq, bf, bf_list);
	return (bf);
}

void
ath_tx_draintxq(struct ath_softc *sc, struct ath_txq *txq)
{
#ifdef ATH_DEBUG
	struct ath_hal *ah = sc->sc_ah;
#endif
	struct ath_buf *bf;
	u_int ix;

	/*
	 * NB: this assumes output has been stopped and
	 *     we do not need to block ath_tx_proc
	 */
	for (ix = 0;; ix++) {
		ATH_TXQ_LOCK(txq);
		bf = ath_tx_draintxq_get_one(sc, txq);
		if (bf == NULL) {
			ATH_TXQ_UNLOCK(txq);
			break;
		}
		if (bf->bf_state.bfs_aggr)
			txq->axq_aggr_depth--;
#ifdef ATH_DEBUG
		if (sc->sc_debug & ATH_DEBUG_RESET) {
			struct ieee80211com *ic = &sc->sc_ic;
			int status = 0;

			/*
			 * EDMA operation has a TX completion FIFO
			 * separate from the TX descriptor, so this
			 * method of checking the "completion" status
			 * is wrong.
			 */
			if (! sc->sc_isedma) {
				status = (ath_hal_txprocdesc(ah,
				    bf->bf_lastds,
				    &bf->bf_status.ds_txstat) == HAL_OK);
			}
			ath_printtxbuf(sc, bf, txq->axq_qnum, ix, status);
			ieee80211_dump_pkt(ic, mtod(bf->bf_m, const uint8_t *),
			    bf->bf_m->m_len, 0, -1);
		}
#endif /* ATH_DEBUG */
		/*
		 * Since we're now doing magic in the completion
		 * functions, we -must- call it for aggregation
		 * destinations or BAW tracking will get upset.
		 */
		/*
		 * Clear ATH_BUF_BUSY; the completion handler
		 * will free the buffer.
		 */
		ATH_TXQ_UNLOCK(txq);
		bf->bf_flags &= ~ATH_BUF_BUSY;
		if (bf->bf_comp)
			bf->bf_comp(sc, bf, 1);
		else
			ath_tx_default_comp(sc, bf, 1);
	}

	/*
	 * Free the holding buffer if it exists
	 */
	ATH_TXQ_LOCK(txq);
	ath_txq_freeholdingbuf(sc, txq);
	ATH_TXQ_UNLOCK(txq);

	/*
	 * Drain software queued frames which are on
	 * active TIDs.
	 */
	ath_tx_txq_drain(sc, txq);
}

static void
ath_tx_stopdma(struct ath_softc *sc, struct ath_txq *txq)
{
	struct ath_hal *ah = sc->sc_ah;

	ATH_TXQ_LOCK_ASSERT(txq);

	DPRINTF(sc, ATH_DEBUG_RESET,
	    "%s: tx queue [%u] %p, active=%d, hwpending=%d, flags 0x%08x, "
	    "link %p, holdingbf=%p\n",
	    __func__,
	    txq->axq_qnum,
	    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, txq->axq_qnum),
	    (int) (!! ath_hal_txqenabled(ah, txq->axq_qnum)),
	    (int) ath_hal_numtxpending(ah, txq->axq_qnum),
	    txq->axq_flags,
	    txq->axq_link,
	    txq->axq_holdingbf);

	(void) ath_hal_stoptxdma(ah, txq->axq_qnum);
	/* We've stopped TX DMA, so mark this as stopped. */
	txq->axq_flags &= ~ATH_TXQ_PUTRUNNING;

#ifdef	ATH_DEBUG
	if ((sc->sc_debug & ATH_DEBUG_RESET)
	    && (txq->axq_holdingbf != NULL)) {
		ath_printtxbuf(sc, txq->axq_holdingbf, txq->axq_qnum, 0, 0);
	}
#endif
}

int
ath_stoptxdma(struct ath_softc *sc)
{
	struct ath_hal *ah = sc->sc_ah;
	int i;

	/* XXX return value */
	if (sc->sc_invalid)
		return 0;

	if (!sc->sc_invalid) {
		/* don't touch the hardware if marked invalid */
		DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
		    __func__, sc->sc_bhalq,
		    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, sc->sc_bhalq),
		    NULL);

		/* stop the beacon queue */
		(void) ath_hal_stoptxdma(ah, sc->sc_bhalq);

		/* Stop the data queues */
		for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
			if (ATH_TXQ_SETUP(sc, i)) {
				ATH_TXQ_LOCK(&sc->sc_txq[i]);
				ath_tx_stopdma(sc, &sc->sc_txq[i]);
				ATH_TXQ_UNLOCK(&sc->sc_txq[i]);
			}
		}
	}

	return 1;
}

#ifdef	ATH_DEBUG
void
ath_tx_dump(struct ath_softc *sc, struct ath_txq *txq)
{
	struct ath_hal *ah = sc->sc_ah;
	struct ath_buf *bf;
	int i = 0;

	if (! (sc->sc_debug & ATH_DEBUG_RESET))
		return;

	device_printf(sc->sc_dev, "%s: Q%d: begin\n",
	    __func__, txq->axq_qnum);
	TAILQ_FOREACH(bf, &txq->axq_q, bf_list) {
		ath_printtxbuf(sc, bf, txq->axq_qnum, i,
			ath_hal_txprocdesc(ah, bf->bf_lastds,
			    &bf->bf_status.ds_txstat) == HAL_OK);
		i++;
	}
	device_printf(sc->sc_dev, "%s: Q%d: end\n",
	    __func__, txq->axq_qnum);
}
#endif /* ATH_DEBUG */

/*
 * Drain the transmit queues and reclaim resources.
 */
void
ath_legacy_tx_drain(struct ath_softc *sc, ATH_RESET_TYPE reset_type)
{
	struct ath_hal *ah = sc->sc_ah;
	struct ath_buf *bf_last;
	int i;

	(void) ath_stoptxdma(sc);

	/*
	 * Dump the queue contents
	 */
	for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
		/*
		 * XXX TODO: should we just handle the completed TX frames
		 * here, whether or not the reset is a full one or not?
		 */
		if (ATH_TXQ_SETUP(sc, i)) {
#ifdef	ATH_DEBUG
			if (sc->sc_debug & ATH_DEBUG_RESET)
				ath_tx_dump(sc, &sc->sc_txq[i]);
#endif	/* ATH_DEBUG */
			if (reset_type == ATH_RESET_NOLOSS) {
				ath_tx_processq(sc, &sc->sc_txq[i], 0);
				ATH_TXQ_LOCK(&sc->sc_txq[i]);
				/*
				 * Free the holding buffer; DMA is now
				 * stopped.
				 */
				ath_txq_freeholdingbuf(sc, &sc->sc_txq[i]);
				/*
				 * Setup the link pointer to be the
				 * _last_ buffer/descriptor in the list.
				 * If there's nothing in the list, set it
				 * to NULL.
				 */
				bf_last = ATH_TXQ_LAST(&sc->sc_txq[i],
				    axq_q_s);
				if (bf_last != NULL) {
					ath_hal_gettxdesclinkptr(ah,
					    bf_last->bf_lastds,
					    &sc->sc_txq[i].axq_link);
				} else {
					sc->sc_txq[i].axq_link = NULL;
				}
				ATH_TXQ_UNLOCK(&sc->sc_txq[i]);
			} else
				ath_tx_draintxq(sc, &sc->sc_txq[i]);
		}
	}
#ifdef ATH_DEBUG
	if (sc->sc_debug & ATH_DEBUG_RESET) {
		struct ath_buf *bf = TAILQ_FIRST(&sc->sc_bbuf);
		if (bf != NULL && bf->bf_m != NULL) {
			ath_printtxbuf(sc, bf, sc->sc_bhalq, 0,
				ath_hal_txprocdesc(ah, bf->bf_lastds,
				    &bf->bf_status.ds_txstat) == HAL_OK);
			ieee80211_dump_pkt(&sc->sc_ic,
			    mtod(bf->bf_m, const uint8_t *), bf->bf_m->m_len,
			    0, -1);
		}
	}
#endif /* ATH_DEBUG */
	sc->sc_wd_timer = 0;
}

/*
 * Update internal state after a channel change.
 */
static void
ath_chan_change(struct ath_softc *sc, struct ieee80211_channel *chan)
{
	enum ieee80211_phymode mode;

	/*
	 * Change channels and update the h/w rate map
	 * if we're switching; e.g. 11a to 11b/g.
	 */
	mode = ieee80211_chan2mode(chan);
	if (mode != sc->sc_curmode)
		ath_setcurmode(sc, mode);
	sc->sc_curchan = chan;
}

/*
 * Set/change channels.  If the channel is really being changed,
 * it's done by resetting the chip.  To accomplish this we must
 * first cleanup any pending DMA, then restart stuff after a la
 * ath_init.
 */
static int
ath_chan_set(struct ath_softc *sc, struct ieee80211_channel *chan)
{
	struct ieee80211com *ic = &sc->sc_ic;
	struct ath_hal *ah = sc->sc_ah;
	int ret = 0;

	/* Treat this as an interface reset */
	ATH_PCU_UNLOCK_ASSERT(sc);
	ATH_UNLOCK_ASSERT(sc);

	/* (Try to) stop TX/RX from occurring */
	taskqueue_block(sc->sc_tq);

	ATH_PCU_LOCK(sc);

	/* Disable interrupts */
	ath_hal_intrset(ah, 0);

	/* Stop new RX/TX/interrupt completion */
	if (ath_reset_grablock(sc, 1) == 0) {
		device_printf(sc->sc_dev, "%s: concurrent reset! Danger!\n",
		    __func__);
	}

	/* Stop pending RX/TX completion */
	ath_txrx_stop_locked(sc);

	ATH_PCU_UNLOCK(sc);

	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %u (%u MHz, flags 0x%x)\n",
	    __func__, ieee80211_chan2ieee(ic, chan),
	    chan->ic_freq, chan->ic_flags);
	if (chan != sc->sc_curchan) {
		HAL_STATUS status;
		/*
		 * To switch channels clear any pending DMA operations;
		 * wait long enough for the RX fifo to drain, reset the
		 * hardware at the new frequency, and then re-enable
		 * the relevant bits of the h/w.
		 */
#if 0
		ath_hal_intrset(ah, 0);		/* disable interrupts */
#endif
		ath_stoprecv(sc, 1);		/* turn off frame recv */
		/*
		 * First, handle completed TX/RX frames.
		 */
		ath_rx_flush(sc);
		ath_draintxq(sc, ATH_RESET_NOLOSS);
		/*
		 * Next, flush the non-scheduled frames.
		 */
		ath_draintxq(sc, ATH_RESET_FULL);	/* clear pending tx frames */

		ath_update_chainmasks(sc, chan);
		ath_hal_setchainmasks(sc->sc_ah, sc->sc_cur_txchainmask,
		    sc->sc_cur_rxchainmask);
		if (!ath_hal_reset(ah, sc->sc_opmode, chan, AH_TRUE,
		    HAL_RESET_NORMAL, &status)) {
			device_printf(sc->sc_dev, "%s: unable to reset "
			    "channel %u (%u MHz, flags 0x%x), hal status %u\n",
			    __func__, ieee80211_chan2ieee(ic, chan),
			    chan->ic_freq, chan->ic_flags, status);
			ret = EIO;
			goto finish;
		}
		sc->sc_diversity = ath_hal_getdiversity(ah);

		ATH_RX_LOCK(sc);
		sc->sc_rx_stopped = 1;
		sc->sc_rx_resetted = 1;
		ATH_RX_UNLOCK(sc);

		/* Quiet time handling - ensure we resync */
		ath_vap_clear_quiet_ie(sc);

		/* Let DFS at it in case it's a DFS channel */
		ath_dfs_radar_enable(sc, chan);

		/* Let spectral at in case spectral is enabled */
		ath_spectral_enable(sc, chan);

		/*
		 * Let bluetooth coexistence at in case it's needed for this
		 * channel
		 */
		ath_btcoex_enable(sc, ic->ic_curchan);

		/*
		 * If we're doing TDMA, enforce the TXOP limitation for chips
		 * that support it.
		 */
		if (sc->sc_hasenforcetxop && sc->sc_tdma)
			ath_hal_setenforcetxop(sc->sc_ah, 1);
		else
			ath_hal_setenforcetxop(sc->sc_ah, 0);

		/*
		 * Re-enable rx framework.
		 */
		if (ath_startrecv(sc) != 0) {
			device_printf(sc->sc_dev,
			    "%s: unable to restart recv logic\n", __func__);
			ret = EIO;
			goto finish;
		}

		/*
		 * Change channels and update the h/w rate map
		 * if we're switching; e.g. 11a to 11b/g.
		 */
		ath_chan_change(sc, chan);

		/*
		 * Reset clears the beacon timers; reset them
		 * here if needed.
		 */
		if (sc->sc_beacons) {		/* restart beacons */
#ifdef IEEE80211_SUPPORT_TDMA
			if (sc->sc_tdma)
				ath_tdma_config(sc, NULL);
			else
#endif
			ath_beacon_config(sc, NULL);
		}

		/*
		 * Re-enable interrupts.
		 */
#if 0
		ath_hal_intrset(ah, sc->sc_imask);
#endif
	}

finish:
	ATH_PCU_LOCK(sc);
	sc->sc_inreset_cnt--;
	/* XXX only do this if sc_inreset_cnt == 0? */
	ath_hal_intrset(ah, sc->sc_imask);
	ATH_PCU_UNLOCK(sc);

	ath_txrx_start(sc);
	/* XXX ath_start? */

	return ret;
}

/*
 * Periodically recalibrate the PHY to account
 * for temperature/environment changes.
 */
static void
ath_calibrate(void *arg)
{
	struct ath_softc *sc = arg;
	struct ath_hal *ah = sc->sc_ah;
	struct ieee80211com *ic = &sc->sc_ic;
	HAL_BOOL longCal, isCalDone = AH_TRUE;
	HAL_BOOL aniCal, shortCal = AH_FALSE;
	int nextcal;

	ATH_LOCK_ASSERT(sc);

	/*
	 * Force the hardware awake for ANI work.
	 */
	ath_power_set_power_state(sc, HAL_PM_AWAKE);

	/* Skip trying to do this if we're in reset */
	if (sc->sc_inreset_cnt)
		goto restart;

	if (ic->ic_flags & IEEE80211_F_SCAN)	/* defer, off channel */
		goto restart;
	longCal = (ticks - sc->sc_lastlongcal >= ath_longcalinterval*hz);
	aniCal = (ticks - sc->sc_lastani >= ath_anicalinterval*hz/1000);
	if (sc->sc_doresetcal)
		shortCal = (ticks - sc->sc_lastshortcal >= ath_shortcalinterval*hz/1000);

	DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: shortCal=%d; longCal=%d; aniCal=%d\n", __func__, shortCal, longCal, aniCal);
	if (aniCal) {
		sc->sc_stats.ast_ani_cal++;
		sc->sc_lastani = ticks;
		ath_hal_ani_poll(ah, sc->sc_curchan);
	}

	if (longCal) {
		sc->sc_stats.ast_per_cal++;
		sc->sc_lastlongcal = ticks;
		if (ath_hal_getrfgain(ah) == HAL_RFGAIN_NEED_CHANGE) {
			/*
			 * Rfgain is out of bounds, reset the chip
			 * to load new gain values.
			 */
			DPRINTF(sc, ATH_DEBUG_CALIBRATE,
				"%s: rfgain change\n", __func__);
			sc->sc_stats.ast_per_rfgain++;
			sc->sc_resetcal = 0;
			sc->sc_doresetcal = AH_TRUE;
			taskqueue_enqueue(sc->sc_tq, &sc->sc_resettask);
			callout_reset(&sc->sc_cal_ch, 1, ath_calibrate, sc);
			ath_power_restore_power_state(sc);
			return;
		}
		/*
		 * If this long cal is after an idle period, then
		 * reset the data collection state so we start fresh.
		 */
		if (sc->sc_resetcal) {
			(void) ath_hal_calreset(ah, sc->sc_curchan);
			sc->sc_lastcalreset = ticks;
			sc->sc_lastshortcal = ticks;
			sc->sc_resetcal = 0;
			sc->sc_doresetcal = AH_TRUE;
		}
	}

	/* Only call if we're doing a short/long cal, not for ANI calibration */
	if (shortCal || longCal) {
		isCalDone = AH_FALSE;
		if (ath_hal_calibrateN(ah, sc->sc_curchan, longCal, &isCalDone)) {
			if (longCal) {
				/*
				 * Calibrate noise floor data again in case of change.
				 */
				ath_hal_process_noisefloor(ah);
			}
		} else {
			DPRINTF(sc, ATH_DEBUG_ANY,
				"%s: calibration of channel %u failed\n",
				__func__, sc->sc_curchan->ic_freq);
			sc->sc_stats.ast_per_calfail++;
		}
		if (shortCal)
			sc->sc_lastshortcal = ticks;
	}
	if (!isCalDone) {
restart:
		/*
		 * Use a shorter interval to potentially collect multiple
		 * data samples required to complete calibration.  Once
		 * we're told the work is done we drop back to a longer
		 * interval between requests.  We're more aggressive doing
		 * work when operating as an AP to improve operation right
		 * after startup.
		 */
		sc->sc_lastshortcal = ticks;
		nextcal = ath_shortcalinterval*hz/1000;
		if (sc->sc_opmode != HAL_M_HOSTAP)
			nextcal *= 10;
		sc->sc_doresetcal = AH_TRUE;
	} else {
		/* nextcal should be the shortest time for next event */
		nextcal = ath_longcalinterval*hz;
		if (sc->sc_lastcalreset == 0)
			sc->sc_lastcalreset = sc->sc_lastlongcal;
		else if (ticks - sc->sc_lastcalreset >= ath_resetcalinterval*hz)
			sc->sc_resetcal = 1;	/* setup reset next trip */
		sc->sc_doresetcal = AH_FALSE;
	}
	/* ANI calibration may occur more often than short/long/resetcal */
	if (ath_anicalinterval > 0)
		nextcal = MIN(nextcal, ath_anicalinterval*hz/1000);

	if (nextcal != 0) {
		DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: next +%u (%sisCalDone)\n",
		    __func__, nextcal, isCalDone ? "" : "!");
		callout_reset(&sc->sc_cal_ch, nextcal, ath_calibrate, sc);
	} else {
		DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: calibration disabled\n",
		    __func__);
		/* NB: don't rearm timer */
	}
	/*
	 * Restore power state now that we're done.
	 */
	ath_power_restore_power_state(sc);
}

static void
ath_scan_start(struct ieee80211com *ic)
{
	struct ath_softc *sc = ic->ic_softc;
	struct ath_hal *ah = sc->sc_ah;
	u_int32_t rfilt;

	/* XXX calibration timer? */
	/* XXXGL: is constant ieee80211broadcastaddr a correct choice? */

	ATH_LOCK(sc);
	sc->sc_scanning = 1;
	sc->sc_syncbeacon = 0;
	rfilt = ath_calcrxfilter(sc);
	ATH_UNLOCK(sc);

	ATH_PCU_LOCK(sc);
	ath_hal_setrxfilter(ah, rfilt);
	ath_hal_setassocid(ah, ieee80211broadcastaddr, 0);
	ATH_PCU_UNLOCK(sc);

	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0\n",
		 __func__, rfilt, ether_sprintf(ieee80211broadcastaddr));
}

static void
ath_scan_end(struct ieee80211com *ic)
{
	struct ath_softc *sc = ic->ic_softc;
	struct ath_hal *ah = sc->sc_ah;
	u_int32_t rfilt;

	ATH_LOCK(sc);
	sc->sc_scanning = 0;
	rfilt = ath_calcrxfilter(sc);
	ATH_UNLOCK(sc);

	ATH_PCU_LOCK(sc);
	ath_hal_setrxfilter(ah, rfilt);
	ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);

	ath_hal_process_noisefloor(ah);
	ATH_PCU_UNLOCK(sc);

	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0x%x\n",
		 __func__, rfilt, ether_sprintf(sc->sc_curbssid),
		 sc->sc_curaid);
}

#ifdef	ATH_ENABLE_11N
/*
 * For now, just do a channel change.
 *
 * Later, we'll go through the hard slog of suspending tx/rx, changing rate
 * control state and resetting the hardware without dropping frames out
 * of the queue.
 *
 * The unfortunate trouble here is making absolutely sure that the
 * channel width change has propagated enough so the hardware
 * absolutely isn't handed bogus frames for it's current operating
 * mode. (Eg, 40MHz frames in 20MHz mode.) Since TX and RX can and
 * does occur in parallel, we need to make certain we've blocked
 * any further ongoing TX (and RX, that can cause raw TX)
 * before we do this.
 */
static void
ath_update_chw(struct ieee80211com *ic)
{
	struct ath_softc *sc = ic->ic_softc;

	//DPRINTF(sc, ATH_DEBUG_STATE, "%s: called\n", __func__);
	device_printf(sc->sc_dev, "%s: called\n", __func__);

	/*
	 * XXX TODO: schedule a tasklet that stops things without freeing,
	 * walks the now stopped TX queue(s) looking for frames to retry
	 * as if we TX filtered them (whch may mean dropping non-ampdu frames!)
	 * but okay) then place them back on the software queue so they
	 * can have the rate control lookup done again.
	 */
	ath_set_channel(ic);
}
#endif	/* ATH_ENABLE_11N */

/*
 * This is called by the beacon parsing routine in the receive
 * path to update the current quiet time information provided by
 * an AP.
 *
 * This is STA specific, it doesn't take the AP TBTT/beacon slot
 * offset into account.
 *
 * The quiet IE doesn't control the /now/ beacon interval - it
 * controls the upcoming beacon interval.  So, when tbtt=1,
 * the quiet element programming shall be for the next beacon
 * interval.  There's no tbtt=0 behaviour defined, so don't.
 *
 * Since we're programming the next quiet interval, we have
 * to keep in mind what we will see when the next beacon
 * is received with potentially a quiet IE.  For example, if
 * quiet_period is 1, then we are always getting a quiet interval
 * each TBTT - so if we just program it in upon each beacon received,
 * it will constantly reflect the "next" TBTT and we will never
 * let the counter stay programmed correctly.
 *
 * So:
 * + the first time we see the quiet IE, program it and store
 *   the details somewhere;
 * + if the quiet parameters don't change (ie, period/duration/offset)
 *   then just leave the programming enabled;
 * + (we can "skip" beacons, so don't try to enforce tbttcount unless
 *   you're willing to also do the skipped beacon math);
 * + if the quiet IE is removed, then halt quiet time.
 */
static int
ath_set_quiet_ie(struct ieee80211_node *ni, uint8_t *ie)
{
	struct ieee80211_quiet_ie *q;
	struct ieee80211vap *vap = ni->ni_vap;
	struct ath_vap *avp = ATH_VAP(vap);
	struct ieee80211com *ic = vap->iv_ic;
	struct ath_softc *sc = ic->ic_softc;

	if (vap->iv_opmode != IEEE80211_M_STA)
		return (0);

	/* Verify we have a quiet time IE */
	if (ie == NULL) {
		DPRINTF(sc, ATH_DEBUG_QUIETIE,
		    "%s: called; NULL IE, disabling\n", __func__);

		ath_hal_set_quiet(sc->sc_ah, 0, 0, 0, HAL_QUIET_DISABLE);
		memset(&avp->quiet_ie, 0, sizeof(avp->quiet_ie));
		return (0);
	}

	/* If we do, verify it's actually legit */
	if (ie[0] != IEEE80211_ELEMID_QUIET)
		return 0;
	if (ie[1] != 6)
		return 0;

	/* Note: this belongs in net80211, parsed out and everything */
	q = (void *) ie;

	/*
	 * Compare what we have stored to what we last saw.
	 * If they're the same then don't program in anything.
	 */
	if ((q->period == avp->quiet_ie.period) &&
	    (le16dec(&q->duration) == le16dec(&avp->quiet_ie.duration)) &&
	    (le16dec(&q->offset) == le16dec(&avp->quiet_ie.offset)))
		return (0);

	DPRINTF(sc, ATH_DEBUG_QUIETIE,
	    "%s: called; tbttcount=%d, period=%d, duration=%d, offset=%d\n",
	    __func__,
	    (int) q->tbttcount,
	    (int) q->period,
	    (int) le16dec(&q->duration),
	    (int) le16dec(&q->offset));

	/*
	 * Don't program in garbage values.
	 */
	if ((le16dec(&q->duration) == 0) ||
	    (le16dec(&q->duration) >= ni->ni_intval)) {
		DPRINTF(sc, ATH_DEBUG_QUIETIE,
		    "%s: invalid duration (%d)\n", __func__,
		    le16dec(&q->duration));
		    return (0);
	}
	/*
	 * Can have a 0 offset, but not a duration - so just check
	 * they don't exceed the intval.
	 */
	if (le16dec(&q->duration) + le16dec(&q->offset) >= ni->ni_intval) {
		DPRINTF(sc, ATH_DEBUG_QUIETIE,
		    "%s: invalid duration + offset (%d+%d)\n", __func__,
		    le16dec(&q->duration),
		    le16dec(&q->offset));
		    return (0);
	}
	if (q->tbttcount == 0) {
		DPRINTF(sc, ATH_DEBUG_QUIETIE,
		    "%s: invalid tbttcount (0)\n", __func__);
		    return (0);
	}
	if (q->period == 0) {
		DPRINTF(sc, ATH_DEBUG_QUIETIE,
		    "%s: invalid period (0)\n", __func__);
		    return (0);
	}

	/*
	 * This is a new quiet time IE config, so wait until tbttcount
	 * is equal to 1, and program it in.
	 */
	if (q->tbttcount == 1) {
		DPRINTF(sc, ATH_DEBUG_QUIETIE,
		    "%s: programming\n", __func__);
		ath_hal_set_quiet(sc->sc_ah,
		    q->period * ni->ni_intval,	/* convert to TU */
		    le16dec(&q->duration),	/* already in TU */
		    le16dec(&q->offset) + ni->ni_intval,
		    HAL_QUIET_ENABLE | HAL_QUIET_ADD_CURRENT_TSF);
		/*
		 * Note: no HAL_QUIET_ADD_SWBA_RESP_TIME; as this is for
		 * STA mode
		 */

		/* Update local state */
		memcpy(&avp->quiet_ie, ie, sizeof(struct ieee80211_quiet_ie));
	}

	return (0);
}

static void
ath_set_channel(struct ieee80211com *ic)
{
	struct ath_softc *sc = ic->ic_softc;

	ATH_LOCK(sc);
	ath_power_set_power_state(sc, HAL_PM_AWAKE);
	ATH_UNLOCK(sc);

	(void) ath_chan_set(sc, ic->ic_curchan);
	/*
	 * If we are returning to our bss channel then mark state
	 * so the next recv'd beacon's tsf will be used to sync the
	 * beacon timers.  Note that since we only hear beacons in
	 * sta/ibss mode this has no effect in other operating modes.
	 */
	ATH_LOCK(sc);
	if (!sc->sc_scanning && ic->ic_curchan == ic->ic_bsschan)
		sc->sc_syncbeacon = 1;
	ath_power_restore_power_state(sc);
	ATH_UNLOCK(sc);
}

/*
 * Walk the vap list and check if there any vap's in RUN state.
 */
static int
ath_isanyrunningvaps(struct ieee80211vap *this)
{
	struct ieee80211com *ic = this->iv_ic;
	struct ieee80211vap *vap;

	IEEE80211_LOCK_ASSERT(ic);

	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
		if (vap != this && vap->iv_state >= IEEE80211_S_RUN)
			return 1;
	}
	return 0;
}

static int
ath_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
{
	struct ieee80211com *ic = vap->iv_ic;
	struct ath_softc *sc = ic->ic_softc;
	struct ath_vap *avp = ATH_VAP(vap);
	struct ath_hal *ah = sc->sc_ah;
	struct ieee80211_node *ni = NULL;
	int i, error, stamode;
	u_int32_t rfilt;
	int csa_run_transition = 0;
	enum ieee80211_state ostate = vap->iv_state;

	static const HAL_LED_STATE leds[] = {
	    HAL_LED_INIT,	/* IEEE80211_S_INIT */
	    HAL_LED_SCAN,	/* IEEE80211_S_SCAN */
	    HAL_LED_AUTH,	/* IEEE80211_S_AUTH */
	    HAL_LED_ASSOC, 	/* IEEE80211_S_ASSOC */
	    HAL_LED_RUN, 	/* IEEE80211_S_CAC */
	    HAL_LED_RUN, 	/* IEEE80211_S_RUN */
	    HAL_LED_RUN, 	/* IEEE80211_S_CSA */
	    HAL_LED_RUN, 	/* IEEE80211_S_SLEEP */
	};

	DPRINTF(sc, ATH_DEBUG_STATE, "%s: %s -> %s\n", __func__,
		ieee80211_state_name[ostate],
		ieee80211_state_name[nstate]);

	/*
	 * net80211 _should_ have the comlock asserted at this point.
	 * There are some comments around the calls to vap->iv_newstate
	 * which indicate that it (newstate) may end up dropping the
	 * lock.  This and the subsequent lock assert check after newstate
	 * are an attempt to catch these and figure out how/why.
	 */
	IEEE80211_LOCK_ASSERT(ic);

	/* Before we touch the hardware - wake it up */
	ATH_LOCK(sc);
	/*
	 * If the NIC is in anything other than SLEEP state,
	 * we need to ensure that self-generated frames are
	 * set for PWRMGT=0.  Otherwise we may end up with
	 * strange situations.
	 *
	 * XXX TODO: is this actually the case? :-)
	 */
	if (nstate != IEEE80211_S_SLEEP)
		ath_power_setselfgen(sc, HAL_PM_AWAKE);

	/*
	 * Now, wake the thing up.
	 */
	ath_power_set_power_state(sc, HAL_PM_AWAKE);

	/*
	 * And stop the calibration callout whilst we have
	 * ATH_LOCK held.
	 */
	callout_stop(&sc->sc_cal_ch);
	ATH_UNLOCK(sc);

	if (ostate == IEEE80211_S_CSA && nstate == IEEE80211_S_RUN)
		csa_run_transition = 1;

	ath_hal_setledstate(ah, leds[nstate]);	/* set LED */

	if (nstate == IEEE80211_S_SCAN) {
		/*
		 * Scanning: turn off beacon miss and don't beacon.
		 * Mark beacon state so when we reach RUN state we'll
		 * [re]setup beacons.  Unblock the task q thread so
		 * deferred interrupt processing is done.
		 */

		/* Ensure we stay awake during scan */
		ATH_LOCK(sc);
		ath_power_setselfgen(sc, HAL_PM_AWAKE);
		ath_power_setpower(sc, HAL_PM_AWAKE, 1);
		ATH_UNLOCK(sc);

		ath_hal_intrset(ah,
		    sc->sc_imask &~ (HAL_INT_SWBA | HAL_INT_BMISS));
		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
		sc->sc_beacons = 0;
		taskqueue_unblock(sc->sc_tq);
	}

	ni = ieee80211_ref_node(vap->iv_bss);
	rfilt = ath_calcrxfilter(sc);
	stamode = (vap->iv_opmode == IEEE80211_M_STA ||
		   vap->iv_opmode == IEEE80211_M_AHDEMO ||
		   vap->iv_opmode == IEEE80211_M_IBSS);

	/*
	 * XXX Dont need to do this (and others) if we've transitioned
	 * from SLEEP->RUN.
	 */
	if (stamode && nstate == IEEE80211_S_RUN) {
		sc->sc_curaid = ni->ni_associd;
		IEEE80211_ADDR_COPY(sc->sc_curbssid, ni->ni_bssid);
		ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);
	}
	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0x%x\n",
	   __func__, rfilt, ether_sprintf(sc->sc_curbssid), sc->sc_curaid);
	ath_hal_setrxfilter(ah, rfilt);

	/* XXX is this to restore keycache on resume? */
	if (vap->iv_opmode != IEEE80211_M_STA &&
	    (vap->iv_flags & IEEE80211_F_PRIVACY)) {
		for (i = 0; i < IEEE80211_WEP_NKID; i++)
			if (ath_hal_keyisvalid(ah, i))
				ath_hal_keysetmac(ah, i, ni->ni_bssid);
	}

	/*
	 * Invoke the parent method to do net80211 work.
	 */
	error = avp->av_newstate(vap, nstate, arg);
	if (error != 0)
		goto bad;

	/*
	 * See above: ensure av_newstate() doesn't drop the lock
	 * on us.
	 */
	IEEE80211_LOCK_ASSERT(ic);

	/*
	 * XXX TODO: if nstate is _S_CAC, then we should disable
	 * ACK processing until CAC is completed.
	 */

	/*
	 * XXX TODO: if we're on a passive channel, then we should
	 * not allow any ACKs or self-generated frames until we hear
	 * a beacon.  Unfortunately there isn't a notification from
	 * net80211 so perhaps we could slot that particular check
	 * into the mgmt receive path and just ensure that we clear
	 * it on RX of beacons in passive mode (and only clear it
	 * once, obviously.)
	 */

	/*
	 * XXX TODO: net80211 should be tracking whether channels
	 * have heard beacons and are thus considered "OK" for
	 * transmitting - and then inform the driver about this
	 * state change.  That way if we hear an AP go quiet
	 * (and nothing else is beaconing on a channel) the
	 * channel can go back to being passive until another
	 * beacon is heard.
	 */

	/*
	 * XXX TODO: if nstate is _S_CAC, then we should disable
	 * ACK processing until CAC is completed.
	 */

	/*
	 * XXX TODO: if we're on a passive channel, then we should
	 * not allow any ACKs or self-generated frames until we hear
	 * a beacon.  Unfortunately there isn't a notification from
	 * net80211 so perhaps we could slot that particular check
	 * into the mgmt receive path and just ensure that we clear
	 * it on RX of beacons in passive mode (and only clear it
	 * once, obviously.)
	 */

	/*
	 * XXX TODO: net80211 should be tracking whether channels
	 * have heard beacons and are thus considered "OK" for
	 * transmitting - and then inform the driver about this
	 * state change.  That way if we hear an AP go quiet
	 * (and nothing else is beaconing on a channel) the
	 * channel can go back to being passive until another
	 * beacon is heard.
	 */

	if (nstate == IEEE80211_S_RUN) {
		/* NB: collect bss node again, it may have changed */
		ieee80211_free_node(ni);
		ni = ieee80211_ref_node(vap->iv_bss);

		DPRINTF(sc, ATH_DEBUG_STATE,
		    "%s(RUN): iv_flags 0x%08x bintvl %d bssid %s "
		    "capinfo 0x%04x chan %d\n", __func__,
		    vap->iv_flags, ni->ni_intval, ether_sprintf(ni->ni_bssid),
		    ni->ni_capinfo, ieee80211_chan2ieee(ic, ic->ic_curchan));

		switch (vap->iv_opmode) {
#ifdef IEEE80211_SUPPORT_TDMA
		case IEEE80211_M_AHDEMO:
			if ((vap->iv_caps & IEEE80211_C_TDMA) == 0)
				break;
			/* fall thru... */
#endif
		case IEEE80211_M_HOSTAP:
		case IEEE80211_M_IBSS:
		case IEEE80211_M_MBSS:

			/*
			 * TODO: Enable ACK processing (ie, clear AR_DIAG_ACK_DIS.)
			 * For channels that are in CAC, we may have disabled
			 * this during CAC to ensure we don't ACK frames
			 * sent to us.
			 */

			/*
			 * Allocate and setup the beacon frame.
			 *
			 * Stop any previous beacon DMA.  This may be
			 * necessary, for example, when an ibss merge
			 * causes reconfiguration; there will be a state
			 * transition from RUN->RUN that means we may
			 * be called with beacon transmission active.
			 */
			ath_hal_stoptxdma(ah, sc->sc_bhalq);

			error = ath_beacon_alloc(sc, ni);
			if (error != 0)
				goto bad;
			/*
			 * If joining an adhoc network defer beacon timer
			 * configuration to the next beacon frame so we
			 * have a current TSF to use.  Otherwise we're
			 * starting an ibss/bss so there's no need to delay;
			 * if this is the first vap moving to RUN state, then
			 * beacon state needs to be [re]configured.
			 */
			if (vap->iv_opmode == IEEE80211_M_IBSS &&
			    ni->ni_tstamp.tsf != 0) {
				sc->sc_syncbeacon = 1;
			} else if (!sc->sc_beacons) {
#ifdef IEEE80211_SUPPORT_TDMA
				if (vap->iv_caps & IEEE80211_C_TDMA)
					ath_tdma_config(sc, vap);
				else
#endif
					ath_beacon_config(sc, vap);
				sc->sc_beacons = 1;
			}
			break;
		case IEEE80211_M_STA:
			/*
			 * Defer beacon timer configuration to the next
			 * beacon frame so we have a current TSF to use
			 * (any TSF collected when scanning is likely old).
			 * However if it's due to a CSA -> RUN transition,
			 * force a beacon update so we pick up a lack of
			 * beacons from an AP in CAC and thus force a
			 * scan.
			 *
			 * And, there's also corner cases here where
			 * after a scan, the AP may have disappeared.
			 * In that case, we may not receive an actual
			 * beacon to update the beacon timer and thus we
			 * won't get notified of the missing beacons.
			 */
			if (ostate != IEEE80211_S_RUN &&
			    ostate != IEEE80211_S_SLEEP) {
				DPRINTF(sc, ATH_DEBUG_BEACON,
				    "%s: STA; syncbeacon=1\n", __func__);
				sc->sc_syncbeacon = 1;

				/* Quiet time handling - ensure we resync */
				memset(&avp->quiet_ie, 0, sizeof(avp->quiet_ie));

				if (csa_run_transition)
					ath_beacon_config(sc, vap);

			/*
			 * PR: kern/175227
			 *
			 * Reconfigure beacons during reset; as otherwise
			 * we won't get the beacon timers reprogrammed
			 * after a reset and thus we won't pick up a
			 * beacon miss interrupt.
			 *
			 * Hopefully we'll see a beacon before the BMISS
			 * timer fires (too often), leading to a STA
			 * disassociation.
			 */
				sc->sc_beacons = 1;
			}
			break;
		case IEEE80211_M_MONITOR:
			/*
			 * Monitor mode vaps have only INIT->RUN and RUN->RUN
			 * transitions so we must re-enable interrupts here to
			 * handle the case of a single monitor mode vap.
			 */
			ath_hal_intrset(ah, sc->sc_imask);
			break;
		case IEEE80211_M_WDS:
			break;
		default:
			break;
		}
		/*
		 * Let the hal process statistics collected during a
		 * scan so it can provide calibrated noise floor data.
		 */
		ath_hal_process_noisefloor(ah);
		/*
		 * Reset rssi stats; maybe not the best place...
		 */
		sc->sc_halstats.ns_avgbrssi = ATH_RSSI_DUMMY_MARKER;
		sc->sc_halstats.ns_avgrssi = ATH_RSSI_DUMMY_MARKER;
		sc->sc_halstats.ns_avgtxrssi = ATH_RSSI_DUMMY_MARKER;

		/*
		 * Force awake for RUN mode.
		 */
		ATH_LOCK(sc);
		ath_power_setselfgen(sc, HAL_PM_AWAKE);
		ath_power_setpower(sc, HAL_PM_AWAKE, 1);

		/*
		 * Finally, start any timers and the task q thread
		 * (in case we didn't go through SCAN state).
		 */
		if (ath_longcalinterval != 0) {
			/* start periodic recalibration timer */
			callout_reset(&sc->sc_cal_ch, 1, ath_calibrate, sc);
		} else {
			DPRINTF(sc, ATH_DEBUG_CALIBRATE,
			    "%s: calibration disabled\n", __func__);
		}
		ATH_UNLOCK(sc);

		taskqueue_unblock(sc->sc_tq);
	} else if (nstate == IEEE80211_S_INIT) {

		/* Quiet time handling - ensure we resync */
		memset(&avp->quiet_ie, 0, sizeof(avp->quiet_ie));

		/*
		 * If there are no vaps left in RUN state then
		 * shutdown host/driver operation:
		 * o disable interrupts
		 * o disable the task queue thread
		 * o mark beacon processing as stopped
		 */
		if (!ath_isanyrunningvaps(vap)) {
			sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
			/* disable interrupts  */
			ath_hal_intrset(ah, sc->sc_imask &~ HAL_INT_GLOBAL);
			taskqueue_block(sc->sc_tq);
			sc->sc_beacons = 0;
		}
#ifdef IEEE80211_SUPPORT_TDMA
		ath_hal_setcca(ah, AH_TRUE);
#endif
	} else if (nstate == IEEE80211_S_SLEEP) {
		/* We're going to sleep, so transition appropriately */
		/* For now, only do this if we're a single STA vap */
		if (sc->sc_nvaps == 1 &&
		    vap->iv_opmode == IEEE80211_M_STA) {
			DPRINTF(sc, ATH_DEBUG_BEACON, "%s: syncbeacon=%d\n", __func__, sc->sc_syncbeacon);
			ATH_LOCK(sc);
			/*
			 * Always at least set the self-generated
			 * frame config to set PWRMGT=1.
			 */
			ath_power_setselfgen(sc, HAL_PM_NETWORK_SLEEP);

			/*
			 * If we're not syncing beacons, transition
			 * to NETWORK_SLEEP.
			 *
			 * We stay awake if syncbeacon > 0 in case
			 * we need to listen for some beacons otherwise
			 * our beacon timer config may be wrong.
			 */
			if (sc->sc_syncbeacon == 0) {
				ath_power_setpower(sc, HAL_PM_NETWORK_SLEEP, 1);
			}
			ATH_UNLOCK(sc);
		}
	} else if (nstate == IEEE80211_S_SCAN) {
		/* Quiet time handling - ensure we resync */
		memset(&avp->quiet_ie, 0, sizeof(avp->quiet_ie));
	}
bad:
	ieee80211_free_node(ni);

	/*
	 * Restore the power state - either to what it was, or
	 * to network_sleep if it's alright.
	 */
	ATH_LOCK(sc);
	ath_power_restore_power_state(sc);
	ATH_UNLOCK(sc);
	return error;
}

/*
 * Allocate a key cache slot to the station so we can
 * setup a mapping from key index to node. The key cache
 * slot is needed for managing antenna state and for
 * compression when stations do not use crypto.  We do
 * it uniliaterally here; if crypto is employed this slot
 * will be reassigned.
 */
static void
ath_setup_stationkey(struct ieee80211_node *ni)
{
	struct ieee80211vap *vap = ni->ni_vap;
	struct ath_softc *sc = vap->iv_ic->ic_softc;
	ieee80211_keyix keyix, rxkeyix;

	/* XXX should take a locked ref to vap->iv_bss */
	if (!ath_key_alloc(vap, &ni->ni_ucastkey, &keyix, &rxkeyix)) {
		/*
		 * Key cache is full; we'll fall back to doing
		 * the more expensive lookup in software.  Note
		 * this also means no h/w compression.
		 */
		/* XXX msg+statistic */
	} else {
		/* XXX locking? */
		ni->ni_ucastkey.wk_keyix = keyix;
		ni->ni_ucastkey.wk_rxkeyix = rxkeyix;
		/* NB: must mark device key to get called back on delete */
		ni->ni_ucastkey.wk_flags |= IEEE80211_KEY_DEVKEY;
		IEEE80211_ADDR_COPY(ni->ni_ucastkey.wk_macaddr, ni->ni_macaddr);
		/* NB: this will create a pass-thru key entry */
		ath_keyset(sc, vap, &ni->ni_ucastkey, vap->iv_bss);
	}
}

/*
 * Setup driver-specific state for a newly associated node.
 * Note that we're called also on a re-associate, the isnew
 * param tells us if this is the first time or not.
 */
static void
ath_newassoc(struct ieee80211_node *ni, int isnew)
{
	struct ath_node *an = ATH_NODE(ni);
	struct ieee80211vap *vap = ni->ni_vap;
	struct ath_softc *sc = vap->iv_ic->ic_softc;
	const struct ieee80211_txparam *tp = ni->ni_txparms;

	an->an_mcastrix = ath_tx_findrix(sc, tp->mcastrate);
	an->an_mgmtrix = ath_tx_findrix(sc, tp->mgmtrate);

	DPRINTF(sc, ATH_DEBUG_NODE, "%s: %6D: reassoc; isnew=%d, is_powersave=%d\n",
	    __func__,
	    ni->ni_macaddr,
	    ":",
	    isnew,
	    an->an_is_powersave);

	ATH_NODE_LOCK(an);
	ath_rate_newassoc(sc, an, isnew);
	ATH_NODE_UNLOCK(an);

	if (isnew &&
	    (vap->iv_flags & IEEE80211_F_PRIVACY) == 0 && sc->sc_hasclrkey &&
	    ni->ni_ucastkey.wk_keyix == IEEE80211_KEYIX_NONE)
		ath_setup_stationkey(ni);

	/*
	 * If we're reassociating, make sure that any paused queues
	 * get unpaused.
	 *
	 * Now, we may have frames in the hardware queue for this node.
	 * So if we are reassociating and there are frames in the queue,
	 * we need to go through the cleanup path to ensure that they're
	 * marked as non-aggregate.
	 */
	if (! isnew) {
		DPRINTF(sc, ATH_DEBUG_NODE,
		    "%s: %6D: reassoc; is_powersave=%d\n",
		    __func__,
		    ni->ni_macaddr,
		    ":",
		    an->an_is_powersave);

		/* XXX for now, we can't hold the lock across assoc */
		ath_tx_node_reassoc(sc, an);

		/* XXX for now, we can't hold the lock across wakeup */
		if (an->an_is_powersave)
			ath_tx_node_wakeup(sc, an);
	}
}

static int
ath_setregdomain(struct ieee80211com *ic, struct ieee80211_regdomain *reg,
	int nchans, struct ieee80211_channel chans[])
{
	struct ath_softc *sc = ic->ic_softc;
	struct ath_hal *ah = sc->sc_ah;
	HAL_STATUS status;

	DPRINTF(sc, ATH_DEBUG_REGDOMAIN,
	    "%s: rd %u cc %u location %c%s\n",
	    __func__, reg->regdomain, reg->country, reg->location,
	    reg->ecm ? " ecm" : "");

	status = ath_hal_set_channels(ah, chans, nchans,
	    reg->country, reg->regdomain);
	if (status != HAL_OK) {
		DPRINTF(sc, ATH_DEBUG_REGDOMAIN, "%s: failed, status %u\n",
		    __func__, status);
		return EINVAL;		/* XXX */
	}

	return 0;
}

static void
ath_getradiocaps(struct ieee80211com *ic,
	int maxchans, int *nchans, struct ieee80211_channel chans[])
{
	struct ath_softc *sc = ic->ic_softc;
	struct ath_hal *ah = sc->sc_ah;

	DPRINTF(sc, ATH_DEBUG_REGDOMAIN, "%s: use rd %u cc %d\n",
	    __func__, SKU_DEBUG, CTRY_DEFAULT);

	/* XXX check return */
	(void) ath_hal_getchannels(ah, chans, maxchans, nchans,
	    HAL_MODE_ALL, CTRY_DEFAULT, SKU_DEBUG, AH_TRUE);

}

static int
ath_getchannels(struct ath_softc *sc)
{
	struct ieee80211com *ic = &sc->sc_ic;
	struct ath_hal *ah = sc->sc_ah;
	HAL_STATUS status;

	/*
	 * Collect channel set based on EEPROM contents.
	 */
	status = ath_hal_init_channels(ah, ic->ic_channels, IEEE80211_CHAN_MAX,
	    &ic->ic_nchans, HAL_MODE_ALL, CTRY_DEFAULT, SKU_NONE, AH_TRUE);
	if (status != HAL_OK) {
		device_printf(sc->sc_dev,
		    "%s: unable to collect channel list from hal, status %d\n",
		    __func__, status);
		return EINVAL;
	}
	(void) ath_hal_getregdomain(ah, &sc->sc_eerd);
	ath_hal_getcountrycode(ah, &sc->sc_eecc);	/* NB: cannot fail */
	/* XXX map Atheros sku's to net80211 SKU's */
	/* XXX net80211 types too small */
	ic->ic_regdomain.regdomain = (uint16_t) sc->sc_eerd;
	ic->ic_regdomain.country = (uint16_t) sc->sc_eecc;
	ic->ic_regdomain.isocc[0] = ' ';	/* XXX don't know */
	ic->ic_regdomain.isocc[1] = ' ';

	ic->ic_regdomain.ecm = 1;
	ic->ic_regdomain.location = 'I';

	DPRINTF(sc, ATH_DEBUG_REGDOMAIN,
	    "%s: eeprom rd %u cc %u (mapped rd %u cc %u) location %c%s\n",
	    __func__, sc->sc_eerd, sc->sc_eecc,
	    ic->ic_regdomain.regdomain, ic->ic_regdomain.country,
	    ic->ic_regdomain.location, ic->ic_regdomain.ecm ? " ecm" : "");
	return 0;
}

static int
ath_rate_setup(struct ath_softc *sc, u_int mode)
{
	struct ath_hal *ah = sc->sc_ah;
	const HAL_RATE_TABLE *rt;

	switch (mode) {
	case IEEE80211_MODE_11A:
		rt = ath_hal_getratetable(ah, HAL_MODE_11A);
		break;
	case IEEE80211_MODE_HALF:
		rt = ath_hal_getratetable(ah, HAL_MODE_11A_HALF_RATE);
		break;
	case IEEE80211_MODE_QUARTER:
		rt = ath_hal_getratetable(ah, HAL_MODE_11A_QUARTER_RATE);
		break;
	case IEEE80211_MODE_11B:
		rt = ath_hal_getratetable(ah, HAL_MODE_11B);
		break;
	case IEEE80211_MODE_11G:
		rt = ath_hal_getratetable(ah, HAL_MODE_11G);
		break;
	case IEEE80211_MODE_TURBO_A:
		rt = ath_hal_getratetable(ah, HAL_MODE_108A);
		break;
	case IEEE80211_MODE_TURBO_G:
		rt = ath_hal_getratetable(ah, HAL_MODE_108G);
		break;
	case IEEE80211_MODE_STURBO_A:
		rt = ath_hal_getratetable(ah, HAL_MODE_TURBO);
		break;
	case IEEE80211_MODE_11NA:
		rt = ath_hal_getratetable(ah, HAL_MODE_11NA_HT20);
		break;
	case IEEE80211_MODE_11NG:
		rt = ath_hal_getratetable(ah, HAL_MODE_11NG_HT20);
		break;
	default:
		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid mode %u\n",
			__func__, mode);
		return 0;
	}
	sc->sc_rates[mode] = rt;
	return (rt != NULL);
}

static void
ath_setcurmode(struct ath_softc *sc, enum ieee80211_phymode mode)
{
	/* NB: on/off times from the Atheros NDIS driver, w/ permission */
	static const struct {
		u_int		rate;		/* tx/rx 802.11 rate */
		u_int16_t	timeOn;		/* LED on time (ms) */
		u_int16_t	timeOff;	/* LED off time (ms) */
	} blinkrates[] = {
		{ 108,  40,  10 },
		{  96,  44,  11 },
		{  72,  50,  13 },
		{  48,  57,  14 },
		{  36,  67,  16 },
		{  24,  80,  20 },
		{  22, 100,  25 },
		{  18, 133,  34 },
		{  12, 160,  40 },
		{  10, 200,  50 },
		{   6, 240,  58 },
		{   4, 267,  66 },
		{   2, 400, 100 },
		{   0, 500, 130 },
		/* XXX half/quarter rates */
	};
	const HAL_RATE_TABLE *rt;
	int i, j;

	memset(sc->sc_rixmap, 0xff, sizeof(sc->sc_rixmap));
	rt = sc->sc_rates[mode];
	KASSERT(rt != NULL, ("no h/w rate set for phy mode %u", mode));
	for (i = 0; i < rt->rateCount; i++) {
		uint8_t ieeerate = rt->info[i].dot11Rate & IEEE80211_RATE_VAL;
		if (rt->info[i].phy != IEEE80211_T_HT)
			sc->sc_rixmap[ieeerate] = i;
		else
			sc->sc_rixmap[ieeerate | IEEE80211_RATE_MCS] = i;
	}
	memset(sc->sc_hwmap, 0, sizeof(sc->sc_hwmap));
	for (i = 0; i < nitems(sc->sc_hwmap); i++) {
		if (i >= rt->rateCount) {
			sc->sc_hwmap[i].ledon = (500 * hz) / 1000;
			sc->sc_hwmap[i].ledoff = (130 * hz) / 1000;
			continue;
		}
		sc->sc_hwmap[i].ieeerate =
			rt->info[i].dot11Rate & IEEE80211_RATE_VAL;
		if (rt->info[i].phy == IEEE80211_T_HT)
			sc->sc_hwmap[i].ieeerate |= IEEE80211_RATE_MCS;
		sc->sc_hwmap[i].txflags = IEEE80211_RADIOTAP_F_DATAPAD;
		if (rt->info[i].shortPreamble ||
		    rt->info[i].phy == IEEE80211_T_OFDM)
			sc->sc_hwmap[i].txflags |= IEEE80211_RADIOTAP_F_SHORTPRE;
		sc->sc_hwmap[i].rxflags = sc->sc_hwmap[i].txflags;
		for (j = 0; j < nitems(blinkrates)-1; j++)
			if (blinkrates[j].rate == sc->sc_hwmap[i].ieeerate)
				break;
		/* NB: this uses the last entry if the rate isn't found */
		/* XXX beware of overlow */
		sc->sc_hwmap[i].ledon = (blinkrates[j].timeOn * hz) / 1000;
		sc->sc_hwmap[i].ledoff = (blinkrates[j].timeOff * hz) / 1000;
	}
	sc->sc_currates = rt;
	sc->sc_curmode = mode;
	/*
	 * All protection frames are transmitted at 2Mb/s for
	 * 11g, otherwise at 1Mb/s.
	 */
	if (mode == IEEE80211_MODE_11G)
		sc->sc_protrix = ath_tx_findrix(sc, 2*2);
	else
		sc->sc_protrix = ath_tx_findrix(sc, 2*1);
	/* NB: caller is responsible for resetting rate control state */
}

static void
ath_watchdog(void *arg)
{
	struct ath_softc *sc = arg;
	struct ieee80211com *ic = &sc->sc_ic;
	int do_reset = 0;

	ATH_LOCK_ASSERT(sc);

	if (sc->sc_wd_timer != 0 && --sc->sc_wd_timer == 0) {
		uint32_t hangs;

		ath_power_set_power_state(sc, HAL_PM_AWAKE);

		if (ath_hal_gethangstate(sc->sc_ah, 0xffff, &hangs) &&
		    hangs != 0) {
			device_printf(sc->sc_dev, "%s hang detected (0x%x)\n",
			    hangs & 0xff ? "bb" : "mac", hangs);
		} else
			device_printf(sc->sc_dev, "device timeout\n");
		do_reset = 1;
		counter_u64_add(ic->ic_oerrors, 1);
		sc->sc_stats.ast_watchdog++;

		ath_power_restore_power_state(sc);
	}

	/*
	 * We can't hold the lock across the ath_reset() call.
	 *
	 * And since this routine can't hold a lock and sleep,
	 * do the reset deferred.
	 */
	if (do_reset) {
		taskqueue_enqueue(sc->sc_tq, &sc->sc_resettask);
	}

	callout_schedule(&sc->sc_wd_ch, hz);
}

static void
ath_parent(struct ieee80211com *ic)
{
	struct ath_softc *sc = ic->ic_softc;
	int error = EDOOFUS;

	ATH_LOCK(sc);
	if (ic->ic_nrunning > 0) {
		/*
		 * To avoid rescanning another access point,
		 * do not call ath_init() here.  Instead,
		 * only reflect promisc mode settings.
		 */
		if (sc->sc_running) {
			ath_power_set_power_state(sc, HAL_PM_AWAKE);
			ath_mode_init(sc);
			ath_power_restore_power_state(sc);
		} else if (!sc->sc_invalid) {
			/*
			 * Beware of being called during attach/detach
			 * to reset promiscuous mode.  In that case we
			 * will still be marked UP but not RUNNING.
			 * However trying to re-init the interface
			 * is the wrong thing to do as we've already
			 * torn down much of our state.  There's
			 * probably a better way to deal with this.
			 */
			error = ath_init(sc);
		}
	} else {
		ath_stop(sc);
		if (!sc->sc_invalid)
			ath_power_setpower(sc, HAL_PM_FULL_SLEEP, 1);
	}
	ATH_UNLOCK(sc);

	if (error == 0) {                        
#ifdef ATH_TX99_DIAG
		if (sc->sc_tx99 != NULL)
			sc->sc_tx99->start(sc->sc_tx99);
		else
#endif
		ieee80211_start_all(ic);
	}
}

/*
 * Announce various information on device/driver attach.
 */
static void
ath_announce(struct ath_softc *sc)
{
	struct ath_hal *ah = sc->sc_ah;

	device_printf(sc->sc_dev, "%s mac %d.%d RF%s phy %d.%d\n",
		ath_hal_mac_name(ah), ah->ah_macVersion, ah->ah_macRev,
		ath_hal_rf_name(ah), ah->ah_phyRev >> 4, ah->ah_phyRev & 0xf);
	device_printf(sc->sc_dev, "2GHz radio: 0x%.4x; 5GHz radio: 0x%.4x\n",
		ah->ah_analog2GhzRev, ah->ah_analog5GhzRev);
	if (bootverbose) {
		int i;
		for (i = 0; i <= WME_AC_VO; i++) {
			struct ath_txq *txq = sc->sc_ac2q[i];
			device_printf(sc->sc_dev,
			    "Use hw queue %u for %s traffic\n",
			    txq->axq_qnum, ieee80211_wme_acnames[i]);
		}
		device_printf(sc->sc_dev, "Use hw queue %u for CAB traffic\n",
		    sc->sc_cabq->axq_qnum);
		device_printf(sc->sc_dev, "Use hw queue %u for beacons\n",
		    sc->sc_bhalq);
	}
	if (ath_rxbuf != ATH_RXBUF)
		device_printf(sc->sc_dev, "using %u rx buffers\n", ath_rxbuf);
	if (ath_txbuf != ATH_TXBUF)
		device_printf(sc->sc_dev, "using %u tx buffers\n", ath_txbuf);
	if (sc->sc_mcastkey && bootverbose)
		device_printf(sc->sc_dev, "using multicast key search\n");
}

static void
ath_dfs_tasklet(void *p, int npending)
{
	struct ath_softc *sc = (struct ath_softc *) p;
	struct ieee80211com *ic = &sc->sc_ic;

	/*
	 * If previous processing has found a radar event,
	 * signal this to the net80211 layer to begin DFS
	 * processing.
	 */
	if (ath_dfs_process_radar_event(sc, sc->sc_curchan)) {
		/* DFS event found, initiate channel change */

		/*
		 * XXX TODO: immediately disable ACK processing
		 * on the current channel.  This would be done
		 * by setting AR_DIAG_ACK_DIS (AR5212; may be
		 * different for others) until we are out of
		 * CAC.
		 */

		/*
		 * XXX doesn't currently tell us whether the event
		 * XXX was found in the primary or extension
		 * XXX channel!
		 */
		IEEE80211_LOCK(ic);
		ieee80211_dfs_notify_radar(ic, sc->sc_curchan);
		IEEE80211_UNLOCK(ic);
	}
}

/*
 * Enable/disable power save.  This must be called with
 * no TX driver locks currently held, so it should only
 * be called from the RX path (which doesn't hold any
 * TX driver locks.)
 */
static void
ath_node_powersave(struct ieee80211_node *ni, int enable)
{
#ifdef	ATH_SW_PSQ
	struct ath_node *an = ATH_NODE(ni);
	struct ieee80211com *ic = ni->ni_ic;
	struct ath_softc *sc = ic->ic_softc;
	struct ath_vap *avp = ATH_VAP(ni->ni_vap);

	/* XXX and no TXQ locks should be held here */

	DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE, "%s: %6D: enable=%d\n",
	    __func__,
	    ni->ni_macaddr,
	    ":",
	    !! enable);

	/* Suspend or resume software queue handling */
	if (enable)
		ath_tx_node_sleep(sc, an);
	else
		ath_tx_node_wakeup(sc, an);

	/* Update net80211 state */
	avp->av_node_ps(ni, enable);
#else
	struct ath_vap *avp = ATH_VAP(ni->ni_vap);

	/* Update net80211 state */
	avp->av_node_ps(ni, enable);
#endif/* ATH_SW_PSQ */
}

/*
 * Notification from net80211 that the powersave queue state has
 * changed.
 *
 * Since the software queue also may have some frames:
 *
 * + if the node software queue has frames and the TID state
 *   is 0, we set the TIM;
 * + if the node and the stack are both empty, we clear the TIM bit.
 * + If the stack tries to set the bit, always set it.
 * + If the stack tries to clear the bit, only clear it if the
 *   software queue in question is also cleared.
 *
 * TODO: this is called during node teardown; so let's ensure this
 * is all correctly handled and that the TIM bit is cleared.
 * It may be that the node flush is called _AFTER_ the net80211
 * stack clears the TIM.
 *
 * Here is the racy part.  Since it's possible >1 concurrent,
 * overlapping TXes will appear complete with a TX completion in
 * another thread, it's possible that the concurrent TIM calls will
 * clash.  We can't hold the node lock here because setting the
 * TIM grabs the net80211 comlock and this may cause a LOR.
 * The solution is either to totally serialise _everything_ at
 * this point (ie, all TX, completion and any reset/flush go into
 * one taskqueue) or a new "ath TIM lock" needs to be created that
 * just wraps the driver state change and this call to avp->av_set_tim().
 *
 * The same race exists in the net80211 power save queue handling
 * as well.  Since multiple transmitting threads may queue frames
 * into the driver, as well as ps-poll and the driver transmitting
 * frames (and thus clearing the psq), it's quite possible that
 * a packet entering the PSQ and a ps-poll being handled will
 * race, causing the TIM to be cleared and not re-set.
 */
static int
ath_node_set_tim(struct ieee80211_node *ni, int enable)
{
#ifdef	ATH_SW_PSQ
	struct ieee80211com *ic = ni->ni_ic;
	struct ath_softc *sc = ic->ic_softc;
	struct ath_node *an = ATH_NODE(ni);
	struct ath_vap *avp = ATH_VAP(ni->ni_vap);
	int changed = 0;

	ATH_TX_LOCK(sc);
	an->an_stack_psq = enable;

	/*
	 * This will get called for all operating modes,
	 * even if avp->av_set_tim is unset.
	 * It's currently set for hostap/ibss modes; but
	 * the same infrastructure is used for both STA
	 * and AP/IBSS node power save.
	 */
	if (avp->av_set_tim == NULL) {
		ATH_TX_UNLOCK(sc);
		return (0);
	}

	/*
	 * If setting the bit, always set it here.
	 * If clearing the bit, only clear it if the
	 * software queue is also empty.
	 *
	 * If the node has left power save, just clear the TIM
	 * bit regardless of the state of the power save queue.
	 *
	 * XXX TODO: although atomics are used, it's quite possible
	 * that a race will occur between this and setting/clearing
	 * in another thread.  TX completion will occur always in
	 * one thread, however setting/clearing the TIM bit can come
	 * from a variety of different process contexts!
	 */
	if (enable && an->an_tim_set == 1) {
		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
		    "%s: %6D: enable=%d, tim_set=1, ignoring\n",
		    __func__,
		    ni->ni_macaddr,
		    ":",
		    enable);
		ATH_TX_UNLOCK(sc);
	} else if (enable) {
		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
		    "%s: %6D: enable=%d, enabling TIM\n",
		    __func__,
		    ni->ni_macaddr,
		    ":",
		    enable);
		an->an_tim_set = 1;
		ATH_TX_UNLOCK(sc);
		changed = avp->av_set_tim(ni, enable);
	} else if (an->an_swq_depth == 0) {
		/* disable */
		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
		    "%s: %6D: enable=%d, an_swq_depth == 0, disabling\n",
		    __func__,
		    ni->ni_macaddr,
		    ":",
		    enable);
		an->an_tim_set = 0;
		ATH_TX_UNLOCK(sc);
		changed = avp->av_set_tim(ni, enable);
	} else if (! an->an_is_powersave) {
		/*
		 * disable regardless; the node isn't in powersave now
		 */
		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
		    "%s: %6D: enable=%d, an_pwrsave=0, disabling\n",
		    __func__,
		    ni->ni_macaddr,
		    ":",
		    enable);
		an->an_tim_set = 0;
		ATH_TX_UNLOCK(sc);
		changed = avp->av_set_tim(ni, enable);
	} else {
		/*
		 * psq disable, node is currently in powersave, node
		 * software queue isn't empty, so don't clear the TIM bit
		 * for now.
		 */
		ATH_TX_UNLOCK(sc);
		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
		    "%s: %6D: enable=%d, an_swq_depth > 0, ignoring\n",
		    __func__,
		    ni->ni_macaddr,
		    ":",
		    enable);
		changed = 0;
	}

	return (changed);
#else
	struct ath_vap *avp = ATH_VAP(ni->ni_vap);

	/*
	 * Some operating modes don't set av_set_tim(), so don't
	 * update it here.
	 */
	if (avp->av_set_tim == NULL)
		return (0);

	return (avp->av_set_tim(ni, enable));
#endif /* ATH_SW_PSQ */
}

/*
 * Set or update the TIM from the software queue.
 *
 * Check the software queue depth before attempting to do lock
 * anything; that avoids trying to obtain the lock.  Then,
 * re-check afterwards to ensure nothing has changed in the
 * meantime.
 *
 * set:   This is designed to be called from the TX path, after
 *        a frame has been queued; to see if the swq > 0.
 *
 * clear: This is designed to be called from the buffer completion point
 *        (right now it's ath_tx_default_comp()) where the state of
 *        a software queue has changed.
 *
 * It makes sense to place it at buffer free / completion rather
 * than after each software queue operation, as there's no real
 * point in churning the TIM bit as the last frames in the software
 * queue are transmitted.  If they fail and we retry them, we'd
 * just be setting the TIM bit again anyway.
 */
void
ath_tx_update_tim(struct ath_softc *sc, struct ieee80211_node *ni,
     int enable)
{
#ifdef	ATH_SW_PSQ
	struct ath_node *an;
	struct ath_vap *avp;

	/* Don't do this for broadcast/etc frames */
	if (ni == NULL)
		return;

	an = ATH_NODE(ni);
	avp = ATH_VAP(ni->ni_vap);

	/*
	 * And for operating modes without the TIM handler set, let's
	 * just skip those.
	 */
	if (avp->av_set_tim == NULL)
		return;

	ATH_TX_LOCK_ASSERT(sc);

	if (enable) {
		if (an->an_is_powersave &&
		    an->an_tim_set == 0 &&
		    an->an_swq_depth != 0) {
			DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
			    "%s: %6D: swq_depth>0, tim_set=0, set!\n",
			    __func__,
			    ni->ni_macaddr,
			    ":");
			an->an_tim_set = 1;
			(void) avp->av_set_tim(ni, 1);
		}
	} else {
		/*
		 * Don't bother grabbing the lock unless the queue is empty.
		 */
		if (an->an_swq_depth != 0)
			return;

		if (an->an_is_powersave &&
		    an->an_stack_psq == 0 &&
		    an->an_tim_set == 1 &&
		    an->an_swq_depth == 0) {
			DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
			    "%s: %6D: swq_depth=0, tim_set=1, psq_set=0,"
			    " clear!\n",
			    __func__,
			    ni->ni_macaddr,
			    ":");
			an->an_tim_set = 0;
			(void) avp->av_set_tim(ni, 0);
		}
	}
#else
	return;
#endif	/* ATH_SW_PSQ */
}

/*
 * Received a ps-poll frame from net80211.
 *
 * Here we get a chance to serve out a software-queued frame ourselves
 * before we punt it to net80211 to transmit us one itself - either
 * because there's traffic in the net80211 psq, or a NULL frame to
 * indicate there's nothing else.
 */
static void
ath_node_recv_pspoll(struct ieee80211_node *ni, struct mbuf *m)
{
#ifdef	ATH_SW_PSQ
	struct ath_node *an;
	struct ath_vap *avp;
	struct ieee80211com *ic = ni->ni_ic;
	struct ath_softc *sc = ic->ic_softc;
	int tid;

	/* Just paranoia */
	if (ni == NULL)
		return;

	/*
	 * Unassociated (temporary node) station.
	 */
	if (ni->ni_associd == 0)
		return;

	/*
	 * We do have an active node, so let's begin looking into it.
	 */
	an = ATH_NODE(ni);
	avp = ATH_VAP(ni->ni_vap);

	/*
	 * For now, we just call the original ps-poll method.
	 * Once we're ready to flip this on:
	 *
	 * + Set leak to 1, as no matter what we're going to have
	 *   to send a frame;
	 * + Check the software queue and if there's something in it,
	 *   schedule the highest TID thas has traffic from this node.
	 *   Then make sure we schedule the software scheduler to
	 *   run so it picks up said frame.
	 *
	 * That way whatever happens, we'll at least send _a_ frame
	 * to the given node.
	 *
	 * Again, yes, it's crappy QoS if the node has multiple
	 * TIDs worth of traffic - but let's get it working first
	 * before we optimise it.
	 *
	 * Also yes, there's definitely latency here - we're not
	 * direct dispatching to the hardware in this path (and
	 * we're likely being called from the packet receive path,
	 * so going back into TX may be a little hairy!) but again
	 * I'd like to get this working first before optimising
	 * turn-around time.
	 */

	ATH_TX_LOCK(sc);

	/*
	 * Legacy - we're called and the node isn't asleep.
	 * Immediately punt.
	 */
	if (! an->an_is_powersave) {
		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
		    "%s: %6D: not in powersave?\n",
		    __func__,
		    ni->ni_macaddr,
		    ":");
		ATH_TX_UNLOCK(sc);
		avp->av_recv_pspoll(ni, m);
		return;
	}

	/*
	 * We're in powersave.
	 *
	 * Leak a frame.
	 */
	an->an_leak_count = 1;

	/*
	 * Now, if there's no frames in the node, just punt to
	 * recv_pspoll.
	 *
	 * Don't bother checking if the TIM bit is set, we really
	 * only care if there are any frames here!
	 */
	if (an->an_swq_depth == 0) {
		ATH_TX_UNLOCK(sc);
		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
		    "%s: %6D: SWQ empty; punting to net80211\n",
		    __func__,
		    ni->ni_macaddr,
		    ":");
		avp->av_recv_pspoll(ni, m);
		return;
	}

	/*
	 * Ok, let's schedule the highest TID that has traffic
	 * and then schedule something.
	 */
	for (tid = IEEE80211_TID_SIZE - 1; tid >= 0; tid--) {
		struct ath_tid *atid = &an->an_tid[tid];
		/*
		 * No frames? Skip.
		 */
		if (atid->axq_depth == 0)
			continue;
		ath_tx_tid_sched(sc, atid);
		/*
		 * XXX we could do a direct call to the TXQ
		 * scheduler code here to optimise latency
		 * at the expense of a REALLY deep callstack.
		 */
		ATH_TX_UNLOCK(sc);
		taskqueue_enqueue(sc->sc_tq, &sc->sc_txqtask);
		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
		    "%s: %6D: leaking frame to TID %d\n",
		    __func__,
		    ni->ni_macaddr,
		    ":",
		    tid);
		return;
	}

	ATH_TX_UNLOCK(sc);

	/*
	 * XXX nothing in the TIDs at this point? Eek.
	 */
	DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
	    "%s: %6D: TIDs empty, but ath_node showed traffic?!\n",
	    __func__,
	    ni->ni_macaddr,
	    ":");
	avp->av_recv_pspoll(ni, m);
#else
	avp->av_recv_pspoll(ni, m);
#endif	/* ATH_SW_PSQ */
}

MODULE_VERSION(ath_main, 1);
MODULE_DEPEND(ath_main, wlan, 1, 1, 1);          /* 802.11 media layer */
MODULE_DEPEND(ath_main, ath_rate, 1, 1, 1);
MODULE_DEPEND(ath_main, ath_dfs, 1, 1, 1);
MODULE_DEPEND(ath_main, ath_hal, 1, 1, 1);
#if	defined(IEEE80211_ALQ) || defined(AH_DEBUG_ALQ) || defined(ATH_DEBUG_ALQ)
MODULE_DEPEND(ath_main, alq, 1, 1, 1);
#endif