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

/*-
 * Copyright (c) 2010 Damien Bergamini <damien.bergamini@free.fr>
 * Copyright (c) 2014 Kevin Lo <kevlo@FreeBSD.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/*
 * Driver for Realtek RTL8188CE-VAU/RTL8188CUS/RTL8188EU/RTL8188RU/RTL8192CU.
 */

#include "bpfilter.h"

#include <sys/param.h>
#include <sys/sockio.h>
#include <sys/mbuf.h>
#include <sys/kernel.h>
#include <sys/socket.h>
#include <sys/systm.h>
#include <sys/timeout.h>
#include <sys/conf.h>
#include <sys/device.h>
#include <sys/endian.h>

#include <machine/intr.h>

#if NBPFILTER > 0
#include <net/bpf.h>
#endif
#include <net/if.h>
#include <net/if_dl.h>
#include <net/if_media.h>

#include <netinet/in.h>
#include <netinet/if_ether.h>

#include <net80211/ieee80211_var.h>
#include <net80211/ieee80211_amrr.h>
#include <net80211/ieee80211_radiotap.h>

#include <dev/usb/usb.h>
#include <dev/usb/usbdi.h>
#include <dev/usb/usbdi_util.h>
#include <dev/usb/usbdevs.h>

#include <dev/ic/r92creg.h>
#include <dev/ic/rtwnvar.h>

/* Maximum number of output pipes is 3. */
#define R92C_MAX_EPOUT	3

#define R92C_HQ_NPAGES		12
#define R92C_LQ_NPAGES		2
#define R92C_NQ_NPAGES		2
#define R92C_TXPKTBUF_COUNT	256
#define R92C_TX_PAGE_COUNT	248
#define R92C_TX_PAGE_BOUNDARY	(R92C_TX_PAGE_COUNT + 1)
#define R92C_MAX_RX_DMA_SIZE	0x2800
#define R88E_HQ_NPAGES		0
#define R88E_LQ_NPAGES		9
#define R88E_NQ_NPAGES		0
#define R88E_TXPKTBUF_COUNT	177
#define R88E_TX_PAGE_COUNT	168
#define R88E_TX_PAGE_BOUNDARY	(R88E_TX_PAGE_COUNT + 1)
#define R88E_MAX_RX_DMA_SIZE	0x2400

/* USB Requests. */
#define R92C_REQ_REGS	0x05

/*
 * Driver definitions.
 */
#define URTWN_RX_LIST_COUNT		1
#define URTWN_TX_LIST_COUNT		8
#define URTWN_HOST_CMD_RING_COUNT	32

#define URTWN_RXBUFSZ	(16 * 1024)
#define URTWN_TXBUFSZ	(sizeof(struct r92c_tx_desc_usb) + IEEE80211_MAX_LEN)

#define URTWN_RIDX_COUNT	28

#define URTWN_TX_TIMEOUT	5000	/* ms */

#define URTWN_LED_LINK	0
#define URTWN_LED_DATA	1

struct urtwn_rx_radiotap_header {
	struct ieee80211_radiotap_header wr_ihdr;
	uint8_t		wr_flags;
	uint8_t		wr_rate;
	uint16_t	wr_chan_freq;
	uint16_t	wr_chan_flags;
	uint8_t		wr_dbm_antsignal;
} __packed;

#define URTWN_RX_RADIOTAP_PRESENT			\
	(1 << IEEE80211_RADIOTAP_FLAGS |		\
	 1 << IEEE80211_RADIOTAP_RATE |			\
	 1 << IEEE80211_RADIOTAP_CHANNEL |		\
	 1 << IEEE80211_RADIOTAP_DBM_ANTSIGNAL)

struct urtwn_tx_radiotap_header {
	struct ieee80211_radiotap_header wt_ihdr;
	uint8_t		wt_flags;
	uint16_t	wt_chan_freq;
	uint16_t	wt_chan_flags;
} __packed;

#define URTWN_TX_RADIOTAP_PRESENT			\
	(1 << IEEE80211_RADIOTAP_FLAGS |		\
	 1 << IEEE80211_RADIOTAP_CHANNEL)

struct urtwn_softc;

struct urtwn_rx_data {
	struct urtwn_softc	*sc;
	struct usbd_xfer	*xfer;
	uint8_t			*buf;
};

struct urtwn_tx_data {
	struct urtwn_softc		*sc;
	struct usbd_pipe		*pipe;
	struct usbd_xfer		*xfer;
	uint8_t				*buf;
	TAILQ_ENTRY(urtwn_tx_data)	next;
};

struct urtwn_host_cmd {
	void	(*cb)(struct urtwn_softc *, void *);
	uint8_t	data[256];
};

struct urtwn_cmd_newstate {
	enum ieee80211_state	state;
	int			arg;
};

struct urtwn_cmd_key {
	struct ieee80211_key	key;
	struct ieee80211_node	*ni;
};

struct urtwn_host_cmd_ring {
	struct urtwn_host_cmd	cmd[URTWN_HOST_CMD_RING_COUNT];
	int			cur;
	int			next;
	int			queued;
};

struct urtwn_softc {
	struct device			sc_dev;
	struct rtwn_softc		sc_sc;

	struct usbd_device		*sc_udev;
	struct usbd_interface		*sc_iface;
	struct usb_task			sc_task;

	struct timeout			scan_to;
	struct timeout			calib_to;

	int				ntx;
	struct usbd_pipe		*rx_pipe;
	struct usbd_pipe		*tx_pipe[R92C_MAX_EPOUT];
	int				ac2idx[EDCA_NUM_AC];

	struct urtwn_host_cmd_ring	cmdq;
	struct urtwn_rx_data		rx_data[URTWN_RX_LIST_COUNT];
	struct urtwn_tx_data		tx_data[URTWN_TX_LIST_COUNT];
	TAILQ_HEAD(, urtwn_tx_data)	tx_free_list;

	struct ieee80211_amrr		amrr;
	struct ieee80211_amrr_node	amn;

#if NBPFILTER > 0
	caddr_t				sc_drvbpf;

	union {
		struct urtwn_rx_radiotap_header th;
		uint8_t	pad[64];
	}				sc_rxtapu;
#define sc_rxtap	sc_rxtapu.th
	int				sc_rxtap_len;

	union {
		struct urtwn_tx_radiotap_header th;
		uint8_t	pad[64];
	}				sc_txtapu;
#define sc_txtap	sc_txtapu.th
	int				sc_txtap_len;
#endif
};

#ifdef URTWN_DEBUG
#define DPRINTF(x)	do { if (urtwn_debug) printf x; } while (0)
#define DPRINTFN(n, x)	do { if (urtwn_debug >= (n)) printf x; } while (0)
int urtwn_debug = 4;
#else
#define DPRINTF(x)
#define DPRINTFN(n, x)
#endif

/*
 * Various supported device vendors/products.
 */
