]> CyberLeo.Net >> Repos - FreeBSD/releng/8.2.git/blob - sys/dev/usb/wlan/if_run.c
MFC r217511:
[FreeBSD/releng/8.2.git] / sys / dev / usb / wlan / if_run.c
1 /*-
2  * Copyright (c) 2008,2010 Damien Bergamini <damien.bergamini@free.fr>
3  * ported to FreeBSD by Akinori Furukoshi <moonlightakkiy@yahoo.ca>
4  * USB Consulting, Hans Petter Selasky <hselasky@freebsd.org>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18
19 #include <sys/cdefs.h>
20 __FBSDID("$FreeBSD$");
21
22 /*-
23  * Ralink Technology RT2700U/RT2800U/RT3000U chipset driver.
24  * http://www.ralinktech.com/
25  */
26
27 #include <sys/param.h>
28 #include <sys/sockio.h>
29 #include <sys/sysctl.h>
30 #include <sys/lock.h>
31 #include <sys/mutex.h>
32 #include <sys/mbuf.h>
33 #include <sys/kernel.h>
34 #include <sys/socket.h>
35 #include <sys/systm.h>
36 #include <sys/malloc.h>
37 #include <sys/module.h>
38 #include <sys/bus.h>
39 #include <sys/endian.h>
40 #include <sys/linker.h>
41 #include <sys/firmware.h>
42 #include <sys/kdb.h>
43
44 #include <machine/bus.h>
45 #include <machine/resource.h>
46 #include <sys/rman.h>
47
48 #include <net/bpf.h>
49 #include <net/if.h>
50 #include <net/if_arp.h>
51 #include <net/ethernet.h>
52 #include <net/if_dl.h>
53 #include <net/if_media.h>
54 #include <net/if_types.h>
55
56 #include <netinet/in.h>
57 #include <netinet/in_systm.h>
58 #include <netinet/in_var.h>
59 #include <netinet/if_ether.h>
60 #include <netinet/ip.h>
61
62 #include <net80211/ieee80211_var.h>
63 #include <net80211/ieee80211_regdomain.h>
64 #include <net80211/ieee80211_radiotap.h>
65 #include <net80211/ieee80211_ratectl.h>
66
67 #include <dev/usb/usb.h>
68 #include <dev/usb/usbdi.h>
69 #include "usbdevs.h"
70
71 #define USB_DEBUG_VAR run_debug
72 #include <dev/usb/usb_debug.h>
73
74 #include "if_runreg.h"
75 #include "if_runvar.h"
76
77 #define nitems(_a)      (sizeof((_a)) / sizeof((_a)[0]))
78
79 #ifdef  USB_DEBUG
80 #define RUN_DEBUG
81 #endif
82
83 #ifdef  RUN_DEBUG
84 int run_debug = 0;
85 SYSCTL_NODE(_hw_usb, OID_AUTO, run, CTLFLAG_RW, 0, "USB run");
86 SYSCTL_INT(_hw_usb_run, OID_AUTO, debug, CTLFLAG_RW, &run_debug, 0,
87     "run debug level");
88 #endif
89
90 #define IEEE80211_HAS_ADDR4(wh) \
91         (((wh)->i_fc[1] & IEEE80211_FC1_DIR_MASK) == IEEE80211_FC1_DIR_DSTODS)
92
93 /*
94  * Because of LOR in run_key_delete(), use atomic instead.
95  * '& RUN_CMDQ_MASQ' is to loop cmdq[].
96  */
97 #define RUN_CMDQ_GET(c) (atomic_fetchadd_32((c), 1) & RUN_CMDQ_MASQ)
98
99 static const struct usb_device_id run_devs[] = {
100 #define RUN_DEV(v,p) { USB_VP(USB_VENDOR_##v, USB_PRODUCT_##v##_##p) }
101     RUN_DEV(ABOCOM,             RT2770),
102     RUN_DEV(ABOCOM,             RT2870),
103     RUN_DEV(ABOCOM,             RT3070),
104     RUN_DEV(ABOCOM,             RT3071),
105     RUN_DEV(ABOCOM,             RT3072),
106     RUN_DEV(ABOCOM2,            RT2870_1),
107     RUN_DEV(ACCTON,             RT2770),
108     RUN_DEV(ACCTON,             RT2870_1),
109     RUN_DEV(ACCTON,             RT2870_2),
110     RUN_DEV(ACCTON,             RT2870_3),
111     RUN_DEV(ACCTON,             RT2870_4),
112     RUN_DEV(ACCTON,             RT2870_5),
113     RUN_DEV(ACCTON,             RT3070),
114     RUN_DEV(ACCTON,             RT3070_1),
115     RUN_DEV(ACCTON,             RT3070_2),
116     RUN_DEV(ACCTON,             RT3070_3),
117     RUN_DEV(ACCTON,             RT3070_4),
118     RUN_DEV(ACCTON,             RT3070_5),
119     RUN_DEV(AIRTIES,            RT3070),
120     RUN_DEV(ALLWIN,             RT2070),
121     RUN_DEV(ALLWIN,             RT2770),
122     RUN_DEV(ALLWIN,             RT2870),
123     RUN_DEV(ALLWIN,             RT3070),
124     RUN_DEV(ALLWIN,             RT3071),
125     RUN_DEV(ALLWIN,             RT3072),
126     RUN_DEV(ALLWIN,             RT3572),
127     RUN_DEV(AMIGO,              RT2870_1),
128     RUN_DEV(AMIGO,              RT2870_2),
129     RUN_DEV(AMIT,               CGWLUSB2GNR),
130     RUN_DEV(AMIT,               RT2870_1),
131     RUN_DEV(AMIT2,              RT2870),
132     RUN_DEV(ASUS,               RT2870_1),
133     RUN_DEV(ASUS,               RT2870_2),
134     RUN_DEV(ASUS,               RT2870_3),
135     RUN_DEV(ASUS,               RT2870_4),
136     RUN_DEV(ASUS,               RT2870_5),
137     RUN_DEV(ASUS,               USBN13),
138     RUN_DEV(ASUS,               RT3070_1),
139     RUN_DEV(ASUS2,              USBN11),
140     RUN_DEV(AZUREWAVE,          RT2870_1),
141     RUN_DEV(AZUREWAVE,          RT2870_2),
142     RUN_DEV(AZUREWAVE,          RT3070_1),
143     RUN_DEV(AZUREWAVE,          RT3070_2),
144     RUN_DEV(AZUREWAVE,          RT3070_3),
145     RUN_DEV(BELKIN,             F5D8053V3),
146     RUN_DEV(BELKIN,             F5D8055),
147     RUN_DEV(BELKIN,             F6D4050V1),
148     RUN_DEV(BELKIN,             RT2870_1),
149     RUN_DEV(BELKIN,             RT2870_2),
150     RUN_DEV(CISCOLINKSYS2,      RT3070),
151     RUN_DEV(CISCOLINKSYS3,      RT3070),
152     RUN_DEV(CONCEPTRONIC2,      RT2870_1),
153     RUN_DEV(CONCEPTRONIC2,      RT2870_2),
154     RUN_DEV(CONCEPTRONIC2,      RT2870_3),
155     RUN_DEV(CONCEPTRONIC2,      RT2870_4),
156     RUN_DEV(CONCEPTRONIC2,      RT2870_5),
157     RUN_DEV(CONCEPTRONIC2,      RT2870_6),
158     RUN_DEV(CONCEPTRONIC2,      RT2870_7),
159     RUN_DEV(CONCEPTRONIC2,      RT2870_8),
160     RUN_DEV(CONCEPTRONIC2,      RT3070_1),
161     RUN_DEV(CONCEPTRONIC2,      RT3070_2),
162     RUN_DEV(CONCEPTRONIC2,      VIGORN61),
163     RUN_DEV(COREGA,             CGWLUSB300GNM),
164     RUN_DEV(COREGA,             RT2870_1),
165     RUN_DEV(COREGA,             RT2870_2),
166     RUN_DEV(COREGA,             RT2870_3),
167     RUN_DEV(COREGA,             RT3070),
168     RUN_DEV(CYBERTAN,           RT2870),
169     RUN_DEV(DLINK,              RT2870),
170     RUN_DEV(DLINK,              RT3072),
171     RUN_DEV(DLINK2,             DWA130),
172     RUN_DEV(DLINK2,             RT2870_1),
173     RUN_DEV(DLINK2,             RT2870_2),
174     RUN_DEV(DLINK2,             RT3070_1),
175     RUN_DEV(DLINK2,             RT3070_2),
176     RUN_DEV(DLINK2,             RT3070_3),
177     RUN_DEV(DLINK2,             RT3070_4),
178     RUN_DEV(DLINK2,             RT3070_5),
179     RUN_DEV(DLINK2,             RT3072),
180     RUN_DEV(DLINK2,             RT3072_1),
181     RUN_DEV(EDIMAX,             EW7717),
182     RUN_DEV(EDIMAX,             EW7718),
183     RUN_DEV(EDIMAX,             RT2870_1),
184     RUN_DEV(ENCORE,             RT3070_1),
185     RUN_DEV(ENCORE,             RT3070_2),
186     RUN_DEV(ENCORE,             RT3070_3),
187     RUN_DEV(GIGABYTE,           GNWB31N),
188     RUN_DEV(GIGABYTE,           GNWB32L),
189     RUN_DEV(GIGABYTE,           RT2870_1),
190     RUN_DEV(GIGASET,            RT3070_1),
191     RUN_DEV(GIGASET,            RT3070_2),
192     RUN_DEV(GUILLEMOT,          HWNU300),
193     RUN_DEV(HAWKING,            HWUN2),
194     RUN_DEV(HAWKING,            RT2870_1),
195     RUN_DEV(HAWKING,            RT2870_2),
196     RUN_DEV(HAWKING,            RT3070),
197     RUN_DEV(IODATA,             RT3072_1),
198     RUN_DEV(IODATA,             RT3072_2),
199     RUN_DEV(IODATA,             RT3072_3),
200     RUN_DEV(IODATA,             RT3072_4),
201     RUN_DEV(LINKSYS4,           RT3070),
202     RUN_DEV(LINKSYS4,           WUSB100),
203     RUN_DEV(LINKSYS4,           WUSB54GCV3),
204     RUN_DEV(LINKSYS4,           WUSB600N),
205     RUN_DEV(LINKSYS4,           WUSB600NV2),
206     RUN_DEV(LOGITEC,            RT2870_1),
207     RUN_DEV(LOGITEC,            RT2870_2),
208     RUN_DEV(LOGITEC,            RT2870_3),
209     RUN_DEV(MELCO,              RT2870_1),
210     RUN_DEV(MELCO,              RT2870_2),
211     RUN_DEV(MELCO,              WLIUCAG300N),
212     RUN_DEV(MELCO,              WLIUCG300N),
213     RUN_DEV(MELCO,              WLIUCGN),
214     RUN_DEV(MOTOROLA4,          RT2770),
215     RUN_DEV(MOTOROLA4,          RT3070),
216     RUN_DEV(MSI,                RT3070_1),
217     RUN_DEV(MSI,                RT3070_2),
218     RUN_DEV(MSI,                RT3070_3),
219     RUN_DEV(MSI,                RT3070_4),
220     RUN_DEV(MSI,                RT3070_5),
221     RUN_DEV(MSI,                RT3070_6),
222     RUN_DEV(MSI,                RT3070_7),
223     RUN_DEV(MSI,                RT3070_8),
224     RUN_DEV(MSI,                RT3070_9),
225     RUN_DEV(MSI,                RT3070_10),
226     RUN_DEV(MSI,                RT3070_11),
227     RUN_DEV(OVISLINK,           RT3072),
228     RUN_DEV(PARA,               RT3070),
229     RUN_DEV(PEGATRON,           RT2870),
230     RUN_DEV(PEGATRON,           RT3070),
231     RUN_DEV(PEGATRON,           RT3070_2),
232     RUN_DEV(PEGATRON,           RT3070_3),
233     RUN_DEV(PHILIPS,            RT2870),
234     RUN_DEV(PLANEX2,            GWUS300MINIS),
235     RUN_DEV(PLANEX2,            GWUSMICRON),
236     RUN_DEV(PLANEX2,            RT2870),
237     RUN_DEV(PLANEX2,            RT3070),
238     RUN_DEV(QCOM,               RT2870),
239     RUN_DEV(QUANTA,             RT3070),
240     RUN_DEV(RALINK,             RT2070),
241     RUN_DEV(RALINK,             RT2770),
242     RUN_DEV(RALINK,             RT2870),
243     RUN_DEV(RALINK,             RT3070),
244     RUN_DEV(RALINK,             RT3071),
245     RUN_DEV(RALINK,             RT3072),
246     RUN_DEV(RALINK,             RT3370),
247     RUN_DEV(RALINK,             RT3572),
248     RUN_DEV(RALINK,             RT8070),
249     RUN_DEV(SAMSUNG2,           RT2870_1),
250     RUN_DEV(SENAO,              RT2870_1),
251     RUN_DEV(SENAO,              RT2870_2),
252     RUN_DEV(SENAO,              RT2870_3),
253     RUN_DEV(SENAO,              RT2870_4),
254     RUN_DEV(SENAO,              RT3070),
255     RUN_DEV(SENAO,              RT3071),
256     RUN_DEV(SENAO,              RT3072_1),
257     RUN_DEV(SENAO,              RT3072_2),
258     RUN_DEV(SENAO,              RT3072_3),
259     RUN_DEV(SENAO,              RT3072_4),
260     RUN_DEV(SENAO,              RT3072_5),
261     RUN_DEV(SITECOMEU,          RT2770),
262     RUN_DEV(SITECOMEU,          RT2870_1),
263     RUN_DEV(SITECOMEU,          RT2870_2),
264     RUN_DEV(SITECOMEU,          RT2870_3),
265     RUN_DEV(SITECOMEU,          RT2870_4),
266     RUN_DEV(SITECOMEU,          RT3070),
267     RUN_DEV(SITECOMEU,          RT3070_2),
268     RUN_DEV(SITECOMEU,          RT3070_3),
269     RUN_DEV(SITECOMEU,          RT3070_4),
270     RUN_DEV(SITECOMEU,          RT3071),
271     RUN_DEV(SITECOMEU,          RT3072_1),
272     RUN_DEV(SITECOMEU,          RT3072_2),
273     RUN_DEV(SITECOMEU,          RT3072_3),
274     RUN_DEV(SITECOMEU,          RT3072_4),
275     RUN_DEV(SITECOMEU,          RT3072_5),
276     RUN_DEV(SITECOMEU,          RT3072_6),
277     RUN_DEV(SITECOMEU,          WL608),
278     RUN_DEV(SPARKLAN,           RT2870_1),
279     RUN_DEV(SPARKLAN,           RT3070),
280     RUN_DEV(SWEEX2,             LW153),
281     RUN_DEV(SWEEX2,             LW303),
282     RUN_DEV(SWEEX2,             LW313),
283     RUN_DEV(TOSHIBA,            RT3070),
284     RUN_DEV(UMEDIA,             RT2870_1),
285     RUN_DEV(ZCOM,               RT2870_1),
286     RUN_DEV(ZCOM,               RT2870_2),
287     RUN_DEV(ZINWELL,            RT2870_1),
288     RUN_DEV(ZINWELL,            RT2870_2),
289     RUN_DEV(ZINWELL,            RT3070),
290     RUN_DEV(ZINWELL,            RT3072_1),
291     RUN_DEV(ZINWELL,            RT3072_2),
292     RUN_DEV(ZYXEL,              RT2870_1),
293     RUN_DEV(ZYXEL,              RT2870_2),
294 #undef RUN_DEV
295 };
296
297 static device_probe_t   run_match;
298 static device_attach_t  run_attach;
299 static device_detach_t  run_detach;
300
301 static usb_callback_t   run_bulk_rx_callback;
302 static usb_callback_t   run_bulk_tx_callback0;
303 static usb_callback_t   run_bulk_tx_callback1;
304 static usb_callback_t   run_bulk_tx_callback2;
305 static usb_callback_t   run_bulk_tx_callback3;
306 static usb_callback_t   run_bulk_tx_callback4;
307 static usb_callback_t   run_bulk_tx_callback5;
308
309 static void     run_bulk_tx_callbackN(struct usb_xfer *xfer,
310                     usb_error_t error, unsigned int index);
311 static struct ieee80211vap *run_vap_create(struct ieee80211com *,
312                     const char name[IFNAMSIZ], int unit, int opmode, int flags,
313                     const uint8_t bssid[IEEE80211_ADDR_LEN], const uint8_t
314                     mac[IEEE80211_ADDR_LEN]);
315 static void     run_vap_delete(struct ieee80211vap *);
316 static void     run_cmdq_cb(void *, int);
317 static void     run_setup_tx_list(struct run_softc *,
318                     struct run_endpoint_queue *);
319 static void     run_unsetup_tx_list(struct run_softc *,
320                     struct run_endpoint_queue *);
321 static int      run_load_microcode(struct run_softc *);
322 static int      run_reset(struct run_softc *);
323 static usb_error_t run_do_request(struct run_softc *,
324                     struct usb_device_request *, void *);
325 static int      run_read(struct run_softc *, uint16_t, uint32_t *);
326 static int      run_read_region_1(struct run_softc *, uint16_t, uint8_t *, int);
327 static int      run_write_2(struct run_softc *, uint16_t, uint16_t);
328 static int      run_write(struct run_softc *, uint16_t, uint32_t);
329 static int      run_write_region_1(struct run_softc *, uint16_t,
330                     const uint8_t *, int);
331 static int      run_set_region_4(struct run_softc *, uint16_t, uint32_t, int);
332 static int      run_efuse_read_2(struct run_softc *, uint16_t, uint16_t *);
333 static int      run_eeprom_read_2(struct run_softc *, uint16_t, uint16_t *);
334 static int      run_rt2870_rf_write(struct run_softc *, uint8_t, uint32_t);
335 static int      run_rt3070_rf_read(struct run_softc *, uint8_t, uint8_t *);
336 static int      run_rt3070_rf_write(struct run_softc *, uint8_t, uint8_t);
337 static int      run_bbp_read(struct run_softc *, uint8_t, uint8_t *);
338 static int      run_bbp_write(struct run_softc *, uint8_t, uint8_t);
339 static int      run_mcu_cmd(struct run_softc *, uint8_t, uint16_t);
340 static const char *run_get_rf(int);
341 static int      run_read_eeprom(struct run_softc *);
342 static struct ieee80211_node *run_node_alloc(struct ieee80211vap *,
343                             const uint8_t mac[IEEE80211_ADDR_LEN]);
344 static int      run_media_change(struct ifnet *);
345 static int      run_newstate(struct ieee80211vap *, enum ieee80211_state, int);
346 static int      run_wme_update(struct ieee80211com *);
347 static void     run_wme_update_cb(void *);
348 static void     run_key_update_begin(struct ieee80211vap *);
349 static void     run_key_update_end(struct ieee80211vap *);
350 static void     run_key_set_cb(void *);
351 static int      run_key_set(struct ieee80211vap *, struct ieee80211_key *,
352                             const uint8_t mac[IEEE80211_ADDR_LEN]);
353 static void     run_key_delete_cb(void *);
354 static int      run_key_delete(struct ieee80211vap *, struct ieee80211_key *);
355 static void     run_ratectl_to(void *);
356 static void     run_ratectl_cb(void *, int);
357 static void     run_drain_fifo(void *);
358 static void     run_iter_func(void *, struct ieee80211_node *);
359 static void     run_newassoc_cb(void *);
360 static void     run_newassoc(struct ieee80211_node *, int);
361 static void     run_rx_frame(struct run_softc *, struct mbuf *, uint32_t);
362 static void     run_tx_free(struct run_endpoint_queue *pq,
363                     struct run_tx_data *, int);
364 static void     run_set_tx_desc(struct run_softc *, struct run_tx_data *);
365 static int      run_tx(struct run_softc *, struct mbuf *,
366                     struct ieee80211_node *);
367 static int      run_tx_mgt(struct run_softc *, struct mbuf *,
368                     struct ieee80211_node *);
369 static int      run_sendprot(struct run_softc *, const struct mbuf *,
370                     struct ieee80211_node *, int, int);
371 static int      run_tx_param(struct run_softc *, struct mbuf *,
372                     struct ieee80211_node *,
373                     const struct ieee80211_bpf_params *);
374 static int      run_raw_xmit(struct ieee80211_node *, struct mbuf *,
375                     const struct ieee80211_bpf_params *);
376 static void     run_start(struct ifnet *);
377 static int      run_ioctl(struct ifnet *, u_long, caddr_t);
378 static void     run_set_agc(struct run_softc *, uint8_t);
379 static void     run_select_chan_group(struct run_softc *, int);
380 static void     run_set_rx_antenna(struct run_softc *, int);
381 static void     run_rt2870_set_chan(struct run_softc *, u_int);
382 static void     run_rt3070_set_chan(struct run_softc *, u_int);
383 static void     run_rt3572_set_chan(struct run_softc *, u_int);
384 static int      run_set_chan(struct run_softc *, struct ieee80211_channel *);
385 static void     run_set_channel(struct ieee80211com *);
386 static void     run_scan_start(struct ieee80211com *);
387 static void     run_scan_end(struct ieee80211com *);
388 static void     run_update_beacon(struct ieee80211vap *, int);
389 static void     run_update_beacon_cb(void *);
390 static void     run_updateprot(struct ieee80211com *);
391 static void     run_usb_timeout_cb(void *);
392 static void     run_reset_livelock(struct run_softc *);
393 static void     run_enable_tsf_sync(struct run_softc *);
394 static void     run_enable_mrr(struct run_softc *);
395 static void     run_set_txpreamble(struct run_softc *);
396 static void     run_set_basicrates(struct run_softc *);
397 static void     run_set_leds(struct run_softc *, uint16_t);
398 static void     run_set_bssid(struct run_softc *, const uint8_t *);
399 static void     run_set_macaddr(struct run_softc *, const uint8_t *);
400 static void     run_updateslot(struct ifnet *);
401 static void     run_update_mcast(struct ifnet *);
402 static int8_t   run_rssi2dbm(struct run_softc *, uint8_t, uint8_t);
403 static void     run_update_promisc_locked(struct ifnet *);
404 static void     run_update_promisc(struct ifnet *);
405 static int      run_bbp_init(struct run_softc *);
406 static int      run_rt3070_rf_init(struct run_softc *);
407 static int      run_rt3070_filter_calib(struct run_softc *, uint8_t, uint8_t,
408                     uint8_t *);
409 static void     run_rt3070_rf_setup(struct run_softc *);
410 static int      run_txrx_enable(struct run_softc *);
411 static void     run_init(void *);
412 static void     run_init_locked(struct run_softc *);
413 static void     run_stop(void *);
414 static void     run_delay(struct run_softc *, unsigned int);
415
416 static const struct {
417         uint16_t        reg;
418         uint32_t        val;
419 } rt2870_def_mac[] = {
420         RT2870_DEF_MAC
421 };
422
423 static const struct {
424         uint8_t reg;
425         uint8_t val;
426 } rt2860_def_bbp[] = {
427         RT2860_DEF_BBP
428 };
429
430 static const struct rfprog {
431         uint8_t         chan;
432         uint32_t        r1, r2, r3, r4;
433 } rt2860_rf2850[] = {
434         RT2860_RF2850
435 };
436
437 struct {
438         uint8_t n, r, k;
439 } rt3070_freqs[] = {
440         RT3070_RF3052
441 };
442
443 static const struct {
444         uint8_t reg;
445         uint8_t val;
446 } rt3070_def_rf[] = {
447         RT3070_DEF_RF
448 },rt3572_def_rf[] = {
449         RT3572_DEF_RF
450 };
451
452 static const struct usb_config run_config[RUN_N_XFER] = {
453     [RUN_BULK_TX_BE] = {
454         .type = UE_BULK,
455         .endpoint = UE_ADDR_ANY,
456         .ep_index = 0,
457         .direction = UE_DIR_OUT,
458         .bufsize = RUN_MAX_TXSZ,
459         .flags = {.pipe_bof = 1,.force_short_xfer = 1,},
460         .callback = run_bulk_tx_callback0,
461         .timeout = 5000,        /* ms */
462     },
463     [RUN_BULK_TX_BK] = {
464         .type = UE_BULK,
465         .endpoint = UE_ADDR_ANY,
466         .direction = UE_DIR_OUT,
467         .ep_index = 1,
468         .bufsize = RUN_MAX_TXSZ,
469         .flags = {.pipe_bof = 1,.force_short_xfer = 1,},
470         .callback = run_bulk_tx_callback1,
471         .timeout = 5000,        /* ms */
472     },
473     [RUN_BULK_TX_VI] = {
474         .type = UE_BULK,
475         .endpoint = UE_ADDR_ANY,
476         .direction = UE_DIR_OUT,
477         .ep_index = 2,
478         .bufsize = RUN_MAX_TXSZ,
479         .flags = {.pipe_bof = 1,.force_short_xfer = 1,},
480         .callback = run_bulk_tx_callback2,
481         .timeout = 5000,        /* ms */
482     },
483     [RUN_BULK_TX_VO] = {
484         .type = UE_BULK,
485         .endpoint = UE_ADDR_ANY,
486         .direction = UE_DIR_OUT,
487         .ep_index = 3,
488         .bufsize = RUN_MAX_TXSZ,
489         .flags = {.pipe_bof = 1,.force_short_xfer = 1,},
490         .callback = run_bulk_tx_callback3,
491         .timeout = 5000,        /* ms */
492     },
493     [RUN_BULK_TX_HCCA] = {
494         .type = UE_BULK,
495         .endpoint = UE_ADDR_ANY,
496         .direction = UE_DIR_OUT,
497         .ep_index = 4,
498         .bufsize = RUN_MAX_TXSZ,
499         .flags = {.pipe_bof = 1,.force_short_xfer = 1,.no_pipe_ok = 1,},
500         .callback = run_bulk_tx_callback4,
501         .timeout = 5000,        /* ms */
502     },
503     [RUN_BULK_TX_PRIO] = {
504         .type = UE_BULK,
505         .endpoint = UE_ADDR_ANY,
506         .direction = UE_DIR_OUT,
507         .ep_index = 5,
508         .bufsize = RUN_MAX_TXSZ,
509         .flags = {.pipe_bof = 1,.force_short_xfer = 1,.no_pipe_ok = 1,},
510         .callback = run_bulk_tx_callback5,
511         .timeout = 5000,        /* ms */
512     },
513     [RUN_BULK_RX] = {
514         .type = UE_BULK,
515         .endpoint = UE_ADDR_ANY,
516         .direction = UE_DIR_IN,
517         .bufsize = RUN_MAX_RXSZ,
518         .flags = {.pipe_bof = 1,.short_xfer_ok = 1,},
519         .callback = run_bulk_rx_callback,
520     }
521 };
522
523 int
524 run_match(device_t self)
525 {
526         struct usb_attach_arg *uaa = device_get_ivars(self);
527
528         if (uaa->usb_mode != USB_MODE_HOST)
529                 return (ENXIO);
530         if (uaa->info.bConfigIndex != 0)
531                 return (ENXIO);
532         if (uaa->info.bIfaceIndex != RT2860_IFACE_INDEX)
533                 return (ENXIO);
534
535         return (usbd_lookup_id_by_uaa(run_devs, sizeof(run_devs), uaa));
536 }
537
538 static int
539 run_attach(device_t self)
540 {
541         struct run_softc *sc = device_get_softc(self);
542         struct usb_attach_arg *uaa = device_get_ivars(self);
543         struct ieee80211com *ic;
544         struct ifnet *ifp;
545         uint32_t ver;
546         int i, ntries, error;
547         uint8_t iface_index, bands;
548
549         device_set_usb_desc(self);
550         sc->sc_udev = uaa->device;
551         sc->sc_dev = self;
552
553         mtx_init(&sc->sc_mtx, device_get_nameunit(sc->sc_dev),
554             MTX_NETWORK_LOCK, MTX_DEF);
555
556         iface_index = RT2860_IFACE_INDEX;
557
558         error = usbd_transfer_setup(uaa->device, &iface_index,
559             sc->sc_xfer, run_config, RUN_N_XFER, sc, &sc->sc_mtx);
560         if (error) {
561                 device_printf(self, "could not allocate USB transfers, "
562                     "err=%s\n", usbd_errstr(error));
563                 goto detach;
564         }
565
566         RUN_LOCK(sc);
567
568         /* wait for the chip to settle */
569         for (ntries = 0; ntries < 100; ntries++) {
570                 if (run_read(sc, RT2860_ASIC_VER_ID, &ver) != 0) {
571                         RUN_UNLOCK(sc);
572                         goto detach;
573                 }
574                 if (ver != 0 && ver != 0xffffffff)
575                         break;
576                 run_delay(sc, 10);
577         }
578         if (ntries == 100) {
579                 device_printf(sc->sc_dev,
580                     "timeout waiting for NIC to initialize\n");
581                 RUN_UNLOCK(sc);
582                 goto detach;
583         }
584         sc->mac_ver = ver >> 16;
585         sc->mac_rev = ver & 0xffff;
586
587         /* retrieve RF rev. no and various other things from EEPROM */
588         run_read_eeprom(sc);
589
590         device_printf(sc->sc_dev,
591             "MAC/BBP RT%04X (rev 0x%04X), RF %s (MIMO %dT%dR), address %s\n",
592             sc->mac_ver, sc->mac_rev, run_get_rf(sc->rf_rev),
593             sc->ntxchains, sc->nrxchains, ether_sprintf(sc->sc_bssid));
594
595         if ((error = run_load_microcode(sc)) != 0) {
596                 device_printf(sc->sc_dev, "could not load 8051 microcode\n");
597                 RUN_UNLOCK(sc);
598                 goto detach;
599         }
600
601         RUN_UNLOCK(sc);
602
603         ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211);
604         if(ifp == NULL){
605                 device_printf(sc->sc_dev, "can not if_alloc()\n");
606                 goto detach;
607         }
608         ic = ifp->if_l2com;
609
610         ifp->if_softc = sc;
611         if_initname(ifp, "run", device_get_unit(sc->sc_dev));
612         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
613         ifp->if_init = run_init;
614         ifp->if_ioctl = run_ioctl;
615         ifp->if_start = run_start;
616         IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
617         ifp->if_snd.ifq_drv_maxlen = ifqmaxlen;
618         IFQ_SET_READY(&ifp->if_snd);
619
620         ic->ic_ifp = ifp;
621         ic->ic_phytype = IEEE80211_T_OFDM;      /* not only, but not used */
622         ic->ic_opmode = IEEE80211_M_STA;        /* default to BSS mode */
623
624         /* set device capabilities */
625         ic->ic_caps =
626             IEEE80211_C_STA |           /* station mode supported */
627             IEEE80211_C_MONITOR |       /* monitor mode supported */
628             IEEE80211_C_IBSS |
629             IEEE80211_C_HOSTAP |
630             IEEE80211_C_WDS |           /* 4-address traffic works */
631             IEEE80211_C_MBSS |
632             IEEE80211_C_SHPREAMBLE |    /* short preamble supported */
633             IEEE80211_C_SHSLOT |        /* short slot time supported */
634             IEEE80211_C_WME |           /* WME */
635             IEEE80211_C_WPA;            /* WPA1|WPA2(RSN) */
636
637         ic->ic_cryptocaps =
638             IEEE80211_CRYPTO_WEP |
639             IEEE80211_CRYPTO_AES_CCM |
640             IEEE80211_CRYPTO_TKIPMIC |
641             IEEE80211_CRYPTO_TKIP;
642
643         ic->ic_flags |= IEEE80211_F_DATAPAD;
644         ic->ic_flags_ext |= IEEE80211_FEXT_SWBMISS;
645
646         bands = 0;
647         setbit(&bands, IEEE80211_MODE_11B);
648         setbit(&bands, IEEE80211_MODE_11G);
649         ieee80211_init_channels(ic, NULL, &bands);
650
651         /*
652          * Do this by own because h/w supports
653          * more channels than ieee80211_init_channels()
654          */
655         if (sc->rf_rev == RT2860_RF_2750 ||
656             sc->rf_rev == RT2860_RF_2850 ||
657             sc->rf_rev == RT3070_RF_3052) {
658                 /* set supported .11a rates */
659                 for (i = 14; i < nitems(rt2860_rf2850); i++) {
660                         uint8_t chan = rt2860_rf2850[i].chan;
661                         ic->ic_channels[ic->ic_nchans].ic_freq =
662                             ieee80211_ieee2mhz(chan, IEEE80211_CHAN_A);
663                         ic->ic_channels[ic->ic_nchans].ic_ieee = chan;
664                         ic->ic_channels[ic->ic_nchans].ic_flags = IEEE80211_CHAN_A;
665                         ic->ic_channels[ic->ic_nchans].ic_extieee = 0;
666                         ic->ic_nchans++;
667                 }
668         }
669
670         ieee80211_ifattach(ic, sc->sc_bssid);
671
672         ic->ic_scan_start = run_scan_start;
673         ic->ic_scan_end = run_scan_end;
674         ic->ic_set_channel = run_set_channel;
675         ic->ic_node_alloc = run_node_alloc;
676         ic->ic_newassoc = run_newassoc;
677         //ic->ic_updateslot = run_updateslot;
678         ic->ic_update_mcast = run_update_mcast;
679         ic->ic_wme.wme_update = run_wme_update;
680         ic->ic_raw_xmit = run_raw_xmit;
681         ic->ic_update_promisc = run_update_promisc;
682
683         ic->ic_vap_create = run_vap_create;
684         ic->ic_vap_delete = run_vap_delete;
685
686         ieee80211_radiotap_attach(ic,
687             &sc->sc_txtap.wt_ihdr, sizeof(sc->sc_txtap),
688                 RUN_TX_RADIOTAP_PRESENT,
689             &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap),
690                 RUN_RX_RADIOTAP_PRESENT);
691
692         TASK_INIT(&sc->cmdq_task, 0, run_cmdq_cb, sc);
693         TASK_INIT(&sc->ratectl_task, 0, run_ratectl_cb, sc);
694         callout_init((struct callout *)&sc->ratectl_ch, 1);
695
696         if (bootverbose)
697                 ieee80211_announce(ic);
698
699         return (0);
700
701 detach:
702         run_detach(self);
703         return (ENXIO);
704 }
705
706 static int
707 run_detach(device_t self)
708 {
709         struct run_softc *sc = device_get_softc(self);
710         struct ifnet *ifp = sc->sc_ifp;
711         struct ieee80211com *ic;
712         int i;
713
714         /* stop all USB transfers */
715         usbd_transfer_unsetup(sc->sc_xfer, RUN_N_XFER);
716
717         RUN_LOCK(sc);
718
719         sc->ratectl_run = RUN_RATECTL_OFF;
720         sc->cmdq_run = sc->cmdq_key_set = RUN_CMDQ_ABORT;
721
722         /* free TX list, if any */
723         for (i = 0; i != RUN_EP_QUEUES; i++)
724                 run_unsetup_tx_list(sc, &sc->sc_epq[i]);
725         RUN_UNLOCK(sc);
726
727         if (ifp) {
728                 ic = ifp->if_l2com;
729                 /* drain tasks */
730                 usb_callout_drain(&sc->ratectl_ch);
731                 ieee80211_draintask(ic, &sc->cmdq_task);
732                 ieee80211_draintask(ic, &sc->ratectl_task);
733                 ieee80211_ifdetach(ic);
734                 if_free(ifp);
735         }
736
737         mtx_destroy(&sc->sc_mtx);
738
739         return (0);
740 }
741
742 static struct ieee80211vap *
743 run_vap_create(struct ieee80211com *ic,
744     const char name[IFNAMSIZ], int unit, int opmode, int flags,
745     const uint8_t bssid[IEEE80211_ADDR_LEN],
746     const uint8_t mac[IEEE80211_ADDR_LEN])
747 {
748         struct ifnet *ifp = ic->ic_ifp;
749         struct run_softc *sc = ifp->if_softc;
750         struct run_vap *rvp;
751         struct ieee80211vap *vap;
752         int i;
753
754         if (sc->rvp_cnt >= RUN_VAP_MAX) {
755                 if_printf(ifp, "number of VAPs maxed out\n");
756                 return (NULL);
757         }
758
759         switch (opmode) {
760         case IEEE80211_M_STA:
761                 /* enable s/w bmiss handling for sta mode */
762                 flags |= IEEE80211_CLONE_NOBEACONS; 
763                 /* fall though */
764         case IEEE80211_M_IBSS:
765         case IEEE80211_M_MONITOR:
766         case IEEE80211_M_HOSTAP:
767         case IEEE80211_M_MBSS:
768                 /* other than WDS vaps, only one at a time */
769                 if (!TAILQ_EMPTY(&ic->ic_vaps))
770                         return (NULL);
771                 break;
772         case IEEE80211_M_WDS:
773                 TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next){
774                         if(vap->iv_opmode != IEEE80211_M_HOSTAP)
775                                 continue;
776                         /* WDS vap's always share the local mac address. */
777                         flags &= ~IEEE80211_CLONE_BSSID;
778                         break;
779                 }
780                 if (vap == NULL) {
781                         if_printf(ifp, "wds only supported in ap mode\n");
782                         return (NULL);
783                 }
784                 break;
785         default:
786                 if_printf(ifp, "unknown opmode %d\n", opmode);
787                 return (NULL);
788         }
789
790         rvp = (struct run_vap *) malloc(sizeof(struct run_vap),
791             M_80211_VAP, M_NOWAIT | M_ZERO);
792         if (rvp == NULL)
793                 return (NULL);
794         vap = &rvp->vap;
795         ieee80211_vap_setup(ic, vap, name, unit, opmode, flags, bssid, mac);
796
797         vap->iv_key_update_begin = run_key_update_begin;
798         vap->iv_key_update_end = run_key_update_end;
799         vap->iv_update_beacon = run_update_beacon;
800         vap->iv_max_aid = RT2870_WCID_MAX;
801         /*
802          * To delete the right key from h/w, we need wcid.
803          * Luckily, there is unused space in ieee80211_key{}, wk_pad,
804          * and matching wcid will be written into there. So, cast
805          * some spells to remove 'const' from ieee80211_key{}
806          */
807         vap->iv_key_delete = (void *)run_key_delete;
808         vap->iv_key_set = (void *)run_key_set;
809
810         /* override state transition machine */
811         rvp->newstate = vap->iv_newstate;
812         vap->iv_newstate = run_newstate;
813
814         ieee80211_ratectl_init(vap);
815         ieee80211_ratectl_setinterval(vap, 1000 /* 1 sec */);
816
817         /* complete setup */
818         ieee80211_vap_attach(vap, run_media_change, ieee80211_media_status);
819
820         /* make sure id is always unique */
821         for (i = 0; i < RUN_VAP_MAX; i++) {
822                 if((sc->rvp_bmap & 1 << i) == 0){
823                         sc->rvp_bmap |= 1 << i;
824                         rvp->rvp_id = i;
825                         break;
826                 }
827         }
828         if (sc->rvp_cnt++ == 0)
829                 ic->ic_opmode = opmode;
830
831         if (opmode == IEEE80211_M_HOSTAP)
832                 sc->cmdq_run = RUN_CMDQ_GO;
833
834         DPRINTF("rvp_id=%d bmap=%x rvp_cnt=%d\n",
835             rvp->rvp_id, sc->rvp_bmap, sc->rvp_cnt);
836
837         return (vap);
838 }
839
840 static void
841 run_vap_delete(struct ieee80211vap *vap)
842 {
843         struct run_vap *rvp = RUN_VAP(vap);
844         struct ifnet *ifp;
845         struct ieee80211com *ic;
846         struct run_softc *sc;
847         uint8_t rvp_id;
848
849         if (vap == NULL)
850                 return;
851
852         ic = vap->iv_ic;
853         ifp = ic->ic_ifp;
854
855         sc = ifp->if_softc;
856
857         RUN_LOCK(sc);
858
859         rvp_id = rvp->rvp_id;
860         sc->ratectl_run &= ~(1 << rvp_id);
861         sc->rvp_bmap &= ~(1 << rvp_id);
862         run_set_region_4(sc, RT2860_SKEY(rvp_id, 0), 0, 128);
863         run_set_region_4(sc, RT2860_BCN_BASE(rvp_id), 0, 512);
864         --sc->rvp_cnt;
865
866         DPRINTF("vap=%p rvp_id=%d bmap=%x rvp_cnt=%d\n",
867             vap, rvp_id, sc->rvp_bmap, sc->rvp_cnt);
868
869         RUN_UNLOCK(sc);
870
871         ieee80211_ratectl_deinit(vap);
872         ieee80211_vap_detach(vap);
873         free(rvp, M_80211_VAP);
874 }
875
876 /*
877  * There are numbers of functions need to be called in context thread.
878  * Rather than creating taskqueue event for each of those functions,
879  * here is all-for-one taskqueue callback function. This function
880  * gurantees deferred functions are executed in the same order they
881  * were enqueued.
882  * '& RUN_CMDQ_MASQ' is to loop cmdq[].
883  */
884 static void
885 run_cmdq_cb(void *arg, int pending)
886 {
887         struct run_softc *sc = arg;
888         uint8_t i;
889
890         /* call cmdq[].func locked */
891         RUN_LOCK(sc);
892         for (i = sc->cmdq_exec; sc->cmdq[i].func && pending;
893             i = sc->cmdq_exec, pending--) {
894                 DPRINTFN(6, "cmdq_exec=%d pending=%d\n", i, pending);
895                 if (sc->cmdq_run == RUN_CMDQ_GO) {
896                         /*
897                          * If arg0 is NULL, callback func needs more
898                          * than one arg. So, pass ptr to cmdq struct.
899                          */
900                         if (sc->cmdq[i].arg0)
901                                 sc->cmdq[i].func(sc->cmdq[i].arg0);
902                         else
903                                 sc->cmdq[i].func(&sc->cmdq[i]);
904                 }
905                 sc->cmdq[i].arg0 = NULL;
906                 sc->cmdq[i].func = NULL;
907                 sc->cmdq_exec++;
908                 sc->cmdq_exec &= RUN_CMDQ_MASQ;
909         }
910         RUN_UNLOCK(sc);
911 }
912
913 static void
914 run_setup_tx_list(struct run_softc *sc, struct run_endpoint_queue *pq)
915 {
916         struct run_tx_data *data;
917
918         memset(pq, 0, sizeof(*pq));
919
920         STAILQ_INIT(&pq->tx_qh);
921         STAILQ_INIT(&pq->tx_fh);
922
923         for (data = &pq->tx_data[0];
924             data < &pq->tx_data[RUN_TX_RING_COUNT]; data++) {
925                 data->sc = sc;
926                 STAILQ_INSERT_TAIL(&pq->tx_fh, data, next);
927         }
928         pq->tx_nfree = RUN_TX_RING_COUNT;
929 }
930
931 static void
932 run_unsetup_tx_list(struct run_softc *sc, struct run_endpoint_queue *pq)
933 {
934         struct run_tx_data *data;
935
936         /* make sure any subsequent use of the queues will fail */
937         pq->tx_nfree = 0;
938         STAILQ_INIT(&pq->tx_fh);
939         STAILQ_INIT(&pq->tx_qh);
940
941         /* free up all node references and mbufs */
942         for (data = &pq->tx_data[0];
943             data < &pq->tx_data[RUN_TX_RING_COUNT]; data++) {
944                 if (data->m != NULL) {
945                         m_freem(data->m);
946                         data->m = NULL;
947                 }
948                 if (data->ni != NULL) {
949                         ieee80211_free_node(data->ni);
950                         data->ni = NULL;
951                 }
952         }
953 }
954
955 int
956 run_load_microcode(struct run_softc *sc)
957 {
958         usb_device_request_t req;
959         const struct firmware *fw;
960         const u_char *base;
961         uint32_t tmp;
962         int ntries, error;
963         const uint64_t *temp;
964         uint64_t bytes;
965
966         RUN_UNLOCK(sc);
967         fw = firmware_get("runfw");
968         RUN_LOCK(sc);
969         if (fw == NULL) {
970                 device_printf(sc->sc_dev,
971                     "failed loadfirmware of file %s\n", "runfw");
972                 return ENOENT;
973         }
974
975         if (fw->datasize != 8192) {
976                 device_printf(sc->sc_dev,
977                     "invalid firmware size (should be 8KB)\n");
978                 error = EINVAL;
979                 goto fail;
980         }
981
982         /*
983          * RT3071/RT3072 use a different firmware
984          * run-rt2870 (8KB) contains both,
985          * first half (4KB) is for rt2870,
986          * last half is for rt3071.
987          */
988         base = fw->data;
989         if ((sc->mac_ver) != 0x2860 &&
990             (sc->mac_ver) != 0x2872 &&
991             (sc->mac_ver) != 0x3070) { 
992                 base += 4096;
993         }
994
995         /* cheap sanity check */
996         temp = fw->data;
997         bytes = *temp;
998         if (bytes != be64toh(0xffffff0210280210)) {
999                 device_printf(sc->sc_dev, "firmware checksum failed\n");
1000                 error = EINVAL;
1001                 goto fail;
1002         }
1003
1004         run_read(sc, RT2860_ASIC_VER_ID, &tmp);
1005         /* write microcode image */
1006         run_write_region_1(sc, RT2870_FW_BASE, base, 4096);
1007         run_write(sc, RT2860_H2M_MAILBOX_CID, 0xffffffff);
1008         run_write(sc, RT2860_H2M_MAILBOX_STATUS, 0xffffffff);
1009
1010         req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1011         req.bRequest = RT2870_RESET;
1012         USETW(req.wValue, 8);
1013         USETW(req.wIndex, 0);
1014         USETW(req.wLength, 0);
1015         if ((error = usbd_do_request(sc->sc_udev, &sc->sc_mtx, &req, NULL)) != 0) {
1016                 device_printf(sc->sc_dev, "firmware reset failed\n");
1017                 goto fail;
1018         }
1019
1020         run_delay(sc, 10);
1021
1022         run_write(sc, RT2860_H2M_MAILBOX, 0);
1023         if ((error = run_mcu_cmd(sc, RT2860_MCU_CMD_RFRESET, 0)) != 0)
1024                 goto fail;
1025
1026         /* wait until microcontroller is ready */
1027         for (ntries = 0; ntries < 1000; ntries++) {
1028                 if ((error = run_read(sc, RT2860_SYS_CTRL, &tmp)) != 0) {
1029                         goto fail;
1030                 }
1031                 if (tmp & RT2860_MCU_READY)
1032                         break;
1033                 run_delay(sc, 10);
1034         }
1035         if (ntries == 1000) {
1036                 device_printf(sc->sc_dev,
1037                     "timeout waiting for MCU to initialize\n");
1038                 error = ETIMEDOUT;
1039                 goto fail;
1040         }
1041         device_printf(sc->sc_dev, "firmware %s loaded\n",
1042             (base == fw->data) ? "RT2870" : "RT3071");
1043
1044 fail:
1045         firmware_put(fw, FIRMWARE_UNLOAD);
1046         return (error);
1047 }
1048
1049 int
1050 run_reset(struct run_softc *sc)
1051 {
1052         usb_device_request_t req;
1053
1054         req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1055         req.bRequest = RT2870_RESET;
1056         USETW(req.wValue, 1);
1057         USETW(req.wIndex, 0);
1058         USETW(req.wLength, 0);
1059         return (usbd_do_request(sc->sc_udev, &sc->sc_mtx, &req, NULL));
1060 }
1061
1062 static usb_error_t
1063 run_do_request(struct run_softc *sc,
1064     struct usb_device_request *req, void *data)
1065 {
1066         usb_error_t err;
1067         int ntries = 10;
1068
1069         RUN_LOCK_ASSERT(sc, MA_OWNED);
1070
1071         while (ntries--) {
1072                 err = usbd_do_request_flags(sc->sc_udev, &sc->sc_mtx,
1073                     req, data, 0, NULL, 250 /* ms */);
1074                 if (err == 0)
1075                         break;
1076                 DPRINTFN(1, "Control request failed, %s (retrying)\n",
1077                     usbd_errstr(err));
1078                 run_delay(sc, 10);
1079         }
1080         return (err);
1081 }
1082
1083 static int
1084 run_read(struct run_softc *sc, uint16_t reg, uint32_t *val)
1085 {
1086         uint32_t tmp;
1087         int error;
1088
1089         error = run_read_region_1(sc, reg, (uint8_t *)&tmp, sizeof tmp);
1090         if (error == 0)
1091                 *val = le32toh(tmp);
1092         else
1093                 *val = 0xffffffff;
1094         return (error);
1095 }
1096
1097 static int
1098 run_read_region_1(struct run_softc *sc, uint16_t reg, uint8_t *buf, int len)
1099 {
1100         usb_device_request_t req;
1101
1102         req.bmRequestType = UT_READ_VENDOR_DEVICE;
1103         req.bRequest = RT2870_READ_REGION_1;
1104         USETW(req.wValue, 0);
1105         USETW(req.wIndex, reg);
1106         USETW(req.wLength, len);
1107
1108         return (run_do_request(sc, &req, buf));
1109 }
1110
1111 static int
1112 run_write_2(struct run_softc *sc, uint16_t reg, uint16_t val)
1113 {
1114         usb_device_request_t req;
1115
1116         req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1117         req.bRequest = RT2870_WRITE_2;
1118         USETW(req.wValue, val);
1119         USETW(req.wIndex, reg);
1120         USETW(req.wLength, 0);
1121
1122         return (run_do_request(sc, &req, NULL));
1123 }
1124
1125 static int
1126 run_write(struct run_softc *sc, uint16_t reg, uint32_t val)
1127 {
1128         int error;
1129
1130         if ((error = run_write_2(sc, reg, val & 0xffff)) == 0)
1131                 error = run_write_2(sc, reg + 2, val >> 16);
1132         return (error);
1133 }
1134
1135 static int
1136 run_write_region_1(struct run_softc *sc, uint16_t reg, const uint8_t *buf,
1137     int len)
1138 {
1139 #if 1
1140         int i, error = 0;
1141         /*
1142          * NB: the WRITE_REGION_1 command is not stable on RT2860.
1143          * We thus issue multiple WRITE_2 commands instead.
1144          */
1145         KASSERT((len & 1) == 0, ("run_write_region_1: Data too long.\n"));
1146         for (i = 0; i < len && error == 0; i += 2)
1147                 error = run_write_2(sc, reg + i, buf[i] | buf[i + 1] << 8);
1148         return (error);
1149 #else
1150         usb_device_request_t req;
1151
1152         req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1153         req.bRequest = RT2870_WRITE_REGION_1;
1154         USETW(req.wValue, 0);
1155         USETW(req.wIndex, reg);
1156         USETW(req.wLength, len);
1157         return (run_do_request(sc, &req, buf));
1158 #endif
1159 }
1160
1161 static int
1162 run_set_region_4(struct run_softc *sc, uint16_t reg, uint32_t val, int len)
1163 {
1164         int i, error = 0;
1165
1166         KASSERT((len & 3) == 0, ("run_set_region_4: Invalid data length.\n"));
1167         for (i = 0; i < len && error == 0; i += 4)
1168                 error = run_write(sc, reg + i, val);
1169         return (error);
1170 }
1171
1172 /* Read 16-bit from eFUSE ROM (RT3070 only.) */
1173 static int
1174 run_efuse_read_2(struct run_softc *sc, uint16_t addr, uint16_t *val)
1175 {
1176         uint32_t tmp;
1177         uint16_t reg;
1178         int error, ntries;
1179
1180         if ((error = run_read(sc, RT3070_EFUSE_CTRL, &tmp)) != 0)
1181                 return (error);
1182
1183         addr *= 2;
1184         /*-
1185          * Read one 16-byte block into registers EFUSE_DATA[0-3]:
1186          * DATA0: F E D C
1187          * DATA1: B A 9 8
1188          * DATA2: 7 6 5 4
1189          * DATA3: 3 2 1 0
1190          */
1191         tmp &= ~(RT3070_EFSROM_MODE_MASK | RT3070_EFSROM_AIN_MASK);
1192         tmp |= (addr & ~0xf) << RT3070_EFSROM_AIN_SHIFT | RT3070_EFSROM_KICK;
1193         run_write(sc, RT3070_EFUSE_CTRL, tmp);
1194         for (ntries = 0; ntries < 100; ntries++) {
1195                 if ((error = run_read(sc, RT3070_EFUSE_CTRL, &tmp)) != 0)
1196                         return (error);
1197                 if (!(tmp & RT3070_EFSROM_KICK))
1198                         break;
1199                 run_delay(sc, 2);
1200         }
1201         if (ntries == 100)
1202                 return (ETIMEDOUT);
1203
1204         if ((tmp & RT3070_EFUSE_AOUT_MASK) == RT3070_EFUSE_AOUT_MASK) {
1205                 *val = 0xffff;  /* address not found */
1206                 return (0);
1207         }
1208         /* determine to which 32-bit register our 16-bit word belongs */
1209         reg = RT3070_EFUSE_DATA3 - (addr & 0xc);
1210         if ((error = run_read(sc, reg, &tmp)) != 0)
1211                 return (error);
1212
1213         *val = (addr & 2) ? tmp >> 16 : tmp & 0xffff;
1214         return (0);
1215 }
1216
1217 static int
1218 run_eeprom_read_2(struct run_softc *sc, uint16_t addr, uint16_t *val)
1219 {
1220         usb_device_request_t req;
1221         uint16_t tmp;
1222         int error;
1223
1224         addr *= 2;
1225         req.bmRequestType = UT_READ_VENDOR_DEVICE;
1226         req.bRequest = RT2870_EEPROM_READ;
1227         USETW(req.wValue, 0);
1228         USETW(req.wIndex, addr);
1229         USETW(req.wLength, sizeof tmp);
1230
1231         error = usbd_do_request(sc->sc_udev, &sc->sc_mtx, &req, &tmp);
1232         if (error == 0)
1233                 *val = le16toh(tmp);
1234         else
1235                 *val = 0xffff;
1236         return (error);
1237 }
1238
1239 static __inline int
1240 run_srom_read(struct run_softc *sc, uint16_t addr, uint16_t *val)
1241 {
1242         /* either eFUSE ROM or EEPROM */
1243         return sc->sc_srom_read(sc, addr, val);
1244 }
1245
1246 static int
1247 run_rt2870_rf_write(struct run_softc *sc, uint8_t reg, uint32_t val)
1248 {
1249         uint32_t tmp;
1250         int error, ntries;
1251
1252         for (ntries = 0; ntries < 10; ntries++) {
1253                 if ((error = run_read(sc, RT2860_RF_CSR_CFG0, &tmp)) != 0)
1254                         return (error);
1255                 if (!(tmp & RT2860_RF_REG_CTRL))
1256                         break;
1257         }
1258         if (ntries == 10)
1259                 return (ETIMEDOUT);
1260
1261         /* RF registers are 24-bit on the RT2860 */
1262         tmp = RT2860_RF_REG_CTRL | 24 << RT2860_RF_REG_WIDTH_SHIFT |
1263             (val & 0x3fffff) << 2 | (reg & 3);
1264         return (run_write(sc, RT2860_RF_CSR_CFG0, tmp));
1265 }
1266
1267 static int
1268 run_rt3070_rf_read(struct run_softc *sc, uint8_t reg, uint8_t *val)
1269 {
1270         uint32_t tmp;
1271         int error, ntries;
1272
1273         for (ntries = 0; ntries < 100; ntries++) {
1274                 if ((error = run_read(sc, RT3070_RF_CSR_CFG, &tmp)) != 0)
1275                         return (error);
1276                 if (!(tmp & RT3070_RF_KICK))
1277                         break;
1278         }
1279         if (ntries == 100)
1280                 return (ETIMEDOUT);
1281
1282         tmp = RT3070_RF_KICK | reg << 8;
1283         if ((error = run_write(sc, RT3070_RF_CSR_CFG, tmp)) != 0)
1284                 return (error);
1285
1286         for (ntries = 0; ntries < 100; ntries++) {
1287                 if ((error = run_read(sc, RT3070_RF_CSR_CFG, &tmp)) != 0)
1288                         return (error);
1289                 if (!(tmp & RT3070_RF_KICK))
1290                         break;
1291         }
1292         if (ntries == 100)
1293                 return (ETIMEDOUT);
1294
1295         *val = tmp & 0xff;
1296         return (0);
1297 }
1298
1299 static int
1300 run_rt3070_rf_write(struct run_softc *sc, uint8_t reg, uint8_t val)
1301 {
1302         uint32_t tmp;
1303         int error, ntries;
1304
1305         for (ntries = 0; ntries < 10; ntries++) {
1306                 if ((error = run_read(sc, RT3070_RF_CSR_CFG, &tmp)) != 0)
1307                         return (error);
1308                 if (!(tmp & RT3070_RF_KICK))
1309                         break;
1310         }
1311         if (ntries == 10)
1312                 return (ETIMEDOUT);
1313
1314         tmp = RT3070_RF_WRITE | RT3070_RF_KICK | reg << 8 | val;
1315         return (run_write(sc, RT3070_RF_CSR_CFG, tmp));
1316 }
1317
1318 static int
1319 run_bbp_read(struct run_softc *sc, uint8_t reg, uint8_t *val)
1320 {
1321         uint32_t tmp;
1322         int ntries, error;
1323
1324         for (ntries = 0; ntries < 10; ntries++) {
1325                 if ((error = run_read(sc, RT2860_BBP_CSR_CFG, &tmp)) != 0)
1326                         return (error);
1327                 if (!(tmp & RT2860_BBP_CSR_KICK))
1328                         break;
1329         }
1330         if (ntries == 10)
1331                 return (ETIMEDOUT);
1332
1333         tmp = RT2860_BBP_CSR_READ | RT2860_BBP_CSR_KICK | reg << 8;
1334         if ((error = run_write(sc, RT2860_BBP_CSR_CFG, tmp)) != 0)
1335                 return (error);
1336
1337         for (ntries = 0; ntries < 10; ntries++) {
1338                 if ((error = run_read(sc, RT2860_BBP_CSR_CFG, &tmp)) != 0)
1339                         return (error);
1340                 if (!(tmp & RT2860_BBP_CSR_KICK))
1341                         break;
1342         }
1343         if (ntries == 10)
1344                 return (ETIMEDOUT);
1345
1346         *val = tmp & 0xff;
1347         return (0);
1348 }
1349
1350 static int
1351 run_bbp_write(struct run_softc *sc, uint8_t reg, uint8_t val)
1352 {
1353         uint32_t tmp;
1354         int ntries, error;
1355
1356         for (ntries = 0; ntries < 10; ntries++) {
1357                 if ((error = run_read(sc, RT2860_BBP_CSR_CFG, &tmp)) != 0)
1358                         return (error);
1359                 if (!(tmp & RT2860_BBP_CSR_KICK))
1360                         break;
1361         }
1362         if (ntries == 10)
1363                 return (ETIMEDOUT);
1364
1365         tmp = RT2860_BBP_CSR_KICK | reg << 8 | val;
1366         return (run_write(sc, RT2860_BBP_CSR_CFG, tmp));
1367 }
1368
1369 /*
1370  * Send a command to the 8051 microcontroller unit.
1371  */
1372 static int
1373 run_mcu_cmd(struct run_softc *sc, uint8_t cmd, uint16_t arg)
1374 {
1375         uint32_t tmp;
1376         int error, ntries;
1377
1378         for (ntries = 0; ntries < 100; ntries++) {
1379                 if ((error = run_read(sc, RT2860_H2M_MAILBOX, &tmp)) != 0)
1380                         return error;
1381                 if (!(tmp & RT2860_H2M_BUSY))
1382                         break;
1383         }
1384         if (ntries == 100)
1385                 return ETIMEDOUT;
1386
1387         tmp = RT2860_H2M_BUSY | RT2860_TOKEN_NO_INTR << 16 | arg;
1388         if ((error = run_write(sc, RT2860_H2M_MAILBOX, tmp)) == 0)
1389                 error = run_write(sc, RT2860_HOST_CMD, cmd);
1390         return (error);
1391 }
1392
1393 /*
1394  * Add `delta' (signed) to each 4-bit sub-word of a 32-bit word.
1395  * Used to adjust per-rate Tx power registers.
1396  */
1397 static __inline uint32_t
1398 b4inc(uint32_t b32, int8_t delta)
1399 {
1400         int8_t i, b4;
1401
1402         for (i = 0; i < 8; i++) {
1403                 b4 = b32 & 0xf;
1404                 b4 += delta;
1405                 if (b4 < 0)
1406                         b4 = 0;
1407                 else if (b4 > 0xf)
1408                         b4 = 0xf;
1409                 b32 = b32 >> 4 | b4 << 28;
1410         }
1411         return (b32);
1412 }
1413
1414 static const char *
1415 run_get_rf(int rev)
1416 {
1417         switch (rev) {
1418         case RT2860_RF_2820:    return "RT2820";
1419         case RT2860_RF_2850:    return "RT2850";
1420         case RT2860_RF_2720:    return "RT2720";
1421         case RT2860_RF_2750:    return "RT2750";
1422         case RT3070_RF_3020:    return "RT3020";
1423         case RT3070_RF_2020:    return "RT2020";
1424         case RT3070_RF_3021:    return "RT3021";
1425         case RT3070_RF_3022:    return "RT3022";
1426         case RT3070_RF_3052:    return "RT3052";
1427         }
1428         return ("unknown");
1429 }
1430
1431 int
1432 run_read_eeprom(struct run_softc *sc)
1433 {
1434         int8_t delta_2ghz, delta_5ghz;
1435         uint32_t tmp;
1436         uint16_t val;
1437         int ridx, ant, i;
1438
1439         /* check whether the ROM is eFUSE ROM or EEPROM */
1440         sc->sc_srom_read = run_eeprom_read_2;
1441         if (sc->mac_ver >= 0x3070) {
1442                 run_read(sc, RT3070_EFUSE_CTRL, &tmp);
1443                 DPRINTF("EFUSE_CTRL=0x%08x\n", tmp);
1444                 if (tmp & RT3070_SEL_EFUSE)
1445                         sc->sc_srom_read = run_efuse_read_2;
1446         }
1447
1448         /* read ROM version */
1449         run_srom_read(sc, RT2860_EEPROM_VERSION, &val);
1450         DPRINTF("EEPROM rev=%d, FAE=%d\n", val & 0xff, val >> 8);
1451
1452         /* read MAC address */
1453         run_srom_read(sc, RT2860_EEPROM_MAC01, &val);
1454         sc->sc_bssid[0] = val & 0xff;
1455         sc->sc_bssid[1] = val >> 8;
1456         run_srom_read(sc, RT2860_EEPROM_MAC23, &val);
1457         sc->sc_bssid[2] = val & 0xff;
1458         sc->sc_bssid[3] = val >> 8;
1459         run_srom_read(sc, RT2860_EEPROM_MAC45, &val);
1460         sc->sc_bssid[4] = val & 0xff;
1461         sc->sc_bssid[5] = val >> 8;
1462
1463         /* read vender BBP settings */
1464         for (i = 0; i < 10; i++) {
1465                 run_srom_read(sc, RT2860_EEPROM_BBP_BASE + i, &val);
1466                 sc->bbp[i].val = val & 0xff;
1467                 sc->bbp[i].reg = val >> 8;
1468                 DPRINTF("BBP%d=0x%02x\n", sc->bbp[i].reg, sc->bbp[i].val);
1469         }
1470         if (sc->mac_ver >= 0x3071) {
1471                 /* read vendor RF settings */
1472                 for (i = 0; i < 10; i++) {
1473                         run_srom_read(sc, RT3071_EEPROM_RF_BASE + i, &val);
1474                         sc->rf[i].val = val & 0xff;
1475                         sc->rf[i].reg = val >> 8;
1476                         DPRINTF("RF%d=0x%02x\n", sc->rf[i].reg,
1477                             sc->rf[i].val);
1478                 }
1479         }
1480
1481         /* read RF frequency offset from EEPROM */
1482         run_srom_read(sc, RT2860_EEPROM_FREQ_LEDS, &val);
1483         sc->freq = ((val & 0xff) != 0xff) ? val & 0xff : 0;
1484         DPRINTF("EEPROM freq offset %d\n", sc->freq & 0xff);
1485
1486         if (val >> 8 != 0xff) {
1487                 /* read LEDs operating mode */
1488                 sc->leds = val >> 8;
1489                 run_srom_read(sc, RT2860_EEPROM_LED1, &sc->led[0]);
1490                 run_srom_read(sc, RT2860_EEPROM_LED2, &sc->led[1]);
1491                 run_srom_read(sc, RT2860_EEPROM_LED3, &sc->led[2]);
1492         } else {
1493                 /* broken EEPROM, use default settings */
1494                 sc->leds = 0x01;
1495                 sc->led[0] = 0x5555;
1496                 sc->led[1] = 0x2221;
1497                 sc->led[2] = 0x5627;    /* differs from RT2860 */
1498         }
1499         DPRINTF("EEPROM LED mode=0x%02x, LEDs=0x%04x/0x%04x/0x%04x\n",
1500             sc->leds, sc->led[0], sc->led[1], sc->led[2]);
1501
1502         /* read RF information */
1503         run_srom_read(sc, RT2860_EEPROM_ANTENNA, &val);
1504         if (val == 0xffff) {
1505                 DPRINTF("invalid EEPROM antenna info, using default\n");
1506                 if (sc->mac_ver == 0x3572) {
1507                         /* default to RF3052 2T2R */
1508                         sc->rf_rev = RT3070_RF_3052;
1509                         sc->ntxchains = 2;
1510                         sc->nrxchains = 2;
1511                 } else if (sc->mac_ver >= 0x3070) {
1512                         /* default to RF3020 1T1R */
1513                         sc->rf_rev = RT3070_RF_3020;
1514                         sc->ntxchains = 1;
1515                         sc->nrxchains = 1;
1516                 } else {
1517                         /* default to RF2820 1T2R */
1518                         sc->rf_rev = RT2860_RF_2820;
1519                         sc->ntxchains = 1;
1520                         sc->nrxchains = 2;
1521                 }
1522         } else {
1523                 sc->rf_rev = (val >> 8) & 0xf;
1524                 sc->ntxchains = (val >> 4) & 0xf;
1525                 sc->nrxchains = val & 0xf;
1526         }
1527         DPRINTF("EEPROM RF rev=0x%02x chains=%dT%dR\n",
1528             sc->rf_rev, sc->ntxchains, sc->nrxchains);
1529
1530         /* check if RF supports automatic Tx access gain control */
1531         run_srom_read(sc, RT2860_EEPROM_CONFIG, &val);
1532         DPRINTF("EEPROM CFG 0x%04x\n", val);
1533         /* check if driver should patch the DAC issue */
1534         if ((val >> 8) != 0xff)
1535                 sc->patch_dac = (val >> 15) & 1;
1536         if ((val & 0xff) != 0xff) {
1537                 sc->ext_5ghz_lna = (val >> 3) & 1;
1538                 sc->ext_2ghz_lna = (val >> 2) & 1;
1539                 /* check if RF supports automatic Tx access gain control */
1540                 sc->calib_2ghz = sc->calib_5ghz = (val >> 1) & 1;
1541                 /* check if we have a hardware radio switch */
1542                 sc->rfswitch = val & 1;
1543         }
1544
1545         /* read power settings for 2GHz channels */
1546         for (i = 0; i < 14; i += 2) {
1547                 run_srom_read(sc, RT2860_EEPROM_PWR2GHZ_BASE1 + i / 2, &val);
1548                 sc->txpow1[i + 0] = (int8_t)(val & 0xff);
1549                 sc->txpow1[i + 1] = (int8_t)(val >> 8);
1550
1551                 run_srom_read(sc, RT2860_EEPROM_PWR2GHZ_BASE2 + i / 2, &val);
1552                 sc->txpow2[i + 0] = (int8_t)(val & 0xff);
1553                 sc->txpow2[i + 1] = (int8_t)(val >> 8);
1554         }
1555         /* fix broken Tx power entries */
1556         for (i = 0; i < 14; i++) {
1557                 if (sc->txpow1[i] < 0 || sc->txpow1[i] > 31)
1558                         sc->txpow1[i] = 5;
1559                 if (sc->txpow2[i] < 0 || sc->txpow2[i] > 31)
1560                         sc->txpow2[i] = 5;
1561                 DPRINTF("chan %d: power1=%d, power2=%d\n",
1562                     rt2860_rf2850[i].chan, sc->txpow1[i], sc->txpow2[i]);
1563         }
1564         /* read power settings for 5GHz channels */
1565         for (i = 0; i < 40; i += 2) {
1566                 run_srom_read(sc, RT2860_EEPROM_PWR5GHZ_BASE1 + i / 2, &val);
1567                 sc->txpow1[i + 14] = (int8_t)(val & 0xff);
1568                 sc->txpow1[i + 15] = (int8_t)(val >> 8);
1569
1570                 run_srom_read(sc, RT2860_EEPROM_PWR5GHZ_BASE2 + i / 2, &val);
1571                 sc->txpow2[i + 14] = (int8_t)(val & 0xff);
1572                 sc->txpow2[i + 15] = (int8_t)(val >> 8);
1573         }
1574         /* fix broken Tx power entries */
1575         for (i = 0; i < 40; i++) {
1576                 if (sc->txpow1[14 + i] < -7 || sc->txpow1[14 + i] > 15)
1577                         sc->txpow1[14 + i] = 5;
1578                 if (sc->txpow2[14 + i] < -7 || sc->txpow2[14 + i] > 15)
1579                         sc->txpow2[14 + i] = 5;
1580                 DPRINTF("chan %d: power1=%d, power2=%d\n",
1581                     rt2860_rf2850[14 + i].chan, sc->txpow1[14 + i],
1582                     sc->txpow2[14 + i]);
1583         }
1584
1585         /* read Tx power compensation for each Tx rate */
1586         run_srom_read(sc, RT2860_EEPROM_DELTAPWR, &val);
1587         delta_2ghz = delta_5ghz = 0;
1588         if ((val & 0xff) != 0xff && (val & 0x80)) {
1589                 delta_2ghz = val & 0xf;
1590                 if (!(val & 0x40))      /* negative number */
1591                         delta_2ghz = -delta_2ghz;
1592         }
1593         val >>= 8;
1594         if ((val & 0xff) != 0xff && (val & 0x80)) {
1595                 delta_5ghz = val & 0xf;
1596                 if (!(val & 0x40))      /* negative number */
1597                         delta_5ghz = -delta_5ghz;
1598         }
1599         DPRINTF("power compensation=%d (2GHz), %d (5GHz)\n",
1600             delta_2ghz, delta_5ghz);
1601
1602         for (ridx = 0; ridx < 5; ridx++) {
1603                 uint32_t reg;
1604
1605                 run_srom_read(sc, RT2860_EEPROM_RPWR + ridx * 2, &val);
1606                 reg = val;
1607                 run_srom_read(sc, RT2860_EEPROM_RPWR + ridx * 2 + 1, &val);
1608                 reg |= (uint32_t)val << 16;
1609
1610                 sc->txpow20mhz[ridx] = reg;
1611                 sc->txpow40mhz_2ghz[ridx] = b4inc(reg, delta_2ghz);
1612                 sc->txpow40mhz_5ghz[ridx] = b4inc(reg, delta_5ghz);
1613
1614                 DPRINTF("ridx %d: power 20MHz=0x%08x, 40MHz/2GHz=0x%08x, "
1615                     "40MHz/5GHz=0x%08x\n", ridx, sc->txpow20mhz[ridx],
1616                     sc->txpow40mhz_2ghz[ridx], sc->txpow40mhz_5ghz[ridx]);
1617         }
1618
1619         /* read RSSI offsets and LNA gains from EEPROM */
1620         run_srom_read(sc, RT2860_EEPROM_RSSI1_2GHZ, &val);
1621         sc->rssi_2ghz[0] = val & 0xff;  /* Ant A */
1622         sc->rssi_2ghz[1] = val >> 8;    /* Ant B */
1623         run_srom_read(sc, RT2860_EEPROM_RSSI2_2GHZ, &val);
1624         if (sc->mac_ver >= 0x3070) {
1625                 /*
1626                  * On RT3070 chips (limited to 2 Rx chains), this ROM
1627                  * field contains the Tx mixer gain for the 2GHz band.
1628                  */
1629                 if ((val & 0xff) != 0xff)
1630                         sc->txmixgain_2ghz = val & 0x7;
1631                 DPRINTF("tx mixer gain=%u (2GHz)\n", sc->txmixgain_2ghz);
1632         } else
1633                 sc->rssi_2ghz[2] = val & 0xff;  /* Ant C */
1634         sc->lna[2] = val >> 8;          /* channel group 2 */
1635
1636         run_srom_read(sc, RT2860_EEPROM_RSSI1_5GHZ, &val);
1637         sc->rssi_5ghz[0] = val & 0xff;  /* Ant A */
1638         sc->rssi_5ghz[1] = val >> 8;    /* Ant B */
1639         run_srom_read(sc, RT2860_EEPROM_RSSI2_5GHZ, &val);
1640         if (sc->mac_ver == 0x3572) {
1641                 /*
1642                  * On RT3572 chips (limited to 2 Rx chains), this ROM
1643                  * field contains the Tx mixer gain for the 5GHz band.
1644                  */
1645                 if ((val & 0xff) != 0xff)
1646                         sc->txmixgain_5ghz = val & 0x7;
1647                 DPRINTF("tx mixer gain=%u (5GHz)\n", sc->txmixgain_5ghz);
1648         } else
1649                 sc->rssi_5ghz[2] = val & 0xff;  /* Ant C */
1650         sc->lna[3] = val >> 8;          /* channel group 3 */
1651
1652         run_srom_read(sc, RT2860_EEPROM_LNA, &val);
1653         sc->lna[0] = val & 0xff;        /* channel group 0 */
1654         sc->lna[1] = val >> 8;          /* channel group 1 */
1655
1656         /* fix broken 5GHz LNA entries */
1657         if (sc->lna[2] == 0 || sc->lna[2] == 0xff) {
1658                 DPRINTF("invalid LNA for channel group %d\n", 2);
1659                 sc->lna[2] = sc->lna[1];
1660         }
1661         if (sc->lna[3] == 0 || sc->lna[3] == 0xff) {
1662                 DPRINTF("invalid LNA for channel group %d\n", 3);
1663                 sc->lna[3] = sc->lna[1];
1664         }
1665
1666         /* fix broken RSSI offset entries */
1667         for (ant = 0; ant < 3; ant++) {
1668                 if (sc->rssi_2ghz[ant] < -10 || sc->rssi_2ghz[ant] > 10) {
1669                         DPRINTF("invalid RSSI%d offset: %d (2GHz)\n",
1670                             ant + 1, sc->rssi_2ghz[ant]);
1671                         sc->rssi_2ghz[ant] = 0;
1672                 }
1673                 if (sc->rssi_5ghz[ant] < -10 || sc->rssi_5ghz[ant] > 10) {
1674                         DPRINTF("invalid RSSI%d offset: %d (5GHz)\n",
1675                             ant + 1, sc->rssi_5ghz[ant]);
1676                         sc->rssi_5ghz[ant] = 0;
1677                 }
1678         }
1679         return (0);
1680 }
1681
1682 struct ieee80211_node *
1683 run_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
1684 {
1685         return malloc(sizeof (struct run_node), M_DEVBUF, M_NOWAIT | M_ZERO);
1686 }
1687
1688 static int
1689 run_media_change(struct ifnet *ifp)
1690 {
1691         struct ieee80211vap *vap = ifp->if_softc;
1692         struct ieee80211com *ic = vap->iv_ic;
1693         const struct ieee80211_txparam *tp;
1694         struct run_softc *sc = ic->ic_ifp->if_softc;
1695         uint8_t rate, ridx;
1696         int error;
1697
1698         RUN_LOCK(sc);
1699
1700         error = ieee80211_media_change(ifp);
1701         if (error != ENETRESET) {
1702                 RUN_UNLOCK(sc);
1703                 return (error);
1704         }
1705
1706         tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)];
1707         if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE) {
1708                 struct ieee80211_node *ni;
1709                 struct run_node *rn;
1710
1711                 rate = ic->ic_sup_rates[ic->ic_curmode].
1712                     rs_rates[tp->ucastrate] & IEEE80211_RATE_VAL;
1713                 for (ridx = 0; ridx < RT2860_RIDX_MAX; ridx++)
1714                         if (rt2860_rates[ridx].rate == rate)
1715                                 break;
1716                 ni = ieee80211_ref_node(vap->iv_bss);
1717                 rn = (struct run_node *)ni;
1718                 rn->fix_ridx = ridx;
1719                 DPRINTF("rate=%d, fix_ridx=%d\n", rate, rn->fix_ridx);
1720                 ieee80211_free_node(ni);
1721         }
1722
1723 #if 0
1724         if ((ifp->if_flags & IFF_UP) &&
1725             (ifp->if_drv_flags &  IFF_DRV_RUNNING)){
1726                 run_init_locked(sc);
1727         }
1728 #endif
1729
1730         RUN_UNLOCK(sc);
1731
1732         return (0);
1733 }
1734
1735 static int
1736 run_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
1737 {
1738         const struct ieee80211_txparam *tp;
1739         struct ieee80211com *ic = vap->iv_ic;
1740         struct run_softc *sc = ic->ic_ifp->if_softc;
1741         struct run_vap *rvp = RUN_VAP(vap);
1742         enum ieee80211_state ostate;
1743         uint32_t sta[3];
1744         uint32_t tmp;
1745         uint8_t ratectl;
1746         uint8_t restart_ratectl = 0;
1747         uint8_t bid = 1 << rvp->rvp_id;
1748
1749         ostate = vap->iv_state;
1750         DPRINTF("%s -> %s\n",
1751                 ieee80211_state_name[ostate],
1752                 ieee80211_state_name[nstate]);
1753
1754         IEEE80211_UNLOCK(ic);
1755         RUN_LOCK(sc);
1756
1757         ratectl = sc->ratectl_run; /* remember current state */
1758         sc->ratectl_run = RUN_RATECTL_OFF;
1759         usb_callout_stop(&sc->ratectl_ch);
1760
1761         if (ostate == IEEE80211_S_RUN) {
1762                 /* turn link LED off */
1763                 run_set_leds(sc, RT2860_LED_RADIO);
1764         }
1765
1766         switch (nstate) {
1767         case IEEE80211_S_INIT:
1768                 restart_ratectl = 1;
1769
1770                 if (ostate != IEEE80211_S_RUN)
1771                         break;
1772
1773                 ratectl &= ~bid;
1774                 sc->runbmap &= ~bid;
1775
1776                 /* abort TSF synchronization if there is no vap running */
1777                 if (--sc->running == 0) {
1778                         run_read(sc, RT2860_BCN_TIME_CFG, &tmp);
1779                         run_write(sc, RT2860_BCN_TIME_CFG,
1780                             tmp & ~(RT2860_BCN_TX_EN | RT2860_TSF_TIMER_EN |
1781                             RT2860_TBTT_TIMER_EN));
1782                 }
1783                 break;
1784
1785
1786         case IEEE80211_S_RUN:
1787                 if (!(sc->runbmap & bid)) {
1788                         if(sc->running++)
1789                                 restart_ratectl = 1;
1790                         sc->runbmap |= bid;
1791                 }
1792
1793                 switch (vap->iv_opmode) {
1794                 case IEEE80211_M_HOSTAP:
1795                 case IEEE80211_M_MBSS:
1796                         sc->ap_running |= bid;
1797                         ic->ic_opmode = vap->iv_opmode;
1798                         run_update_beacon_cb(vap);
1799                         break;
1800                 case IEEE80211_M_IBSS:
1801                         sc->adhoc_running |= bid;
1802                         if (!sc->ap_running)
1803                                 ic->ic_opmode = vap->iv_opmode;
1804                         run_update_beacon_cb(vap);
1805                         break;
1806                 case IEEE80211_M_STA:
1807                         sc->sta_running |= bid;
1808                         if (!sc->ap_running && !sc->adhoc_running)
1809                                 ic->ic_opmode = vap->iv_opmode;
1810
1811                         /* read statistic counters (clear on read) */
1812                         run_read_region_1(sc, RT2860_TX_STA_CNT0,
1813                             (uint8_t *)sta, sizeof sta);
1814
1815                         break;
1816                 default:
1817                         ic->ic_opmode = vap->iv_opmode;
1818                         break;
1819                 }
1820
1821                 if (vap->iv_opmode != IEEE80211_M_MONITOR) {
1822                         struct ieee80211_node *ni;
1823
1824                         run_updateslot(ic->ic_ifp);
1825                         run_enable_mrr(sc);
1826                         run_set_txpreamble(sc);
1827                         run_set_basicrates(sc);
1828                         ni = ieee80211_ref_node(vap->iv_bss);
1829                         IEEE80211_ADDR_COPY(sc->sc_bssid, ni->ni_bssid);
1830                         run_set_bssid(sc, ni->ni_bssid);
1831                         ieee80211_free_node(ni);
1832                         run_enable_tsf_sync(sc);
1833
1834                         /* enable automatic rate adaptation */
1835                         tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)];
1836                         if (tp->ucastrate == IEEE80211_FIXED_RATE_NONE)
1837                                 ratectl |= bid;
1838                 }
1839
1840                 /* turn link LED on */
1841                 run_set_leds(sc, RT2860_LED_RADIO |
1842                     (IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan) ?
1843                      RT2860_LED_LINK_2GHZ : RT2860_LED_LINK_5GHZ));
1844
1845                 break;
1846         default:
1847                 DPRINTFN(6, "undefined case\n");
1848                 break;
1849         }
1850
1851         /* restart amrr for running VAPs */
1852         if ((sc->ratectl_run = ratectl) && restart_ratectl)
1853                 usb_callout_reset(&sc->ratectl_ch, hz, run_ratectl_to, sc);
1854
1855         RUN_UNLOCK(sc);
1856         IEEE80211_LOCK(ic);
1857
1858         return(rvp->newstate(vap, nstate, arg));
1859 }
1860
1861 /* ARGSUSED */
1862 static void
1863 run_wme_update_cb(void *arg)
1864 {
1865         struct ieee80211com *ic = arg;
1866         struct run_softc *sc = ic->ic_ifp->if_softc;
1867         struct ieee80211_wme_state *wmesp = &ic->ic_wme;
1868         int aci, error = 0;
1869
1870         RUN_LOCK_ASSERT(sc, MA_OWNED);
1871
1872         /* update MAC TX configuration registers */
1873         for (aci = 0; aci < WME_NUM_AC; aci++) {
1874                 error = run_write(sc, RT2860_EDCA_AC_CFG(aci),
1875                     wmesp->wme_params[aci].wmep_logcwmax << 16 |
1876                     wmesp->wme_params[aci].wmep_logcwmin << 12 |
1877                     wmesp->wme_params[aci].wmep_aifsn  <<  8 |
1878                     wmesp->wme_params[aci].wmep_txopLimit);
1879                 if (error) goto err;
1880         }
1881
1882         /* update SCH/DMA registers too */
1883         error = run_write(sc, RT2860_WMM_AIFSN_CFG,
1884             wmesp->wme_params[WME_AC_VO].wmep_aifsn  << 12 |
1885             wmesp->wme_params[WME_AC_VI].wmep_aifsn  <<  8 |
1886             wmesp->wme_params[WME_AC_BK].wmep_aifsn  <<  4 |
1887             wmesp->wme_params[WME_AC_BE].wmep_aifsn);
1888         if (error) goto err;
1889         error = run_write(sc, RT2860_WMM_CWMIN_CFG,
1890             wmesp->wme_params[WME_AC_VO].wmep_logcwmin << 12 |
1891             wmesp->wme_params[WME_AC_VI].wmep_logcwmin <<  8 |
1892             wmesp->wme_params[WME_AC_BK].wmep_logcwmin <<  4 |
1893             wmesp->wme_params[WME_AC_BE].wmep_logcwmin);
1894         if (error) goto err;
1895         error = run_write(sc, RT2860_WMM_CWMAX_CFG,
1896             wmesp->wme_params[WME_AC_VO].wmep_logcwmax << 12 |
1897             wmesp->wme_params[WME_AC_VI].wmep_logcwmax <<  8 |
1898             wmesp->wme_params[WME_AC_BK].wmep_logcwmax <<  4 |
1899             wmesp->wme_params[WME_AC_BE].wmep_logcwmax);
1900         if (error) goto err;
1901         error = run_write(sc, RT2860_WMM_TXOP0_CFG,
1902             wmesp->wme_params[WME_AC_BK].wmep_txopLimit << 16 |
1903             wmesp->wme_params[WME_AC_BE].wmep_txopLimit);
1904         if (error) goto err;
1905         error = run_write(sc, RT2860_WMM_TXOP1_CFG,
1906             wmesp->wme_params[WME_AC_VO].wmep_txopLimit << 16 |
1907             wmesp->wme_params[WME_AC_VI].wmep_txopLimit);
1908
1909 err:
1910         if (error)
1911                 DPRINTF("WME update failed\n");
1912
1913         return;
1914 }
1915
1916 static int
1917 run_wme_update(struct ieee80211com *ic)
1918 {
1919         struct run_softc *sc = ic->ic_ifp->if_softc;
1920
1921         /* sometime called wothout lock */
1922         if (mtx_owned(&ic->ic_comlock.mtx)) {
1923                 uint32_t i = RUN_CMDQ_GET(&sc->cmdq_store);
1924                 DPRINTF("cmdq_store=%d\n", i);
1925                 sc->cmdq[i].func = run_wme_update_cb;
1926                 sc->cmdq[i].arg0 = ic;
1927                 ieee80211_runtask(ic, &sc->cmdq_task);
1928                 return (0);
1929         }
1930
1931         RUN_LOCK(sc);
1932         run_wme_update_cb(ic);
1933         RUN_UNLOCK(sc);
1934
1935         /* return whatever, upper layer desn't care anyway */
1936         return (0);
1937 }
1938
1939 static void
1940 run_key_update_begin(struct ieee80211vap *vap)
1941 {
1942         /*
1943          * To avoid out-of-order events, both run_key_set() and
1944          * _delete() are deferred and handled by run_cmdq_cb().
1945          * So, there is nothing we need to do here.
1946          */
1947 }
1948
1949 static void
1950 run_key_update_end(struct ieee80211vap *vap)
1951 {
1952         /* null */
1953 }
1954
1955 static void
1956 run_key_set_cb(void *arg)
1957 {
1958         struct run_cmdq *cmdq = arg;
1959         struct ieee80211vap *vap = cmdq->arg1;
1960         struct ieee80211_key *k = cmdq->k;
1961         struct ieee80211com *ic = vap->iv_ic;
1962         struct run_softc *sc = ic->ic_ifp->if_softc;
1963         struct ieee80211_node *ni;
1964         uint32_t attr;
1965         uint16_t base, associd;
1966         uint8_t mode, wcid, iv[8];
1967
1968         RUN_LOCK_ASSERT(sc, MA_OWNED);
1969
1970         if (vap->iv_opmode == IEEE80211_M_HOSTAP)
1971                 ni = ieee80211_find_vap_node(&ic->ic_sta, vap, cmdq->mac);
1972         else
1973                 ni = vap->iv_bss;
1974         associd = (ni != NULL) ? ni->ni_associd : 0;
1975
1976         /* map net80211 cipher to RT2860 security mode */
1977         switch (k->wk_cipher->ic_cipher) {
1978         case IEEE80211_CIPHER_WEP:
1979                 if(k->wk_keylen < 8)
1980                         mode = RT2860_MODE_WEP40;
1981                 else
1982                         mode = RT2860_MODE_WEP104;
1983                 break;
1984         case IEEE80211_CIPHER_TKIP:
1985                 mode = RT2860_MODE_TKIP;
1986                 break;
1987         case IEEE80211_CIPHER_AES_CCM:
1988                 mode = RT2860_MODE_AES_CCMP;
1989                 break;
1990         default:
1991                 DPRINTF("undefined case\n");
1992                 return;
1993         }
1994
1995         DPRINTFN(1, "associd=%x, keyix=%d, mode=%x, type=%s, tx=%s, rx=%s\n",
1996             associd, k->wk_keyix, mode,
1997             (k->wk_flags & IEEE80211_KEY_GROUP) ? "group" : "pairwise",
1998             (k->wk_flags & IEEE80211_KEY_XMIT) ? "on" : "off",
1999             (k->wk_flags & IEEE80211_KEY_RECV) ? "on" : "off");
2000
2001         if (k->wk_flags & IEEE80211_KEY_GROUP) {
2002                 wcid = 0;       /* NB: update WCID0 for group keys */
2003                 base = RT2860_SKEY(RUN_VAP(vap)->rvp_id, k->wk_keyix);
2004         } else {
2005                 wcid = RUN_AID2WCID(associd);
2006                 base = RT2860_PKEY(wcid);
2007         }
2008
2009         if (k->wk_cipher->ic_cipher == IEEE80211_CIPHER_TKIP) {
2010                 if(run_write_region_1(sc, base, k->wk_key, 16))
2011                         return;
2012                 if(run_write_region_1(sc, base + 16, &k->wk_key[16], 8))        /* wk_txmic */
2013                         return;
2014                 if(run_write_region_1(sc, base + 24, &k->wk_key[24], 8))        /* wk_rxmic */
2015                         return;
2016         } else {
2017                 /* roundup len to 16-bit: XXX fix write_region_1() instead */
2018                 if(run_write_region_1(sc, base, k->wk_key, (k->wk_keylen + 1) & ~1))
2019                         return;
2020         }
2021
2022         if (!(k->wk_flags & IEEE80211_KEY_GROUP) ||
2023             (k->wk_flags & (IEEE80211_KEY_XMIT | IEEE80211_KEY_RECV))) {
2024                 /* set initial packet number in IV+EIV */
2025                 if (k->wk_cipher == IEEE80211_CIPHER_WEP) {
2026                         memset(iv, 0, sizeof iv);
2027                         iv[3] = vap->iv_def_txkey << 6;
2028                 } else {
2029                         if (k->wk_cipher->ic_cipher == IEEE80211_CIPHER_TKIP) {
2030                                 iv[0] = k->wk_keytsc >> 8;
2031                                 iv[1] = (iv[0] | 0x20) & 0x7f;
2032                                 iv[2] = k->wk_keytsc;
2033                         } else /* CCMP */ {
2034                                 iv[0] = k->wk_keytsc;
2035                                 iv[1] = k->wk_keytsc >> 8;
2036                                 iv[2] = 0;
2037                         }
2038                         iv[3] = k->wk_keyix << 6 | IEEE80211_WEP_EXTIV;
2039                         iv[4] = k->wk_keytsc >> 16;
2040                         iv[5] = k->wk_keytsc >> 24;
2041                         iv[6] = k->wk_keytsc >> 32;
2042                         iv[7] = k->wk_keytsc >> 40;
2043                 }
2044                 if (run_write_region_1(sc, RT2860_IVEIV(wcid), iv, 8))
2045                         return;
2046         }
2047
2048         if (k->wk_flags & IEEE80211_KEY_GROUP) {
2049                 /* install group key */
2050                 if (run_read(sc, RT2860_SKEY_MODE_0_7, &attr))
2051                         return;
2052                 attr &= ~(0xf << (k->wk_keyix * 4));
2053                 attr |= mode << (k->wk_keyix * 4);
2054                 if (run_write(sc, RT2860_SKEY_MODE_0_7, attr))
2055                         return;
2056         } else {
2057                 /* install pairwise key */
2058                 if (run_read(sc, RT2860_WCID_ATTR(wcid), &attr))
2059                         return;
2060                 attr = (attr & ~0xf) | (mode << 1) | RT2860_RX_PKEY_EN;
2061                 if (run_write(sc, RT2860_WCID_ATTR(wcid), attr))
2062                         return;
2063         }
2064
2065         /* TODO create a pass-thru key entry? */
2066
2067         /* need wcid to delete the right key later */
2068         k->wk_pad = wcid;
2069 }
2070
2071 /*
2072  * Don't have to be deferred, but in order to keep order of
2073  * execution, i.e. with run_key_delete(), defer this and let
2074  * run_cmdq_cb() maintain the order.
2075  *
2076  * return 0 on error
2077  */
2078 static int
2079 run_key_set(struct ieee80211vap *vap, struct ieee80211_key *k,
2080                 const uint8_t mac[IEEE80211_ADDR_LEN])
2081 {
2082         struct ieee80211com *ic = vap->iv_ic;
2083         struct run_softc *sc = ic->ic_ifp->if_softc;
2084         uint32_t i;
2085
2086         i = RUN_CMDQ_GET(&sc->cmdq_store);
2087         DPRINTF("cmdq_store=%d\n", i);
2088         sc->cmdq[i].func = run_key_set_cb;
2089         sc->cmdq[i].arg0 = NULL;
2090         sc->cmdq[i].arg1 = vap;
2091         sc->cmdq[i].k = k;
2092         IEEE80211_ADDR_COPY(sc->cmdq[i].mac, mac);
2093         ieee80211_runtask(ic, &sc->cmdq_task);
2094
2095         /*
2096          * To make sure key will be set when hostapd
2097          * calls iv_key_set() before if_init().
2098          */
2099         if (vap->iv_opmode == IEEE80211_M_HOSTAP) {
2100                 RUN_LOCK(sc);
2101                 sc->cmdq_key_set = RUN_CMDQ_GO;
2102                 RUN_UNLOCK(sc);
2103         }
2104
2105         return (1);
2106 }
2107
2108 /*
2109  * If wlan is destroyed without being brought down i.e. without
2110  * wlan down or wpa_cli terminate, this function is called after
2111  * vap is gone. Don't refer it.
2112  */
2113 static void
2114 run_key_delete_cb(void *arg)
2115 {
2116         struct run_cmdq *cmdq = arg;
2117         struct run_softc *sc = cmdq->arg1;
2118         struct ieee80211_key *k = &cmdq->key;
2119         uint32_t attr;
2120         uint8_t wcid;
2121
2122         RUN_LOCK_ASSERT(sc, MA_OWNED);
2123
2124         if (k->wk_flags & IEEE80211_KEY_GROUP) {
2125                 /* remove group key */
2126                 DPRINTF("removing group key\n");
2127                 run_read(sc, RT2860_SKEY_MODE_0_7, &attr);
2128                 attr &= ~(0xf << (k->wk_keyix * 4));
2129                 run_write(sc, RT2860_SKEY_MODE_0_7, attr);
2130         } else {
2131                 /* remove pairwise key */
2132                 DPRINTF("removing key for wcid %x\n", k->wk_pad);
2133                 /* matching wcid was written to wk_pad in run_key_set() */
2134                 wcid = k->wk_pad;
2135                 run_read(sc, RT2860_WCID_ATTR(wcid), &attr);
2136                 attr &= ~0xf;
2137                 run_write(sc, RT2860_WCID_ATTR(wcid), attr);
2138                 run_set_region_4(sc, RT2860_WCID_ENTRY(wcid), 0, 8);
2139         }
2140
2141         k->wk_pad = 0;
2142 }
2143
2144 /*
2145  * return 0 on error
2146  */
2147 static int
2148 run_key_delete(struct ieee80211vap *vap, struct ieee80211_key *k)
2149 {
2150         struct ieee80211com *ic = vap->iv_ic;
2151         struct run_softc *sc = ic->ic_ifp->if_softc;
2152         struct ieee80211_key *k0;
2153         uint32_t i;
2154
2155         /*
2156          * When called back, key might be gone. So, make a copy
2157          * of some values need to delete keys before deferring.
2158          * But, because of LOR with node lock, cannot use lock here.
2159          * So, use atomic instead.
2160          */
2161         i = RUN_CMDQ_GET(&sc->cmdq_store);
2162         DPRINTF("cmdq_store=%d\n", i);
2163         sc->cmdq[i].func = run_key_delete_cb;
2164         sc->cmdq[i].arg0 = NULL;
2165         sc->cmdq[i].arg1 = sc;
2166         k0 = &sc->cmdq[i].key;
2167         k0->wk_flags = k->wk_flags;
2168         k0->wk_keyix = k->wk_keyix;
2169         /* matching wcid was written to wk_pad in run_key_set() */
2170         k0->wk_pad = k->wk_pad;
2171         ieee80211_runtask(ic, &sc->cmdq_task);
2172         return (1);     /* return fake success */
2173
2174 }
2175
2176 static void
2177 run_ratectl_to(void *arg)
2178 {
2179         struct run_softc *sc = arg;
2180
2181         /* do it in a process context, so it can go sleep */
2182         ieee80211_runtask(sc->sc_ifp->if_l2com, &sc->ratectl_task);
2183         /* next timeout will be rescheduled in the callback task */
2184 }
2185
2186 /* ARGSUSED */
2187 static void
2188 run_ratectl_cb(void *arg, int pending)
2189 {
2190         struct run_softc *sc = arg;
2191         struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2192         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2193
2194         if (vap == NULL)
2195                 return;
2196
2197         if (sc->rvp_cnt <= 1 && vap->iv_opmode == IEEE80211_M_STA)
2198                 run_iter_func(sc, vap->iv_bss);
2199         else {
2200                 /*
2201                  * run_reset_livelock() doesn't do anything with AMRR,
2202                  * but Ralink wants us to call it every 1 sec. So, we
2203                  * piggyback here rather than creating another callout.
2204                  * Livelock may occur only in HOSTAP or IBSS mode
2205                  * (when h/w is sending beacons).
2206                  */
2207                 RUN_LOCK(sc);
2208                 run_reset_livelock(sc);
2209                 /* just in case, there are some stats to drain */
2210                 run_drain_fifo(sc);
2211                 RUN_UNLOCK(sc);
2212                 ieee80211_iterate_nodes(&ic->ic_sta, run_iter_func, sc);
2213         }
2214
2215         if(sc->ratectl_run != RUN_RATECTL_OFF)
2216                 usb_callout_reset(&sc->ratectl_ch, hz, run_ratectl_to, sc);
2217 }
2218
2219 static void
2220 run_drain_fifo(void *arg)
2221 {
2222         struct run_softc *sc = arg;
2223         struct ifnet *ifp = sc->sc_ifp;
2224         struct ieee80211_node *ni = sc->sc_ni[0];       /* make compiler happy */
2225         uint32_t stat;
2226         int retrycnt = 0;
2227         uint8_t wcid, mcs, pid;
2228
2229         RUN_LOCK_ASSERT(sc, MA_OWNED);
2230
2231         for (;;) {
2232                 /* drain Tx status FIFO (maxsize = 16) */
2233                 run_read(sc, RT2860_TX_STAT_FIFO, &stat);
2234                 DPRINTFN(4, "tx stat 0x%08x\n", stat);
2235                 if (!(stat & RT2860_TXQ_VLD))
2236                         break;
2237
2238                 wcid = (stat >> RT2860_TXQ_WCID_SHIFT) & 0xff;
2239
2240                 /* if no ACK was requested, no feedback is available */
2241                 if (!(stat & RT2860_TXQ_ACKREQ) || wcid > RT2870_WCID_MAX ||
2242                     wcid == 0)
2243                         continue;
2244
2245                 ni = sc->sc_ni[wcid];
2246                 if (ni->ni_rctls == NULL)
2247                         continue;
2248
2249                 /* update per-STA AMRR stats */
2250                 if (stat & RT2860_TXQ_OK) {
2251                         /*
2252                          * Check if there were retries, ie if the Tx
2253                          * success rate is different from the requested
2254                          * rate. Note that it works only because we do
2255                          * not allow rate fallback from OFDM to CCK.
2256                          */
2257                         mcs = (stat >> RT2860_TXQ_MCS_SHIFT) & 0x7f;
2258                         pid = (stat >> RT2860_TXQ_PID_SHIFT) & 0xf;
2259                         if (mcs + 1 != pid)
2260                                 retrycnt = 1;
2261                         ieee80211_ratectl_tx_complete(ni->ni_vap, ni,
2262                             IEEE80211_RATECTL_TX_SUCCESS,
2263                             &retrycnt, NULL);
2264                 } else {
2265                         retrycnt = 1;
2266                         ieee80211_ratectl_tx_complete(ni->ni_vap, ni,
2267                             IEEE80211_RATECTL_TX_FAILURE,
2268                             &retrycnt, NULL);
2269                         ifp->if_oerrors++;
2270                 }
2271         }
2272         DPRINTFN(3, "count=%d\n", sc->fifo_cnt);
2273
2274         sc->fifo_cnt = 0;
2275 }
2276
2277 static void
2278 run_iter_func(void *arg, struct ieee80211_node *ni)
2279 {
2280         struct run_softc *sc = arg;
2281         struct ieee80211vap *vap = ni->ni_vap;
2282         struct ieee80211com *ic = ni->ni_ic;
2283         struct ifnet *ifp = ic->ic_ifp;
2284         struct run_node *rn = (void *)ni;
2285         uint32_t sta[3];
2286         int txcnt = 0, success = 0, retrycnt = 0;
2287         int error;
2288
2289         if (sc->rvp_cnt <= 1 && (vap->iv_opmode == IEEE80211_M_IBSS ||
2290             vap->iv_opmode == IEEE80211_M_STA)) {
2291                 RUN_LOCK(sc);
2292
2293                 /* read statistic counters (clear on read) and update AMRR state */
2294                 error = run_read_region_1(sc, RT2860_TX_STA_CNT0, (uint8_t *)sta,
2295                     sizeof sta);
2296                 if (error != 0)
2297                         return;
2298
2299                 DPRINTFN(3, "retrycnt=%d txcnt=%d failcnt=%d\n",
2300                     le32toh(sta[1]) >> 16, le32toh(sta[1]) & 0xffff,
2301                     le32toh(sta[0]) & 0xffff);
2302
2303                 /* count failed TX as errors */
2304                 ifp->if_oerrors += le32toh(sta[0]) & 0xffff;
2305
2306                 retrycnt =
2307                     (le32toh(sta[0]) & 0xffff) +        /* failed TX count */
2308                     (le32toh(sta[1]) >> 16);            /* TX retransmission count */
2309
2310                 txcnt =
2311                     retrycnt +
2312                     (le32toh(sta[1]) & 0xffff);         /* successful TX count */
2313
2314                 success =
2315                     (le32toh(sta[1]) >> 16) +
2316                     (le32toh(sta[1]) & 0xffff);
2317
2318                 ieee80211_ratectl_tx_update(vap, ni, &txcnt, &success,
2319                     &retrycnt);
2320
2321                 RUN_UNLOCK(sc);
2322         }
2323
2324         rn->amrr_ridx = ieee80211_ratectl_rate(ni, NULL, 0);
2325         DPRINTFN(3, "ridx=%d\n", rn->amrr_ridx);
2326 }
2327
2328 static void
2329 run_newassoc_cb(void *arg)
2330 {
2331         struct run_cmdq *cmdq = arg;
2332         struct ieee80211_node *ni = cmdq->arg1;
2333         struct run_softc *sc = ni->ni_vap->iv_ic->ic_ifp->if_softc;
2334         uint8_t wcid = cmdq->wcid;
2335
2336         RUN_LOCK_ASSERT(sc, MA_OWNED);
2337
2338         run_write_region_1(sc, RT2860_WCID_ENTRY(wcid),
2339             ni->ni_macaddr, IEEE80211_ADDR_LEN);
2340 }
2341
2342 static void
2343 run_newassoc(struct ieee80211_node *ni, int isnew)
2344 {
2345         struct run_node *rn = (void *)ni;
2346         struct ieee80211_rateset *rs = &ni->ni_rates;
2347         struct ieee80211vap *vap = ni->ni_vap;
2348         struct ieee80211com *ic = vap->iv_ic;
2349         struct run_softc *sc = ic->ic_ifp->if_softc;
2350         uint8_t rate;
2351         uint8_t ridx;
2352         uint8_t wcid = RUN_AID2WCID(ni->ni_associd);
2353         int i, j;
2354
2355         if (wcid > RT2870_WCID_MAX) {
2356                 device_printf(sc->sc_dev, "wcid=%d out of range\n", wcid);
2357                 return;
2358         }
2359
2360         /* only interested in true associations */
2361         if (isnew && ni->ni_associd != 0) {
2362
2363                 /*
2364                  * This function could is called though timeout function.
2365                  * Need to defer.
2366                  */
2367                 uint32_t cnt = RUN_CMDQ_GET(&sc->cmdq_store);
2368                 DPRINTF("cmdq_store=%d\n", cnt);
2369                 sc->cmdq[cnt].func = run_newassoc_cb;
2370                 sc->cmdq[cnt].arg0 = NULL;
2371                 sc->cmdq[cnt].arg1 = ni;
2372                 sc->cmdq[cnt].wcid = wcid;
2373                 ieee80211_runtask(ic, &sc->cmdq_task);
2374         }
2375
2376         DPRINTF("new assoc isnew=%d associd=%x addr=%s\n",
2377             isnew, ni->ni_associd, ether_sprintf(ni->ni_macaddr));
2378
2379         sc->sc_ni[wcid] = ni;
2380
2381         for (i = 0; i < rs->rs_nrates; i++) {
2382                 rate = rs->rs_rates[i] & IEEE80211_RATE_VAL;
2383                 /* convert 802.11 rate to hardware rate index */
2384                 for (ridx = 0; ridx < RT2860_RIDX_MAX; ridx++)
2385                         if (rt2860_rates[ridx].rate == rate)
2386                                 break;
2387                 rn->ridx[i] = ridx;
2388                 /* determine rate of control response frames */
2389                 for (j = i; j >= 0; j--) {
2390                         if ((rs->rs_rates[j] & IEEE80211_RATE_BASIC) &&
2391                             rt2860_rates[rn->ridx[i]].phy ==
2392                             rt2860_rates[rn->ridx[j]].phy)
2393                                 break;
2394                 }
2395                 if (j >= 0) {
2396                         rn->ctl_ridx[i] = rn->ridx[j];
2397                 } else {
2398                         /* no basic rate found, use mandatory one */
2399                         rn->ctl_ridx[i] = rt2860_rates[ridx].ctl_ridx;
2400                 }
2401                 DPRINTF("rate=0x%02x ridx=%d ctl_ridx=%d\n",
2402                     rs->rs_rates[i], rn->ridx[i], rn->ctl_ridx[i]);
2403         }
2404         rate = vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)].mgmtrate;
2405         for (ridx = 0; ridx < RT2860_RIDX_MAX; ridx++)
2406                 if (rt2860_rates[ridx].rate == rate)
2407                         break;
2408         rn->mgt_ridx = ridx;
2409         DPRINTF("rate=%d, mgmt_ridx=%d\n", rate, rn->mgt_ridx);
2410
2411         usb_callout_reset(&sc->ratectl_ch, hz, run_ratectl_to, sc);
2412 }
2413
2414 /*
2415  * Return the Rx chain with the highest RSSI for a given frame.
2416  */
2417 static __inline uint8_t
2418 run_maxrssi_chain(struct run_softc *sc, const struct rt2860_rxwi *rxwi)
2419 {
2420         uint8_t rxchain = 0;
2421
2422         if (sc->nrxchains > 1) {
2423                 if (rxwi->rssi[1] > rxwi->rssi[rxchain])
2424                         rxchain = 1;
2425                 if (sc->nrxchains > 2)
2426                         if (rxwi->rssi[2] > rxwi->rssi[rxchain])
2427                                 rxchain = 2;
2428         }
2429         return (rxchain);
2430 }
2431
2432 static void
2433 run_rx_frame(struct run_softc *sc, struct mbuf *m, uint32_t dmalen)
2434 {
2435         struct ifnet *ifp = sc->sc_ifp;
2436         struct ieee80211com *ic = ifp->if_l2com;
2437         struct ieee80211_frame *wh;
2438         struct ieee80211_node *ni;
2439         struct rt2870_rxd *rxd;
2440         struct rt2860_rxwi *rxwi;
2441         uint32_t flags;
2442         uint16_t len, phy;
2443         uint8_t ant, rssi;
2444         int8_t nf;
2445
2446         rxwi = mtod(m, struct rt2860_rxwi *);
2447         len = le16toh(rxwi->len) & 0xfff;
2448         if (__predict_false(len > dmalen)) {
2449                 m_freem(m);
2450                 ifp->if_ierrors++;
2451                 DPRINTF("bad RXWI length %u > %u\n", len, dmalen);
2452                 return;
2453         }
2454         /* Rx descriptor is located at the end */
2455         rxd = (struct rt2870_rxd *)(mtod(m, caddr_t) + dmalen);
2456         flags = le32toh(rxd->flags);
2457
2458         if (__predict_false(flags & (RT2860_RX_CRCERR | RT2860_RX_ICVERR))) {
2459                 m_freem(m);
2460                 ifp->if_ierrors++;
2461                 DPRINTF("%s error.\n", (flags & RT2860_RX_CRCERR)?"CRC":"ICV");
2462                 return;
2463         }
2464
2465         m->m_data += sizeof(struct rt2860_rxwi);
2466         m->m_pkthdr.len = m->m_len -= sizeof(struct rt2860_rxwi);
2467
2468         wh = mtod(m, struct ieee80211_frame *);
2469
2470         if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
2471                 wh->i_fc[1] &= ~IEEE80211_FC1_WEP;
2472                 m->m_flags |= M_WEP;
2473         }
2474
2475         if (flags & RT2860_RX_L2PAD) {
2476                 DPRINTFN(8, "received RT2860_RX_L2PAD frame\n");
2477                 len += 2;
2478         }
2479
2480         ni = ieee80211_find_rxnode(ic,
2481             mtod(m, struct ieee80211_frame_min *));
2482
2483         if (__predict_false(flags & RT2860_RX_MICERR)) {
2484                 /* report MIC failures to net80211 for TKIP */
2485                 if (ni != NULL)
2486                         ieee80211_notify_michael_failure(ni->ni_vap, wh, rxwi->keyidx);
2487                 m_freem(m);
2488                 ifp->if_ierrors++;
2489                 DPRINTF("MIC error. Someone is lying.\n");
2490                 return;
2491         }
2492
2493         ant = run_maxrssi_chain(sc, rxwi);
2494         rssi = rxwi->rssi[ant];
2495         nf = run_rssi2dbm(sc, rssi, ant);
2496
2497         m->m_pkthdr.rcvif = ifp;
2498         m->m_pkthdr.len = m->m_len = len;
2499
2500         if (ni != NULL) {
2501                 (void)ieee80211_input(ni, m, rssi, nf);
2502                 ieee80211_free_node(ni);
2503         } else {
2504                 (void)ieee80211_input_all(ic, m, rssi, nf);
2505         }
2506
2507         if (__predict_false(ieee80211_radiotap_active(ic))) {
2508                 struct run_rx_radiotap_header *tap = &sc->sc_rxtap;
2509
2510                 tap->wr_flags = 0;
2511                 tap->wr_chan_freq = htole16(ic->ic_bsschan->ic_freq);
2512                 tap->wr_chan_flags = htole16(ic->ic_bsschan->ic_flags);
2513                 tap->wr_antsignal = rssi;
2514                 tap->wr_antenna = ant;
2515                 tap->wr_dbm_antsignal = run_rssi2dbm(sc, rssi, ant);
2516                 tap->wr_rate = 2;       /* in case it can't be found below */
2517                 phy = le16toh(rxwi->phy);
2518                 switch (phy & RT2860_PHY_MODE) {
2519                 case RT2860_PHY_CCK:
2520                         switch ((phy & RT2860_PHY_MCS) & ~RT2860_PHY_SHPRE) {
2521                         case 0: tap->wr_rate =   2; break;
2522                         case 1: tap->wr_rate =   4; break;
2523                         case 2: tap->wr_rate =  11; break;
2524                         case 3: tap->wr_rate =  22; break;
2525                         }
2526                         if (phy & RT2860_PHY_SHPRE)
2527                                 tap->wr_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
2528                         break;
2529                 case RT2860_PHY_OFDM:
2530                         switch (phy & RT2860_PHY_MCS) {
2531                         case 0: tap->wr_rate =  12; break;
2532                         case 1: tap->wr_rate =  18; break;
2533                         case 2: tap->wr_rate =  24; break;
2534                         case 3: tap->wr_rate =  36; break;
2535                         case 4: tap->wr_rate =  48; break;
2536                         case 5: tap->wr_rate =  72; break;
2537                         case 6: tap->wr_rate =  96; break;
2538                         case 7: tap->wr_rate = 108; break;
2539                         }
2540                         break;
2541                 }
2542         }
2543 }
2544
2545 static void
2546 run_bulk_rx_callback(struct usb_xfer *xfer, usb_error_t error)
2547 {
2548         struct run_softc *sc = usbd_xfer_softc(xfer);
2549         struct ifnet *ifp = sc->sc_ifp;
2550         struct mbuf *m = NULL;
2551         struct mbuf *m0;
2552         uint32_t dmalen;
2553         int xferlen;
2554
2555         usbd_xfer_status(xfer, &xferlen, NULL, NULL, NULL);
2556
2557         switch (USB_GET_STATE(xfer)) {
2558         case USB_ST_TRANSFERRED:
2559
2560                 DPRINTFN(15, "rx done, actlen=%d\n", xferlen);
2561
2562                 if (xferlen < sizeof (uint32_t) +
2563                     sizeof (struct rt2860_rxwi) + sizeof (struct rt2870_rxd)) {
2564                         DPRINTF("xfer too short %d\n", xferlen);
2565                         goto tr_setup;
2566                 }
2567
2568                 m = sc->rx_m;
2569                 sc->rx_m = NULL;
2570
2571                 /* FALLTHROUGH */
2572         case USB_ST_SETUP:
2573 tr_setup:
2574                 if (sc->rx_m == NULL) {
2575                         sc->rx_m = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR,
2576                             MJUMPAGESIZE /* xfer can be bigger than MCLBYTES */);
2577                 }
2578                 if (sc->rx_m == NULL) {
2579                         DPRINTF("could not allocate mbuf - idle with stall\n");
2580                         ifp->if_ierrors++;
2581                         usbd_xfer_set_stall(xfer);
2582                         usbd_xfer_set_frames(xfer, 0);
2583                 } else {
2584                         /*
2585                          * Directly loading a mbuf cluster into DMA to
2586                          * save some data copying. This works because
2587                          * there is only one cluster.
2588                          */
2589                         usbd_xfer_set_frame_data(xfer, 0, 
2590                             mtod(sc->rx_m, caddr_t), RUN_MAX_RXSZ);
2591                         usbd_xfer_set_frames(xfer, 1);
2592                 }
2593                 usbd_transfer_submit(xfer);
2594                 break;
2595
2596         default:        /* Error */
2597                 if (error != USB_ERR_CANCELLED) {
2598                         /* try to clear stall first */
2599                         usbd_xfer_set_stall(xfer);
2600
2601                         if (error == USB_ERR_TIMEOUT)
2602                                 device_printf(sc->sc_dev, "device timeout\n");
2603
2604                         ifp->if_ierrors++;
2605
2606                         goto tr_setup;
2607                 }
2608                 if (sc->rx_m != NULL) {
2609                         m_freem(sc->rx_m);
2610                         sc->rx_m = NULL;
2611                 }
2612                 break;
2613         }
2614
2615         if (m == NULL)
2616                 return;
2617
2618         /* inputting all the frames must be last */
2619
2620         RUN_UNLOCK(sc);
2621
2622         m->m_pkthdr.len = m->m_len = xferlen;
2623
2624         /* HW can aggregate multiple 802.11 frames in a single USB xfer */
2625         for(;;) {
2626                 dmalen = le32toh(*mtod(m, uint32_t *)) & 0xffff;
2627
2628                 if ((dmalen == 0) || ((dmalen & 3) != 0)) {
2629                         DPRINTF("bad DMA length %u\n", dmalen);
2630                         break;
2631                 }
2632                 if ((dmalen + 8) > xferlen) {
2633                         DPRINTF("bad DMA length %u > %d\n",
2634                         dmalen + 8, xferlen);
2635                         break;
2636                 }
2637
2638                 /* If it is the last one or a single frame, we won't copy. */
2639                 if ((xferlen -= dmalen + 8) <= 8) {
2640                         /* trim 32-bit DMA-len header */
2641                         m->m_data += 4;
2642                         m->m_pkthdr.len = m->m_len -= 4;
2643                         run_rx_frame(sc, m, dmalen);
2644                         break;
2645                 }
2646
2647                 /* copy aggregated frames to another mbuf */
2648                 m0 = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
2649                 if (__predict_false(m0 == NULL)) {
2650                         DPRINTF("could not allocate mbuf\n");
2651                         ifp->if_ierrors++;
2652                         break;
2653                 }
2654                 m_copydata(m, 4 /* skip 32-bit DMA-len header */,
2655                     dmalen + sizeof(struct rt2870_rxd), mtod(m0, caddr_t));
2656                 m0->m_pkthdr.len = m0->m_len =
2657                     dmalen + sizeof(struct rt2870_rxd);
2658                 run_rx_frame(sc, m0, dmalen);
2659
2660                 /* update data ptr */
2661                 m->m_data += dmalen + 8;
2662                 m->m_pkthdr.len = m->m_len -= dmalen + 8;
2663         }
2664
2665         RUN_LOCK(sc);
2666 }
2667
2668 static void
2669 run_tx_free(struct run_endpoint_queue *pq,
2670     struct run_tx_data *data, int txerr)
2671 {
2672         if (data->m != NULL) {
2673                 if (data->m->m_flags & M_TXCB)
2674                         ieee80211_process_callback(data->ni, data->m,
2675                             txerr ? ETIMEDOUT : 0);
2676                 m_freem(data->m);
2677                 data->m = NULL;
2678
2679                 if (data->ni == NULL) {
2680                         DPRINTF("no node\n");
2681                 } else {
2682                         ieee80211_free_node(data->ni);
2683                         data->ni = NULL;
2684                 }
2685         }
2686
2687         STAILQ_INSERT_TAIL(&pq->tx_fh, data, next);
2688         pq->tx_nfree++;
2689 }
2690
2691 static void
2692 run_bulk_tx_callbackN(struct usb_xfer *xfer, usb_error_t error, unsigned int index)
2693 {
2694         struct run_softc *sc = usbd_xfer_softc(xfer);
2695         struct ifnet *ifp = sc->sc_ifp;
2696         struct ieee80211com *ic = ifp->if_l2com;
2697         struct run_tx_data *data;
2698         struct ieee80211vap *vap = NULL;
2699         struct usb_page_cache *pc;
2700         struct run_endpoint_queue *pq = &sc->sc_epq[index];
2701         struct mbuf *m;
2702         usb_frlength_t size;
2703         unsigned int len;
2704         int actlen;
2705         int sumlen;
2706
2707         usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
2708
2709         switch (USB_GET_STATE(xfer)) {
2710         case USB_ST_TRANSFERRED:
2711                 DPRINTFN(11, "transfer complete: %d "
2712                     "bytes @ index %d\n", actlen, index);
2713
2714                 data = usbd_xfer_get_priv(xfer);
2715
2716                 run_tx_free(pq, data, 0);
2717                 ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
2718
2719                 usbd_xfer_set_priv(xfer, NULL);
2720
2721                 ifp->if_opackets++;
2722
2723                 /* FALLTHROUGH */
2724         case USB_ST_SETUP:
2725 tr_setup:
2726                 data = STAILQ_FIRST(&pq->tx_qh);
2727                 if (data == NULL)
2728                         break;
2729
2730                 STAILQ_REMOVE_HEAD(&pq->tx_qh, next);
2731
2732                 m = data->m;
2733                 if (m->m_pkthdr.len > RUN_MAX_TXSZ) {
2734                         DPRINTF("data overflow, %u bytes\n",
2735                             m->m_pkthdr.len);
2736
2737                         ifp->if_oerrors++;
2738
2739                         run_tx_free(pq, data, 1);
2740
2741                         goto tr_setup;
2742                 }
2743
2744                 pc = usbd_xfer_get_frame(xfer, 0);
2745                 size = sizeof(data->desc);
2746                 usbd_copy_in(pc, 0, &data->desc, size);
2747                 usbd_m_copy_in(pc, size, m, 0, m->m_pkthdr.len);
2748
2749                 vap = data->ni->ni_vap;
2750                 if (ieee80211_radiotap_active_vap(vap)) {
2751                         struct run_tx_radiotap_header *tap = &sc->sc_txtap;
2752                         struct rt2860_txwi *txwi =
2753                             (struct rt2860_txwi *)(&data->desc + sizeof(struct rt2870_txd));
2754
2755                         tap->wt_flags = 0;
2756                         tap->wt_rate = rt2860_rates[data->ridx].rate;
2757                         tap->wt_chan_freq = htole16(vap->iv_bss->ni_chan->ic_freq);
2758                         tap->wt_chan_flags = htole16(vap->iv_bss->ni_chan->ic_flags);
2759                         tap->wt_hwqueue = index;
2760                         if (le16toh(txwi->phy) & RT2860_PHY_SHPRE)
2761                                 tap->wt_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
2762
2763                         ieee80211_radiotap_tx(vap, m);
2764                 }
2765
2766                 /* align end on a 4-bytes boundary */
2767                 len = (size + IEEE80211_CRC_LEN + m->m_pkthdr.len + 3) & ~3;
2768
2769                 DPRINTFN(11, "sending frame len=%u xferlen=%u @ index %d\n",
2770                         m->m_pkthdr.len, len, index);
2771
2772                 usbd_xfer_set_frame_len(xfer, 0, len);
2773                 usbd_xfer_set_priv(xfer, data);
2774
2775                 usbd_transfer_submit(xfer);
2776
2777                 RUN_UNLOCK(sc);
2778                 run_start(ifp);
2779                 RUN_LOCK(sc);
2780
2781                 break;
2782
2783         default:
2784                 DPRINTF("USB transfer error, %s\n",
2785                     usbd_errstr(error));
2786
2787                 data = usbd_xfer_get_priv(xfer);
2788
2789                 ifp->if_oerrors++;
2790
2791                 if (data != NULL) {
2792                         if(data->ni != NULL)
2793                                 vap = data->ni->ni_vap;
2794                         run_tx_free(pq, data, error);
2795                         usbd_xfer_set_priv(xfer, NULL);
2796                 }
2797                 if (vap == NULL)
2798                         vap = TAILQ_FIRST(&ic->ic_vaps);
2799
2800                 if (error != USB_ERR_CANCELLED) {
2801                         if (error == USB_ERR_TIMEOUT) {
2802                                 device_printf(sc->sc_dev, "device timeout\n");
2803                                 uint32_t i = RUN_CMDQ_GET(&sc->cmdq_store);
2804                                 DPRINTF("cmdq_store=%d\n", i);
2805                                 sc->cmdq[i].func = run_usb_timeout_cb;
2806                                 sc->cmdq[i].arg0 = vap;
2807                                 ieee80211_runtask(ic, &sc->cmdq_task);
2808                         }
2809
2810                         /*
2811                          * Try to clear stall first, also if other
2812                          * errors occur, hence clearing stall
2813                          * introduces a 50 ms delay:
2814                          */
2815                         usbd_xfer_set_stall(xfer);
2816                         goto tr_setup;
2817                 }
2818                 break;
2819         }
2820 }
2821
2822 static void
2823 run_bulk_tx_callback0(struct usb_xfer *xfer, usb_error_t error)
2824 {
2825         run_bulk_tx_callbackN(xfer, error, 0);
2826 }
2827
2828 static void
2829 run_bulk_tx_callback1(struct usb_xfer *xfer, usb_error_t error)
2830 {
2831         run_bulk_tx_callbackN(xfer, error, 1);
2832 }
2833
2834 static void
2835 run_bulk_tx_callback2(struct usb_xfer *xfer, usb_error_t error)
2836 {
2837         run_bulk_tx_callbackN(xfer, error, 2);
2838 }
2839
2840 static void
2841 run_bulk_tx_callback3(struct usb_xfer *xfer, usb_error_t error)
2842 {
2843         run_bulk_tx_callbackN(xfer, error, 3);
2844 }
2845
2846 static void
2847 run_bulk_tx_callback4(struct usb_xfer *xfer, usb_error_t error)
2848 {
2849         run_bulk_tx_callbackN(xfer, error, 4);
2850 }
2851
2852 static void
2853 run_bulk_tx_callback5(struct usb_xfer *xfer, usb_error_t error)
2854 {
2855         run_bulk_tx_callbackN(xfer, error, 5);
2856 }
2857
2858 static void
2859 run_set_tx_desc(struct run_softc *sc, struct run_tx_data *data)
2860 {
2861         struct mbuf *m = data->m;
2862         struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2863         struct ieee80211vap *vap = data->ni->ni_vap;
2864         struct ieee80211_frame *wh;
2865         struct rt2870_txd *txd;
2866         struct rt2860_txwi *txwi;
2867         uint16_t xferlen;
2868         uint16_t mcs;
2869         uint8_t ridx = data->ridx;
2870         uint8_t pad;
2871
2872         /* get MCS code from rate index */
2873         mcs = rt2860_rates[ridx].mcs;
2874
2875         xferlen = sizeof(*txwi) + m->m_pkthdr.len;
2876
2877         /* roundup to 32-bit alignment */
2878         xferlen = (xferlen + 3) & ~3;
2879
2880         txd = (struct rt2870_txd *)&data->desc;
2881         txd->len = htole16(xferlen);
2882
2883         wh = mtod(m, struct ieee80211_frame *);
2884
2885         /*
2886          * Ether both are true or both are false, the header
2887          * are nicely aligned to 32-bit. So, no L2 padding.
2888          */
2889         if(IEEE80211_HAS_ADDR4(wh) == IEEE80211_QOS_HAS_SEQ(wh))
2890                 pad = 0;
2891         else
2892                 pad = 2;
2893
2894         /* setup TX Wireless Information */
2895         txwi = (struct rt2860_txwi *)(txd + 1);
2896         txwi->len = htole16(m->m_pkthdr.len - pad);
2897         if (rt2860_rates[ridx].phy == IEEE80211_T_DS) {
2898                 txwi->phy = htole16(RT2860_PHY_CCK);
2899                 if (ridx != RT2860_RIDX_CCK1 &&
2900                     (ic->ic_flags & IEEE80211_F_SHPREAMBLE))
2901                         mcs |= RT2860_PHY_SHPRE;
2902         } else
2903                 txwi->phy = htole16(RT2860_PHY_OFDM);
2904         txwi->phy |= htole16(mcs);
2905
2906         /* check if RTS/CTS or CTS-to-self protection is required */
2907         if (!IEEE80211_IS_MULTICAST(wh->i_addr1) &&
2908             (m->m_pkthdr.len + IEEE80211_CRC_LEN > vap->iv_rtsthreshold ||
2909              ((ic->ic_flags & IEEE80211_F_USEPROT) &&
2910               rt2860_rates[ridx].phy == IEEE80211_T_OFDM)))
2911                 txwi->txop |= RT2860_TX_TXOP_HT;
2912         else
2913                 txwi->txop |= RT2860_TX_TXOP_BACKOFF;
2914
2915         if (vap->iv_opmode != IEEE80211_M_STA && !IEEE80211_QOS_HAS_SEQ(wh))
2916                 txwi->xflags |= RT2860_TX_NSEQ;
2917 }
2918
2919 /* This function must be called locked */
2920 static int
2921 run_tx(struct run_softc *sc, struct mbuf *m, struct ieee80211_node *ni)
2922 {
2923         struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2924         struct ieee80211vap *vap = ni->ni_vap;
2925         struct ieee80211_frame *wh;
2926         struct ieee80211_channel *chan;
2927         const struct ieee80211_txparam *tp;
2928         struct run_node *rn = (void *)ni;
2929         struct run_tx_data *data;
2930         struct rt2870_txd *txd;
2931         struct rt2860_txwi *txwi;
2932         uint16_t qos;
2933         uint16_t dur;
2934         uint16_t qid;
2935         uint8_t type;
2936         uint8_t tid;
2937         uint8_t ridx;
2938         uint8_t ctl_ridx;
2939         uint8_t qflags;
2940         uint8_t xflags = 0;
2941         int hasqos;
2942
2943         RUN_LOCK_ASSERT(sc, MA_OWNED);
2944
2945         wh = mtod(m, struct ieee80211_frame *);
2946
2947         type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
2948
2949         /*
2950          * There are 7 bulk endpoints: 1 for RX
2951          * and 6 for TX (4 EDCAs + HCCA + Prio).
2952          * Update 03-14-2009:  some devices like the Planex GW-US300MiniS
2953          * seem to have only 4 TX bulk endpoints (Fukaumi Naoki).
2954          */
2955         if ((hasqos = IEEE80211_QOS_HAS_SEQ(wh))) {
2956                 uint8_t *frm;
2957
2958                 if(IEEE80211_HAS_ADDR4(wh))
2959                         frm = ((struct ieee80211_qosframe_addr4 *)wh)->i_qos;
2960                 else
2961                         frm =((struct ieee80211_qosframe *)wh)->i_qos;
2962
2963                 qos = le16toh(*(const uint16_t *)frm);
2964                 tid = qos & IEEE80211_QOS_TID;
2965                 qid = TID_TO_WME_AC(tid);
2966         } else {
2967                 qos = 0;
2968                 tid = 0;
2969                 qid = WME_AC_BE;
2970         }
2971         qflags = (qid < 4) ? RT2860_TX_QSEL_EDCA : RT2860_TX_QSEL_HCCA;
2972
2973         DPRINTFN(8, "qos %d\tqid %d\ttid %d\tqflags %x\n",
2974             qos, qid, tid, qflags);
2975
2976         chan = (ni->ni_chan != IEEE80211_CHAN_ANYC)?ni->ni_chan:ic->ic_curchan;
2977         tp = &vap->iv_txparms[ieee80211_chan2mode(chan)];
2978
2979         /* pickup a rate index */
2980         if (IEEE80211_IS_MULTICAST(wh->i_addr1) ||
2981             type != IEEE80211_FC0_TYPE_DATA) {
2982                 ridx = (ic->ic_curmode == IEEE80211_MODE_11A) ?
2983                     RT2860_RIDX_OFDM6 : RT2860_RIDX_CCK1;
2984                 ctl_ridx = rt2860_rates[ridx].ctl_ridx;
2985         } else {
2986                 if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE)
2987                         ridx = rn->fix_ridx;
2988                 else
2989                         ridx = rn->amrr_ridx;
2990                 ctl_ridx = rt2860_rates[ridx].ctl_ridx;
2991         }
2992
2993         if (!IEEE80211_IS_MULTICAST(wh->i_addr1) &&
2994             (!hasqos || (qos & IEEE80211_QOS_ACKPOLICY) !=
2995              IEEE80211_QOS_ACKPOLICY_NOACK)) {
2996                 xflags |= RT2860_TX_ACK;
2997                 if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
2998                         dur = rt2860_rates[ctl_ridx].sp_ack_dur;
2999                 else
3000                         dur = rt2860_rates[ctl_ridx].lp_ack_dur;
3001                 *(uint16_t *)wh->i_dur = htole16(dur);
3002         }
3003
3004         /* reserve slots for mgmt packets, just in case */
3005         if (sc->sc_epq[qid].tx_nfree < 3) {
3006                 DPRINTFN(10, "tx ring %d is full\n", qid);
3007                 return (-1);
3008         }
3009
3010         data = STAILQ_FIRST(&sc->sc_epq[qid].tx_fh);
3011         STAILQ_REMOVE_HEAD(&sc->sc_epq[qid].tx_fh, next);
3012         sc->sc_epq[qid].tx_nfree--;
3013
3014         txd = (struct rt2870_txd *)&data->desc;
3015         txd->flags = qflags;
3016         txwi = (struct rt2860_txwi *)(txd + 1);
3017         txwi->xflags = xflags;
3018         txwi->wcid = IEEE80211_IS_MULTICAST(wh->i_addr1) ?
3019             0 : RUN_AID2WCID(ni->ni_associd);
3020         /* clear leftover garbage bits */
3021         txwi->flags = 0;
3022         txwi->txop = 0;
3023
3024         data->m = m;
3025         data->ni = ni;
3026         data->ridx = ridx;
3027
3028         run_set_tx_desc(sc, data);
3029
3030         /*
3031          * The chip keeps track of 2 kind of Tx stats,
3032          *  * TX_STAT_FIFO, for per WCID stats, and
3033          *  * TX_STA_CNT0 for all-TX-in-one stats.
3034          *
3035          * To use FIFO stats, we need to store MCS into the driver-private
3036          * PacketID field. So that, we can tell whose stats when we read them.
3037          * We add 1 to the MCS because setting the PacketID field to 0 means
3038          * that we don't want feedback in TX_STAT_FIFO.
3039          * And, that's what we want for STA mode, since TX_STA_CNT0 does the job.
3040          *
3041          * FIFO stats doesn't count Tx with WCID 0xff, so we do this in run_tx().
3042          */
3043         if (sc->rvp_cnt > 1 || vap->iv_opmode == IEEE80211_M_HOSTAP ||
3044             vap->iv_opmode == IEEE80211_M_MBSS) {
3045                 uint16_t pid = (rt2860_rates[ridx].mcs + 1) & 0xf;
3046                 txwi->len |= htole16(pid << RT2860_TX_PID_SHIFT);
3047
3048                 /*
3049                  * Unlike PCI based devices, we don't get any interrupt from
3050                  * USB devices, so we simulate FIFO-is-full interrupt here.
3051                  * Ralink recomends to drain FIFO stats every 100 ms, but 16 slots
3052                  * quickly get fulled. To prevent overflow, increment a counter on
3053                  * every FIFO stat request, so we know how many slots are left.
3054                  * We do this only in HOSTAP or multiple vap mode since FIFO stats
3055                  * are used only in those modes.
3056                  * We just drain stats. AMRR gets updated every 1 sec by
3057                  * run_ratectl_cb() via callout.
3058                  * Call it early. Otherwise overflow.
3059                  */
3060                 if (sc->fifo_cnt++ == 10) {
3061                         /*
3062                          * With multiple vaps or if_bridge, if_start() is called
3063                          * with a non-sleepable lock, tcpinp. So, need to defer.
3064                          */
3065                         uint32_t i = RUN_CMDQ_GET(&sc->cmdq_store);
3066                         DPRINTFN(6, "cmdq_store=%d\n", i);
3067                         sc->cmdq[i].func = run_drain_fifo;
3068                         sc->cmdq[i].arg0 = sc;
3069                         ieee80211_runtask(ic, &sc->cmdq_task);
3070                 }
3071         }
3072
3073         STAILQ_INSERT_TAIL(&sc->sc_epq[qid].tx_qh, data, next);
3074
3075         usbd_transfer_start(sc->sc_xfer[qid]);
3076
3077         DPRINTFN(8, "sending data frame len=%d rate=%d qid=%d\n", m->m_pkthdr.len +
3078             (int)(sizeof (struct rt2870_txd) + sizeof (struct rt2860_rxwi)),
3079             rt2860_rates[ridx].rate, qid);
3080
3081         return (0);
3082 }
3083
3084 static int
3085 run_tx_mgt(struct run_softc *sc, struct mbuf *m, struct ieee80211_node *ni)
3086 {
3087         struct ifnet *ifp = sc->sc_ifp;
3088         struct ieee80211com *ic = ifp->if_l2com;
3089         struct run_node *rn = (void *)ni;
3090         struct run_tx_data *data;
3091         struct ieee80211_frame *wh;
3092         struct rt2870_txd *txd;
3093         struct rt2860_txwi *txwi;
3094         uint16_t dur;
3095         uint8_t ridx = rn->mgt_ridx;
3096         uint8_t type;
3097         uint8_t xflags = 0;
3098         uint8_t wflags = 0;
3099
3100         RUN_LOCK_ASSERT(sc, MA_OWNED);
3101
3102         wh = mtod(m, struct ieee80211_frame *);
3103
3104         type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
3105
3106         /* tell hardware to add timestamp for probe responses */
3107         if ((wh->i_fc[0] &
3108             (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) ==
3109             (IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_RESP))
3110                 wflags |= RT2860_TX_TS;
3111         else if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
3112                 xflags |= RT2860_TX_ACK;
3113
3114                 dur = ieee80211_ack_duration(ic->ic_rt, rt2860_rates[ridx].rate, 
3115                     ic->ic_flags & IEEE80211_F_SHPREAMBLE);
3116                 *(uint16_t *)wh->i_dur = htole16(dur);
3117         }
3118
3119         if (sc->sc_epq[0].tx_nfree == 0) {
3120                 /* let caller free mbuf */
3121                 ifp->if_drv_flags |= IFF_DRV_OACTIVE;
3122                 return (EIO);
3123         }
3124         data = STAILQ_FIRST(&sc->sc_epq[0].tx_fh);
3125         STAILQ_REMOVE_HEAD(&sc->sc_epq[0].tx_fh, next);
3126         sc->sc_epq[0].tx_nfree--;
3127
3128         txd = (struct rt2870_txd *)&data->desc;
3129         txd->flags = RT2860_TX_QSEL_EDCA;
3130         txwi = (struct rt2860_txwi *)(txd + 1);
3131         txwi->wcid = 0xff;
3132         txwi->flags = wflags;
3133         txwi->xflags = xflags;
3134         txwi->txop = 0; /* clear leftover garbage bits */
3135
3136         data->m = m;
3137         data->ni = ni;
3138         data->ridx = ridx;
3139
3140         run_set_tx_desc(sc, data);
3141
3142         DPRINTFN(10, "sending mgt frame len=%d rate=%d\n", m->m_pkthdr.len +
3143             (int)(sizeof (struct rt2870_txd) + sizeof (struct rt2860_rxwi)),
3144             rt2860_rates[ridx].rate);
3145
3146         STAILQ_INSERT_TAIL(&sc->sc_epq[0].tx_qh, data, next);
3147
3148         usbd_transfer_start(sc->sc_xfer[0]);
3149
3150         return (0);
3151 }
3152
3153 static int
3154 run_sendprot(struct run_softc *sc,
3155     const struct mbuf *m, struct ieee80211_node *ni, int prot, int rate)
3156 {
3157         struct ieee80211com *ic = ni->ni_ic;
3158         struct ieee80211_frame *wh;
3159         struct run_tx_data *data;
3160         struct rt2870_txd *txd;
3161         struct rt2860_txwi *txwi;
3162         struct mbuf *mprot;
3163         int ridx;
3164         int protrate;
3165         int ackrate;
3166         int pktlen;
3167         int isshort;
3168         uint16_t dur;
3169         uint8_t type;
3170         uint8_t wflags = 0;
3171         uint8_t xflags = 0;
3172
3173         RUN_LOCK_ASSERT(sc, MA_OWNED);
3174
3175         KASSERT(prot == IEEE80211_PROT_RTSCTS || prot == IEEE80211_PROT_CTSONLY,
3176             ("protection %d", prot));
3177
3178         wh = mtod(m, struct ieee80211_frame *);
3179         pktlen = m->m_pkthdr.len + IEEE80211_CRC_LEN;
3180         type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
3181
3182         protrate = ieee80211_ctl_rate(ic->ic_rt, rate);
3183         ackrate = ieee80211_ack_rate(ic->ic_rt, rate);
3184
3185         isshort = (ic->ic_flags & IEEE80211_F_SHPREAMBLE) != 0;
3186         dur = ieee80211_compute_duration(ic->ic_rt, pktlen, rate, isshort)
3187             + ieee80211_ack_duration(ic->ic_rt, rate, isshort);
3188         wflags = RT2860_TX_FRAG;
3189
3190         /* check that there are free slots before allocating the mbuf */
3191         if (sc->sc_epq[0].tx_nfree == 0) {
3192                 /* let caller free mbuf */
3193                 sc->sc_ifp->if_drv_flags |= IFF_DRV_OACTIVE;
3194                 return (ENOBUFS);
3195         }
3196
3197         if (prot == IEEE80211_PROT_RTSCTS) {
3198                 /* NB: CTS is the same size as an ACK */
3199                 dur += ieee80211_ack_duration(ic->ic_rt, rate, isshort);
3200                 xflags |= RT2860_TX_ACK;
3201                 mprot = ieee80211_alloc_rts(ic, wh->i_addr1, wh->i_addr2, dur);
3202         } else {
3203                 mprot = ieee80211_alloc_cts(ic, ni->ni_vap->iv_myaddr, dur);
3204         }
3205         if (mprot == NULL) {
3206                 sc->sc_ifp->if_oerrors++;
3207                 DPRINTF("could not allocate mbuf\n");
3208                 return (ENOBUFS);
3209         }
3210
3211         data = STAILQ_FIRST(&sc->sc_epq[0].tx_fh);
3212         STAILQ_REMOVE_HEAD(&sc->sc_epq[0].tx_fh, next);
3213         sc->sc_epq[0].tx_nfree--;
3214
3215         txd = (struct rt2870_txd *)&data->desc;
3216         txd->flags = RT2860_TX_QSEL_EDCA;
3217         txwi = (struct rt2860_txwi *)(txd + 1);
3218         txwi->wcid = 0xff;
3219         txwi->flags = wflags;
3220         txwi->xflags = xflags;
3221         txwi->txop = 0; /* clear leftover garbage bits */
3222
3223         data->m = mprot;
3224         data->ni = ieee80211_ref_node(ni);
3225
3226         for (ridx = 0; ridx < RT2860_RIDX_MAX; ridx++)
3227                 if (rt2860_rates[ridx].rate == protrate)
3228                         break;
3229         data->ridx = ridx;
3230
3231         run_set_tx_desc(sc, data);
3232
3233         DPRINTFN(1, "sending prot len=%u rate=%u\n",
3234             m->m_pkthdr.len, rate);
3235
3236         STAILQ_INSERT_TAIL(&sc->sc_epq[0].tx_qh, data, next);
3237
3238         usbd_transfer_start(sc->sc_xfer[0]);
3239
3240         return (0);
3241 }
3242
3243 static int
3244 run_tx_param(struct run_softc *sc, struct mbuf *m, struct ieee80211_node *ni,
3245     const struct ieee80211_bpf_params *params)
3246 {
3247         struct ieee80211com *ic = ni->ni_ic;
3248         struct ieee80211_frame *wh;
3249         struct run_tx_data *data;
3250         struct rt2870_txd *txd;
3251         struct rt2860_txwi *txwi;
3252         uint8_t type;
3253         uint8_t ridx;
3254         uint8_t rate;
3255         uint8_t opflags = 0;
3256         uint8_t xflags = 0;
3257         int error;
3258
3259         RUN_LOCK_ASSERT(sc, MA_OWNED);
3260
3261         KASSERT(params != NULL, ("no raw xmit params"));
3262
3263         wh = mtod(m, struct ieee80211_frame *);
3264         type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
3265
3266         rate = params->ibp_rate0;
3267         if (!ieee80211_isratevalid(ic->ic_rt, rate)) {
3268                 /* let caller free mbuf */
3269                 return (EINVAL);
3270         }
3271
3272         if ((params->ibp_flags & IEEE80211_BPF_NOACK) == 0)
3273                 xflags |= RT2860_TX_ACK;
3274         if (params->ibp_flags & (IEEE80211_BPF_RTS|IEEE80211_BPF_CTS)) {
3275                 error = run_sendprot(sc, m, ni,
3276                     params->ibp_flags & IEEE80211_BPF_RTS ?
3277                         IEEE80211_PROT_RTSCTS : IEEE80211_PROT_CTSONLY,
3278                     rate);
3279                 if (error) {
3280                         /* let caller free mbuf */
3281                         return error;
3282                 }
3283                 opflags |= /*XXX RT2573_TX_LONG_RETRY |*/ RT2860_TX_TXOP_SIFS;
3284         }
3285
3286         if (sc->sc_epq[0].tx_nfree == 0) {
3287                 /* let caller free mbuf */
3288                 sc->sc_ifp->if_drv_flags |= IFF_DRV_OACTIVE;
3289                 DPRINTF("sending raw frame, but tx ring is full\n");
3290                 return (EIO);
3291         }
3292         data = STAILQ_FIRST(&sc->sc_epq[0].tx_fh);
3293         STAILQ_REMOVE_HEAD(&sc->sc_epq[0].tx_fh, next);
3294         sc->sc_epq[0].tx_nfree--;
3295
3296         txd = (struct rt2870_txd *)&data->desc;
3297         txd->flags = RT2860_TX_QSEL_EDCA;
3298         txwi = (struct rt2860_txwi *)(txd + 1);
3299         txwi->wcid = 0xff;
3300         txwi->xflags = xflags;
3301         txwi->txop = opflags;
3302         txwi->flags = 0;        /* clear leftover garbage bits */
3303
3304         data->m = m;
3305         data->ni = ni;
3306         for (ridx = 0; ridx < RT2860_RIDX_MAX; ridx++)
3307                 if (rt2860_rates[ridx].rate == rate)
3308                         break;
3309         data->ridx = ridx;
3310
3311         run_set_tx_desc(sc, data);
3312
3313         DPRINTFN(10, "sending raw frame len=%u rate=%u\n",
3314             m->m_pkthdr.len, rate);
3315
3316         STAILQ_INSERT_TAIL(&sc->sc_epq[0].tx_qh, data, next);
3317
3318         usbd_transfer_start(sc->sc_xfer[0]);
3319
3320         return (0);
3321 }
3322
3323 static int
3324 run_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
3325     const struct ieee80211_bpf_params *params)
3326 {
3327         struct ifnet *ifp = ni->ni_ic->ic_ifp;
3328         struct run_softc *sc = ifp->if_softc;
3329         int error = 0;
3330  
3331         RUN_LOCK(sc);
3332
3333         /* prevent management frames from being sent if we're not ready */
3334         if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
3335                 error =  ENETDOWN;
3336                 goto done;
3337         }
3338
3339         if (params == NULL) {
3340                 /* tx mgt packet */
3341                 if ((error = run_tx_mgt(sc, m, ni)) != 0) {
3342                         ifp->if_oerrors++;
3343                         DPRINTF("mgt tx failed\n");
3344                         goto done;
3345                 }
3346         } else {
3347                 /* tx raw packet with param */
3348                 if ((error = run_tx_param(sc, m, ni, params)) != 0) {
3349                         ifp->if_oerrors++;
3350                         DPRINTF("tx with param failed\n");
3351                         goto done;
3352                 }
3353         }
3354
3355         ifp->if_opackets++;
3356
3357 done:
3358         RUN_UNLOCK(sc);
3359
3360         if (error != 0) {
3361                 if(m != NULL)
3362                         m_freem(m);
3363                 ieee80211_free_node(ni);
3364         }
3365
3366         return (error);
3367 }
3368
3369 static void
3370 run_start(struct ifnet *ifp)
3371 {
3372         struct run_softc *sc = ifp->if_softc;
3373         struct ieee80211_node *ni;
3374         struct mbuf *m;
3375
3376         RUN_LOCK(sc);
3377
3378         if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
3379                 RUN_UNLOCK(sc);
3380                 return;
3381         }
3382
3383         for (;;) {
3384                 /* send data frames */
3385                 IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
3386                 if (m == NULL)
3387                         break;
3388
3389                 ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
3390                 if (run_tx(sc, m, ni) != 0) {
3391                         IFQ_DRV_PREPEND(&ifp->if_snd, m);
3392                         ifp->if_drv_flags |= IFF_DRV_OACTIVE;
3393                         break;
3394                 }
3395         }
3396
3397         RUN_UNLOCK(sc);
3398 }
3399
3400 static int
3401 run_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
3402 {
3403         struct run_softc *sc = ifp->if_softc;
3404         struct ieee80211com *ic = sc->sc_ifp->if_l2com;
3405         struct ifreq *ifr = (struct ifreq *) data;
3406         int startall = 0;
3407         int error = 0;
3408
3409         switch (cmd) {
3410         case SIOCSIFFLAGS:
3411                 RUN_LOCK(sc);
3412                 if (ifp->if_flags & IFF_UP) {
3413                         if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)){
3414                                 startall = 1;
3415                                 run_init_locked(sc);
3416                         } else
3417                                 run_update_promisc_locked(ifp);
3418                 } else {
3419                         if (ifp->if_drv_flags & IFF_DRV_RUNNING &&
3420                             (ic->ic_nrunning == 0 || sc->rvp_cnt <= 1)) {
3421                                         run_stop(sc);
3422                         }
3423                 }
3424                 RUN_UNLOCK(sc);
3425                 if (startall)
3426                         ieee80211_start_all(ic);
3427                 break;
3428         case SIOCGIFMEDIA:
3429                 error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
3430                 break;
3431         case SIOCGIFADDR:
3432                 error = ether_ioctl(ifp, cmd, data);
3433                 break;
3434         default:
3435                 error = EINVAL;
3436                 break;
3437         }
3438
3439         return (error);
3440 }
3441
3442 static void
3443 run_set_agc(struct run_softc *sc, uint8_t agc)
3444 {
3445         uint8_t bbp;
3446
3447         if (sc->mac_ver == 0x3572) {
3448                 run_bbp_read(sc, 27, &bbp);
3449                 bbp &= ~(0x3 << 5);
3450                 run_bbp_write(sc, 27, bbp | 0 << 5);    /* select Rx0 */
3451                 run_bbp_write(sc, 66, agc);
3452                 run_bbp_write(sc, 27, bbp | 1 << 5);    /* select Rx1 */
3453                 run_bbp_write(sc, 66, agc);
3454         } else
3455                 run_bbp_write(sc, 66, agc);
3456 }
3457
3458 static void
3459 run_select_chan_group(struct run_softc *sc, int group)
3460 {
3461         uint32_t tmp;
3462         uint8_t agc;
3463
3464         run_bbp_write(sc, 62, 0x37 - sc->lna[group]);
3465         run_bbp_write(sc, 63, 0x37 - sc->lna[group]);
3466         run_bbp_write(sc, 64, 0x37 - sc->lna[group]);
3467         run_bbp_write(sc, 86, 0x00);
3468
3469         if (group == 0) {
3470                 if (sc->ext_2ghz_lna) {
3471                         run_bbp_write(sc, 82, 0x62);
3472                         run_bbp_write(sc, 75, 0x46);
3473                 } else {
3474                         run_bbp_write(sc, 82, 0x84);
3475                         run_bbp_write(sc, 75, 0x50);
3476                 }
3477         } else {
3478                 if (sc->mac_ver == 0x3572)
3479                         run_bbp_write(sc, 82, 0x94);
3480                 else
3481                         run_bbp_write(sc, 82, 0xf2);
3482                 if (sc->ext_5ghz_lna)
3483                         run_bbp_write(sc, 75, 0x46);
3484                 else 
3485                         run_bbp_write(sc, 75, 0x50);
3486         }
3487
3488         run_read(sc, RT2860_TX_BAND_CFG, &tmp);
3489         tmp &= ~(RT2860_5G_BAND_SEL_N | RT2860_5G_BAND_SEL_P);
3490         tmp |= (group == 0) ? RT2860_5G_BAND_SEL_N : RT2860_5G_BAND_SEL_P;
3491         run_write(sc, RT2860_TX_BAND_CFG, tmp);
3492
3493         /* enable appropriate Power Amplifiers and Low Noise Amplifiers */
3494         tmp = RT2860_RFTR_EN | RT2860_TRSW_EN | RT2860_LNA_PE0_EN;
3495         if (sc->nrxchains > 1)
3496                 tmp |= RT2860_LNA_PE1_EN;
3497         if (group == 0) {       /* 2GHz */
3498                 tmp |= RT2860_PA_PE_G0_EN;
3499                 if (sc->ntxchains > 1)
3500                         tmp |= RT2860_PA_PE_G1_EN;
3501         } else {                /* 5GHz */
3502                 tmp |= RT2860_PA_PE_A0_EN;
3503                 if (sc->ntxchains > 1)
3504                         tmp |= RT2860_PA_PE_A1_EN;
3505         }
3506         if (sc->mac_ver == 0x3572) {
3507                 run_rt3070_rf_write(sc, 8, 0x00);
3508                 run_write(sc, RT2860_TX_PIN_CFG, tmp);
3509                 run_rt3070_rf_write(sc, 8, 0x80);
3510         } else
3511                 run_write(sc, RT2860_TX_PIN_CFG, tmp);
3512
3513         /* set initial AGC value */
3514         if (group == 0) {       /* 2GHz band */
3515                 if (sc->mac_ver >= 0x3070)
3516                         agc = 0x1c + sc->lna[0] * 2;
3517                 else
3518                         agc = 0x2e + sc->lna[0];
3519         } else {                /* 5GHz band */
3520                 if (sc->mac_ver == 0x3572)
3521                         agc = 0x22 + (sc->lna[group] * 5) / 3;
3522                 else
3523                         agc = 0x32 + (sc->lna[group] * 5) / 3;
3524         }
3525         run_set_agc(sc, agc);
3526 }
3527
3528 static void
3529 run_rt2870_set_chan(struct run_softc *sc, uint32_t chan)
3530 {
3531         const struct rfprog *rfprog = rt2860_rf2850;
3532         uint32_t r2, r3, r4;
3533         int8_t txpow1, txpow2;
3534         int i;
3535
3536         /* find the settings for this channel (we know it exists) */
3537         for (i = 0; rfprog[i].chan != chan; i++);
3538
3539         r2 = rfprog[i].r2;
3540         if (sc->ntxchains == 1)
3541                 r2 |= 1 << 12;          /* 1T: disable Tx chain 2 */
3542         if (sc->nrxchains == 1)
3543                 r2 |= 1 << 15 | 1 << 4; /* 1R: disable Rx chains 2 & 3 */
3544         else if (sc->nrxchains == 2)
3545                 r2 |= 1 << 4;           /* 2R: disable Rx chain 3 */
3546
3547         /* use Tx power values from EEPROM */
3548         txpow1 = sc->txpow1[i];
3549         txpow2 = sc->txpow2[i];
3550         if (chan > 14) {
3551                 if (txpow1 >= 0)
3552                         txpow1 = txpow1 << 1 | 1;
3553                 else
3554                         txpow1 = (7 + txpow1) << 1;
3555                 if (txpow2 >= 0)
3556                         txpow2 = txpow2 << 1 | 1;
3557                 else
3558                         txpow2 = (7 + txpow2) << 1;
3559         }
3560         r3 = rfprog[i].r3 | txpow1 << 7;
3561         r4 = rfprog[i].r4 | sc->freq << 13 | txpow2 << 4;
3562
3563         run_rt2870_rf_write(sc, RT2860_RF1, rfprog[i].r1);
3564         run_rt2870_rf_write(sc, RT2860_RF2, r2);
3565         run_rt2870_rf_write(sc, RT2860_RF3, r3);
3566         run_rt2870_rf_write(sc, RT2860_RF4, r4);
3567
3568         run_delay(sc, 10);
3569
3570         run_rt2870_rf_write(sc, RT2860_RF1, rfprog[i].r1);
3571         run_rt2870_rf_write(sc, RT2860_RF2, r2);
3572         run_rt2870_rf_write(sc, RT2860_RF3, r3 | 1);
3573         run_rt2870_rf_write(sc, RT2860_RF4, r4);
3574
3575         run_delay(sc, 10);
3576
3577         run_rt2870_rf_write(sc, RT2860_RF1, rfprog[i].r1);
3578         run_rt2870_rf_write(sc, RT2860_RF2, r2);
3579         run_rt2870_rf_write(sc, RT2860_RF3, r3);
3580         run_rt2870_rf_write(sc, RT2860_RF4, r4);
3581 }
3582
3583 static void
3584 run_rt3070_set_chan(struct run_softc *sc, uint32_t chan)
3585 {
3586         int8_t txpow1, txpow2;
3587         uint8_t rf;
3588         int i;
3589
3590         /* RT3070 is 2GHz only */
3591         KASSERT(chan >= 1 && chan <= 14, ("wrong channel selected\n"));
3592
3593         /* find the settings for this channel (we know it exists) */
3594         for (i = 0; rt2860_rf2850[i].chan != chan; i++);
3595
3596         /* use Tx power values from EEPROM */
3597         txpow1 = sc->txpow1[i];
3598         txpow2 = sc->txpow2[i];
3599
3600         run_rt3070_rf_write(sc, 2, rt3070_freqs[i].n);
3601         run_rt3070_rf_write(sc, 3, rt3070_freqs[i].k);
3602         run_rt3070_rf_read(sc, 6, &rf);
3603         rf = (rf & ~0x03) | rt3070_freqs[i].r;
3604         run_rt3070_rf_write(sc, 6, rf);
3605
3606         /* set Tx0 power */
3607         run_rt3070_rf_read(sc, 12, &rf);
3608         rf = (rf & ~0x1f) | txpow1;
3609         run_rt3070_rf_write(sc, 12, rf);
3610
3611         /* set Tx1 power */
3612         run_rt3070_rf_read(sc, 13, &rf);
3613         rf = (rf & ~0x1f) | txpow2;
3614         run_rt3070_rf_write(sc, 13, rf);
3615
3616         run_rt3070_rf_read(sc, 1, &rf);
3617         rf &= ~0xfc;
3618         if (sc->ntxchains == 1)
3619                 rf |= 1 << 7 | 1 << 5;  /* 1T: disable Tx chains 2 & 3 */
3620         else if (sc->ntxchains == 2)
3621                 rf |= 1 << 7;           /* 2T: disable Tx chain 3 */
3622         if (sc->nrxchains == 1)
3623                 rf |= 1 << 6 | 1 << 4;  /* 1R: disable Rx chains 2 & 3 */
3624         else if (sc->nrxchains == 2)
3625                 rf |= 1 << 6;           /* 2R: disable Rx chain 3 */
3626         run_rt3070_rf_write(sc, 1, rf);
3627
3628         /* set RF offset */
3629         run_rt3070_rf_read(sc, 23, &rf);
3630         rf = (rf & ~0x7f) | sc->freq;
3631         run_rt3070_rf_write(sc, 23, rf);
3632
3633         /* program RF filter */
3634         run_rt3070_rf_read(sc, 24, &rf);        /* Tx */
3635         rf = (rf & ~0x3f) | sc->rf24_20mhz;
3636         run_rt3070_rf_write(sc, 24, rf);
3637         run_rt3070_rf_read(sc, 31, &rf);        /* Rx */
3638         rf = (rf & ~0x3f) | sc->rf24_20mhz;
3639         run_rt3070_rf_write(sc, 31, rf);
3640
3641         /* enable RF tuning */
3642         run_rt3070_rf_read(sc, 7, &rf);
3643         run_rt3070_rf_write(sc, 7, rf | 0x01);
3644 }
3645
3646 static void
3647 run_rt3572_set_chan(struct run_softc *sc, u_int chan)
3648 {
3649         int8_t txpow1, txpow2;
3650         uint32_t tmp;
3651         uint8_t rf;
3652         int i;
3653
3654         /* find the settings for this channel (we know it exists) */
3655         for (i = 0; rt2860_rf2850[i].chan != chan; i++);
3656
3657         /* use Tx power values from EEPROM */
3658         txpow1 = sc->txpow1[i];
3659         txpow2 = sc->txpow2[i];
3660
3661         if (chan <= 14) {
3662                 run_bbp_write(sc, 25, sc->bbp25);
3663                 run_bbp_write(sc, 26, sc->bbp26);
3664         } else {
3665                 /* enable IQ phase correction */
3666                 run_bbp_write(sc, 25, 0x09);
3667                 run_bbp_write(sc, 26, 0xff);
3668         }
3669
3670         run_rt3070_rf_write(sc, 2, rt3070_freqs[i].n);
3671         run_rt3070_rf_write(sc, 3, rt3070_freqs[i].k);
3672         run_rt3070_rf_read(sc, 6, &rf);
3673         rf  = (rf & ~0x0f) | rt3070_freqs[i].r;
3674         rf |= (chan <= 14) ? 0x08 : 0x04;
3675         run_rt3070_rf_write(sc, 6, rf);
3676
3677         /* set PLL mode */
3678         run_rt3070_rf_read(sc, 5, &rf);
3679         rf &= ~(0x08 | 0x04);
3680         rf |= (chan <= 14) ? 0x04 : 0x08;
3681         run_rt3070_rf_write(sc, 5, rf);
3682
3683         /* set Tx power for chain 0 */
3684         if (chan <= 14)
3685                 rf = 0x60 | txpow1;
3686         else
3687                 rf = 0xe0 | (txpow1 & 0xc) << 1 | (txpow1 & 0x3);
3688         run_rt3070_rf_write(sc, 12, rf);
3689
3690         /* set Tx power for chain 1 */
3691         if (chan <= 14)
3692                 rf = 0x60 | txpow2;
3693         else
3694                 rf = 0xe0 | (txpow2 & 0xc) << 1 | (txpow2 & 0x3);
3695         run_rt3070_rf_write(sc, 13, rf);
3696
3697         /* set Tx/Rx streams */
3698         run_rt3070_rf_read(sc, 1, &rf);
3699         rf &= ~0xfc;
3700         if (sc->ntxchains == 1)
3701                 rf |= 1 << 7 | 1 << 5;  /* 1T: disable Tx chains 2 & 3 */
3702         else if (sc->ntxchains == 2)
3703                 rf |= 1 << 7;           /* 2T: disable Tx chain 3 */
3704         if (sc->nrxchains == 1)
3705                 rf |= 1 << 6 | 1 << 4;  /* 1R: disable Rx chains 2 & 3 */
3706         else if (sc->nrxchains == 2)
3707                 rf |= 1 << 6;           /* 2R: disable Rx chain 3 */
3708         run_rt3070_rf_write(sc, 1, rf);
3709
3710         /* set RF offset */
3711         run_rt3070_rf_read(sc, 23, &rf);
3712         rf = (rf & ~0x7f) | sc->freq;
3713         run_rt3070_rf_write(sc, 23, rf);
3714
3715         /* program RF filter */
3716         rf = sc->rf24_20mhz;
3717         run_rt3070_rf_write(sc, 24, rf);        /* Tx */
3718         run_rt3070_rf_write(sc, 31, rf);        /* Rx */
3719
3720         /* enable RF tuning */
3721         run_rt3070_rf_read(sc, 7, &rf);
3722         rf = (chan <= 14) ? 0xd8 : ((rf & ~0xc8) | 0x14);
3723         run_rt3070_rf_write(sc, 7, rf);
3724
3725         /* TSSI */
3726         rf = (chan <= 14) ? 0xc3 : 0xc0;
3727         run_rt3070_rf_write(sc, 9, rf);
3728
3729         /* set loop filter 1 */
3730         run_rt3070_rf_write(sc, 10, 0xf1);
3731         /* set loop filter 2 */
3732         run_rt3070_rf_write(sc, 11, (chan <= 14) ? 0xb9 : 0x00);
3733
3734         /* set tx_mx2_ic */
3735         run_rt3070_rf_write(sc, 15, (chan <= 14) ? 0x53 : 0x43);
3736         /* set tx_mx1_ic */
3737         if (chan <= 14)
3738                 rf = 0x48 | sc->txmixgain_2ghz;
3739         else
3740                 rf = 0x78 | sc->txmixgain_5ghz;
3741         run_rt3070_rf_write(sc, 16, rf);
3742
3743         /* set tx_lo1 */
3744         run_rt3070_rf_write(sc, 17, 0x23);
3745         /* set tx_lo2 */
3746         if (chan <= 14)
3747                 rf = 0x93;
3748         else if (chan <= 64)
3749                 rf = 0xb7;
3750         else if (chan <= 128)
3751                 rf = 0x74;
3752         else
3753                 rf = 0x72;
3754         run_rt3070_rf_write(sc, 19, rf);
3755
3756         /* set rx_lo1 */
3757         if (chan <= 14)
3758                 rf = 0xb3;
3759         else if (chan <= 64)
3760                 rf = 0xf6;
3761         else if (chan <= 128)
3762                 rf = 0xf4;
3763         else
3764                 rf = 0xf3;
3765         run_rt3070_rf_write(sc, 20, rf);
3766
3767         /* set pfd_delay */
3768         if (chan <= 14)
3769                 rf = 0x15;
3770         else if (chan <= 64)
3771                 rf = 0x3d;
3772         else
3773                 rf = 0x01;
3774         run_rt3070_rf_write(sc, 25, rf);
3775
3776         /* set rx_lo2 */
3777         run_rt3070_rf_write(sc, 26, (chan <= 14) ? 0x85 : 0x87);
3778         /* set ldo_rf_vc */
3779         run_rt3070_rf_write(sc, 27, (chan <= 14) ? 0x00 : 0x01);
3780         /* set drv_cc */
3781         run_rt3070_rf_write(sc, 29, (chan <= 14) ? 0x9b : 0x9f);
3782
3783         run_read(sc, RT2860_GPIO_CTRL, &tmp);
3784         tmp &= ~0x8080;
3785         if (chan <= 14)
3786                 tmp |= 0x80;
3787         run_write(sc, RT2860_GPIO_CTRL, tmp);
3788
3789         /* enable RF tuning */
3790         run_rt3070_rf_read(sc, 7, &rf);
3791         run_rt3070_rf_write(sc, 7, rf | 0x01);
3792
3793         run_delay(sc, 2);
3794 }
3795
3796 static void
3797 run_set_rx_antenna(struct run_softc *sc, int aux)
3798 {
3799         uint32_t tmp;
3800
3801         if (aux) {
3802                 run_mcu_cmd(sc, RT2860_MCU_CMD_ANTSEL, 0);
3803                 run_read(sc, RT2860_GPIO_CTRL, &tmp);
3804                 run_write(sc, RT2860_GPIO_CTRL, (tmp & ~0x0808) | 0x08);
3805         } else {
3806                 run_mcu_cmd(sc, RT2860_MCU_CMD_ANTSEL, 1);
3807                 run_read(sc, RT2860_GPIO_CTRL, &tmp);
3808                 run_write(sc, RT2860_GPIO_CTRL, tmp & ~0x0808);
3809         }
3810 }
3811
3812 static int
3813 run_set_chan(struct run_softc *sc, struct ieee80211_channel *c)
3814 {
3815         struct ieee80211com *ic = sc->sc_ifp->if_l2com;
3816         uint32_t chan, group;
3817
3818         chan = ieee80211_chan2ieee(ic, c);
3819         if (chan == 0 || chan == IEEE80211_CHAN_ANY)
3820                 return (EINVAL);
3821
3822         if (sc->mac_ver == 0x3572)
3823                 run_rt3572_set_chan(sc, chan);
3824         else if (sc->mac_ver >= 0x3070)
3825                 run_rt3070_set_chan(sc, chan);
3826         else
3827                 run_rt2870_set_chan(sc, chan);
3828
3829         /* determine channel group */
3830         if (chan <= 14)
3831                 group = 0;
3832         else if (chan <= 64)
3833                 group = 1;
3834         else if (chan <= 128)
3835                 group = 2;
3836         else
3837                 group = 3;
3838
3839         /* XXX necessary only when group has changed! */
3840         run_select_chan_group(sc, group);
3841
3842         run_delay(sc, 10);
3843
3844         return (0);
3845 }
3846
3847 static void
3848 run_set_channel(struct ieee80211com *ic)
3849 {
3850         struct run_softc *sc = ic->ic_ifp->if_softc;
3851
3852         RUN_LOCK(sc);
3853         run_set_chan(sc, ic->ic_curchan);
3854         RUN_UNLOCK(sc);
3855
3856         return;
3857 }
3858
3859 static void
3860 run_scan_start(struct ieee80211com *ic)
3861 {
3862         struct run_softc *sc = ic->ic_ifp->if_softc;
3863         uint32_t tmp;
3864
3865         RUN_LOCK(sc);
3866
3867         /* abort TSF synchronization */
3868         run_read(sc, RT2860_BCN_TIME_CFG, &tmp);
3869         run_write(sc, RT2860_BCN_TIME_CFG,
3870             tmp & ~(RT2860_BCN_TX_EN | RT2860_TSF_TIMER_EN |
3871             RT2860_TBTT_TIMER_EN));
3872         run_set_bssid(sc, sc->sc_ifp->if_broadcastaddr);
3873
3874         RUN_UNLOCK(sc);
3875
3876         return;
3877 }
3878
3879 static void
3880 run_scan_end(struct ieee80211com *ic)
3881 {
3882         struct run_softc *sc = ic->ic_ifp->if_softc;
3883
3884         RUN_LOCK(sc);
3885
3886         run_enable_tsf_sync(sc);
3887         /* XXX keep local copy */
3888         run_set_bssid(sc, sc->sc_bssid);
3889
3890         RUN_UNLOCK(sc);
3891
3892         return;
3893 }
3894
3895 /*
3896  * Could be called from ieee80211_node_timeout()
3897  * (non-sleepable thread)
3898  */
3899 static void
3900 run_update_beacon(struct ieee80211vap *vap, int item)
3901 {
3902         struct ieee80211com *ic = vap->iv_ic;
3903         struct run_softc *sc = ic->ic_ifp->if_softc;
3904         uint32_t i;
3905
3906         i = RUN_CMDQ_GET(&sc->cmdq_store);
3907         DPRINTF("cmdq_store=%d\n", i);
3908         sc->cmdq[i].func = run_update_beacon_cb;
3909         sc->cmdq[i].arg0 = vap;
3910         ieee80211_runtask(ic, &sc->cmdq_task);
3911
3912         return;
3913 }
3914
3915 static void
3916 run_update_beacon_cb(void *arg)
3917 {
3918         struct ieee80211vap *vap = arg;
3919         struct ieee80211com *ic = vap->iv_ic;
3920         struct run_softc *sc = ic->ic_ifp->if_softc;
3921         struct rt2860_txwi txwi;
3922         struct mbuf *m;
3923         uint8_t ridx;
3924
3925         if (vap->iv_bss->ni_chan == IEEE80211_CHAN_ANYC)
3926                 return;
3927
3928         if ((m = ieee80211_beacon_alloc(vap->iv_bss, &RUN_VAP(vap)->bo)) == NULL)
3929                 return;
3930
3931         memset(&txwi, 0, sizeof txwi);
3932         txwi.wcid = 0xff;
3933         txwi.len = htole16(m->m_pkthdr.len);
3934         /* send beacons at the lowest available rate */
3935         ridx = (ic->ic_curmode == IEEE80211_MODE_11A) ?
3936             RT2860_RIDX_OFDM6 : RT2860_RIDX_CCK1;
3937         txwi.phy = htole16(rt2860_rates[ridx].mcs);
3938         if (rt2860_rates[ridx].phy == IEEE80211_T_OFDM)
3939                 txwi.phy |= htole16(RT2860_PHY_OFDM);
3940         txwi.txop = RT2860_TX_TXOP_HT;
3941         txwi.flags = RT2860_TX_TS;
3942         txwi.xflags = RT2860_TX_NSEQ;
3943
3944         run_write_region_1(sc, RT2860_BCN_BASE(RUN_VAP(vap)->rvp_id),
3945             (uint8_t *)&txwi, sizeof txwi);
3946         run_write_region_1(sc, RT2860_BCN_BASE(RUN_VAP(vap)->rvp_id) + sizeof txwi,
3947             mtod(m, uint8_t *), (m->m_pkthdr.len + 1) & ~1);    /* roundup len */
3948
3949         m_freem(m);
3950
3951         return;
3952 }
3953
3954 static void
3955 run_updateprot(struct ieee80211com *ic)
3956 {
3957         struct run_softc *sc = ic->ic_ifp->if_softc;
3958         uint32_t tmp;
3959
3960         tmp = RT2860_RTSTH_EN | RT2860_PROT_NAV_SHORT | RT2860_TXOP_ALLOW_ALL;
3961         /* setup protection frame rate (MCS code) */
3962         tmp |= (ic->ic_curmode == IEEE80211_MODE_11A) ?
3963             rt2860_rates[RT2860_RIDX_OFDM6].mcs :
3964             rt2860_rates[RT2860_RIDX_CCK11].mcs;
3965
3966         /* CCK frames don't require protection */
3967         run_write(sc, RT2860_CCK_PROT_CFG, tmp);
3968         if (ic->ic_flags & IEEE80211_F_USEPROT) {
3969                 if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
3970                         tmp |= RT2860_PROT_CTRL_RTS_CTS;
3971                 else if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
3972                         tmp |= RT2860_PROT_CTRL_CTS;
3973         }
3974         run_write(sc, RT2860_OFDM_PROT_CFG, tmp);
3975 }
3976
3977 static void
3978 run_usb_timeout_cb(void *arg)
3979 {
3980         struct ieee80211vap *vap = arg;
3981         struct run_softc *sc = vap->iv_ic->ic_ifp->if_softc;
3982
3983         RUN_LOCK_ASSERT(sc, MA_OWNED);
3984
3985         if(vap->iv_state == IEEE80211_S_RUN &&
3986             vap->iv_opmode != IEEE80211_M_STA)
3987                 run_reset_livelock(sc);
3988         else if (vap->iv_state == IEEE80211_S_SCAN) {
3989                 DPRINTF("timeout caused by scan\n");
3990                 /* cancel bgscan */
3991                 ieee80211_cancel_scan(vap);
3992         } else
3993                 DPRINTF("timeout by unknown cause\n");
3994 }
3995
3996 static void
3997 run_reset_livelock(struct run_softc *sc)
3998 {
3999         uint32_t tmp;
4000
4001         RUN_LOCK_ASSERT(sc, MA_OWNED);
4002
4003         /*
4004          * In IBSS or HostAP modes (when the hardware sends beacons), the MAC
4005          * can run into a livelock and start sending CTS-to-self frames like
4006          * crazy if protection is enabled.  Reset MAC/BBP for a while
4007          */
4008         run_read(sc, RT2860_DEBUG, &tmp);
4009         DPRINTFN(3, "debug reg %08x\n", tmp);
4010         if ((tmp & (1 << 29)) && (tmp & (1 << 7 | 1 << 5))) {
4011                 DPRINTF("CTS-to-self livelock detected\n");
4012                 run_write(sc, RT2860_MAC_SYS_CTRL, RT2860_MAC_SRST);
4013                 run_delay(sc, 1);
4014                 run_write(sc, RT2860_MAC_SYS_CTRL,
4015                     RT2860_MAC_RX_EN | RT2860_MAC_TX_EN);
4016         }
4017 }
4018
4019 static void
4020 run_update_promisc_locked(struct ifnet *ifp)
4021 {
4022         struct run_softc *sc = ifp->if_softc;
4023         uint32_t tmp;
4024
4025         run_read(sc, RT2860_RX_FILTR_CFG, &tmp);
4026
4027         tmp |= RT2860_DROP_UC_NOME;
4028         if (ifp->if_flags & IFF_PROMISC)
4029                 tmp &= ~RT2860_DROP_UC_NOME;
4030
4031         run_write(sc, RT2860_RX_FILTR_CFG, tmp);
4032
4033         DPRINTF("%s promiscuous mode\n", (ifp->if_flags & IFF_PROMISC) ?
4034             "entering" : "leaving");
4035 }
4036
4037 static void
4038 run_update_promisc(struct ifnet *ifp)
4039 {
4040         struct run_softc *sc = ifp->if_softc;
4041
4042         if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
4043                 return;
4044
4045         RUN_LOCK(sc);
4046         run_update_promisc_locked(ifp);
4047         RUN_UNLOCK(sc);
4048 }
4049
4050 static void
4051 run_enable_tsf_sync(struct run_softc *sc)
4052 {
4053         struct ieee80211com *ic = sc->sc_ifp->if_l2com;
4054         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
4055         uint32_t tmp;
4056
4057         DPRINTF("rvp_id=%d ic_opmode=%d\n", RUN_VAP(vap)->rvp_id, ic->ic_opmode);
4058
4059         run_read(sc, RT2860_BCN_TIME_CFG, &tmp);
4060         tmp &= ~0x1fffff;
4061         tmp |= vap->iv_bss->ni_intval * 16;
4062         tmp |= RT2860_TSF_TIMER_EN | RT2860_TBTT_TIMER_EN;
4063
4064         if (ic->ic_opmode == IEEE80211_M_STA) {
4065                 /*
4066                  * Local TSF is always updated with remote TSF on beacon
4067                  * reception.
4068                  */
4069                 tmp |= 1 << RT2860_TSF_SYNC_MODE_SHIFT;
4070         } else if (ic->ic_opmode == IEEE80211_M_IBSS) {
4071                 tmp |= RT2860_BCN_TX_EN;
4072                 /*
4073                  * Local TSF is updated with remote TSF on beacon reception
4074                  * only if the remote TSF is greater than local TSF.
4075                  */
4076                 tmp |= 2 << RT2860_TSF_SYNC_MODE_SHIFT;
4077         } else if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
4078                     ic->ic_opmode == IEEE80211_M_MBSS) {
4079                 tmp |= RT2860_BCN_TX_EN;
4080                 /* SYNC with nobody */
4081                 tmp |= 3 << RT2860_TSF_SYNC_MODE_SHIFT;
4082         } else {
4083                 DPRINTF("Enabling TSF failed. undefined opmode\n");
4084                 return;
4085         }
4086
4087         run_write(sc, RT2860_BCN_TIME_CFG, tmp);
4088 }
4089
4090 static void
4091 run_enable_mrr(struct run_softc *sc)
4092 {
4093 #define CCK(mcs)        (mcs)
4094 #define OFDM(mcs)       (1 << 3 | (mcs))
4095         run_write(sc, RT2860_LG_FBK_CFG0,
4096             OFDM(6) << 28 |     /* 54->48 */
4097             OFDM(5) << 24 |     /* 48->36 */
4098             OFDM(4) << 20 |     /* 36->24 */
4099             OFDM(3) << 16 |     /* 24->18 */
4100             OFDM(2) << 12 |     /* 18->12 */
4101             OFDM(1) <<  8 |     /* 12-> 9 */
4102             OFDM(0) <<  4 |     /*  9-> 6 */
4103             OFDM(0));           /*  6-> 6 */
4104
4105         run_write(sc, RT2860_LG_FBK_CFG1,
4106             CCK(2) << 12 |      /* 11->5.5 */
4107             CCK(1) <<  8 |      /* 5.5-> 2 */
4108             CCK(0) <<  4 |      /*   2-> 1 */
4109             CCK(0));            /*   1-> 1 */
4110 #undef OFDM
4111 #undef CCK
4112 }
4113
4114 static void
4115 run_set_txpreamble(struct run_softc *sc)
4116 {
4117         struct ieee80211com *ic = sc->sc_ifp->if_l2com;
4118         uint32_t tmp;
4119
4120         run_read(sc, RT2860_AUTO_RSP_CFG, &tmp);
4121         if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
4122                 tmp |= RT2860_CCK_SHORT_EN;
4123         else
4124                 tmp &= ~RT2860_CCK_SHORT_EN;
4125         run_write(sc, RT2860_AUTO_RSP_CFG, tmp);
4126 }
4127
4128 static void
4129 run_set_basicrates(struct run_softc *sc)
4130 {
4131         struct ieee80211com *ic = sc->sc_ifp->if_l2com;
4132
4133         /* set basic rates mask */
4134         if (ic->ic_curmode == IEEE80211_MODE_11B)
4135                 run_write(sc, RT2860_LEGACY_BASIC_RATE, 0x003);
4136         else if (ic->ic_curmode == IEEE80211_MODE_11A)
4137                 run_write(sc, RT2860_LEGACY_BASIC_RATE, 0x150);
4138         else    /* 11g */
4139                 run_write(sc, RT2860_LEGACY_BASIC_RATE, 0x15f);
4140 }
4141
4142 static void
4143 run_set_leds(struct run_softc *sc, uint16_t which)
4144 {
4145         (void)run_mcu_cmd(sc, RT2860_MCU_CMD_LEDS,
4146             which | (sc->leds & 0x7f));
4147 }
4148
4149 static void
4150 run_set_bssid(struct run_softc *sc, const uint8_t *bssid)
4151 {
4152         run_write(sc, RT2860_MAC_BSSID_DW0,
4153             bssid[0] | bssid[1] << 8 | bssid[2] << 16 | bssid[3] << 24);
4154         run_write(sc, RT2860_MAC_BSSID_DW1,
4155             bssid[4] | bssid[5] << 8);
4156 }
4157
4158 static void
4159 run_set_macaddr(struct run_softc *sc, const uint8_t *addr)
4160 {
4161         run_write(sc, RT2860_MAC_ADDR_DW0,
4162             addr[0] | addr[1] << 8 | addr[2] << 16 | addr[3] << 24);
4163         run_write(sc, RT2860_MAC_ADDR_DW1,
4164             addr[4] | addr[5] << 8 | 0xff << 16);
4165 }
4166
4167 /* ARGSUSED */
4168 static void
4169 run_updateslot(struct ifnet *ifp)
4170 {
4171         struct run_softc *sc = ifp->if_softc;
4172         struct ieee80211com *ic = ifp->if_l2com;
4173         uint32_t tmp;
4174
4175         run_read(sc, RT2860_BKOFF_SLOT_CFG, &tmp);
4176         tmp &= ~0xff;
4177         tmp |= (ic->ic_flags & IEEE80211_F_SHSLOT) ? 9 : 20;
4178         run_write(sc, RT2860_BKOFF_SLOT_CFG, tmp);
4179 }
4180
4181 static void
4182 run_update_mcast(struct ifnet *ifp)
4183 {
4184         /* h/w filter supports getting everything or nothing */
4185         ifp->if_flags |= IFF_ALLMULTI;
4186 }
4187
4188 static int8_t
4189 run_rssi2dbm(struct run_softc *sc, uint8_t rssi, uint8_t rxchain)
4190 {
4191         struct ieee80211com *ic = sc->sc_ifp->if_l2com;
4192         struct ieee80211_channel *c = ic->ic_curchan;
4193         int delta;
4194
4195         if (IEEE80211_IS_CHAN_5GHZ(c)) {
4196                 uint32_t chan = ieee80211_chan2ieee(ic, c);
4197                 delta = sc->rssi_5ghz[rxchain];
4198
4199                 /* determine channel group */
4200                 if (chan <= 64)
4201                         delta -= sc->lna[1];
4202                 else if (chan <= 128)
4203                         delta -= sc->lna[2];
4204                 else
4205                         delta -= sc->lna[3];
4206         } else
4207                 delta = sc->rssi_2ghz[rxchain] - sc->lna[0];
4208
4209         return (-12 - delta - rssi);
4210 }
4211
4212 static int
4213 run_bbp_init(struct run_softc *sc)
4214 {
4215         int i, error, ntries;
4216         uint8_t bbp0;
4217
4218         /* wait for BBP to wake up */
4219         for (ntries = 0; ntries < 20; ntries++) {
4220                 if ((error = run_bbp_read(sc, 0, &bbp0)) != 0)
4221                         return error;
4222                 if (bbp0 != 0 && bbp0 != 0xff)
4223                         break;
4224         }
4225         if (ntries == 20)
4226                 return (ETIMEDOUT);
4227
4228         /* initialize BBP registers to default values */
4229         for (i = 0; i < nitems(rt2860_def_bbp); i++) {
4230                 run_bbp_write(sc, rt2860_def_bbp[i].reg,
4231                     rt2860_def_bbp[i].val);
4232         }
4233
4234         /* fix BBP84 for RT2860E */
4235         if (sc->mac_ver == 0x2860 && sc->mac_rev != 0x0101)
4236                 run_bbp_write(sc, 84, 0x19);
4237
4238         if (sc->mac_ver >= 0x3070) {
4239                 run_bbp_write(sc, 79, 0x13);
4240                 run_bbp_write(sc, 80, 0x05);
4241                 run_bbp_write(sc, 81, 0x33);
4242         } else if (sc->mac_ver == 0x2860 && sc->mac_rev == 0x0100) {
4243                 run_bbp_write(sc, 69, 0x16);
4244                 run_bbp_write(sc, 73, 0x12);
4245         }
4246         return (0);
4247 }
4248
4249 static int
4250 run_rt3070_rf_init(struct run_softc *sc)
4251 {
4252         uint32_t tmp;
4253         uint8_t rf, target, bbp4;
4254         int i;
4255
4256         run_rt3070_rf_read(sc, 30, &rf);
4257         /* toggle RF R30 bit 7 */
4258         run_rt3070_rf_write(sc, 30, rf | 0x80);
4259         run_delay(sc, 10);
4260         run_rt3070_rf_write(sc, 30, rf & ~0x80);
4261
4262         /* initialize RF registers to default value */
4263         if (sc->mac_ver == 0x3572) {
4264                 for (i = 0; i < nitems(rt3572_def_rf); i++) {
4265                         run_rt3070_rf_write(sc, rt3572_def_rf[i].reg,
4266                             rt3572_def_rf[i].val);
4267                 }
4268         } else {
4269                 for (i = 0; i < nitems(rt3070_def_rf); i++) {
4270                         run_rt3070_rf_write(sc, rt3070_def_rf[i].reg,
4271                             rt3070_def_rf[i].val);
4272                 }
4273         }
4274
4275         if (sc->mac_ver == 0x3070) {
4276                 /* change voltage from 1.2V to 1.35V for RT3070 */
4277                 run_read(sc, RT3070_LDO_CFG0, &tmp);
4278                 tmp = (tmp & ~0x0f000000) | 0x0d000000;
4279                 run_write(sc, RT3070_LDO_CFG0, tmp);
4280
4281         } else if (sc->mac_ver == 0x3071) {
4282                 run_rt3070_rf_read(sc, 6, &rf);
4283                 run_rt3070_rf_write(sc, 6, rf | 0x40);
4284                 run_rt3070_rf_write(sc, 31, 0x14);
4285
4286                 run_read(sc, RT3070_LDO_CFG0, &tmp);
4287                 tmp &= ~0x1f000000;
4288                 if (sc->mac_rev < 0x0211)
4289                         tmp |= 0x0d000000;      /* 1.3V */
4290                 else
4291                         tmp |= 0x01000000;      /* 1.2V */
4292                 run_write(sc, RT3070_LDO_CFG0, tmp);
4293
4294                 /* patch LNA_PE_G1 */
4295                 run_read(sc, RT3070_GPIO_SWITCH, &tmp);
4296                 run_write(sc, RT3070_GPIO_SWITCH, tmp & ~0x20);
4297
4298         } else if (sc->mac_ver == 0x3572) {
4299                 run_rt3070_rf_read(sc, 6, &rf);
4300                 run_rt3070_rf_write(sc, 6, rf | 0x40);
4301
4302                 /* increase voltage from 1.2V to 1.35V */
4303                 run_read(sc, RT3070_LDO_CFG0, &tmp);
4304                 tmp = (tmp & ~0x1f000000) | 0x0d000000;
4305                 run_write(sc, RT3070_LDO_CFG0, tmp);
4306
4307                 if (sc->mac_rev < 0x0211 || !sc->patch_dac) {
4308                         run_delay(sc, 1);       /* wait for 1msec */
4309                         /* decrease voltage back to 1.2V */
4310                         tmp = (tmp & ~0x1f000000) | 0x01000000;
4311                         run_write(sc, RT3070_LDO_CFG0, tmp);
4312                 }
4313         }
4314
4315         /* select 20MHz bandwidth */
4316         run_rt3070_rf_read(sc, 31, &rf);
4317         run_rt3070_rf_write(sc, 31, rf & ~0x20);
4318
4319         /* calibrate filter for 20MHz bandwidth */
4320         sc->rf24_20mhz = 0x1f;  /* default value */
4321         target = (sc->mac_ver < 0x3071) ? 0x16 : 0x13;
4322         run_rt3070_filter_calib(sc, 0x07, target, &sc->rf24_20mhz);
4323
4324         /* select 40MHz bandwidth */
4325         run_bbp_read(sc, 4, &bbp4);
4326         run_bbp_write(sc, 4, (bbp4 & ~0x08) | 0x10);
4327         run_rt3070_rf_read(sc, 31, &rf);
4328         run_rt3070_rf_write(sc, 31, rf | 0x20);
4329
4330         /* calibrate filter for 40MHz bandwidth */
4331         sc->rf24_40mhz = 0x2f;  /* default value */
4332         target = (sc->mac_ver < 0x3071) ? 0x19 : 0x15;
4333         run_rt3070_filter_calib(sc, 0x27, target, &sc->rf24_40mhz);
4334
4335         /* go back to 20MHz bandwidth */
4336         run_bbp_read(sc, 4, &bbp4);
4337         run_bbp_write(sc, 4, bbp4 & ~0x18);
4338
4339         if (sc->mac_ver == 0x3572) {
4340                 /* save default BBP registers 25 and 26 values */
4341                 run_bbp_read(sc, 25, &sc->bbp25);
4342                 run_bbp_read(sc, 26, &sc->bbp26);
4343         } else if (sc->mac_rev < 0x0211)
4344                 run_rt3070_rf_write(sc, 27, 0x03);
4345
4346         run_read(sc, RT3070_OPT_14, &tmp);
4347         run_write(sc, RT3070_OPT_14, tmp | 1);
4348
4349         if (sc->mac_ver == 0x3070 || sc->mac_ver == 0x3071) {
4350                 run_rt3070_rf_read(sc, 17, &rf);
4351                 rf &= ~RT3070_TX_LO1;
4352                 if ((sc->mac_ver == 0x3070 ||
4353                      (sc->mac_ver == 0x3071 && sc->mac_rev >= 0x0211)) &&
4354                     !sc->ext_2ghz_lna)
4355                         rf |= 0x20;     /* fix for long range Rx issue */
4356                 if (sc->txmixgain_2ghz >= 1)
4357                         rf = (rf & ~0x7) | sc->txmixgain_2ghz;
4358                 run_rt3070_rf_write(sc, 17, rf);
4359         }
4360
4361         if (sc->mac_rev == 0x3071) {
4362                 run_rt3070_rf_read(sc, 1, &rf);
4363                 rf &= ~(RT3070_RX0_PD | RT3070_TX0_PD);
4364                 rf |= RT3070_RF_BLOCK | RT3070_RX1_PD | RT3070_TX1_PD;
4365                 run_rt3070_rf_write(sc, 1, rf);
4366
4367                 run_rt3070_rf_read(sc, 15, &rf);
4368                 run_rt3070_rf_write(sc, 15, rf & ~RT3070_TX_LO2);
4369
4370                 run_rt3070_rf_read(sc, 20, &rf);
4371                 run_rt3070_rf_write(sc, 20, rf & ~RT3070_RX_LO1);
4372
4373                 run_rt3070_rf_read(sc, 21, &rf);
4374                 run_rt3070_rf_write(sc, 21, rf & ~RT3070_RX_LO2);
4375         }
4376
4377         if (sc->mac_ver == 0x3070 || sc->mac_ver == 0x3071) {
4378                 /* fix Tx to Rx IQ glitch by raising RF voltage */
4379                 run_rt3070_rf_read(sc, 27, &rf);
4380                 rf &= ~0x77;
4381                 if (sc->mac_rev < 0x0211)
4382                         rf |= 0x03;
4383                 run_rt3070_rf_write(sc, 27, rf);
4384         }
4385         return (0);
4386 }
4387
4388 static int
4389 run_rt3070_filter_calib(struct run_softc *sc, uint8_t init, uint8_t target,
4390     uint8_t *val)
4391 {
4392         uint8_t rf22, rf24;
4393         uint8_t bbp55_pb, bbp55_sb, delta;
4394         int ntries;
4395
4396         /* program filter */
4397         run_rt3070_rf_read(sc, 24, &rf24);
4398         rf24 = (rf24 & 0xc0) | init;    /* initial filter value */
4399         run_rt3070_rf_write(sc, 24, rf24);
4400
4401         /* enable baseband loopback mode */
4402         run_rt3070_rf_read(sc, 22, &rf22);
4403         run_rt3070_rf_write(sc, 22, rf22 | 0x01);
4404
4405         /* set power and frequency of passband test tone */
4406         run_bbp_write(sc, 24, 0x00);
4407         for (ntries = 0; ntries < 100; ntries++) {
4408                 /* transmit test tone */
4409                 run_bbp_write(sc, 25, 0x90);
4410                 run_delay(sc, 10);
4411                 /* read received power */
4412                 run_bbp_read(sc, 55, &bbp55_pb);
4413                 if (bbp55_pb != 0)
4414                         break;
4415         }
4416         if (ntries == 100)
4417                 return ETIMEDOUT;
4418
4419         /* set power and frequency of stopband test tone */
4420         run_bbp_write(sc, 24, 0x06);
4421         for (ntries = 0; ntries < 100; ntries++) {
4422                 /* transmit test tone */
4423                 run_bbp_write(sc, 25, 0x90);
4424                 run_delay(sc, 10);
4425                 /* read received power */
4426                 run_bbp_read(sc, 55, &bbp55_sb);
4427
4428                 delta = bbp55_pb - bbp55_sb;
4429                 if (delta > target)
4430                         break;
4431
4432                 /* reprogram filter */
4433                 rf24++;
4434                 run_rt3070_rf_write(sc, 24, rf24);
4435         }
4436         if (ntries < 100) {
4437                 if (rf24 != init)
4438                         rf24--; /* backtrack */
4439                 *val = rf24;
4440                 run_rt3070_rf_write(sc, 24, rf24);
4441         }
4442
4443         /* restore initial state */
4444         run_bbp_write(sc, 24, 0x00);
4445
4446         /* disable baseband loopback mode */
4447         run_rt3070_rf_read(sc, 22, &rf22);
4448         run_rt3070_rf_write(sc, 22, rf22 & ~0x01);
4449
4450         return (0);
4451 }
4452
4453 static void
4454 run_rt3070_rf_setup(struct run_softc *sc)
4455 {
4456         uint8_t bbp, rf;
4457         int i;
4458
4459         if (sc->mac_ver == 0x3572) {
4460                 /* enable DC filter */
4461                 if (sc->mac_rev >= 0x0201)
4462                         run_bbp_write(sc, 103, 0xc0);
4463
4464                 run_bbp_read(sc, 138, &bbp);
4465                 if (sc->ntxchains == 1)
4466                         bbp |= 0x20;    /* turn off DAC1 */
4467                 if (sc->nrxchains == 1)
4468                         bbp &= ~0x02;   /* turn off ADC1 */
4469                 run_bbp_write(sc, 138, bbp);
4470
4471                 if (sc->mac_rev >= 0x0211) {
4472                         /* improve power consumption */
4473                         run_bbp_read(sc, 31, &bbp);
4474                         run_bbp_write(sc, 31, bbp & ~0x03);
4475                 }
4476
4477                 run_rt3070_rf_read(sc, 16, &rf);
4478                 rf = (rf & ~0x07) | sc->txmixgain_2ghz;
4479                 run_rt3070_rf_write(sc, 16, rf);
4480
4481         } else if (sc->mac_ver == 0x3071) {
4482                 /* enable DC filter */
4483                 if (sc->mac_rev >= 0x0201)
4484                         run_bbp_write(sc, 103, 0xc0);
4485
4486                 run_bbp_read(sc, 138, &bbp);
4487                 if (sc->ntxchains == 1)
4488                         bbp |= 0x20;    /* turn off DAC1 */
4489                 if (sc->nrxchains == 1)
4490                         bbp &= ~0x02;   /* turn off ADC1 */
4491                 run_bbp_write(sc, 138, bbp);
4492
4493                 if (sc->mac_rev >= 0x0211) {
4494                         /* improve power consumption */
4495                         run_bbp_read(sc, 31, &bbp);
4496                         run_bbp_write(sc, 31, bbp & ~0x03);
4497                 }
4498
4499                 run_write(sc, RT2860_TX_SW_CFG1, 0);
4500                 if (sc->mac_rev < 0x0211) {
4501                         run_write(sc, RT2860_TX_SW_CFG2,
4502                             sc->patch_dac ? 0x2c : 0x0f);
4503                 } else
4504                         run_write(sc, RT2860_TX_SW_CFG2, 0);
4505
4506         } else if (sc->mac_ver == 0x3070) {
4507                 if (sc->mac_rev >= 0x0201) {
4508                         /* enable DC filter */
4509                         run_bbp_write(sc, 103, 0xc0);
4510
4511                         /* improve power consumption */
4512                         run_bbp_read(sc, 31, &bbp);
4513                         run_bbp_write(sc, 31, bbp & ~0x03);
4514                 }
4515
4516                 if (sc->mac_rev < 0x0211) {
4517                         run_write(sc, RT2860_TX_SW_CFG1, 0);
4518                         run_write(sc, RT2860_TX_SW_CFG2, 0x2c);
4519                 } else
4520                         run_write(sc, RT2860_TX_SW_CFG2, 0);
4521         }
4522
4523         /* initialize RF registers from ROM for >=RT3071*/
4524         if (sc->mac_ver >= 0x3071) {
4525                 for (i = 0; i < 10; i++) {
4526                         if (sc->rf[i].reg == 0 || sc->rf[i].reg == 0xff)
4527                                 continue;
4528                         run_rt3070_rf_write(sc, sc->rf[i].reg, sc->rf[i].val);
4529                 }
4530         }
4531 }
4532
4533 static int
4534 run_txrx_enable(struct run_softc *sc)
4535 {
4536         struct ieee80211com *ic = sc->sc_ifp->if_l2com;
4537         uint32_t tmp;
4538         int error, ntries;
4539
4540         run_write(sc, RT2860_MAC_SYS_CTRL, RT2860_MAC_TX_EN);
4541         for (ntries = 0; ntries < 200; ntries++) {
4542                 if ((error = run_read(sc, RT2860_WPDMA_GLO_CFG, &tmp)) != 0)
4543                         return error;
4544                 if ((tmp & (RT2860_TX_DMA_BUSY | RT2860_RX_DMA_BUSY)) == 0)
4545                         break;
4546                 run_delay(sc, 50);
4547         }
4548         if (ntries == 200)
4549                 return ETIMEDOUT;
4550
4551         run_delay(sc, 50);
4552
4553         tmp |= RT2860_RX_DMA_EN | RT2860_TX_DMA_EN | RT2860_TX_WB_DDONE;
4554         run_write(sc, RT2860_WPDMA_GLO_CFG, tmp);
4555
4556         /* enable Rx bulk aggregation (set timeout and limit) */
4557         tmp = RT2860_USB_TX_EN | RT2860_USB_RX_EN | RT2860_USB_RX_AGG_EN |
4558             RT2860_USB_RX_AGG_TO(128) | RT2860_USB_RX_AGG_LMT(2);
4559         run_write(sc, RT2860_USB_DMA_CFG, tmp);
4560
4561         /* set Rx filter */
4562         tmp = RT2860_DROP_CRC_ERR | RT2860_DROP_PHY_ERR;
4563         if (ic->ic_opmode != IEEE80211_M_MONITOR) {
4564                 tmp |= RT2860_DROP_UC_NOME | RT2860_DROP_DUPL |
4565                     RT2860_DROP_CTS | RT2860_DROP_BA | RT2860_DROP_ACK |
4566                     RT2860_DROP_VER_ERR | RT2860_DROP_CTRL_RSV |
4567                     RT2860_DROP_CFACK | RT2860_DROP_CFEND;
4568                 if (ic->ic_opmode == IEEE80211_M_STA)
4569                         tmp |= RT2860_DROP_RTS | RT2860_DROP_PSPOLL;
4570         }
4571         run_write(sc, RT2860_RX_FILTR_CFG, tmp);
4572
4573         run_write(sc, RT2860_MAC_SYS_CTRL,
4574             RT2860_MAC_RX_EN | RT2860_MAC_TX_EN);
4575
4576         return (0);
4577 }
4578
4579 static void
4580 run_init_locked(struct run_softc *sc)
4581 {
4582         struct ifnet *ifp = sc->sc_ifp;
4583         struct ieee80211com *ic = ifp->if_l2com;
4584         uint32_t tmp;
4585         uint8_t bbp1, bbp3;
4586         int i;
4587         int ridx;
4588         int ntries;
4589
4590         if (ic->ic_nrunning > 1)
4591                 return;
4592
4593         run_stop(sc);
4594
4595         for (ntries = 0; ntries < 100; ntries++) {
4596                 if (run_read(sc, RT2860_ASIC_VER_ID, &tmp) != 0)
4597                         goto fail;
4598                 if (tmp != 0 && tmp != 0xffffffff)
4599                         break;
4600                 run_delay(sc, 10);
4601         }
4602         if (ntries == 100)
4603                 goto fail;
4604
4605         for (i = 0; i != RUN_EP_QUEUES; i++)
4606                 run_setup_tx_list(sc, &sc->sc_epq[i]);
4607
4608         run_set_macaddr(sc, IF_LLADDR(ifp));
4609
4610         for (ntries = 0; ntries < 100; ntries++) {
4611                 if (run_read(sc, RT2860_WPDMA_GLO_CFG, &tmp) != 0)
4612                         goto fail;
4613                 if ((tmp & (RT2860_TX_DMA_BUSY | RT2860_RX_DMA_BUSY)) == 0)
4614                         break;
4615                 run_delay(sc, 10);
4616         }
4617         if (ntries == 100) {
4618                 device_printf(sc->sc_dev, "timeout waiting for DMA engine\n");
4619                 goto fail;
4620         }
4621         tmp &= 0xff0;
4622         tmp |= RT2860_TX_WB_DDONE;
4623         run_write(sc, RT2860_WPDMA_GLO_CFG, tmp);
4624
4625         /* turn off PME_OEN to solve high-current issue */
4626         run_read(sc, RT2860_SYS_CTRL, &tmp);
4627         run_write(sc, RT2860_SYS_CTRL, tmp & ~RT2860_PME_OEN);
4628
4629         run_write(sc, RT2860_MAC_SYS_CTRL,
4630             RT2860_BBP_HRST | RT2860_MAC_SRST);
4631         run_write(sc, RT2860_USB_DMA_CFG, 0);
4632
4633         if (run_reset(sc) != 0) {
4634                 device_printf(sc->sc_dev, "could not reset chipset\n");
4635                 goto fail;
4636         }
4637
4638         run_write(sc, RT2860_MAC_SYS_CTRL, 0);
4639
4640         /* init Tx power for all Tx rates (from EEPROM) */
4641         for (ridx = 0; ridx < 5; ridx++) {
4642                 if (sc->txpow20mhz[ridx] == 0xffffffff)
4643                         continue;
4644                 run_write(sc, RT2860_TX_PWR_CFG(ridx), sc->txpow20mhz[ridx]);
4645         }
4646
4647         for (i = 0; i < nitems(rt2870_def_mac); i++)
4648                 run_write(sc, rt2870_def_mac[i].reg, rt2870_def_mac[i].val);
4649         run_write(sc, RT2860_WMM_AIFSN_CFG, 0x00002273);
4650         run_write(sc, RT2860_WMM_CWMIN_CFG, 0x00002344);
4651         run_write(sc, RT2860_WMM_CWMAX_CFG, 0x000034aa);
4652
4653         if (sc->mac_ver >= 0x3070) {
4654                 /* set delay of PA_PE assertion to 1us (unit of 0.25us) */
4655                 run_write(sc, RT2860_TX_SW_CFG0,
4656                     4 << RT2860_DLY_PAPE_EN_SHIFT);
4657         }
4658
4659         /* wait while MAC is busy */
4660         for (ntries = 0; ntries < 100; ntries++) {
4661                 if (run_read(sc, RT2860_MAC_STATUS_REG, &tmp) != 0)
4662                         goto fail;
4663                 if (!(tmp & (RT2860_RX_STATUS_BUSY | RT2860_TX_STATUS_BUSY)))
4664                         break;
4665                 run_delay(sc, 10);
4666         }
4667         if (ntries == 100)
4668                 goto fail;
4669
4670         /* clear Host to MCU mailbox */
4671         run_write(sc, RT2860_H2M_BBPAGENT, 0);
4672         run_write(sc, RT2860_H2M_MAILBOX, 0);
4673         run_delay(sc, 10);
4674
4675         if (run_bbp_init(sc) != 0) {
4676                 device_printf(sc->sc_dev, "could not initialize BBP\n");
4677                 goto fail;
4678         }
4679
4680         /* abort TSF synchronization */
4681         run_read(sc, RT2860_BCN_TIME_CFG, &tmp);
4682         tmp &= ~(RT2860_BCN_TX_EN | RT2860_TSF_TIMER_EN |
4683             RT2860_TBTT_TIMER_EN);
4684         run_write(sc, RT2860_BCN_TIME_CFG, tmp);
4685
4686         /* clear RX WCID search table */
4687         run_set_region_4(sc, RT2860_WCID_ENTRY(0), 0, 512);
4688         /* clear WCID attribute table */
4689         run_set_region_4(sc, RT2860_WCID_ATTR(0), 0, 8 * 32);
4690
4691         /* hostapd sets a key before init. So, don't clear it. */
4692         if (sc->cmdq_key_set != RUN_CMDQ_GO) {
4693                 /* clear shared key table */
4694                 run_set_region_4(sc, RT2860_SKEY(0, 0), 0, 8 * 32);
4695                 /* clear shared key mode */
4696                 run_set_region_4(sc, RT2860_SKEY_MODE_0_7, 0, 4);
4697         }
4698
4699         run_read(sc, RT2860_US_CYC_CNT, &tmp);
4700         tmp = (tmp & ~0xff) | 0x1e;
4701         run_write(sc, RT2860_US_CYC_CNT, tmp);
4702
4703         if (sc->mac_rev != 0x0101)
4704                 run_write(sc, RT2860_TXOP_CTRL_CFG, 0x0000583f);
4705
4706         run_write(sc, RT2860_WMM_TXOP0_CFG, 0);
4707         run_write(sc, RT2860_WMM_TXOP1_CFG, 48 << 16 | 96);
4708
4709         /* write vendor-specific BBP values (from EEPROM) */
4710         for (i = 0; i < 10; i++) {
4711                 if (sc->bbp[i].reg == 0 || sc->bbp[i].reg == 0xff)
4712                         continue;
4713                 run_bbp_write(sc, sc->bbp[i].reg, sc->bbp[i].val);
4714         }
4715
4716         /* select Main antenna for 1T1R devices */
4717         if (sc->rf_rev == RT3070_RF_3020)
4718                 run_set_rx_antenna(sc, 0);
4719
4720         /* send LEDs operating mode to microcontroller */
4721         (void)run_mcu_cmd(sc, RT2860_MCU_CMD_LED1, sc->led[0]);
4722         (void)run_mcu_cmd(sc, RT2860_MCU_CMD_LED2, sc->led[1]);
4723         (void)run_mcu_cmd(sc, RT2860_MCU_CMD_LED3, sc->led[2]);
4724
4725         if (sc->mac_ver >= 0x3070)
4726                 run_rt3070_rf_init(sc);
4727
4728         /* disable non-existing Rx chains */
4729         run_bbp_read(sc, 3, &bbp3);
4730         bbp3 &= ~(1 << 3 | 1 << 4);
4731         if (sc->nrxchains == 2)
4732                 bbp3 |= 1 << 3;
4733         else if (sc->nrxchains == 3)
4734                 bbp3 |= 1 << 4;
4735         run_bbp_write(sc, 3, bbp3);
4736
4737         /* disable non-existing Tx chains */
4738         run_bbp_read(sc, 1, &bbp1);
4739         if (sc->ntxchains == 1)
4740                 bbp1 &= ~(1 << 3 | 1 << 4);
4741         run_bbp_write(sc, 1, bbp1);
4742
4743         if (sc->mac_ver >= 0x3070)
4744                 run_rt3070_rf_setup(sc);
4745
4746         /* select default channel */
4747         run_set_chan(sc, ic->ic_curchan);
4748
4749         /* setup initial protection mode */
4750         run_updateprot(ic);
4751
4752         /* turn radio LED on */
4753         run_set_leds(sc, RT2860_LED_RADIO);
4754
4755         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4756         ifp->if_drv_flags |= IFF_DRV_RUNNING;
4757         sc->cmdq_run = RUN_CMDQ_GO;
4758
4759         for (i = 0; i != RUN_N_XFER; i++)
4760                 usbd_xfer_set_stall(sc->sc_xfer[i]);
4761
4762         usbd_transfer_start(sc->sc_xfer[RUN_BULK_RX]);
4763
4764         if (run_txrx_enable(sc) != 0)
4765                 goto fail;
4766
4767         return;
4768
4769 fail:
4770         run_stop(sc);
4771 }
4772
4773 static void
4774 run_init(void *arg)
4775 {
4776         struct run_softc *sc = arg;
4777         struct ifnet *ifp = sc->sc_ifp;
4778         struct ieee80211com *ic = ifp->if_l2com;
4779
4780         RUN_LOCK(sc);
4781         run_init_locked(sc);
4782         RUN_UNLOCK(sc);
4783
4784         if (ifp->if_drv_flags & IFF_DRV_RUNNING)
4785                 ieee80211_start_all(ic);
4786 }
4787
4788 static void
4789 run_stop(void *arg)
4790 {
4791         struct run_softc *sc = (struct run_softc *)arg;
4792         struct ifnet *ifp = sc->sc_ifp;
4793         uint32_t tmp;
4794         int i;
4795         int ntries;
4796
4797         RUN_LOCK_ASSERT(sc, MA_OWNED);
4798
4799         if (ifp->if_drv_flags & IFF_DRV_RUNNING)
4800                 run_set_leds(sc, 0);    /* turn all LEDs off */
4801
4802         ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
4803
4804         sc->ratectl_run = RUN_RATECTL_OFF;
4805         sc->cmdq_run = sc->cmdq_key_set;
4806
4807         RUN_UNLOCK(sc);
4808
4809         for(i = 0; i < RUN_N_XFER; i++)
4810                 usbd_transfer_drain(sc->sc_xfer[i]);
4811
4812         RUN_LOCK(sc);
4813
4814         if (sc->rx_m != NULL) {
4815                 m_free(sc->rx_m);
4816                 sc->rx_m = NULL;
4817         }
4818
4819         /* disable Tx/Rx */
4820         run_read(sc, RT2860_MAC_SYS_CTRL, &tmp);
4821         tmp &= ~(RT2860_MAC_RX_EN | RT2860_MAC_TX_EN);
4822         run_write(sc, RT2860_MAC_SYS_CTRL, tmp);
4823
4824         /* wait for pending Tx to complete */
4825         for (ntries = 0; ntries < 100; ntries++) {
4826                 if (run_read(sc, RT2860_TXRXQ_PCNT, &tmp) != 0) {
4827                         DPRINTF("Cannot read Tx queue count\n");
4828                         break;
4829                 }
4830                 if ((tmp & RT2860_TX2Q_PCNT_MASK) == 0) {
4831                         DPRINTF("All Tx cleared\n");
4832                         break;
4833                 }
4834                 run_delay(sc, 10);
4835         }
4836         if (ntries >= 100)
4837                 DPRINTF("There are still pending Tx\n");
4838         run_delay(sc, 10);
4839         run_write(sc, RT2860_USB_DMA_CFG, 0);
4840
4841         run_write(sc, RT2860_MAC_SYS_CTRL, RT2860_BBP_HRST | RT2860_MAC_SRST);
4842         run_write(sc, RT2860_MAC_SYS_CTRL, 0);
4843
4844         for (i = 0; i != RUN_EP_QUEUES; i++)
4845                 run_unsetup_tx_list(sc, &sc->sc_epq[i]);
4846
4847         return;
4848 }
4849
4850 static void
4851 run_delay(struct run_softc *sc, unsigned int ms)
4852 {
4853         usb_pause_mtx(mtx_owned(&sc->sc_mtx) ? 
4854             &sc->sc_mtx : NULL, USB_MS_TO_TICKS(ms));
4855 }
4856
4857 static device_method_t run_methods[] = {
4858         /* Device interface */
4859         DEVMETHOD(device_probe,         run_match),
4860         DEVMETHOD(device_attach,        run_attach),
4861         DEVMETHOD(device_detach,        run_detach),
4862
4863         { 0, 0 }
4864 };
4865
4866 static driver_t run_driver = {
4867         "run",
4868         run_methods,
4869         sizeof(struct run_softc)
4870 };
4871
4872 static devclass_t run_devclass;
4873
4874 DRIVER_MODULE(run, uhub, run_driver, run_devclass, NULL, 0);
4875 MODULE_DEPEND(run, wlan, 1, 1, 1);
4876 MODULE_DEPEND(run, usb, 1, 1, 1);
4877 MODULE_DEPEND(run, firmware, 1, 1, 1);
4878 MODULE_VERSION(run, 1);