#define URTWN_DEV(v, p, f)					\
        { { USB_VENDOR_##v, USB_PRODUCT_##v##_##p }, (f) | RTWN_CHIP_USB }
#define URTWN_DEV_8192CU(v, p)	URTWN_DEV(v, p, RTWN_CHIP_92C | RTWN_CHIP_88C)
#define URTWN_DEV_8188EU(v, p)	URTWN_DEV(v, p, RTWN_CHIP_88E)
static const struct urtwn_type {
	struct usb_devno        dev;
	uint32_t		chip;
} urtwn_devs[] = {
	URTWN_DEV_8192CU(ABOCOM,	RTL8188CU_1),
	URTWN_DEV_8192CU(ABOCOM,	RTL8188CU_1),
	URTWN_DEV_8192CU(ABOCOM,	RTL8188CU_2),
	URTWN_DEV_8192CU(ABOCOM,	RTL8192CU),
	URTWN_DEV_8192CU(ASUS,		RTL8192CU),
	URTWN_DEV_8192CU(ASUS,		RTL8192CU_2),
	URTWN_DEV_8192CU(ASUS,		RTL8192CU_3),
	URTWN_DEV_8192CU(AZUREWAVE,	RTL8188CE_1),
	URTWN_DEV_8192CU(AZUREWAVE,	RTL8188CE_2),
	URTWN_DEV_8192CU(AZUREWAVE,	RTL8188CU),
	URTWN_DEV_8192CU(BELKIN,	F7D2102),
	URTWN_DEV_8192CU(BELKIN,	F9L1004V1),
	URTWN_DEV_8192CU(BELKIN,	RTL8188CU),
	URTWN_DEV_8192CU(BELKIN,	RTL8188CUS),
	URTWN_DEV_8192CU(BELKIN,	RTL8192CU),
	URTWN_DEV_8192CU(BELKIN,	RTL8192CU_1),
	URTWN_DEV_8192CU(BELKIN,	RTL8192CU_2),
	URTWN_DEV_8192CU(CHICONY,	RTL8188CUS_1),
	URTWN_DEV_8192CU(CHICONY,	RTL8188CUS_2),
	URTWN_DEV_8192CU(CHICONY,	RTL8188CUS_3),
	URTWN_DEV_8192CU(CHICONY,	RTL8188CUS_4),
	URTWN_DEV_8192CU(CHICONY,	RTL8188CUS_5),
	URTWN_DEV_8192CU(CHICONY,	RTL8188CUS_6),
	URTWN_DEV_8192CU(COMPARE,	RTL8192CU),
	URTWN_DEV_8192CU(COREGA,	RTL8192CU),
	URTWN_DEV_8192CU(DLINK,		DWA131B),
	URTWN_DEV_8192CU(DLINK,		RTL8188CU),
	URTWN_DEV_8192CU(DLINK,		RTL8192CU_1),
	URTWN_DEV_8192CU(DLINK,		RTL8192CU_2),
	URTWN_DEV_8192CU(DLINK,		RTL8192CU_3),
	URTWN_DEV_8192CU(DLINK,		RTL8192CU_4),
	URTWN_DEV_8192CU(EDIMAX,	EW7811UN),
	URTWN_DEV_8192CU(EDIMAX,	RTL8192CU),
	URTWN_DEV_8192CU(FEIXUN,	RTL8188CU),
	URTWN_DEV_8192CU(FEIXUN,	RTL8192CU),
	URTWN_DEV_8192CU(GUILLEMOT,	HWNUP150),
	URTWN_DEV_8192CU(GUILLEMOT,	RTL8192CU),
	URTWN_DEV_8192CU(HAWKING,	RTL8192CU),
	URTWN_DEV_8192CU(HAWKING,	RTL8192CU_2),
	URTWN_DEV_8192CU(HP3,		RTL8188CU),
	URTWN_DEV_8192CU(IODATA,	WNG150UM),
	URTWN_DEV_8192CU(IODATA,	RTL8192CU),
	URTWN_DEV_8192CU(NETGEAR,	N300MA),
	URTWN_DEV_8192CU(NETGEAR,	WNA1000M),
	URTWN_DEV_8192CU(NETGEAR,	WNA1000Mv2),
	URTWN_DEV_8192CU(NETGEAR,	RTL8192CU),
	URTWN_DEV_8192CU(NETGEAR4,	RTL8188CU),
	URTWN_DEV_8192CU(NETWEEN,	RTL8192CU),
	URTWN_DEV_8192CU(NOVATECH,	RTL8188CU),
	URTWN_DEV_8192CU(PLANEX2,	RTL8188CU_1),
	URTWN_DEV_8192CU(PLANEX2,	RTL8188CU_2),
	URTWN_DEV_8192CU(PLANEX2,	RTL8188CU_3),
	URTWN_DEV_8192CU(PLANEX2,	RTL8188CU_4),
	URTWN_DEV_8192CU(PLANEX2,	RTL8188CUS),
	URTWN_DEV_8192CU(PLANEX2,	RTL8192CU),
	URTWN_DEV_8192CU(REALTEK,	RTL8188CE_0),
	URTWN_DEV_8192CU(REALTEK,	RTL8188CE_1),
	URTWN_DEV_8192CU(REALTEK,	RTL8188CTV),
	URTWN_DEV_8192CU(REALTEK,	RTL8188CU_0),
	URTWN_DEV_8192CU(REALTEK,	RTL8188CU_1),
	URTWN_DEV_8192CU(REALTEK,	RTL8188CU_2),
	URTWN_DEV_8192CU(REALTEK,	RTL8188CU_3),
	URTWN_DEV_8192CU(REALTEK,	RTL8188CU_4),
	URTWN_DEV_8192CU(REALTEK,	RTL8188CU_5),
	URTWN_DEV_8192CU(REALTEK,	RTL8188CU_COMBO),
	URTWN_DEV_8192CU(REALTEK,	RTL8188CUS),
	URTWN_DEV_8192CU(REALTEK,	RTL8188RU),
	URTWN_DEV_8192CU(REALTEK,	RTL8188RU_2),
	URTWN_DEV_8192CU(REALTEK,	RTL8188RU_3),
	URTWN_DEV_8192CU(REALTEK,	RTL8191CU),
	URTWN_DEV_8192CU(REALTEK,	RTL8192CE),
	URTWN_DEV_8192CU(REALTEK,	RTL8192CE_VAU),
	URTWN_DEV_8192CU(REALTEK,	RTL8192CU),
	URTWN_DEV_8192CU(SITECOMEU,	RTL8188CU),
	URTWN_DEV_8192CU(SITECOMEU,	RTL8188CU_2),
	URTWN_DEV_8192CU(SITECOMEU,	RTL8192CU),
	URTWN_DEV_8192CU(SITECOMEU,	RTL8192CU_2),
	URTWN_DEV_8192CU(SITECOMEU,	WLA2100V2),
	URTWN_DEV_8192CU(TPLINK,	RTL8192CU),
	URTWN_DEV_8192CU(TRENDNET,	RTL8188CU),
	URTWN_DEV_8192CU(TRENDNET,	RTL8192CU),
	URTWN_DEV_8192CU(ZYXEL,		RTL8192CU),
	/* URTWN_RTL8188E */
	URTWN_DEV_8188EU(DLINK,		DWA123D1),
	URTWN_DEV_8188EU(DLINK,		DWA125D1),
	URTWN_DEV_8188EU(ELECOM,	WDC150SU2M),
	URTWN_DEV_8188EU(REALTEK,	RTL8188ETV),
	URTWN_DEV_8188EU(REALTEK,	RTL8188EU)
};

#define urtwn_lookup(v, p)	\
	((const struct urtwn_type *)usb_lookup(urtwn_devs, v, p))

int		urtwn_match(struct device *, void *, void *);
void		urtwn_attach(struct device *, struct device *, void *);
int		urtwn_detach(struct device *, int);
int		urtwn_open_pipes(struct urtwn_softc *);
void		urtwn_close_pipes(struct urtwn_softc *);
int		urtwn_alloc_rx_list(struct urtwn_softc *);
void		urtwn_free_rx_list(struct urtwn_softc *);
int		urtwn_alloc_tx_list(struct urtwn_softc *);
void		urtwn_free_tx_list(struct urtwn_softc *);
void		urtwn_task(void *);
void		urtwn_do_async(struct urtwn_softc *,
		    void (*)(struct urtwn_softc *, void *), void *, int);
void		urtwn_wait_async(void *); 
int		urtwn_write_region_1(struct urtwn_softc *, uint16_t, uint8_t *,
		    int);
void		urtwn_write_1(void *, uint16_t, uint8_t);
void		urtwn_write_2(void *, uint16_t, uint16_t);
void		urtwn_write_4(void *, uint16_t, uint32_t);
int		urtwn_read_region_1(struct urtwn_softc *, uint16_t, uint8_t *,
		    int);
uint8_t		urtwn_read_1(void *, uint16_t);
uint16_t	urtwn_read_2(void *, uint16_t);
uint32_t	urtwn_read_4(void *, uint16_t);
int		urtwn_llt_write(struct urtwn_softc *, uint32_t, uint32_t);
void		urtwn_calib_to(void *);
void		urtwn_calib_cb(struct urtwn_softc *, void *);
void		urtwn_scan_to(void *);
void		urtwn_next_scan(void *);
void		urtwn_cancel_scan(void *);
int		urtwn_newstate(struct ieee80211com *, enum ieee80211_state,
		    int);
void		urtwn_newstate_cb(struct urtwn_softc *, void *);
void		urtwn_updateslot(struct ieee80211com *);
void		urtwn_updateslot_cb(struct urtwn_softc *, void *);
void		urtwn_updateedca(struct ieee80211com *);
void		urtwn_updateedca_cb(struct urtwn_softc *, void *);
int		urtwn_set_key(struct ieee80211com *, struct ieee80211_node *,
		    struct ieee80211_key *);
void		urtwn_set_key_cb(struct urtwn_softc *, void *);
void		urtwn_delete_key(struct ieee80211com *,
		    struct ieee80211_node *, struct ieee80211_key *);
void		urtwn_delete_key_cb(struct urtwn_softc *, void *);
void		urtwn_rx_frame(struct urtwn_softc *, uint8_t *, int);
void		urtwn_rxeof(struct usbd_xfer *, void *,
		    usbd_status);
void		urtwn_txeof(struct usbd_xfer *, void *,
		    usbd_status);
int		urtwn_tx(void *, struct mbuf *, struct ieee80211_node *);
int		urtwn_ioctl(struct ifnet *, u_long, caddr_t);
int		urtwn_power_on(void *);
int		urtwn_alloc_buffers(void *);
int		urtwn_r92c_power_on(struct urtwn_softc *);
int		urtwn_r88e_power_on(struct urtwn_softc *);
int		urtwn_llt_init(struct urtwn_softc *, int);
int		urtwn_fw_loadpage(void *, int, uint8_t *, int);
int		urtwn_load_firmware(void *, u_char **, size_t *);
int		urtwn_dma_init(void *);
void		urtwn_mac_init(void *);
void		urtwn_bb_init(void *);
int		urtwn_init(void *);
void		urtwn_stop(void *);
int		urtwn_is_oactive(void *);
void		urtwn_next_calib(void *);
void		urtwn_cancel_calib(void *);

/* Aliases. */
#define	urtwn_bb_write	urtwn_write_4
#define urtwn_bb_read	urtwn_read_4

struct cfdriver urtwn_cd = {
	NULL, "urtwn", DV_IFNET
};

const struct cfattach urtwn_ca = {
	sizeof(struct urtwn_softc), urtwn_match, urtwn_attach, urtwn_detach
};

int
urtwn_match(struct device *parent, void *match, void *aux)
{
	struct usb_attach_arg *uaa = aux;

	if (uaa->iface == NULL || uaa->configno != 1)
		return (UMATCH_NONE);

	return ((urtwn_lookup(uaa->vendor, uaa->product) != NULL) ?
	    UMATCH_VENDOR_PRODUCT_CONF_IFACE : UMATCH_NONE);
}

void
urtwn_attach(struct device *parent, struct device *self, void *aux)
{
	struct urtwn_softc *sc = (struct urtwn_softc *)self;
	struct usb_attach_arg *uaa = aux;
	struct ifnet *ifp;
	struct ieee80211com *ic = &sc->sc_sc.sc_ic;

	sc->sc_udev = uaa->device;
	sc->sc_iface = uaa->iface;

	sc->sc_sc.chip = urtwn_lookup(uaa->vendor, uaa->product)->chip;

	usb_init_task(&sc->sc_task, urtwn_task, sc, USB_TASK_TYPE_GENERIC);
	timeout_set(&sc->scan_to, urtwn_scan_to, sc);
	timeout_set(&sc->calib_to, urtwn_calib_to, sc);
	if (urtwn_open_pipes(sc) != 0)
		return;

	sc->amrr.amrr_min_success_threshold =  1;
	sc->amrr.amrr_max_success_threshold = 10;

	/* Attach the bus-agnostic driver. */
	sc->sc_sc.sc_ops.cookie = sc;
	sc->sc_sc.sc_ops.write_1 = urtwn_write_1;
	sc->sc_sc.sc_ops.write_2 = urtwn_write_2;
	sc->sc_sc.sc_ops.write_4 = urtwn_write_4;
	sc->sc_sc.sc_ops.read_1 = urtwn_read_1;
	sc->sc_sc.sc_ops.read_2 = urtwn_read_2;
	sc->sc_sc.sc_ops.read_4 = urtwn_read_4;
	sc->sc_sc.sc_ops.tx = urtwn_tx;
	sc->sc_sc.sc_ops.power_on = urtwn_power_on;
	sc->sc_sc.sc_ops.dma_init = urtwn_dma_init;
	sc->sc_sc.sc_ops.fw_loadpage = urtwn_fw_loadpage;
	sc->sc_sc.sc_ops.load_firmware = urtwn_load_firmware;
	sc->sc_sc.sc_ops.mac_init = urtwn_mac_init;
	sc->sc_sc.sc_ops.bb_init = urtwn_bb_init;
	sc->sc_sc.sc_ops.alloc_buffers = urtwn_alloc_buffers;
	sc->sc_sc.sc_ops.init = urtwn_init;
	sc->sc_sc.sc_ops.stop = urtwn_stop;
	sc->sc_sc.sc_ops.is_oactive = urtwn_is_oactive;
	sc->sc_sc.sc_ops.next_calib = urtwn_next_calib;
	sc->sc_sc.sc_ops.cancel_calib = urtwn_cancel_calib;
	sc->sc_sc.sc_ops.next_scan = urtwn_next_scan;
	sc->sc_sc.sc_ops.cancel_scan = urtwn_cancel_scan;
	sc->sc_sc.sc_ops.wait_async = urtwn_wait_async;
	if (rtwn_attach(&sc->sc_dev, &sc->sc_sc) != 0) {
		urtwn_close_pipes(sc);
		return;
	}

	/* ifp is now valid */
	ifp = &sc->sc_sc.sc_ic.ic_if;
	ifp->if_ioctl = urtwn_ioctl;

	ic->ic_updateslot = urtwn_updateslot;
	ic->ic_updateedca = urtwn_updateedca;
#ifdef notyet
	ic->ic_set_key = urtwn_set_key;
	ic->ic_delete_key = urtwn_delete_key;
#endif
	/* Override state transition machine. */
	ic->ic_newstate = urtwn_newstate;

#if NBPFILTER > 0
	bpfattach(&sc->sc_drvbpf, ifp, DLT_IEEE802_11_RADIO,
	    sizeof(struct ieee80211_frame) + IEEE80211_RADIOTAP_HDRLEN);

	sc->sc_rxtap_len = sizeof(sc->sc_rxtapu);
	sc->sc_rxtap.wr_ihdr.it_len = htole16(sc->sc_rxtap_len);
	sc->sc_rxtap.wr_ihdr.it_present = htole32(URTWN_RX_RADIOTAP_PRESENT);

	sc->sc_txtap_len = sizeof(sc->sc_txtapu);
	sc->sc_txtap.wt_ihdr.it_len = htole16(sc->sc_txtap_len);
	sc->sc_txtap.wt_ihdr.it_present = htole32(URTWN_TX_RADIOTAP_PRESENT);
#endif
}

int
urtwn_detach(struct device *self, int flags)
{
	struct urtwn_softc *sc = (struct urtwn_softc *)self;
	int s;

	s = splusb();

	if (timeout_initialized(&sc->scan_to))
		timeout_del(&sc->scan_to);
	if (timeout_initialized(&sc->calib_to))
		timeout_del(&sc->calib_to);

	/* Wait for all async commands to complete. */
	usb_rem_wait_task(sc->sc_udev, &sc->sc_task);

	usbd_ref_wait(sc->sc_udev);

	rtwn_detach(&sc->sc_sc, flags);

	/* Abort and close Tx/Rx pipes. */
	urtwn_close_pipes(sc);

	/* Free Tx/Rx buffers. */
	urtwn_free_tx_list(sc);
	urtwn_free_rx_list(sc);
	splx(s);

	return (0);
}

int
urtwn_open_pipes(struct urtwn_softc *sc)
{
	/* Bulk-out endpoints addresses (from highest to lowest prio). */
	uint8_t epaddr[R92C_MAX_EPOUT] = { 0, 0, 0 };
	uint8_t rx_no;
	usb_interface_descriptor_t *id;
	usb_endpoint_descriptor_t *ed;
	int i, error, nrx = 0;

	/* Find all bulk endpoints. */
	id = usbd_get_interface_descriptor(sc->sc_iface);
	for (i = 0; i < id->bNumEndpoints; i++) {
		ed = usbd_interface2endpoint_descriptor(sc->sc_iface, i);
		if (ed == NULL || UE_GET_XFERTYPE(ed->bmAttributes) != UE_BULK)
			continue;

		if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN) {
			rx_no = ed->bEndpointAddress;
			nrx++;
		} else {
			epaddr[sc->ntx] = ed->bEndpointAddress;
			sc->ntx++;
		}
	}
	if (nrx == 0) {
		printf("%s: %d: invalid number of Rx bulk pipes\n",
		    sc->sc_dev.dv_xname, nrx);
		return (EIO);
	}
	DPRINTF(("found %d bulk-out pipes\n", sc->ntx));
	if (sc->ntx == 0 || sc->ntx > R92C_MAX_EPOUT) {
		printf("%s: %d: invalid number of Tx bulk pipes\n",
		    sc->sc_dev.dv_xname, sc->ntx);
		return (EIO);
	}

	/* Open bulk-in pipe. */
	error = usbd_open_pipe(sc->sc_iface, rx_no, 0, &sc->rx_pipe);
	if (error != 0) {
		printf("%s: could not open Rx bulk pipe\n",
		    sc->sc_dev.dv_xname);
		goto fail;
	}

	/* Open bulk-out pipes (up to 3). */
	for (i = 0; i < sc->ntx; i++) {
		error = usbd_open_pipe(sc->sc_iface, epaddr[i], 0,
		    &sc->tx_pipe[i]);
		if (error != 0) {
			printf("%s: could not open Tx bulk pipe 0x%02x\n",
			    sc->sc_dev.dv_xname, epaddr[i]);
			goto fail;
		}
	}

	/* Map 802.11 access categories to USB pipes. */
	sc->ac2idx[EDCA_AC_BK] =
	sc->ac2idx[EDCA_AC_BE] = (sc->ntx == 3) ? 2 : ((sc->ntx == 2) ? 1 : 0);
	sc->ac2idx[EDCA_AC_VI] = (sc->ntx == 3) ? 1 : 0;
	sc->ac2idx[EDCA_AC_VO] = 0;	/* Always use highest prio. */

	if (error != 0)
 fail:		urtwn_close_pipes(sc);
	return (error);
}

void
urtwn_close_pipes(struct urtwn_softc *sc)
{
	int i;

	/* Close Rx pipe. */
	if (sc->rx_pipe != NULL) {
		usbd_abort_pipe(sc->rx_pipe);
		usbd_close_pipe(sc->rx_pipe);
	}
	/* Close Tx pipes. */
	for (i = 0; i < R92C_MAX_EPOUT; i++) {
		if (sc->tx_pipe[i] == NULL)
			continue;
		usbd_abort_pipe(sc->tx_pipe[i]);
		usbd_close_pipe(sc->tx_pipe[i]);
	}
}

int
urtwn_alloc_rx_list(struct urtwn_softc *sc)
{
	struct urtwn_rx_data *data;
	int i, error = 0;

	for (i = 0; i < URTWN_RX_LIST_COUNT; i++) {
		data = &sc->rx_data[i];

		data->sc = sc;	/* Backpointer for callbacks. */

		data->xfer = usbd_alloc_xfer(sc->sc_udev);
		if (data->xfer == NULL) {
			printf("%s: could not allocate xfer\n",
			    sc->sc_dev.dv_xname);
			error = ENOMEM;
			break;
		}
		data->buf = usbd_alloc_buffer(data->xfer, URTWN_RXBUFSZ);
		if (data->buf == NULL) {
			printf("%s: could not allocate xfer buffer\n",
			    sc->sc_dev.dv_xname);
			error = ENOMEM;
			break;
		}
	}
	if (error != 0)
		urtwn_free_rx_list(sc);
	return (error);
}

void
urtwn_free_rx_list(struct urtwn_softc *sc)
{
	int i;

	/* NB: Caller must abort pipe first. */
	for (i = 0; i < URTWN_RX_LIST_COUNT; i++) {
		if (sc->rx_data[i].xfer != NULL)
			usbd_free_xfer(sc->rx_data[i].xfer);
		sc->rx_data[i].xfer = NULL;
	}
}

int
urtwn_alloc_tx_list(struct urtwn_softc *sc)
{
	struct urtwn_tx_data *data;
	int i, error = 0;

	TAILQ_INIT(&sc->tx_free_list);
	for (i = 0; i < URTWN_TX_LIST_COUNT; i++) {
		data = &sc->tx_data[i];

		data->sc = sc;	/* Backpointer for callbacks. */

		data->xfer = usbd_alloc_xfer(sc->sc_udev);
		if (data->xfer == NULL) {
			printf("%s: could not allocate xfer\n",
			    sc->sc_dev.dv_xname);
			error = ENOMEM;
			break;
		}
		data->buf = usbd_alloc_buffer(data->xfer, URTWN_TXBUFSZ);
		if (data->buf == NULL) {
			printf("%s: could not allocate xfer buffer\n",
			    sc->sc_dev.dv_xname);
			error = ENOMEM;
			break;
		}
		/* Append this Tx buffer to our free list. */
		TAILQ_INSERT_TAIL(&sc->tx_free_list, data, next);
	}
	if (error != 0)
		urtwn_free_tx_list(sc);
	return (error);
}

void
urtwn_free_tx_list(struct urtwn_softc *sc)
{
	int i;

	/* NB: Caller must abort pipe first. */
	for (i = 0; i < URTWN_TX_LIST_COUNT; i++) {
		if (sc->tx_data[i].xfer != NULL)
			usbd_free_xfer(sc->tx_data[i].xfer);
		sc->tx_data[i].xfer = NULL;
	}
}

void
urtwn_task(void *arg)
{
	struct urtwn_softc *sc = arg;
	struct urtwn_host_cmd_ring *ring = &sc->cmdq;
	struct urtwn_host_cmd *cmd;
	int s;

	/* Process host commands. */
	s = splusb();
	while (ring->next != ring->cur) {
		cmd = &ring->cmd[ring->next];
		splx(s);
		/* Invoke callback. */
		cmd->cb(sc, cmd->data);
		s = splusb();
		ring->queued--;
		ring->next = (ring->next + 1) % URTWN_HOST_CMD_RING_COUNT;
	}
	splx(s);
}

void
urtwn_do_async(struct urtwn_softc *sc,
    void (*cb)(struct urtwn_softc *, void *), void *arg, int len)
{
	struct urtwn_host_cmd_ring *ring = &sc->cmdq;
	struct urtwn_host_cmd *cmd;
	int s;

	s = splusb();
	cmd = &ring->cmd[ring->cur];
	cmd->cb = cb;
	KASSERT(len <= sizeof(cmd->data));
	memcpy(cmd->data, arg, len);
	ring->cur = (ring->cur + 1) % URTWN_HOST_CMD_RING_COUNT;

	/* If there is no pending command already, schedule a task. */
	if (++ring->queued == 1)
		usb_add_task(sc->sc_udev, &sc->sc_task);
	splx(s);
}

void
urtwn_wait_async(void *cookie)
{
	struct urtwn_softc *sc = cookie;
	int s;

	s = splusb();
	/* Wait for all queued asynchronous commands to complete. */
	usb_wait_task(sc->sc_udev, &sc->sc_task);
	splx(s);
}

int
urtwn_write_region_1(struct urtwn_softc *sc, uint16_t addr, uint8_t *buf,
    int len)
{
	usb_device_request_t req;

	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
	req.bRequest = R92C_REQ_REGS;
	USETW(req.wValue, addr);
	USETW(req.wIndex, 0);
	USETW(req.wLength, len);
	return (usbd_do_request(sc->sc_udev, &req, buf));
}

void
urtwn_write_1(void *cookie, uint16_t addr, uint8_t val)
{
	struct urtwn_softc *sc = cookie;

	urtwn_write_region_1(sc, addr, &val, 1);
}

void
urtwn_write_2(void *cookie, uint16_t addr, uint16_t val)
{
	struct urtwn_softc *sc = cookie;

	val = htole16(val);
	urtwn_write_region_1(sc, addr, (uint8_t *)&val, 2);
}

void
urtwn_write_4(void *cookie, uint16_t addr, uint32_t val)
{
	struct urtwn_softc *sc = cookie;

	val = htole32(val);
	urtwn_write_region_1(sc, addr, (uint8_t *)&val, 4);
}

int
urtwn_read_region_1(struct urtwn_softc *sc, uint16_t addr, uint8_t *buf,
    int len)
{
	usb_device_request_t req;

	req.bmRequestType = UT_READ_VENDOR_DEVICE;
	req.bRequest = R92C_REQ_REGS;
	USETW(req.wValue, addr);
	USETW(req.wIndex, 0);
	USETW(req.wLength, len);
	return (usbd_do_request(sc->sc_udev, &req, buf));
}

uint8_t
urtwn_read_1(void *cookie, uint16_t addr)
{
	struct urtwn_softc *sc = cookie;
	uint8_t val;

	if (urtwn_read_region_1(sc, addr, &val, 1) != 0)
		return (0xff);
	return (val);
}

uint16_t
urtwn_read_2(void *cookie, uint16_t addr)
{
	struct urtwn_softc *sc = cookie;
	uint16_t val;

	if (urtwn_read_region_1(sc, addr, (uint8_t *)&val, 2) != 0)
		return (0xffff);
	return (letoh16(val));
}

uint32_t
urtwn_read_4(void *cookie, uint16_t addr)
{
	struct urtwn_softc *sc = cookie;
	uint32_t val;

	if (urtwn_read_region_1(sc, addr, (uint8_t *)&val, 4) != 0)
		return (0xffffffff);
	return (letoh32(val));
}

int
urtwn_llt_write(struct urtwn_softc *sc, uint32_t addr, uint32_t data)
{
	int ntries;

	urtwn_write_4(sc, R92C_LLT_INIT,
	    SM(R92C_LLT_INIT_OP, R92C_LLT_INIT_OP_WRITE) |
	    SM(R92C_LLT_INIT_ADDR, addr) |
	    SM(R92C_LLT_INIT_DATA, data));
	/* Wait for write operation to complete. */
	for (ntries = 0; ntries < 20; ntries++) {
		if (MS(urtwn_read_4(sc, R92C_LLT_INIT), R92C_LLT_INIT_OP) ==
		    R92C_LLT_INIT_OP_NO_ACTIVE)
			return (0);
		DELAY(5);
	}
	return (ETIMEDOUT);
}

void
urtwn_calib_to(void *arg)
{
	struct urtwn_softc *sc = arg;

	if (usbd_is_dying(sc->sc_udev))
		return;

	usbd_ref_incr(sc->sc_udev);

	/* Do it in a process context. */
	urtwn_do_async(sc, urtwn_calib_cb, NULL, 0);

	usbd_ref_decr(sc->sc_udev);
}

/* ARGSUSED */
void
urtwn_calib_cb(struct urtwn_softc *sc, void *arg)
{
	struct ieee80211com *ic = &sc->sc_sc.sc_ic;
	int s;

	s = splnet();
	if (ic->ic_opmode == IEEE80211_M_STA) {
		ieee80211_amrr_choose(&sc->amrr, ic->ic_bss, &sc->amn);
	}
	splx(s);

	rtwn_calib(&sc->sc_sc);
}

void
urtwn_next_calib(void *cookie)
{
	struct urtwn_softc *sc = cookie;

	if (!usbd_is_dying(sc->sc_udev))
		timeout_add_sec(&sc->calib_to, 2);
}

void
urtwn_cancel_calib(void *cookie)
{
	struct urtwn_softc *sc = cookie;

	if (timeout_initialized(&sc->calib_to))
		timeout_del(&sc->calib_to);
}

void
urtwn_scan_to(void *arg)
{
	struct urtwn_softc *sc = arg;

	if (usbd_is_dying(sc->sc_udev))
		return;

	usbd_ref_incr(sc->sc_udev);
	rtwn_next_scan(&sc->sc_sc);
	usbd_ref_decr(sc->sc_udev);
}

void
urtwn_next_scan(void *arg)
{
	struct urtwn_softc *sc = arg;

	if (!usbd_is_dying(sc->sc_udev))
		timeout_add_msec(&sc->scan_to, 200);
}

void
urtwn_cancel_scan(void *cookie)
{
	struct urtwn_softc *sc = cookie;

	if (timeout_initialized(&sc->scan_to))
		timeout_del(&sc->scan_to);
}

int
urtwn_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
{
	struct rtwn_softc *sc_sc = ic->ic_softc;
	struct device *self = sc_sc->sc_pdev;
	struct urtwn_softc *sc = (struct urtwn_softc *)self;
	struct urtwn_cmd_newstate cmd;

	/* Do it in a process context. */
	cmd.state = nstate;
	cmd.arg = arg;
	urtwn_do_async(sc, urtwn_newstate_cb, &cmd, sizeof(cmd));
	return (0);
}

void
urtwn_newstate_cb(struct urtwn_softc *sc, void *arg)
{
	struct urtwn_cmd_newstate *cmd = arg;
	struct ieee80211com *ic = &sc->sc_sc.sc_ic;

	rtwn_newstate(ic, cmd->state, cmd->arg);
}

void
urtwn_updateslot(struct ieee80211com *ic)
{
	struct rtwn_softc *sc_sc = ic->ic_softc;
	struct device *self = sc_sc->sc_pdev;
	struct urtwn_softc *sc = (struct urtwn_softc *)self;

	/* Do it in a process context. */
	urtwn_do_async(sc, urtwn_updateslot_cb, NULL, 0);
}

/* ARGSUSED */
void
urtwn_updateslot_cb(struct urtwn_softc *sc, void *arg)
{
	struct ieee80211com *ic = &sc->sc_sc.sc_ic;

	rtwn_updateslot(ic);
}

void
urtwn_updateedca(struct ieee80211com *ic)
{
	struct rtwn_softc *sc_sc = ic->ic_softc;
	struct device *self = sc_sc->sc_pdev;
	struct urtwn_softc *sc = (struct urtwn_softc *)self;

	/* Do it in a process context. */
	urtwn_do_async(sc, urtwn_updateedca_cb, NULL, 0);
}

/* ARGSUSED */
void
urtwn_updateedca_cb(struct urtwn_softc *sc, void *arg)
{
	struct ieee80211com *ic = &sc->sc_sc.sc_ic;

	rtwn_updateedca(ic);
}

int
urtwn_set_key(struct ieee80211com *ic, struct ieee80211_node *ni,
    struct ieee80211_key *k)
{
	struct rtwn_softc *sc_sc = ic->ic_softc;
	struct device *self = sc_sc->sc_pdev;
	struct urtwn_softc *sc = (struct urtwn_softc *)self;
	struct urtwn_cmd_key cmd;

	/* Defer setting of WEP keys until interface is brought up. */
	if ((ic->ic_if.if_flags & (IFF_UP | IFF_RUNNING)) !=
	    (IFF_UP | IFF_RUNNING))
		return (0);

	/* Do it in a process context. */
	cmd.key = *k;
	cmd.ni = ni;
	urtwn_do_async(sc, urtwn_set_key_cb, &cmd, sizeof(cmd));
	return (0);
}

void
urtwn_set_key_cb(struct urtwn_softc *sc, void *arg)
{
	struct ieee80211com *ic = &sc->sc_sc.sc_ic;
	struct urtwn_cmd_key *cmd = arg;

	rtwn_set_key(ic, cmd->ni, &cmd->key);
}

void
urtwn_delete_key(struct ieee80211com *ic, struct ieee80211_node *ni,
    struct ieee80211_key *k)
{
	struct rtwn_softc *sc_sc = ic->ic_softc;
	struct device *self = sc_sc->sc_pdev;
	struct urtwn_softc *sc = (struct urtwn_softc *)self;
	struct urtwn_cmd_key cmd;

	if (!(ic->ic_if.if_flags & IFF_RUNNING) ||
	    ic->ic_state != IEEE80211_S_RUN)
		return;	/* Nothing to do. */

	/* Do it in a process context. */
	cmd.key = *k;
	cmd.ni = ni;
	urtwn_do_async(sc, urtwn_delete_key_cb, &cmd, sizeof(cmd));
}

void
urtwn_delete_key_cb(struct urtwn_softc *sc, void *arg)
{
	struct ieee80211com *ic = &sc->sc_sc.sc_ic;
	struct urtwn_cmd_key *cmd = arg;

	rtwn_delete_key(ic, cmd->ni, &cmd->key);
}

void
urtwn_rx_frame(struct urtwn_softc *sc, uint8_t *buf, int pktlen)
{
	struct ieee80211com *ic = &sc->sc_sc.sc_ic;
	struct ifnet *ifp = &ic->ic_if;
	struct ieee80211_rxinfo rxi;
	struct ieee80211_frame *wh;
	struct ieee80211_node *ni;
	struct r92c_rx_desc_usb *rxd;
	uint32_t rxdw0, rxdw3;
	struct mbuf *m;
	uint8_t rate;
	int8_t rssi = 0;
	int s, infosz;

	rxd = (struct r92c_rx_desc_usb *)buf;
	rxdw0 = letoh32(rxd->rxdw0);
	rxdw3 = letoh32(rxd->rxdw3);

	if (__predict_false(rxdw0 & (R92C_RXDW0_CRCERR | R92C_RXDW0_ICVERR))) {
		/*
		 * This should not happen since we setup our Rx filter
		 * to not receive these frames.
		 */
		ifp->if_ierrors++;
		return;
	}
	if (__predict_false(pktlen < sizeof(*wh) || pktlen > MCLBYTES)) {
		ifp->if_ierrors++;
		return;
	}

	rate = MS(rxdw3, R92C_RXDW3_RATE);
	infosz = MS(rxdw0, R92C_RXDW0_INFOSZ) * 8;

	/* Get RSSI from PHY status descriptor if present. */
	if (infosz != 0 && (rxdw0 & R92C_RXDW0_PHYST)) {
		rssi = rtwn_get_rssi(&sc->sc_sc, rate, &rxd[1]);
		/* Update our average RSSI. */
		rtwn_update_avgrssi(&sc->sc_sc, rate, rssi);
	}

	DPRINTFN(5, ("Rx frame len=%d rate=%d infosz=%d rssi=%d\n",
	    pktlen, rate, infosz, rssi));

	MGETHDR(m, M_DONTWAIT, MT_DATA);
	if (__predict_false(m == NULL)) {
		ifp->if_ierrors++;
		return;
	}
	if (pktlen > MHLEN) {
		MCLGET(m, M_DONTWAIT);
		if (__predict_false(!(m->m_flags & M_EXT))) {
			ifp->if_ierrors++;
			m_freem(m);
			return;
		}
	}
	/* Finalize mbuf. */
	wh = (struct ieee80211_frame *)((uint8_t *)&rxd[1] + infosz);
	memcpy(mtod(m, uint8_t *), wh, pktlen);
	m->m_pkthdr.len = m->m_len = pktlen;

	s = splnet();
#if NBPFILTER > 0
	if (__predict_false(sc->sc_drvbpf != NULL)) {
		struct urtwn_rx_radiotap_header *tap = &sc->sc_rxtap;
		struct mbuf mb;

		tap->wr_flags = 0;
		/* Map HW rate index to 802.11 rate. */
		tap->wr_flags = 2;
		if (!(rxdw3 & R92C_RXDW3_HT)) {
			switch (rate) {
			/* CCK. */
			case  0: tap->wr_rate =   2; break;
			case  1: tap->wr_rate =   4; break;
			case  2: tap->wr_rate =  11; break;
			case  3: tap->wr_rate =  22; break;
			/* OFDM. */
			case  4: tap->wr_rate =  12; break;
			case  5: tap->wr_rate =  18; break;
			case  6: tap->wr_rate =  24; break;
			case  7: tap->wr_rate =  36; break;
			case  8: tap->wr_rate =  48; break;
			case  9: tap->wr_rate =  72; break;
			case 10: tap->wr_rate =  96; break;
			case 11: tap->wr_rate = 108; break;
			}
		} else if (rate >= 12) {	/* MCS0~15. */
			/* Bit 7 set means HT MCS instead of rate. */
			tap->wr_rate = 0x80 | (rate - 12);
		}
		tap->wr_dbm_antsignal = rssi;
		tap->wr_chan_freq = htole16(ic->ic_ibss_chan->ic_freq);
		tap->wr_chan_flags = htole16(ic->ic_ibss_chan->ic_flags);

		mb.m_data = (caddr_t)tap;
		mb.m_len = sc->sc_rxtap_len;
		mb.m_next = m;
		mb.m_nextpkt = NULL;
		mb.m_type = 0;
		mb.m_flags = 0;
		bpf_mtap(sc->sc_drvbpf, &mb, BPF_DIRECTION_IN);
	}
#endif

	ni = ieee80211_find_rxnode(ic, wh);
	rxi.rxi_flags = 0;
	rxi.rxi_rssi = rssi;
	rxi.rxi_tstamp = 0;	/* Unused. */
	ieee80211_input(ifp, m, ni, &rxi);
	/* Node is no longer needed. */
	ieee80211_release_node(ic, ni);
	splx(s);
}

void
urtwn_rxeof(struct usbd_xfer *xfer, void *priv,
    usbd_status status)
{
	struct urtwn_rx_data *data = priv;
	struct urtwn_softc *sc = data->sc;
	struct r92c_rx_desc_usb *rxd;
	uint32_t rxdw0;
	uint8_t *buf;
	int len, totlen, pktlen, infosz, npkts, error;

	if (__predict_false(status != USBD_NORMAL_COMPLETION)) {
		DPRINTF(("RX status=%d\n", status));
		if (status == USBD_STALLED)
			usbd_clear_endpoint_stall_async(sc->rx_pipe);
		if (status != USBD_CANCELLED)
			goto resubmit;
		return;
	}
	usbd_get_xfer_status(xfer, NULL, NULL, &len, NULL);

	if (__predict_false(len < sizeof(*rxd))) {
		DPRINTF(("xfer too short %d\n", len));
		goto resubmit;
	}
	buf = data->buf;

	/* Get the number of encapsulated frames. */
	rxd = (struct r92c_rx_desc_usb *)buf;
	npkts = MS(letoh32(rxd->rxdw2), R92C_RXDW2_PKTCNT);
	DPRINTFN(4, ("Rx %d frames in one chunk\n", npkts));

	if (sc->sc_sc.chip & RTWN_CHIP_88E) {
		int ntries, type;
		struct r88e_tx_rpt_ccx *rxstat;

		type = MS(letoh32(rxd->rxdw3), R88E_RXDW3_RPT);

		if (type == R88E_RXDW3_RPT_TX1) {
			buf += sizeof(struct r92c_rx_desc_usb);
			rxstat = (struct r88e_tx_rpt_ccx *)buf;
			ntries = MS(letoh32(rxstat->rptb2),
			    R88E_RPTB2_RETRY_CNT);

			if (rxstat->rptb1 & R88E_RPTB1_PKT_OK)
				sc->amn.amn_txcnt++;
			if (ntries > 0)
				sc->amn.amn_retrycnt++;

			goto resubmit;
		}
	}

	/* Process all of them. */
	while (npkts-- > 0) {
		if (__predict_false(len < sizeof(*rxd)))
			break;
		rxd = (struct r92c_rx_desc_usb *)buf;
		rxdw0 = letoh32(rxd->rxdw0);

		pktlen = MS(rxdw0, R92C_RXDW0_PKTLEN);
		if (__predict_false(pktlen == 0))
			break;

		infosz = MS(rxdw0, R92C_RXDW0_INFOSZ) * 8;

		/* Make sure everything fits in xfer. */
		totlen = sizeof(*rxd) + infosz + pktlen;
		if (__predict_false(totlen > len))
			break;

		/* Process 802.11 frame. */
		urtwn_rx_frame(sc, buf, pktlen);

		/* Next chunk is 128-byte aligned. */
		totlen = (totlen + 127) & ~127;
		buf += totlen;
		len -= totlen;
	}

 resubmit:
	/* Setup a new transfer. */
	usbd_setup_xfer(xfer, sc->rx_pipe, data, data->buf, URTWN_RXBUFSZ,
	    USBD_SHORT_XFER_OK | USBD_NO_COPY, USBD_NO_TIMEOUT, urtwn_rxeof);
	error = usbd_transfer(data->xfer);
	if (error != 0 && error != USBD_IN_PROGRESS)
		DPRINTF(("could not set up new transfer: %d\n", error));
}

void
urtwn_txeof(struct usbd_xfer *xfer, void *priv,
    usbd_status status)
{
	struct urtwn_tx_data *data = priv;
	struct urtwn_softc *sc = data->sc;
	struct ifnet *ifp = &sc->sc_sc.sc_ic.ic_if;
	int s;

	s = splnet();
	/* Put this Tx buffer back to our free list. */
	TAILQ_INSERT_TAIL(&sc->tx_free_list, data, next);

	if (__predict_false(status != USBD_NORMAL_COMPLETION)) {
		DPRINTF(("TX status=%d\n", status));
		if (status == USBD_STALLED)
			usbd_clear_endpoint_stall_async(data->pipe);
		ifp->if_oerrors++;
		splx(s);
		return;
	}
	sc->sc_sc.sc_tx_timer = 0;

	/* We just released a Tx buffer, notify Tx. */
	if (ifq_is_oactive(&ifp->if_snd)) {
		ifq_clr_oactive(&ifp->if_snd);
		rtwn_start(ifp);
	}
	splx(s);
}

int
urtwn_tx(void *cookie, struct mbuf *m, struct ieee80211_node *ni)
{
	struct urtwn_softc *sc = cookie;
	struct ieee80211com *ic = &sc->sc_sc.sc_ic;
	struct ieee80211_frame *wh;
	struct ieee80211_key *k = NULL;
	struct urtwn_tx_data *data;
	struct r92c_tx_desc_usb *txd;
	struct usbd_pipe *pipe;
	uint16_t qos, sum;
	uint8_t raid, type, tid, qid;
	int i, hasqos, xferlen, error;

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

	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
		k = ieee80211_get_txkey(ic, wh, ni);
		if ((m = ieee80211_encrypt(ic, m, k)) == NULL)
			return (ENOBUFS);
		wh = mtod(m, struct ieee80211_frame *);
	}

	if ((hasqos = ieee80211_has_qos(wh))) {
		qos = ieee80211_get_qos(wh);
		tid = qos & IEEE80211_QOS_TID;
		qid = ieee80211_up_to_ac(ic, tid);
	} else if (type != IEEE80211_FC0_TYPE_DATA) {
		/* Use AC VO for management frames. */
		qid = EDCA_AC_VO;
	} else
		qid = EDCA_AC_BE;

	/* Get the USB pipe to use for this AC. */
	pipe = sc->tx_pipe[sc->ac2idx[qid]];

	/* Grab a Tx buffer from our free list. */
	data = TAILQ_FIRST(&sc->tx_free_list);
	TAILQ_REMOVE(&sc->tx_free_list, data, next);

	/* Fill Tx descriptor. */
	txd = (struct r92c_tx_desc_usb *)data->buf;
	memset(txd, 0, sizeof(*txd));

	txd->txdw0 |= htole32(
	    SM(R92C_TXDW0_PKTLEN, m->m_pkthdr.len) |
	    SM(R92C_TXDW0_OFFSET, sizeof(*txd)) |
	    R92C_TXDW0_OWN | R92C_TXDW0_FSG | R92C_TXDW0_LSG);
	if (IEEE80211_IS_MULTICAST(wh->i_addr1))
		txd->txdw0 |= htole32(R92C_TXDW0_BMCAST);

#ifdef notyet
	if (k != NULL) {
		switch (k->k_cipher) {
		case IEEE80211_CIPHER_WEP40:
		case IEEE80211_CIPHER_WEP104:
		case IEEE80211_CIPHER_TKIP:
			cipher = R92C_TXDW1_CIPHER_RC4;
			break;
		case IEEE80211_CIPHER_CCMP:
			cipher = R92C_TXDW1_CIPHER_AES;
			break;
		default:
			cipher = R92C_TXDW1_CIPHER_NONE;
		}
		txd->txdw1 |= htole32(SM(R92C_TXDW1_CIPHER, cipher));
	}
#endif
	if (!IEEE80211_IS_MULTICAST(wh->i_addr1) &&
	    type == IEEE80211_FC0_TYPE_DATA) {
		if (ic->ic_curmode == IEEE80211_MODE_11B ||
		    (sc->sc_sc.sc_flags & RTWN_FLAG_FORCE_RAID_11B))
			raid = R92C_RAID_11B;
		else
			raid = R92C_RAID_11BG;
		if (sc->sc_sc.chip & RTWN_CHIP_88E) {
			txd->txdw1 |= htole32(
			    SM(R88E_TXDW1_MACID, R92C_MACID_BSS) |
			    SM(R92C_TXDW1_QSEL, R92C_TXDW1_QSEL_BE) |
			    SM(R92C_TXDW1_RAID, raid));
			txd->txdw2 |= htole32(R88E_TXDW2_AGGBK);
			/* Request TX status report for AMRR */
			txd->txdw2 |= htole32(R92C_TXDW2_CCX_RPT);
		} else {
			txd->txdw1 |= htole32(
			    SM(R92C_TXDW1_MACID, R92C_MACID_BSS) |
			    SM(R92C_TXDW1_QSEL, R92C_TXDW1_QSEL_BE) |
			    SM(R92C_TXDW1_RAID, raid) | R92C_TXDW1_AGGBK);
		}

		if (m->m_pkthdr.len + IEEE80211_CRC_LEN > ic->ic_rtsthreshold) {
			txd->txdw4 |= htole32(R92C_TXDW4_RTSEN |
			    R92C_TXDW4_HWRTSEN);
		} else if (ic->ic_flags & IEEE80211_F_USEPROT) {
			if (ic->ic_protmode == IEEE80211_PROT_CTSONLY) {
				txd->txdw4 |= htole32(R92C_TXDW4_CTS2SELF |
				    R92C_TXDW4_HWRTSEN);
			} else if (ic->ic_protmode == IEEE80211_PROT_RTSCTS) {
				txd->txdw4 |= htole32(R92C_TXDW4_RTSEN |
				    R92C_TXDW4_HWRTSEN);
			}
		}
		txd->txdw5 |= htole32(0x0001ff00);

		if (sc->sc_sc.chip & RTWN_CHIP_88E) {
			/* Use AMRR */
			txd->txdw4 |= htole32(R92C_TXDW4_DRVRATE);
			txd->txdw4 |= htole32(SM(R92C_TXDW4_RTSRATE,
			    ni->ni_txrate));
			txd->txdw5 |= htole32(SM(R92C_TXDW5_DATARATE,
			    ni->ni_txrate));
		} else {
			/* Send RTS at OFDM24 and data at OFDM54. */
			txd->txdw4 |= htole32(SM(R92C_TXDW4_RTSRATE, 8));
			txd->txdw5 |= htole32(SM(R92C_TXDW5_DATARATE, 11));
		}
	} else {
		txd->txdw1 |= htole32(
		    SM(R92C_TXDW1_MACID, 0) |
		    SM(R92C_TXDW1_QSEL, R92C_TXDW1_QSEL_MGNT) |
		    SM(R92C_TXDW1_RAID, R92C_RAID_11B));

		/* Force CCK1. */
		txd->txdw4 |= htole32(R92C_TXDW4_DRVRATE);
		txd->txdw5 |= htole32(SM(R92C_TXDW5_DATARATE, 0));
	}
	/* Set sequence number (already little endian). */
	txd->txdseq |= *(uint16_t *)wh->i_seq;

	if (!hasqos) {
		/* Use HW sequence numbering for non-QoS frames. */
		txd->txdw4  |= htole32(R92C_TXDW4_HWSEQ);
		txd->txdseq |= htole16(0x8000);		/* WTF? */
	} else
		txd->txdw4 |= htole32(R92C_TXDW4_QOS);

	/* Compute Tx descriptor checksum. */
	sum = 0;
	for (i = 0; i < sizeof(*txd) / 2; i++)
		sum ^= ((uint16_t *)txd)[i];
	txd->txdsum = sum;	/* NB: already little endian. */

#if NBPFILTER > 0
	if (__predict_false(sc->sc_drvbpf != NULL)) {
		struct urtwn_tx_radiotap_header *tap = &sc->sc_txtap;
		struct mbuf mb;

		tap->wt_flags = 0;
		tap->wt_chan_freq = htole16(ic->ic_bss->ni_chan->ic_freq);
		tap->wt_chan_flags = htole16(ic->ic_bss->ni_chan->ic_flags);

		mb.m_data = (caddr_t)tap;
		mb.m_len = sc->sc_txtap_len;
		mb.m_next = m;
		mb.m_nextpkt = NULL;
		mb.m_type = 0;
		mb.m_flags = 0;
		bpf_mtap(sc->sc_drvbpf, &mb, BPF_DIRECTION_OUT);
	}
#endif

	xferlen = sizeof(*txd) + m->m_pkthdr.len;
	m_copydata(m, 0, m->m_pkthdr.len, (caddr_t)&txd[1]);
	m_freem(m);

	data->pipe = pipe;
	usbd_setup_xfer(data->xfer, pipe, data, data->buf, xferlen,
	    USBD_FORCE_SHORT_XFER | USBD_NO_COPY, URTWN_TX_TIMEOUT,
	    urtwn_txeof);
	error = usbd_transfer(data->xfer);
	if (__predict_false(error != USBD_IN_PROGRESS && error != 0)) {
		/* Put this Tx buffer back to our free list. */
		TAILQ_INSERT_TAIL(&sc->tx_free_list, data, next);
		return (error);
	}
	ieee80211_release_node(ic, ni);
	return (0);
}

int
urtwn_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
{
	struct rtwn_softc *sc_sc = ifp->if_softc;
	struct device *self = sc_sc->sc_pdev;
	struct urtwn_softc *sc = (struct urtwn_softc *)self;
	int error;

	if (usbd_is_dying(sc->sc_udev))
		return ENXIO;

	usbd_ref_incr(sc->sc_udev);
	error = rtwn_ioctl(ifp, cmd, data);
	usbd_ref_decr(sc->sc_udev);

	return (error);
}

int
urtwn_r92c_power_on(struct urtwn_softc *sc)
{
	uint32_t reg;
	int ntries;

	/* Wait for autoload done bit. */
	for (ntries = 0; ntries < 1000; ntries++) {
		if (urtwn_read_1(sc, R92C_APS_FSMCO) & R92C_APS_FSMCO_PFM_ALDN)
			break;
		DELAY(5);
	}
	if (ntries == 1000) {
		printf("%s: timeout waiting for chip autoload\n",
		    sc->sc_dev.dv_xname);
		return (ETIMEDOUT);
	}

	/* Unlock ISO/CLK/Power control register. */
	urtwn_write_1(sc, R92C_RSV_CTRL, 0);
	/* Move SPS into PWM mode. */
	urtwn_write_1(sc, R92C_SPS0_CTRL, 0x2b);
	DELAY(100);

	reg = urtwn_read_1(sc, R92C_LDOV12D_CTRL);
	if (!(reg & R92C_LDOV12D_CTRL_LDV12_EN)) {
		urtwn_write_1(sc, R92C_LDOV12D_CTRL,
		    reg | R92C_LDOV12D_CTRL_LDV12_EN);
		DELAY(100);
		urtwn_write_1(sc, R92C_SYS_ISO_CTRL,
		    urtwn_read_1(sc, R92C_SYS_ISO_CTRL) &
		    ~R92C_SYS_ISO_CTRL_MD2PP);
	}

	/* Auto enable WLAN. */
	urtwn_write_2(sc, R92C_APS_FSMCO,
	    urtwn_read_2(sc, R92C_APS_FSMCO) | R92C_APS_FSMCO_APFM_ONMAC);
	for (ntries = 0; ntries < 1000; ntries++) {
		if (!(urtwn_read_2(sc, R92C_APS_FSMCO) &
		    R92C_APS_FSMCO_APFM_ONMAC))
			break;
		DELAY(5);
	}
	if (ntries == 1000) {
		printf("%s: timeout waiting for MAC auto ON\n",
		    sc->sc_dev.dv_xname);
		return (ETIMEDOUT);
	}

	/* Enable radio, GPIO and LED functions. */
	urtwn_write_2(sc, R92C_APS_FSMCO,
	    R92C_APS_FSMCO_AFSM_HSUS |
	    R92C_APS_FSMCO_PDN_EN |
	    R92C_APS_FSMCO_PFM_ALDN);
	/* Release RF digital isolation. */
	urtwn_write_2(sc, R92C_SYS_ISO_CTRL,
	    urtwn_read_2(sc, R92C_SYS_ISO_CTRL) & ~R92C_SYS_ISO_CTRL_DIOR);

	/* Initialize MAC. */
	urtwn_write_1(sc, R92C_APSD_CTRL,
	    urtwn_read_1(sc, R92C_APSD_CTRL) & ~R92C_APSD_CTRL_OFF);
	for (ntries = 0; ntries < 200; ntries++) {
		if (!(urtwn_read_1(sc, R92C_APSD_CTRL) &
		    R92C_APSD_CTRL_OFF_STATUS))
			break;
		DELAY(5);
	}
	if (ntries == 200) {
		printf("%s: timeout waiting for MAC initialization\n",
		    sc->sc_dev.dv_xname);
		return (ETIMEDOUT);
	}

	/* Enable MAC DMA/WMAC/SCHEDULE/SEC blocks. */
	reg = urtwn_read_2(sc, R92C_CR);
	reg |= R92C_CR_HCI_TXDMA_EN | R92C_CR_HCI_RXDMA_EN |
	    R92C_CR_TXDMA_EN | R92C_CR_RXDMA_EN | R92C_CR_PROTOCOL_EN |
	    R92C_CR_SCHEDULE_EN | R92C_CR_MACTXEN | R92C_CR_MACRXEN |
	    R92C_CR_ENSEC;
	urtwn_write_2(sc, R92C_CR, reg);

	urtwn_write_1(sc, 0xfe10, 0x19);
	return (0);
}

int
urtwn_r88e_power_on(struct urtwn_softc *sc)
{
	uint32_t reg;
	int ntries;

	/* Wait for power ready bit. */
	for (ntries = 0; ntries < 5000; ntries++) {
		if (urtwn_read_4(sc, R92C_APS_FSMCO) & R92C_APS_FSMCO_SUS_HOST)
			break;
		DELAY(10);
	}
	if (ntries == 5000) {
		printf("%s: timeout waiting for chip power up\n",
		    sc->sc_dev.dv_xname);
		return (ETIMEDOUT);
	}

	/* Reset BB. */
	urtwn_write_1(sc, R92C_SYS_FUNC_EN,
	    urtwn_read_1(sc, R92C_SYS_FUNC_EN) & ~(R92C_SYS_FUNC_EN_BBRSTB |
	    R92C_SYS_FUNC_EN_BB_GLB_RST));

	urtwn_write_1(sc, R92C_AFE_XTAL_CTRL + 2,
	    urtwn_read_1(sc, R92C_AFE_XTAL_CTRL + 2) | 0x80);

	/* Disable HWPDN. */
	urtwn_write_2(sc, R92C_APS_FSMCO,
	    urtwn_read_2(sc, R92C_APS_FSMCO) & ~R92C_APS_FSMCO_APDM_HPDN);
	/* Disable WL suspend. */
	urtwn_write_2(sc, R92C_APS_FSMCO,
	    urtwn_read_2(sc, R92C_APS_FSMCO) &
	    ~(R92C_APS_FSMCO_AFSM_HSUS | R92C_APS_FSMCO_AFSM_PCIE));

	/* Auto enable WLAN. */
	urtwn_write_2(sc, R92C_APS_FSMCO,
	    urtwn_read_2(sc, R92C_APS_FSMCO) | R92C_APS_FSMCO_APFM_ONMAC);
	for (ntries = 0; ntries < 5000; ntries++) {
		if (!(urtwn_read_2(sc, R92C_APS_FSMCO) &
		    R92C_APS_FSMCO_APFM_ONMAC))
			break;
		DELAY(10);
	}
	if (ntries == 5000) {
		printf("%s: timeout waiting for MAC auto ON\n",
		    sc->sc_dev.dv_xname);
		return (ETIMEDOUT);
	}

	/* Enable LDO normal mode. */
	urtwn_write_1(sc, R92C_LPLDO_CTRL,
	    urtwn_read_1(sc, R92C_LPLDO_CTRL) & ~0x10);

	/* Enable MAC DMA/WMAC/SCHEDULE/SEC blocks. */
	urtwn_write_2(sc, R92C_CR, 0);
	reg = urtwn_read_2(sc, R92C_CR);
	reg |= R92C_CR_HCI_TXDMA_EN | R92C_CR_HCI_RXDMA_EN |
	    R92C_CR_TXDMA_EN | R92C_CR_RXDMA_EN | R92C_CR_PROTOCOL_EN |
	    R92C_CR_SCHEDULE_EN | R92C_CR_ENSEC | R92C_CR_CALTMR_EN;
	urtwn_write_2(sc, R92C_CR, reg);
	return (0);
}

int
urtwn_llt_init(struct urtwn_softc *sc, int page_count)
{
	int i, error, pktbuf_count;

	pktbuf_count = (sc->sc_sc.chip & RTWN_CHIP_88E) ?
	    R88E_TXPKTBUF_COUNT : R92C_TXPKTBUF_COUNT;

	/* Reserve pages [0; page_count]. */
	for (i = 0; i < page_count; i++) {
		if ((error = urtwn_llt_write(sc, i, i + 1)) != 0)
			return (error);
	}
	/* NB: 0xff indicates end-of-list. */
	if ((error = urtwn_llt_write(sc, i, 0xff)) != 0)
		return (error);
	/*
	 * Use pages [page_count + 1; pktbuf_count - 1]
	 * as ring buffer.
	 */
	for (++i; i < pktbuf_count - 1; i++) {
		if ((error = urtwn_llt_write(sc, i, i + 1)) != 0)
			return (error);
	}
	/* Make the last page point to the beginning of the ring buffer. */
	error = urtwn_llt_write(sc, i, page_count + 1);
	return (error);
}

int
urtwn_fw_loadpage(void *cookie, int page, uint8_t *buf, int len)
{
	struct urtwn_softc *sc = cookie;
	uint32_t reg;
	int off, mlen, error = 0;

	reg = urtwn_read_4(sc, R92C_MCUFWDL);
	reg = RW(reg, R92C_MCUFWDL_PAGE, page);
	urtwn_write_4(sc, R92C_MCUFWDL, reg);

	off = R92C_FW_START_ADDR;
	while (len > 0) {
		if (len > 196)
			mlen = 196;
		else if (len > 4)
			mlen = 4;
		else
			mlen = 1;
		error = urtwn_write_region_1(sc, off, buf, mlen);
		if (error != 0)
			break;
		off += mlen;
		buf += mlen;
		len -= mlen;
	}
	return (error);
}

int
urtwn_load_firmware(void *cookie, u_char **fw, size_t *len)
{
	struct urtwn_softc *sc = cookie;
	const char *name;
	int error;

	if (sc->sc_sc.chip & RTWN_CHIP_88E)
		name = "urtwn-rtl8188eufw";
	else if ((sc->sc_sc.chip & (RTWN_CHIP_UMC_A_CUT | RTWN_CHIP_92C)) ==
		    RTWN_CHIP_UMC_A_CUT)
		name = "urtwn-rtl8192cfwU";
	else
		name = "urtwn-rtl8192cfwT";

	error = loadfirmware(name, fw, len);
	if (error)
		printf("%s: could not read firmware %s (error %d)\n",
		    sc->sc_dev.dv_xname, name, error);
	return (error);
}

int
urtwn_dma_init(void *cookie)
{
	struct urtwn_softc *sc = cookie;
	uint32_t reg;
	uint16_t dmasize;
	int hqpages, lqpages, nqpages, pagecnt, boundary;
	int error, hashq, haslq, hasnq;

	/* Default initialization of chipset values. */
	if (sc->sc_sc.chip & RTWN_CHIP_88E) {
		hqpages = R88E_HQ_NPAGES;
		lqpages = R88E_LQ_NPAGES;
		nqpages = R88E_NQ_NPAGES;
		pagecnt = R88E_TX_PAGE_COUNT;
		boundary = R88E_TX_PAGE_BOUNDARY;
		dmasize = R88E_MAX_RX_DMA_SIZE;
	} else {
		hqpages = R92C_HQ_NPAGES;
		lqpages = R92C_LQ_NPAGES;
		nqpages = R92C_NQ_NPAGES;
		pagecnt = R92C_TX_PAGE_COUNT;
		boundary = R92C_TX_PAGE_BOUNDARY;
		dmasize = R92C_MAX_RX_DMA_SIZE;
	}

	/* Initialize LLT table. */
	error = urtwn_llt_init(sc, pagecnt);
	if (error != 0)
		return (error);

	/* Get Tx queues to USB endpoints mapping. */
	hashq = hasnq = haslq = 0;
	switch (sc->ntx) {
	case 3:
		haslq = 1;
		pagecnt -= lqpages;
		/* FALLTHROUGH */
	case 2:
		hasnq = 1;
		pagecnt -= nqpages;
		/* FALLTHROUGH */
	case 1:
		hashq = 1;
		pagecnt -= hqpages;
		break;
	}

	/* Set number of pages for normal priority queue. */
	urtwn_write_1(sc, R92C_RQPN_NPQ, hasnq ? nqpages : 0);
	urtwn_write_4(sc, R92C_RQPN,
	    /* Set number of pages for public queue. */
	    SM(R92C_RQPN_PUBQ, pagecnt) |
	    /* Set number of pages for high priority queue. */
	    SM(R92C_RQPN_HPQ, hashq ? hqpages : 0) |
	    /* Set number of pages for low priority queue. */
	    SM(R92C_RQPN_LPQ, haslq ? lqpages : 0) |
	    /* Load values. */
	    R92C_RQPN_LD);

	urtwn_write_1(sc, R92C_TXPKTBUF_BCNQ_BDNY, boundary);
	urtwn_write_1(sc, R92C_TXPKTBUF_MGQ_BDNY, boundary);
	urtwn_write_1(sc, R92C_TXPKTBUF_WMAC_LBK_BF_HD, boundary);
	urtwn_write_1(sc, R92C_TRXFF_BNDY, boundary);
	urtwn_write_1(sc, R92C_TDECTRL + 1, boundary);

	/* Set queue to USB pipe mapping. */
	reg = urtwn_read_2(sc, R92C_TRXDMA_CTRL);
	reg &= ~R92C_TRXDMA_CTRL_QMAP_M;
	if (haslq)
		reg |= R92C_TRXDMA_CTRL_QMAP_3EP;
	else if (hashq) {
		if (!hasnq)
			reg |= R92C_TRXDMA_CTRL_QMAP_HQ;
		else
			reg |= R92C_TRXDMA_CTRL_QMAP_HQ_NQ;
	}
	urtwn_write_2(sc, R92C_TRXDMA_CTRL, reg);

	/* Set Tx/Rx transfer page boundary. */
	urtwn_write_2(sc, R92C_TRXFF_BNDY + 2, dmasize - 1);

	/* Set Tx/Rx transfer page size. */
	urtwn_write_1(sc, R92C_PBP,
	    SM(R92C_PBP_PSRX, R92C_PBP_128) |
	    SM(R92C_PBP_PSTX, R92C_PBP_128));
	return (error);
}

void
urtwn_mac_init(void *cookie)
{
	struct urtwn_softc *sc = cookie;
	int i;

	/* Write MAC initialization values. */
	if (sc->sc_sc.chip & RTWN_CHIP_88E) {
		for (i = 0; i < nitems(rtl8188eu_mac); i++) {
			urtwn_write_1(sc, rtl8188eu_mac[i].reg,
			    rtl8188eu_mac[i].val);
		}
		urtwn_write_1(sc, R92C_MAX_AGGR_NUM, 0x07);
	} else {
		for (i = 0; i < nitems(rtl8192cu_mac); i++)
			urtwn_write_1(sc, rtl8192cu_mac[i].reg,
			    rtl8192cu_mac[i].val);
	}
}

void
urtwn_bb_init(void *cookie)
{
	struct urtwn_softc *sc = cookie;
	const struct r92c_bb_prog *prog;
	uint32_t reg;
	uint8_t xtal;
	int i;

	/* Enable BB and RF. */
	urtwn_write_2(sc, R92C_SYS_FUNC_EN,
	    urtwn_read_2(sc, R92C_SYS_FUNC_EN) |
	    R92C_SYS_FUNC_EN_BBRSTB | R92C_SYS_FUNC_EN_BB_GLB_RST |
	    R92C_SYS_FUNC_EN_DIO_RF);

	if (!(sc->sc_sc.chip & RTWN_CHIP_88E))
		urtwn_write_2(sc, R92C_AFE_PLL_CTRL, 0xdb83);

	urtwn_write_1(sc, R92C_RF_CTRL,
	    R92C_RF_CTRL_EN | R92C_RF_CTRL_RSTB | R92C_RF_CTRL_SDMRSTB);
	urtwn_write_1(sc, R92C_SYS_FUNC_EN,
	    R92C_SYS_FUNC_EN_USBA | R92C_SYS_FUNC_EN_USBD |
	    R92C_SYS_FUNC_EN_BB_GLB_RST | R92C_SYS_FUNC_EN_BBRSTB);

	if (!(sc->sc_sc.chip & RTWN_CHIP_88E)) {
		urtwn_write_1(sc, R92C_LDOHCI12_CTRL, 0x0f);
		urtwn_write_1(sc, 0x15, 0xe9);
		urtwn_write_1(sc, R92C_AFE_XTAL_CTRL + 1, 0x80);
	}

	/* Select BB programming based on board type. */
	if (sc->sc_sc.chip & RTWN_CHIP_88E)
		prog = &rtl8188eu_bb_prog;
	else if (!(sc->sc_sc.chip & RTWN_CHIP_92C)) {
		if (sc->sc_sc.board_type == R92C_BOARD_TYPE_MINICARD)
			prog = &rtl8188ce_bb_prog;
		else if (sc->sc_sc.board_type == R92C_BOARD_TYPE_HIGHPA)
			prog = &rtl8188ru_bb_prog;
		else
			prog = &rtl8188cu_bb_prog;
	} else {
		if (sc->sc_sc.board_type == R92C_BOARD_TYPE_MINICARD)
			prog = &rtl8192ce_bb_prog;
		else
			prog = &rtl8192cu_bb_prog;
	}
	/* Write BB initialization values. */
	for (i = 0; i < prog->count; i++) {
		urtwn_bb_write(sc, prog->regs[i], prog->vals[i]);
		DELAY(1);
	}

	if (sc->sc_sc.chip & RTWN_CHIP_92C_1T2R) {
		/* 8192C 1T only configuration. */
		reg = urtwn_bb_read(sc, R92C_FPGA0_TXINFO);
		reg = (reg & ~0x00000003) | 0x2;
		urtwn_bb_write(sc, R92C_FPGA0_TXINFO, reg);

		reg = urtwn_bb_read(sc, R92C_FPGA1_TXINFO);
		reg = (reg & ~0x00300033) | 0x00200022;
		urtwn_bb_write(sc, R92C_FPGA1_TXINFO, reg);

		reg = urtwn_bb_read(sc, R92C_CCK0_AFESETTING);
		reg = (reg & ~0xff000000) | 0x45 << 24;
		urtwn_bb_write(sc, R92C_CCK0_AFESETTING, reg);

		reg = urtwn_bb_read(sc, R92C_OFDM0_TRXPATHENA);
		reg = (reg & ~0x000000ff) | 0x23;
		urtwn_bb_write(sc, R92C_OFDM0_TRXPATHENA, reg);

		reg = urtwn_bb_read(sc, R92C_OFDM0_AGCPARAM1);
		reg = (reg & ~0x00000030) | 1 << 4;
		urtwn_bb_write(sc, R92C_OFDM0_AGCPARAM1, reg);

		reg = urtwn_bb_read(sc, 0xe74);
		reg = (reg & ~0x0c000000) | 2 << 26;
		urtwn_bb_write(sc, 0xe74, reg);
		reg = urtwn_bb_read(sc, 0xe78);
		reg = (reg & ~0x0c000000) | 2 << 26;
		urtwn_bb_write(sc, 0xe78, reg);
		reg = urtwn_bb_read(sc, 0xe7c);
		reg = (reg & ~0x0c000000) | 2 << 26;
		urtwn_bb_write(sc, 0xe7c, reg);
		reg = urtwn_bb_read(sc, 0xe80);
		reg = (reg & ~0x0c000000) | 2 << 26;
		urtwn_bb_write(sc, 0xe80, reg);
		reg = urtwn_bb_read(sc, 0xe88);
		reg = (reg & ~0x0c000000) | 2 << 26;
		urtwn_bb_write(sc, 0xe88, reg);
	}

	/* Write AGC values. */
	for (i = 0; i < prog->agccount; i++) {
		urtwn_bb_write(sc, R92C_OFDM0_AGCRSSITABLE,
		    prog->agcvals[i]);
		DELAY(1);
	}

	if (sc->sc_sc.chip & RTWN_CHIP_88E) {
		urtwn_bb_write(sc, R92C_OFDM0_AGCCORE1(0), 0x69553422);
		DELAY(1);
		urtwn_bb_write(sc, R92C_OFDM0_AGCCORE1(0), 0x69553420);
		DELAY(1);

		xtal = sc->sc_sc.crystal_cap & 0x3f;
		reg = urtwn_bb_read(sc, R92C_AFE_XTAL_CTRL);
		urtwn_bb_write(sc, R92C_AFE_XTAL_CTRL,
		    RW(reg, R92C_AFE_XTAL_CTRL_ADDR, xtal | xtal << 6));
	}

	if (urtwn_bb_read(sc, R92C_HSSI_PARAM2(0)) & R92C_HSSI_PARAM2_CCK_HIPWR)
		sc->sc_sc.sc_flags |= RTWN_FLAG_CCK_HIPWR;
}

int
urtwn_power_on(void *cookie)
{
	struct urtwn_softc *sc = cookie;

	if (sc->sc_sc.chip & RTWN_CHIP_88E)
		return (urtwn_r88e_power_on(sc));

	return (urtwn_r92c_power_on(sc));
}

int
urtwn_alloc_buffers(void *cookie)
{
	struct urtwn_softc *sc = cookie;
	int error;

	/* Init host async commands ring. */
	sc->cmdq.cur = sc->cmdq.next = sc->cmdq.queued = 0;

	/* Allocate Tx/Rx buffers. */
	error = urtwn_alloc_rx_list(sc);
	if (error != 0) {
		printf("%s: could not allocate Rx buffers\n",
		    sc->sc_dev.dv_xname);
		return (error);
	}
	error = urtwn_alloc_tx_list(sc);
	if (error != 0) {
		printf("%s: could not allocate Tx buffers\n",
		    sc->sc_dev.dv_xname);
		return (error);
	}

	return (0);
}

int
urtwn_init(void *cookie)
{
	struct urtwn_softc *sc = cookie;
	int i, error;

	/* Queue Rx xfers. */
	for (i = 0; i < URTWN_RX_LIST_COUNT; i++) {
		struct urtwn_rx_data *data = &sc->rx_data[i];

		usbd_setup_xfer(data->xfer, sc->rx_pipe, data, data->buf,
		    URTWN_RXBUFSZ, USBD_SHORT_XFER_OK | USBD_NO_COPY,
		    USBD_NO_TIMEOUT, urtwn_rxeof);
		error = usbd_transfer(data->xfer);
		if (error != 0 && error != USBD_IN_PROGRESS)
			return (error);
	}

	ieee80211_amrr_node_init(&sc->amrr, &sc->amn);

	/*
	 * Enable TX reports for AMRR.
	 * In order to get reports we need to explicitly reset the register.
	 */
	if (sc->sc_sc.chip & RTWN_CHIP_88E)
		urtwn_write_1(sc, R88E_TX_RPT_CTRL, (urtwn_read_1(sc,
		    R88E_TX_RPT_CTRL) & ~0) | R88E_TX_RPT_CTRL_EN);

	return (0);
}

void
urtwn_stop(void *cookie)
{
	struct urtwn_softc *sc = cookie;
	int i;

	/* Abort Tx. */
	for (i = 0; i < R92C_MAX_EPOUT; i++) {
		if (sc->tx_pipe[i] != NULL)
			usbd_abort_pipe(sc->tx_pipe[i]);
	}
	/* Stop Rx pipe. */
	usbd_abort_pipe(sc->rx_pipe);
	/* Free Tx/Rx buffers. */
	urtwn_free_tx_list(sc);
	urtwn_free_rx_list(sc);
}

int
urtwn_is_oactive(void *cookie)
{
	struct urtwn_softc *sc = cookie;
	
	return (TAILQ_EMPTY(&sc->tx_free_list));
}