]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/dev/usb/wlan/if_ural.c
MFC r343541:
[FreeBSD/stable/10.git] / sys / dev / usb / wlan / if_ural.c
1 /*      $FreeBSD$       */
2
3 /*-
4  * Copyright (c) 2005, 2006
5  *      Damien Bergamini <damien.bergamini@free.fr>
6  *
7  * Copyright (c) 2006, 2008
8  *      Hans Petter Selasky <hselasky@FreeBSD.org>
9  *
10  * Permission to use, copy, modify, and distribute this software for any
11  * purpose with or without fee is hereby granted, provided that the above
12  * copyright notice and this permission notice appear in all copies.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
15  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
16  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
17  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
18  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
19  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
20  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
21  */
22
23 #include <sys/cdefs.h>
24 __FBSDID("$FreeBSD$");
25
26 /*-
27  * Ralink Technology RT2500USB chipset driver
28  * http://www.ralinktech.com/
29  */
30
31 #include <sys/param.h>
32 #include <sys/sockio.h>
33 #include <sys/sysctl.h>
34 #include <sys/lock.h>
35 #include <sys/mutex.h>
36 #include <sys/mbuf.h>
37 #include <sys/kernel.h>
38 #include <sys/socket.h>
39 #include <sys/systm.h>
40 #include <sys/malloc.h>
41 #include <sys/module.h>
42 #include <sys/bus.h>
43 #include <sys/endian.h>
44 #include <sys/kdb.h>
45
46 #include <net/bpf.h>
47 #include <net/if.h>
48 #include <net/if_arp.h>
49 #include <net/ethernet.h>
50 #include <net/if_dl.h>
51 #include <net/if_media.h>
52 #include <net/if_types.h>
53
54 #ifdef INET
55 #include <netinet/in.h>
56 #include <netinet/in_systm.h>
57 #include <netinet/in_var.h>
58 #include <netinet/if_ether.h>
59 #include <netinet/ip.h>
60 #endif
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 ural_debug
72 #include <dev/usb/usb_debug.h>
73
74 #include <dev/usb/wlan/if_uralreg.h>
75 #include <dev/usb/wlan/if_uralvar.h>
76
77 #ifdef USB_DEBUG
78 static int ural_debug = 0;
79
80 static SYSCTL_NODE(_hw_usb, OID_AUTO, ural, CTLFLAG_RW, 0, "USB ural");
81 SYSCTL_INT(_hw_usb_ural, OID_AUTO, debug, CTLFLAG_RW, &ural_debug, 0,
82     "Debug level");
83 #endif
84
85 #define URAL_RSSI(rssi)                                 \
86         ((rssi) > (RAL_NOISE_FLOOR + RAL_RSSI_CORR) ?   \
87          ((rssi) - (RAL_NOISE_FLOOR + RAL_RSSI_CORR)) : 0)
88
89 /* various supported device vendors/products */
90 static const STRUCT_USB_HOST_ID ural_devs[] = {
91 #define URAL_DEV(v,p)  { USB_VP(USB_VENDOR_##v, USB_PRODUCT_##v##_##p) }
92         URAL_DEV(ASUS, WL167G),
93         URAL_DEV(ASUS, RT2570),
94         URAL_DEV(BELKIN, F5D7050),
95         URAL_DEV(BELKIN, F5D7051),
96         URAL_DEV(CISCOLINKSYS, HU200TS),
97         URAL_DEV(CISCOLINKSYS, WUSB54G),
98         URAL_DEV(CISCOLINKSYS, WUSB54GP),
99         URAL_DEV(CONCEPTRONIC2, C54RU),
100         URAL_DEV(DLINK, DWLG122),
101         URAL_DEV(GIGABYTE, GN54G),
102         URAL_DEV(GIGABYTE, GNWBKG),
103         URAL_DEV(GUILLEMOT, HWGUSB254),
104         URAL_DEV(MELCO, KG54),
105         URAL_DEV(MELCO, KG54AI),
106         URAL_DEV(MELCO, KG54YB),
107         URAL_DEV(MELCO, NINWIFI),
108         URAL_DEV(MSI, RT2570),
109         URAL_DEV(MSI, RT2570_2),
110         URAL_DEV(MSI, RT2570_3),
111         URAL_DEV(NOVATECH, NV902),
112         URAL_DEV(RALINK, RT2570),
113         URAL_DEV(RALINK, RT2570_2),
114         URAL_DEV(RALINK, RT2570_3),
115         URAL_DEV(SIEMENS2, WL54G),
116         URAL_DEV(SMC, 2862WG),
117         URAL_DEV(SPHAIRON, UB801R),
118         URAL_DEV(SURECOM, RT2570),
119         URAL_DEV(VTECH, RT2570),
120         URAL_DEV(ZINWELL, RT2570),
121 #undef URAL_DEV
122 };
123
124 static usb_callback_t ural_bulk_read_callback;
125 static usb_callback_t ural_bulk_write_callback;
126
127 static usb_error_t      ural_do_request(struct ural_softc *sc,
128                             struct usb_device_request *req, void *data);
129 static struct ieee80211vap *ural_vap_create(struct ieee80211com *,
130                             const char [IFNAMSIZ], int, enum ieee80211_opmode,
131                             int, const uint8_t [IEEE80211_ADDR_LEN],
132                             const uint8_t [IEEE80211_ADDR_LEN]);
133 static void             ural_vap_delete(struct ieee80211vap *);
134 static void             ural_tx_free(struct ural_tx_data *, int);
135 static void             ural_setup_tx_list(struct ural_softc *);
136 static void             ural_unsetup_tx_list(struct ural_softc *);
137 static int              ural_newstate(struct ieee80211vap *,
138                             enum ieee80211_state, int);
139 static void             ural_setup_tx_desc(struct ural_softc *,
140                             struct ural_tx_desc *, uint32_t, int, int);
141 static int              ural_tx_bcn(struct ural_softc *, struct mbuf *,
142                             struct ieee80211_node *);
143 static int              ural_tx_mgt(struct ural_softc *, struct mbuf *,
144                             struct ieee80211_node *);
145 static int              ural_tx_data(struct ural_softc *, struct mbuf *,
146                             struct ieee80211_node *);
147 static void             ural_start(struct ifnet *);
148 static int              ural_ioctl(struct ifnet *, u_long, caddr_t);
149 static void             ural_set_testmode(struct ural_softc *);
150 static void             ural_eeprom_read(struct ural_softc *, uint16_t, void *,
151                             int);
152 static uint16_t         ural_read(struct ural_softc *, uint16_t);
153 static void             ural_read_multi(struct ural_softc *, uint16_t, void *,
154                             int);
155 static void             ural_write(struct ural_softc *, uint16_t, uint16_t);
156 static void             ural_write_multi(struct ural_softc *, uint16_t, void *,
157                             int) __unused;
158 static void             ural_bbp_write(struct ural_softc *, uint8_t, uint8_t);
159 static uint8_t          ural_bbp_read(struct ural_softc *, uint8_t);
160 static void             ural_rf_write(struct ural_softc *, uint8_t, uint32_t);
161 static void             ural_scan_start(struct ieee80211com *);
162 static void             ural_scan_end(struct ieee80211com *);
163 static void             ural_set_channel(struct ieee80211com *);
164 static void             ural_set_chan(struct ural_softc *,
165                             struct ieee80211_channel *);
166 static void             ural_disable_rf_tune(struct ural_softc *);
167 static void             ural_enable_tsf_sync(struct ural_softc *);
168 static void             ural_enable_tsf(struct ural_softc *);
169 static void             ural_update_slot(struct ifnet *);
170 static void             ural_set_txpreamble(struct ural_softc *);
171 static void             ural_set_basicrates(struct ural_softc *,
172                             const struct ieee80211_channel *);
173 static void             ural_set_bssid(struct ural_softc *, const uint8_t *);
174 static void             ural_set_macaddr(struct ural_softc *, uint8_t *);
175 static void             ural_update_promisc(struct ifnet *);
176 static void             ural_setpromisc(struct ural_softc *);
177 static const char       *ural_get_rf(int);
178 static void             ural_read_eeprom(struct ural_softc *);
179 static int              ural_bbp_init(struct ural_softc *);
180 static void             ural_set_txantenna(struct ural_softc *, int);
181 static void             ural_set_rxantenna(struct ural_softc *, int);
182 static void             ural_init_locked(struct ural_softc *);
183 static void             ural_init(void *);
184 static void             ural_stop(struct ural_softc *);
185 static int              ural_raw_xmit(struct ieee80211_node *, struct mbuf *,
186                             const struct ieee80211_bpf_params *);
187 static void             ural_ratectl_start(struct ural_softc *,
188                             struct ieee80211_node *);
189 static void             ural_ratectl_timeout(void *);
190 static void             ural_ratectl_task(void *, int);
191 static int              ural_pause(struct ural_softc *sc, int timeout);
192
193 /*
194  * Default values for MAC registers; values taken from the reference driver.
195  */
196 static const struct {
197         uint16_t        reg;
198         uint16_t        val;
199 } ural_def_mac[] = {
200         { RAL_TXRX_CSR5,  0x8c8d },
201         { RAL_TXRX_CSR6,  0x8b8a },
202         { RAL_TXRX_CSR7,  0x8687 },
203         { RAL_TXRX_CSR8,  0x0085 },
204         { RAL_MAC_CSR13,  0x1111 },
205         { RAL_MAC_CSR14,  0x1e11 },
206         { RAL_TXRX_CSR21, 0xe78f },
207         { RAL_MAC_CSR9,   0xff1d },
208         { RAL_MAC_CSR11,  0x0002 },
209         { RAL_MAC_CSR22,  0x0053 },
210         { RAL_MAC_CSR15,  0x0000 },
211         { RAL_MAC_CSR8,   RAL_FRAME_SIZE },
212         { RAL_TXRX_CSR19, 0x0000 },
213         { RAL_TXRX_CSR18, 0x005a },
214         { RAL_PHY_CSR2,   0x0000 },
215         { RAL_TXRX_CSR0,  0x1ec0 },
216         { RAL_PHY_CSR4,   0x000f }
217 };
218
219 /*
220  * Default values for BBP registers; values taken from the reference driver.
221  */
222 static const struct {
223         uint8_t reg;
224         uint8_t val;
225 } ural_def_bbp[] = {
226         {  3, 0x02 },
227         {  4, 0x19 },
228         { 14, 0x1c },
229         { 15, 0x30 },
230         { 16, 0xac },
231         { 17, 0x48 },
232         { 18, 0x18 },
233         { 19, 0xff },
234         { 20, 0x1e },
235         { 21, 0x08 },
236         { 22, 0x08 },
237         { 23, 0x08 },
238         { 24, 0x80 },
239         { 25, 0x50 },
240         { 26, 0x08 },
241         { 27, 0x23 },
242         { 30, 0x10 },
243         { 31, 0x2b },
244         { 32, 0xb9 },
245         { 34, 0x12 },
246         { 35, 0x50 },
247         { 39, 0xc4 },
248         { 40, 0x02 },
249         { 41, 0x60 },
250         { 53, 0x10 },
251         { 54, 0x18 },
252         { 56, 0x08 },
253         { 57, 0x10 },
254         { 58, 0x08 },
255         { 61, 0x60 },
256         { 62, 0x10 },
257         { 75, 0xff }
258 };
259
260 /*
261  * Default values for RF register R2 indexed by channel numbers.
262  */
263 static const uint32_t ural_rf2522_r2[] = {
264         0x307f6, 0x307fb, 0x30800, 0x30805, 0x3080a, 0x3080f, 0x30814,
265         0x30819, 0x3081e, 0x30823, 0x30828, 0x3082d, 0x30832, 0x3083e
266 };
267
268 static const uint32_t ural_rf2523_r2[] = {
269         0x00327, 0x00328, 0x00329, 0x0032a, 0x0032b, 0x0032c, 0x0032d,
270         0x0032e, 0x0032f, 0x00340, 0x00341, 0x00342, 0x00343, 0x00346
271 };
272
273 static const uint32_t ural_rf2524_r2[] = {
274         0x00327, 0x00328, 0x00329, 0x0032a, 0x0032b, 0x0032c, 0x0032d,
275         0x0032e, 0x0032f, 0x00340, 0x00341, 0x00342, 0x00343, 0x00346
276 };
277
278 static const uint32_t ural_rf2525_r2[] = {
279         0x20327, 0x20328, 0x20329, 0x2032a, 0x2032b, 0x2032c, 0x2032d,
280         0x2032e, 0x2032f, 0x20340, 0x20341, 0x20342, 0x20343, 0x20346
281 };
282
283 static const uint32_t ural_rf2525_hi_r2[] = {
284         0x2032f, 0x20340, 0x20341, 0x20342, 0x20343, 0x20344, 0x20345,
285         0x20346, 0x20347, 0x20348, 0x20349, 0x2034a, 0x2034b, 0x2034e
286 };
287
288 static const uint32_t ural_rf2525e_r2[] = {
289         0x2044d, 0x2044e, 0x2044f, 0x20460, 0x20461, 0x20462, 0x20463,
290         0x20464, 0x20465, 0x20466, 0x20467, 0x20468, 0x20469, 0x2046b
291 };
292
293 static const uint32_t ural_rf2526_hi_r2[] = {
294         0x0022a, 0x0022b, 0x0022b, 0x0022c, 0x0022c, 0x0022d, 0x0022d,
295         0x0022e, 0x0022e, 0x0022f, 0x0022d, 0x00240, 0x00240, 0x00241
296 };
297
298 static const uint32_t ural_rf2526_r2[] = {
299         0x00226, 0x00227, 0x00227, 0x00228, 0x00228, 0x00229, 0x00229,
300         0x0022a, 0x0022a, 0x0022b, 0x0022b, 0x0022c, 0x0022c, 0x0022d
301 };
302
303 /*
304  * For dual-band RF, RF registers R1 and R4 also depend on channel number;
305  * values taken from the reference driver.
306  */
307 static const struct {
308         uint8_t         chan;
309         uint32_t        r1;
310         uint32_t        r2;
311         uint32_t        r4;
312 } ural_rf5222[] = {
313         {   1, 0x08808, 0x0044d, 0x00282 },
314         {   2, 0x08808, 0x0044e, 0x00282 },
315         {   3, 0x08808, 0x0044f, 0x00282 },
316         {   4, 0x08808, 0x00460, 0x00282 },
317         {   5, 0x08808, 0x00461, 0x00282 },
318         {   6, 0x08808, 0x00462, 0x00282 },
319         {   7, 0x08808, 0x00463, 0x00282 },
320         {   8, 0x08808, 0x00464, 0x00282 },
321         {   9, 0x08808, 0x00465, 0x00282 },
322         {  10, 0x08808, 0x00466, 0x00282 },
323         {  11, 0x08808, 0x00467, 0x00282 },
324         {  12, 0x08808, 0x00468, 0x00282 },
325         {  13, 0x08808, 0x00469, 0x00282 },
326         {  14, 0x08808, 0x0046b, 0x00286 },
327
328         {  36, 0x08804, 0x06225, 0x00287 },
329         {  40, 0x08804, 0x06226, 0x00287 },
330         {  44, 0x08804, 0x06227, 0x00287 },
331         {  48, 0x08804, 0x06228, 0x00287 },
332         {  52, 0x08804, 0x06229, 0x00287 },
333         {  56, 0x08804, 0x0622a, 0x00287 },
334         {  60, 0x08804, 0x0622b, 0x00287 },
335         {  64, 0x08804, 0x0622c, 0x00287 },
336
337         { 100, 0x08804, 0x02200, 0x00283 },
338         { 104, 0x08804, 0x02201, 0x00283 },
339         { 108, 0x08804, 0x02202, 0x00283 },
340         { 112, 0x08804, 0x02203, 0x00283 },
341         { 116, 0x08804, 0x02204, 0x00283 },
342         { 120, 0x08804, 0x02205, 0x00283 },
343         { 124, 0x08804, 0x02206, 0x00283 },
344         { 128, 0x08804, 0x02207, 0x00283 },
345         { 132, 0x08804, 0x02208, 0x00283 },
346         { 136, 0x08804, 0x02209, 0x00283 },
347         { 140, 0x08804, 0x0220a, 0x00283 },
348
349         { 149, 0x08808, 0x02429, 0x00281 },
350         { 153, 0x08808, 0x0242b, 0x00281 },
351         { 157, 0x08808, 0x0242d, 0x00281 },
352         { 161, 0x08808, 0x0242f, 0x00281 }
353 };
354
355 static const struct usb_config ural_config[URAL_N_TRANSFER] = {
356         [URAL_BULK_WR] = {
357                 .type = UE_BULK,
358                 .endpoint = UE_ADDR_ANY,
359                 .direction = UE_DIR_OUT,
360                 .bufsize = (RAL_FRAME_SIZE + RAL_TX_DESC_SIZE + 4),
361                 .flags = {.pipe_bof = 1,.force_short_xfer = 1,},
362                 .callback = ural_bulk_write_callback,
363                 .timeout = 5000,        /* ms */
364         },
365         [URAL_BULK_RD] = {
366                 .type = UE_BULK,
367                 .endpoint = UE_ADDR_ANY,
368                 .direction = UE_DIR_IN,
369                 .bufsize = (RAL_FRAME_SIZE + RAL_RX_DESC_SIZE),
370                 .flags = {.pipe_bof = 1,.short_xfer_ok = 1,},
371                 .callback = ural_bulk_read_callback,
372         },
373 };
374
375 static device_probe_t ural_match;
376 static device_attach_t ural_attach;
377 static device_detach_t ural_detach;
378
379 static device_method_t ural_methods[] = {
380         /* Device interface */
381         DEVMETHOD(device_probe,         ural_match),
382         DEVMETHOD(device_attach,        ural_attach),
383         DEVMETHOD(device_detach,        ural_detach),
384         DEVMETHOD_END
385 };
386
387 static driver_t ural_driver = {
388         .name = "ural",
389         .methods = ural_methods,
390         .size = sizeof(struct ural_softc),
391 };
392
393 static devclass_t ural_devclass;
394
395 DRIVER_MODULE(ural, uhub, ural_driver, ural_devclass, NULL, 0);
396 MODULE_DEPEND(ural, usb, 1, 1, 1);
397 MODULE_DEPEND(ural, wlan, 1, 1, 1);
398 MODULE_VERSION(ural, 1);
399
400 static int
401 ural_match(device_t self)
402 {
403         struct usb_attach_arg *uaa = device_get_ivars(self);
404
405         if (uaa->usb_mode != USB_MODE_HOST)
406                 return (ENXIO);
407         if (uaa->info.bConfigIndex != 0)
408                 return (ENXIO);
409         if (uaa->info.bIfaceIndex != RAL_IFACE_INDEX)
410                 return (ENXIO);
411
412         return (usbd_lookup_id_by_uaa(ural_devs, sizeof(ural_devs), uaa));
413 }
414
415 static int
416 ural_attach(device_t self)
417 {
418         struct usb_attach_arg *uaa = device_get_ivars(self);
419         struct ural_softc *sc = device_get_softc(self);
420         struct ifnet *ifp;
421         struct ieee80211com *ic;
422         uint8_t iface_index, bands;
423         int error;
424
425         device_set_usb_desc(self);
426         sc->sc_udev = uaa->device;
427         sc->sc_dev = self;
428
429         mtx_init(&sc->sc_mtx, device_get_nameunit(self),
430             MTX_NETWORK_LOCK, MTX_DEF);
431
432         iface_index = RAL_IFACE_INDEX;
433         error = usbd_transfer_setup(uaa->device,
434             &iface_index, sc->sc_xfer, ural_config,
435             URAL_N_TRANSFER, sc, &sc->sc_mtx);
436         if (error) {
437                 device_printf(self, "could not allocate USB transfers, "
438                     "err=%s\n", usbd_errstr(error));
439                 goto detach;
440         }
441
442         RAL_LOCK(sc);
443         /* retrieve RT2570 rev. no */
444         sc->asic_rev = ural_read(sc, RAL_MAC_CSR0);
445
446         /* retrieve MAC address and various other things from EEPROM */
447         ural_read_eeprom(sc);
448         RAL_UNLOCK(sc);
449
450         device_printf(self, "MAC/BBP RT2570 (rev 0x%02x), RF %s\n",
451             sc->asic_rev, ural_get_rf(sc->rf_rev));
452
453         ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211);
454         if (ifp == NULL) {
455                 device_printf(sc->sc_dev, "can not if_alloc()\n");
456                 goto detach;
457         }
458         ic = ifp->if_l2com;
459
460         ifp->if_softc = sc;
461         if_initname(ifp, "ural", device_get_unit(sc->sc_dev));
462         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
463         ifp->if_init = ural_init;
464         ifp->if_ioctl = ural_ioctl;
465         ifp->if_start = ural_start;
466         IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
467         ifp->if_snd.ifq_drv_maxlen = ifqmaxlen;
468         IFQ_SET_READY(&ifp->if_snd);
469
470         ic->ic_ifp = ifp;
471         ic->ic_phytype = IEEE80211_T_OFDM; /* not only, but not used */
472
473         /* set device capabilities */
474         ic->ic_caps =
475               IEEE80211_C_STA           /* station mode supported */
476             | IEEE80211_C_IBSS          /* IBSS mode supported */
477             | IEEE80211_C_MONITOR       /* monitor mode supported */
478             | IEEE80211_C_HOSTAP        /* HostAp mode supported */
479             | IEEE80211_C_TXPMGT        /* tx power management */
480             | IEEE80211_C_SHPREAMBLE    /* short preamble supported */
481             | IEEE80211_C_SHSLOT        /* short slot time supported */
482             | IEEE80211_C_BGSCAN        /* bg scanning supported */
483             | IEEE80211_C_WPA           /* 802.11i */
484             ;
485
486         bands = 0;
487         setbit(&bands, IEEE80211_MODE_11B);
488         setbit(&bands, IEEE80211_MODE_11G);
489         if (sc->rf_rev == RAL_RF_5222)
490                 setbit(&bands, IEEE80211_MODE_11A);
491         ieee80211_init_channels(ic, NULL, &bands);
492
493         ieee80211_ifattach(ic, sc->sc_bssid);
494         ic->ic_update_promisc = ural_update_promisc;
495         ic->ic_raw_xmit = ural_raw_xmit;
496         ic->ic_scan_start = ural_scan_start;
497         ic->ic_scan_end = ural_scan_end;
498         ic->ic_set_channel = ural_set_channel;
499
500         ic->ic_vap_create = ural_vap_create;
501         ic->ic_vap_delete = ural_vap_delete;
502
503         ieee80211_radiotap_attach(ic,
504             &sc->sc_txtap.wt_ihdr, sizeof(sc->sc_txtap),
505                 RAL_TX_RADIOTAP_PRESENT,
506             &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap),
507                 RAL_RX_RADIOTAP_PRESENT);
508
509         if (bootverbose)
510                 ieee80211_announce(ic);
511
512         return (0);
513
514 detach:
515         ural_detach(self);
516         return (ENXIO);                 /* failure */
517 }
518
519 static int
520 ural_detach(device_t self)
521 {
522         struct ural_softc *sc = device_get_softc(self);
523         struct ifnet *ifp = sc->sc_ifp;
524         struct ieee80211com *ic;
525
526         /* prevent further ioctls */
527         RAL_LOCK(sc);
528         sc->sc_detached = 1;
529         RAL_UNLOCK(sc);
530
531         /* stop all USB transfers */
532         usbd_transfer_unsetup(sc->sc_xfer, URAL_N_TRANSFER);
533
534         /* free TX list, if any */
535         RAL_LOCK(sc);
536         ural_unsetup_tx_list(sc);
537         RAL_UNLOCK(sc);
538
539         if (ifp) {
540                 ic = ifp->if_l2com;
541                 ieee80211_ifdetach(ic);
542                 if_free(ifp);
543         }
544         mtx_destroy(&sc->sc_mtx);
545
546         return (0);
547 }
548
549 static usb_error_t
550 ural_do_request(struct ural_softc *sc,
551     struct usb_device_request *req, void *data)
552 {
553         usb_error_t err;
554         int ntries = 10;
555
556         while (ntries--) {
557                 err = usbd_do_request_flags(sc->sc_udev, &sc->sc_mtx,
558                     req, data, 0, NULL, 250 /* ms */);
559                 if (err == 0)
560                         break;
561
562                 DPRINTFN(1, "Control request failed, %s (retrying)\n",
563                     usbd_errstr(err));
564                 if (ural_pause(sc, hz / 100))
565                         break;
566         }
567         return (err);
568 }
569
570 static struct ieee80211vap *
571 ural_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
572     enum ieee80211_opmode opmode, int flags,
573     const uint8_t bssid[IEEE80211_ADDR_LEN],
574     const uint8_t mac[IEEE80211_ADDR_LEN])
575 {
576         struct ural_softc *sc = ic->ic_ifp->if_softc;
577         struct ural_vap *uvp;
578         struct ieee80211vap *vap;
579
580         if (!TAILQ_EMPTY(&ic->ic_vaps))         /* only one at a time */
581                 return NULL;
582         uvp = (struct ural_vap *) malloc(sizeof(struct ural_vap),
583             M_80211_VAP, M_NOWAIT | M_ZERO);
584         if (uvp == NULL)
585                 return NULL;
586         vap = &uvp->vap;
587         /* enable s/w bmiss handling for sta mode */
588
589         if (ieee80211_vap_setup(ic, vap, name, unit, opmode,
590             flags | IEEE80211_CLONE_NOBEACONS, bssid, mac) != 0) {
591                 /* out of memory */
592                 free(uvp, M_80211_VAP);
593                 return (NULL);
594         }
595
596         /* override state transition machine */
597         uvp->newstate = vap->iv_newstate;
598         vap->iv_newstate = ural_newstate;
599
600         usb_callout_init_mtx(&uvp->ratectl_ch, &sc->sc_mtx, 0);
601         TASK_INIT(&uvp->ratectl_task, 0, ural_ratectl_task, uvp);
602         ieee80211_ratectl_init(vap);
603         ieee80211_ratectl_setinterval(vap, 1000 /* 1 sec */);
604
605         /* complete setup */
606         ieee80211_vap_attach(vap, ieee80211_media_change, ieee80211_media_status);
607         ic->ic_opmode = opmode;
608         return vap;
609 }
610
611 static void
612 ural_vap_delete(struct ieee80211vap *vap)
613 {
614         struct ural_vap *uvp = URAL_VAP(vap);
615         struct ieee80211com *ic = vap->iv_ic;
616
617         usb_callout_drain(&uvp->ratectl_ch);
618         ieee80211_draintask(ic, &uvp->ratectl_task);
619         ieee80211_ratectl_deinit(vap);
620         ieee80211_vap_detach(vap);
621         free(uvp, M_80211_VAP);
622 }
623
624 static void
625 ural_tx_free(struct ural_tx_data *data, int txerr)
626 {
627         struct ural_softc *sc = data->sc;
628
629         if (data->m != NULL) {
630                 if (data->m->m_flags & M_TXCB)
631                         ieee80211_process_callback(data->ni, data->m,
632                             txerr ? ETIMEDOUT : 0);
633                 m_freem(data->m);
634                 data->m = NULL;
635
636                 ieee80211_free_node(data->ni);
637                 data->ni = NULL;
638         }
639         STAILQ_INSERT_TAIL(&sc->tx_free, data, next);
640         sc->tx_nfree++;
641 }
642
643 static void
644 ural_setup_tx_list(struct ural_softc *sc)
645 {
646         struct ural_tx_data *data;
647         int i;
648
649         sc->tx_nfree = 0;
650         STAILQ_INIT(&sc->tx_q);
651         STAILQ_INIT(&sc->tx_free);
652
653         for (i = 0; i < RAL_TX_LIST_COUNT; i++) {
654                 data = &sc->tx_data[i];
655
656                 data->sc = sc;
657                 STAILQ_INSERT_TAIL(&sc->tx_free, data, next);
658                 sc->tx_nfree++;
659         }
660 }
661
662 static void
663 ural_unsetup_tx_list(struct ural_softc *sc)
664 {
665         struct ural_tx_data *data;
666         int i;
667
668         /* make sure any subsequent use of the queues will fail */
669         sc->tx_nfree = 0;
670         STAILQ_INIT(&sc->tx_q);
671         STAILQ_INIT(&sc->tx_free);
672
673         /* free up all node references and mbufs */
674         for (i = 0; i < RAL_TX_LIST_COUNT; i++) {
675                 data = &sc->tx_data[i];
676
677                 if (data->m != NULL) {
678                         m_freem(data->m);
679                         data->m = NULL;
680                 }
681                 if (data->ni != NULL) {
682                         ieee80211_free_node(data->ni);
683                         data->ni = NULL;
684                 }
685         }
686 }
687
688 static int
689 ural_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
690 {
691         struct ural_vap *uvp = URAL_VAP(vap);
692         struct ieee80211com *ic = vap->iv_ic;
693         struct ural_softc *sc = ic->ic_ifp->if_softc;
694         const struct ieee80211_txparam *tp;
695         struct ieee80211_node *ni;
696         struct mbuf *m;
697
698         DPRINTF("%s -> %s\n",
699                 ieee80211_state_name[vap->iv_state],
700                 ieee80211_state_name[nstate]);
701
702         IEEE80211_UNLOCK(ic);
703         RAL_LOCK(sc);
704         usb_callout_stop(&uvp->ratectl_ch);
705
706         switch (nstate) {
707         case IEEE80211_S_INIT:
708                 if (vap->iv_state == IEEE80211_S_RUN) {
709                         /* abort TSF synchronization */
710                         ural_write(sc, RAL_TXRX_CSR19, 0);
711
712                         /* force tx led to stop blinking */
713                         ural_write(sc, RAL_MAC_CSR20, 0);
714                 }
715                 break;
716
717         case IEEE80211_S_RUN:
718                 ni = ieee80211_ref_node(vap->iv_bss);
719
720                 if (vap->iv_opmode != IEEE80211_M_MONITOR) {
721                         if (ic->ic_bsschan == IEEE80211_CHAN_ANYC) {
722                                 RAL_UNLOCK(sc);
723                                 IEEE80211_LOCK(ic);
724                                 ieee80211_free_node(ni);
725                                 return (-1);
726                         }
727                         ural_update_slot(ic->ic_ifp);
728                         ural_set_txpreamble(sc);
729                         ural_set_basicrates(sc, ic->ic_bsschan);
730                         IEEE80211_ADDR_COPY(sc->sc_bssid, ni->ni_bssid);
731                         ural_set_bssid(sc, sc->sc_bssid);
732                 }
733
734                 if (vap->iv_opmode == IEEE80211_M_HOSTAP ||
735                     vap->iv_opmode == IEEE80211_M_IBSS) {
736                         m = ieee80211_beacon_alloc(ni, &uvp->bo);
737                         if (m == NULL) {
738                                 device_printf(sc->sc_dev,
739                                     "could not allocate beacon\n");
740                                 RAL_UNLOCK(sc);
741                                 IEEE80211_LOCK(ic);
742                                 ieee80211_free_node(ni);
743                                 return (-1);
744                         }
745                         ieee80211_ref_node(ni);
746                         if (ural_tx_bcn(sc, m, ni) != 0) {
747                                 device_printf(sc->sc_dev,
748                                     "could not send beacon\n");
749                                 RAL_UNLOCK(sc);
750                                 IEEE80211_LOCK(ic);
751                                 ieee80211_free_node(ni);
752                                 return (-1);
753                         }
754                 }
755
756                 /* make tx led blink on tx (controlled by ASIC) */
757                 ural_write(sc, RAL_MAC_CSR20, 1);
758
759                 if (vap->iv_opmode != IEEE80211_M_MONITOR)
760                         ural_enable_tsf_sync(sc);
761                 else
762                         ural_enable_tsf(sc);
763
764                 /* enable automatic rate adaptation */
765                 /* XXX should use ic_bsschan but not valid until after newstate call below */
766                 tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)];
767                 if (tp->ucastrate == IEEE80211_FIXED_RATE_NONE)
768                         ural_ratectl_start(sc, ni);
769                 ieee80211_free_node(ni);
770                 break;
771
772         default:
773                 break;
774         }
775         RAL_UNLOCK(sc);
776         IEEE80211_LOCK(ic);
777         return (uvp->newstate(vap, nstate, arg));
778 }
779
780
781 static void
782 ural_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error)
783 {
784         struct ural_softc *sc = usbd_xfer_softc(xfer);
785         struct ifnet *ifp = sc->sc_ifp;
786         struct ieee80211vap *vap;
787         struct ural_tx_data *data;
788         struct mbuf *m;
789         struct usb_page_cache *pc;
790         int len;
791
792         usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
793
794         switch (USB_GET_STATE(xfer)) {
795         case USB_ST_TRANSFERRED:
796                 DPRINTFN(11, "transfer complete, %d bytes\n", len);
797
798                 /* free resources */
799                 data = usbd_xfer_get_priv(xfer);
800                 ural_tx_free(data, 0);
801                 usbd_xfer_set_priv(xfer, NULL);
802
803                 ifp->if_opackets++;
804                 ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
805
806                 /* FALLTHROUGH */
807         case USB_ST_SETUP:
808 tr_setup:
809                 data = STAILQ_FIRST(&sc->tx_q);
810                 if (data) {
811                         STAILQ_REMOVE_HEAD(&sc->tx_q, next);
812                         m = data->m;
813
814                         if (m->m_pkthdr.len > (int)(RAL_FRAME_SIZE + RAL_TX_DESC_SIZE)) {
815                                 DPRINTFN(0, "data overflow, %u bytes\n",
816                                     m->m_pkthdr.len);
817                                 m->m_pkthdr.len = (RAL_FRAME_SIZE + RAL_TX_DESC_SIZE);
818                         }
819                         pc = usbd_xfer_get_frame(xfer, 0);
820                         usbd_copy_in(pc, 0, &data->desc, RAL_TX_DESC_SIZE);
821                         usbd_m_copy_in(pc, RAL_TX_DESC_SIZE, m, 0,
822                             m->m_pkthdr.len);
823
824                         vap = data->ni->ni_vap;
825                         if (ieee80211_radiotap_active_vap(vap)) {
826                                 struct ural_tx_radiotap_header *tap = &sc->sc_txtap;
827
828                                 tap->wt_flags = 0;
829                                 tap->wt_rate = data->rate;
830                                 tap->wt_antenna = sc->tx_ant;
831
832                                 ieee80211_radiotap_tx(vap, m);
833                         }
834
835                         /* xfer length needs to be a multiple of two! */
836                         len = (RAL_TX_DESC_SIZE + m->m_pkthdr.len + 1) & ~1;
837                         if ((len % 64) == 0)
838                                 len += 2;
839
840                         DPRINTFN(11, "sending frame len=%u xferlen=%u\n",
841                             m->m_pkthdr.len, len);
842
843                         usbd_xfer_set_frame_len(xfer, 0, len);
844                         usbd_xfer_set_priv(xfer, data);
845
846                         usbd_transfer_submit(xfer);
847                 }
848                 RAL_UNLOCK(sc);
849                 ural_start(ifp);
850                 RAL_LOCK(sc);
851                 break;
852
853         default:                        /* Error */
854                 DPRINTFN(11, "transfer error, %s\n",
855                     usbd_errstr(error));
856
857                 ifp->if_oerrors++;
858                 data = usbd_xfer_get_priv(xfer);
859                 if (data != NULL) {
860                         ural_tx_free(data, error);
861                         usbd_xfer_set_priv(xfer, NULL);
862                 }
863
864                 if (error == USB_ERR_STALLED) {
865                         /* try to clear stall first */
866                         usbd_xfer_set_stall(xfer);
867                         goto tr_setup;
868                 }
869                 if (error == USB_ERR_TIMEOUT)
870                         device_printf(sc->sc_dev, "device timeout\n");
871                 break;
872         }
873 }
874
875 static void
876 ural_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error)
877 {
878         struct ural_softc *sc = usbd_xfer_softc(xfer);
879         struct ifnet *ifp = sc->sc_ifp;
880         struct ieee80211com *ic = ifp->if_l2com;
881         struct ieee80211_node *ni;
882         struct mbuf *m = NULL;
883         struct usb_page_cache *pc;
884         uint32_t flags;
885         int8_t rssi = 0, nf = 0;
886         int len;
887
888         usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
889
890         switch (USB_GET_STATE(xfer)) {
891         case USB_ST_TRANSFERRED:
892
893                 DPRINTFN(15, "rx done, actlen=%d\n", len);
894
895                 if (len < (int)(RAL_RX_DESC_SIZE + IEEE80211_MIN_LEN)) {
896                         DPRINTF("%s: xfer too short %d\n",
897                             device_get_nameunit(sc->sc_dev), len);
898                         ifp->if_ierrors++;
899                         goto tr_setup;
900                 }
901
902                 len -= RAL_RX_DESC_SIZE;
903                 /* rx descriptor is located at the end */
904                 pc = usbd_xfer_get_frame(xfer, 0);
905                 usbd_copy_out(pc, len, &sc->sc_rx_desc, RAL_RX_DESC_SIZE);
906
907                 rssi = URAL_RSSI(sc->sc_rx_desc.rssi);
908                 nf = RAL_NOISE_FLOOR;
909                 flags = le32toh(sc->sc_rx_desc.flags);
910                 if (flags & (RAL_RX_PHY_ERROR | RAL_RX_CRC_ERROR)) {
911                         /*
912                          * This should not happen since we did not
913                          * request to receive those frames when we
914                          * filled RAL_TXRX_CSR2:
915                          */
916                         DPRINTFN(5, "PHY or CRC error\n");
917                         ifp->if_ierrors++;
918                         goto tr_setup;
919                 }
920
921                 m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
922                 if (m == NULL) {
923                         DPRINTF("could not allocate mbuf\n");
924                         ifp->if_ierrors++;
925                         goto tr_setup;
926                 }
927                 usbd_copy_out(pc, 0, mtod(m, uint8_t *), len);
928
929                 /* finalize mbuf */
930                 m->m_pkthdr.rcvif = ifp;
931                 m->m_pkthdr.len = m->m_len = (flags >> 16) & 0xfff;
932
933                 if (ieee80211_radiotap_active(ic)) {
934                         struct ural_rx_radiotap_header *tap = &sc->sc_rxtap;
935
936                         /* XXX set once */
937                         tap->wr_flags = 0;
938                         tap->wr_rate = ieee80211_plcp2rate(sc->sc_rx_desc.rate,
939                             (flags & RAL_RX_OFDM) ?
940                             IEEE80211_T_OFDM : IEEE80211_T_CCK);
941                         tap->wr_antenna = sc->rx_ant;
942                         tap->wr_antsignal = nf + rssi;
943                         tap->wr_antnoise = nf;
944                 }
945                 /* Strip trailing 802.11 MAC FCS. */
946                 m_adj(m, -IEEE80211_CRC_LEN);
947
948                 /* FALLTHROUGH */
949         case USB_ST_SETUP:
950 tr_setup:
951                 usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
952                 usbd_transfer_submit(xfer);
953
954                 /*
955                  * At the end of a USB callback it is always safe to unlock
956                  * the private mutex of a device! That is why we do the
957                  * "ieee80211_input" here, and not some lines up!
958                  */
959                 RAL_UNLOCK(sc);
960                 if (m) {
961                         ni = ieee80211_find_rxnode(ic,
962                             mtod(m, struct ieee80211_frame_min *));
963                         if (ni != NULL) {
964                                 (void) ieee80211_input(ni, m, rssi, nf);
965                                 ieee80211_free_node(ni);
966                         } else
967                                 (void) ieee80211_input_all(ic, m, rssi, nf);
968                 }
969                 if ((ifp->if_drv_flags & IFF_DRV_OACTIVE) == 0 &&
970                     !IFQ_IS_EMPTY(&ifp->if_snd))
971                         ural_start(ifp);
972                 RAL_LOCK(sc);
973                 return;
974
975         default:                        /* Error */
976                 if (error != USB_ERR_CANCELLED) {
977                         /* try to clear stall first */
978                         usbd_xfer_set_stall(xfer);
979                         goto tr_setup;
980                 }
981                 return;
982         }
983 }
984
985 static uint8_t
986 ural_plcp_signal(int rate)
987 {
988         switch (rate) {
989         /* OFDM rates (cf IEEE Std 802.11a-1999, pp. 14 Table 80) */
990         case 12:        return 0xb;
991         case 18:        return 0xf;
992         case 24:        return 0xa;
993         case 36:        return 0xe;
994         case 48:        return 0x9;
995         case 72:        return 0xd;
996         case 96:        return 0x8;
997         case 108:       return 0xc;
998
999         /* CCK rates (NB: not IEEE std, device-specific) */
1000         case 2:         return 0x0;
1001         case 4:         return 0x1;
1002         case 11:        return 0x2;
1003         case 22:        return 0x3;
1004         }
1005         return 0xff;            /* XXX unsupported/unknown rate */
1006 }
1007
1008 static void
1009 ural_setup_tx_desc(struct ural_softc *sc, struct ural_tx_desc *desc,
1010     uint32_t flags, int len, int rate)
1011 {
1012         struct ifnet *ifp = sc->sc_ifp;
1013         struct ieee80211com *ic = ifp->if_l2com;
1014         uint16_t plcp_length;
1015         int remainder;
1016
1017         desc->flags = htole32(flags);
1018         desc->flags |= htole32(RAL_TX_NEWSEQ);
1019         desc->flags |= htole32(len << 16);
1020
1021         desc->wme = htole16(RAL_AIFSN(2) | RAL_LOGCWMIN(3) | RAL_LOGCWMAX(5));
1022         desc->wme |= htole16(RAL_IVOFFSET(sizeof (struct ieee80211_frame)));
1023
1024         /* setup PLCP fields */
1025         desc->plcp_signal  = ural_plcp_signal(rate);
1026         desc->plcp_service = 4;
1027
1028         len += IEEE80211_CRC_LEN;
1029         if (ieee80211_rate2phytype(ic->ic_rt, rate) == IEEE80211_T_OFDM) {
1030                 desc->flags |= htole32(RAL_TX_OFDM);
1031
1032                 plcp_length = len & 0xfff;
1033                 desc->plcp_length_hi = plcp_length >> 6;
1034                 desc->plcp_length_lo = plcp_length & 0x3f;
1035         } else {
1036                 if (rate == 0)
1037                         rate = 2;       /* avoid division by zero */
1038                 plcp_length = (16 * len + rate - 1) / rate;
1039                 if (rate == 22) {
1040                         remainder = (16 * len) % 22;
1041                         if (remainder != 0 && remainder < 7)
1042                                 desc->plcp_service |= RAL_PLCP_LENGEXT;
1043                 }
1044                 desc->plcp_length_hi = plcp_length >> 8;
1045                 desc->plcp_length_lo = plcp_length & 0xff;
1046
1047                 if (rate != 2 && (ic->ic_flags & IEEE80211_F_SHPREAMBLE))
1048                         desc->plcp_signal |= 0x08;
1049         }
1050
1051         desc->iv = 0;
1052         desc->eiv = 0;
1053 }
1054
1055 #define RAL_TX_TIMEOUT  5000
1056
1057 static int
1058 ural_tx_bcn(struct ural_softc *sc, struct mbuf *m0, struct ieee80211_node *ni)
1059 {
1060         struct ieee80211vap *vap = ni->ni_vap;
1061         struct ieee80211com *ic = ni->ni_ic;
1062         struct ifnet *ifp = sc->sc_ifp;
1063         const struct ieee80211_txparam *tp;
1064         struct ural_tx_data *data;
1065
1066         if (sc->tx_nfree == 0) {
1067                 ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1068                 m_freem(m0);
1069                 ieee80211_free_node(ni);
1070                 return (EIO);
1071         }
1072         if (ic->ic_bsschan == IEEE80211_CHAN_ANYC) {
1073                 m_freem(m0);
1074                 ieee80211_free_node(ni);
1075                 return (ENXIO);
1076         }
1077         data = STAILQ_FIRST(&sc->tx_free);
1078         STAILQ_REMOVE_HEAD(&sc->tx_free, next);
1079         sc->tx_nfree--;
1080         tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_bsschan)];
1081
1082         data->m = m0;
1083         data->ni = ni;
1084         data->rate = tp->mgmtrate;
1085
1086         ural_setup_tx_desc(sc, &data->desc,
1087             RAL_TX_IFS_NEWBACKOFF | RAL_TX_TIMESTAMP, m0->m_pkthdr.len,
1088             tp->mgmtrate);
1089
1090         DPRINTFN(10, "sending beacon frame len=%u rate=%u\n",
1091             m0->m_pkthdr.len, tp->mgmtrate);
1092
1093         STAILQ_INSERT_TAIL(&sc->tx_q, data, next);
1094         usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]);
1095
1096         return (0);
1097 }
1098
1099 static int
1100 ural_tx_mgt(struct ural_softc *sc, struct mbuf *m0, struct ieee80211_node *ni)
1101 {
1102         struct ieee80211vap *vap = ni->ni_vap;
1103         struct ieee80211com *ic = ni->ni_ic;
1104         const struct ieee80211_txparam *tp;
1105         struct ural_tx_data *data;
1106         struct ieee80211_frame *wh;
1107         struct ieee80211_key *k;
1108         uint32_t flags;
1109         uint16_t dur;
1110
1111         RAL_LOCK_ASSERT(sc, MA_OWNED);
1112
1113         data = STAILQ_FIRST(&sc->tx_free);
1114         STAILQ_REMOVE_HEAD(&sc->tx_free, next);
1115         sc->tx_nfree--;
1116
1117         tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)];
1118
1119         wh = mtod(m0, struct ieee80211_frame *);
1120         if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
1121                 k = ieee80211_crypto_encap(ni, m0);
1122                 if (k == NULL) {
1123                         m_freem(m0);
1124                         return ENOBUFS;
1125                 }
1126                 wh = mtod(m0, struct ieee80211_frame *);
1127         }
1128
1129         data->m = m0;
1130         data->ni = ni;
1131         data->rate = tp->mgmtrate;
1132
1133         flags = 0;
1134         if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1135                 flags |= RAL_TX_ACK;
1136
1137                 dur = ieee80211_ack_duration(ic->ic_rt, tp->mgmtrate, 
1138                     ic->ic_flags & IEEE80211_F_SHPREAMBLE);
1139                 USETW(wh->i_dur, dur);
1140
1141                 /* tell hardware to add timestamp for probe responses */
1142                 if ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) ==
1143                     IEEE80211_FC0_TYPE_MGT &&
1144                     (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) ==
1145                     IEEE80211_FC0_SUBTYPE_PROBE_RESP)
1146                         flags |= RAL_TX_TIMESTAMP;
1147         }
1148
1149         ural_setup_tx_desc(sc, &data->desc, flags, m0->m_pkthdr.len, tp->mgmtrate);
1150
1151         DPRINTFN(10, "sending mgt frame len=%u rate=%u\n",
1152             m0->m_pkthdr.len, tp->mgmtrate);
1153
1154         STAILQ_INSERT_TAIL(&sc->tx_q, data, next);
1155         usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]);
1156
1157         return 0;
1158 }
1159
1160 static int
1161 ural_sendprot(struct ural_softc *sc,
1162     const struct mbuf *m, struct ieee80211_node *ni, int prot, int rate)
1163 {
1164         struct ieee80211com *ic = ni->ni_ic;
1165         const struct ieee80211_frame *wh;
1166         struct ural_tx_data *data;
1167         struct mbuf *mprot;
1168         int protrate, ackrate, pktlen, flags, isshort;
1169         uint16_t dur;
1170
1171         KASSERT(prot == IEEE80211_PROT_RTSCTS || prot == IEEE80211_PROT_CTSONLY,
1172             ("protection %d", prot));
1173
1174         wh = mtod(m, const struct ieee80211_frame *);
1175         pktlen = m->m_pkthdr.len + IEEE80211_CRC_LEN;
1176
1177         protrate = ieee80211_ctl_rate(ic->ic_rt, rate);
1178         ackrate = ieee80211_ack_rate(ic->ic_rt, rate);
1179
1180         isshort = (ic->ic_flags & IEEE80211_F_SHPREAMBLE) != 0;
1181         dur = ieee80211_compute_duration(ic->ic_rt, pktlen, rate, isshort)
1182             + ieee80211_ack_duration(ic->ic_rt, rate, isshort);
1183         flags = RAL_TX_RETRY(7);
1184         if (prot == IEEE80211_PROT_RTSCTS) {
1185                 /* NB: CTS is the same size as an ACK */
1186                 dur += ieee80211_ack_duration(ic->ic_rt, rate, isshort);
1187                 flags |= RAL_TX_ACK;
1188                 mprot = ieee80211_alloc_rts(ic, wh->i_addr1, wh->i_addr2, dur);
1189         } else {
1190                 mprot = ieee80211_alloc_cts(ic, ni->ni_vap->iv_myaddr, dur);
1191         }
1192         if (mprot == NULL) {
1193                 /* XXX stat + msg */
1194                 return ENOBUFS;
1195         }
1196         data = STAILQ_FIRST(&sc->tx_free);
1197         STAILQ_REMOVE_HEAD(&sc->tx_free, next);
1198         sc->tx_nfree--;
1199
1200         data->m = mprot;
1201         data->ni = ieee80211_ref_node(ni);
1202         data->rate = protrate;
1203         ural_setup_tx_desc(sc, &data->desc, flags, mprot->m_pkthdr.len, protrate);
1204
1205         STAILQ_INSERT_TAIL(&sc->tx_q, data, next);
1206         usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]);
1207
1208         return 0;
1209 }
1210
1211 static int
1212 ural_tx_raw(struct ural_softc *sc, struct mbuf *m0, struct ieee80211_node *ni,
1213     const struct ieee80211_bpf_params *params)
1214 {
1215         struct ieee80211com *ic = ni->ni_ic;
1216         struct ural_tx_data *data;
1217         uint32_t flags;
1218         int error;
1219         int rate;
1220
1221         RAL_LOCK_ASSERT(sc, MA_OWNED);
1222         KASSERT(params != NULL, ("no raw xmit params"));
1223
1224         rate = params->ibp_rate0;
1225         if (!ieee80211_isratevalid(ic->ic_rt, rate)) {
1226                 m_freem(m0);
1227                 return EINVAL;
1228         }
1229         flags = 0;
1230         if ((params->ibp_flags & IEEE80211_BPF_NOACK) == 0)
1231                 flags |= RAL_TX_ACK;
1232         if (params->ibp_flags & (IEEE80211_BPF_RTS|IEEE80211_BPF_CTS)) {
1233                 error = ural_sendprot(sc, m0, ni,
1234                     params->ibp_flags & IEEE80211_BPF_RTS ?
1235                          IEEE80211_PROT_RTSCTS : IEEE80211_PROT_CTSONLY,
1236                     rate);
1237                 if (error || sc->tx_nfree == 0) {
1238                         m_freem(m0);
1239                         return ENOBUFS;
1240                 }
1241                 flags |= RAL_TX_IFS_SIFS;
1242         }
1243
1244         data = STAILQ_FIRST(&sc->tx_free);
1245         STAILQ_REMOVE_HEAD(&sc->tx_free, next);
1246         sc->tx_nfree--;
1247
1248         data->m = m0;
1249         data->ni = ni;
1250         data->rate = rate;
1251
1252         /* XXX need to setup descriptor ourself */
1253         ural_setup_tx_desc(sc, &data->desc, flags, m0->m_pkthdr.len, rate);
1254
1255         DPRINTFN(10, "sending raw frame len=%u rate=%u\n",
1256             m0->m_pkthdr.len, rate);
1257
1258         STAILQ_INSERT_TAIL(&sc->tx_q, data, next);
1259         usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]);
1260
1261         return 0;
1262 }
1263
1264 static int
1265 ural_tx_data(struct ural_softc *sc, struct mbuf *m0, struct ieee80211_node *ni)
1266 {
1267         struct ieee80211vap *vap = ni->ni_vap;
1268         struct ieee80211com *ic = ni->ni_ic;
1269         struct ural_tx_data *data;
1270         struct ieee80211_frame *wh;
1271         const struct ieee80211_txparam *tp;
1272         struct ieee80211_key *k;
1273         uint32_t flags = 0;
1274         uint16_t dur;
1275         int error, rate;
1276
1277         RAL_LOCK_ASSERT(sc, MA_OWNED);
1278
1279         wh = mtod(m0, struct ieee80211_frame *);
1280
1281         tp = &vap->iv_txparms[ieee80211_chan2mode(ni->ni_chan)];
1282         if (IEEE80211_IS_MULTICAST(wh->i_addr1))
1283                 rate = tp->mcastrate;
1284         else if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE)
1285                 rate = tp->ucastrate;
1286         else
1287                 rate = ni->ni_txrate;
1288
1289         if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
1290                 k = ieee80211_crypto_encap(ni, m0);
1291                 if (k == NULL) {
1292                         m_freem(m0);
1293                         return ENOBUFS;
1294                 }
1295                 /* packet header may have moved, reset our local pointer */
1296                 wh = mtod(m0, struct ieee80211_frame *);
1297         }
1298
1299         if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1300                 int prot = IEEE80211_PROT_NONE;
1301                 if (m0->m_pkthdr.len + IEEE80211_CRC_LEN > vap->iv_rtsthreshold)
1302                         prot = IEEE80211_PROT_RTSCTS;
1303                 else if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
1304                     ieee80211_rate2phytype(ic->ic_rt, rate) == IEEE80211_T_OFDM)
1305                         prot = ic->ic_protmode;
1306                 if (prot != IEEE80211_PROT_NONE) {
1307                         error = ural_sendprot(sc, m0, ni, prot, rate);
1308                         if (error || sc->tx_nfree == 0) {
1309                                 m_freem(m0);
1310                                 return ENOBUFS;
1311                         }
1312                         flags |= RAL_TX_IFS_SIFS;
1313                 }
1314         }
1315
1316         data = STAILQ_FIRST(&sc->tx_free);
1317         STAILQ_REMOVE_HEAD(&sc->tx_free, next);
1318         sc->tx_nfree--;
1319
1320         data->m = m0;
1321         data->ni = ni;
1322         data->rate = rate;
1323
1324         if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1325                 flags |= RAL_TX_ACK;
1326                 flags |= RAL_TX_RETRY(7);
1327
1328                 dur = ieee80211_ack_duration(ic->ic_rt, rate, 
1329                     ic->ic_flags & IEEE80211_F_SHPREAMBLE);
1330                 USETW(wh->i_dur, dur);
1331         }
1332
1333         ural_setup_tx_desc(sc, &data->desc, flags, m0->m_pkthdr.len, rate);
1334
1335         DPRINTFN(10, "sending data frame len=%u rate=%u\n",
1336             m0->m_pkthdr.len, rate);
1337
1338         STAILQ_INSERT_TAIL(&sc->tx_q, data, next);
1339         usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]);
1340
1341         return 0;
1342 }
1343
1344 static void
1345 ural_start(struct ifnet *ifp)
1346 {
1347         struct ural_softc *sc = ifp->if_softc;
1348         struct ieee80211_node *ni;
1349         struct mbuf *m;
1350
1351         RAL_LOCK(sc);
1352         if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
1353                 RAL_UNLOCK(sc);
1354                 return;
1355         }
1356         for (;;) {
1357                 IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
1358                 if (m == NULL)
1359                         break;
1360                 if (sc->tx_nfree < RAL_TX_MINFREE) {
1361                         IFQ_DRV_PREPEND(&ifp->if_snd, m);
1362                         ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1363                         break;
1364                 }
1365                 ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
1366                 if (ural_tx_data(sc, m, ni) != 0) {
1367                         ieee80211_free_node(ni);
1368                         ifp->if_oerrors++;
1369                         break;
1370                 }
1371         }
1372         RAL_UNLOCK(sc);
1373 }
1374
1375 static int
1376 ural_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1377 {
1378         struct ural_softc *sc = ifp->if_softc;
1379         struct ieee80211com *ic = ifp->if_l2com;
1380         struct ifreq *ifr = (struct ifreq *) data;
1381         int error;
1382         int startall = 0;
1383
1384         RAL_LOCK(sc);
1385         error = sc->sc_detached ? ENXIO : 0;
1386         RAL_UNLOCK(sc);
1387         if (error)
1388                 return (error);
1389
1390         switch (cmd) {
1391         case SIOCSIFFLAGS:
1392                 RAL_LOCK(sc);
1393                 if (ifp->if_flags & IFF_UP) {
1394                         if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
1395                                 ural_init_locked(sc);
1396                                 startall = 1;
1397                         } else
1398                                 ural_setpromisc(sc);
1399                 } else {
1400                         if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1401                                 ural_stop(sc);
1402                 }
1403                 RAL_UNLOCK(sc);
1404                 if (startall)
1405                         ieee80211_start_all(ic);
1406                 break;
1407         case SIOCGIFMEDIA:
1408         case SIOCSIFMEDIA:
1409                 error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
1410                 break;
1411         default:
1412                 error = ether_ioctl(ifp, cmd, data);
1413                 break;
1414         }
1415         return error;
1416 }
1417
1418 static void
1419 ural_set_testmode(struct ural_softc *sc)
1420 {
1421         struct usb_device_request req;
1422         usb_error_t error;
1423
1424         req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1425         req.bRequest = RAL_VENDOR_REQUEST;
1426         USETW(req.wValue, 4);
1427         USETW(req.wIndex, 1);
1428         USETW(req.wLength, 0);
1429
1430         error = ural_do_request(sc, &req, NULL);
1431         if (error != 0) {
1432                 device_printf(sc->sc_dev, "could not set test mode: %s\n",
1433                     usbd_errstr(error));
1434         }
1435 }
1436
1437 static void
1438 ural_eeprom_read(struct ural_softc *sc, uint16_t addr, void *buf, int len)
1439 {
1440         struct usb_device_request req;
1441         usb_error_t error;
1442
1443         req.bmRequestType = UT_READ_VENDOR_DEVICE;
1444         req.bRequest = RAL_READ_EEPROM;
1445         USETW(req.wValue, 0);
1446         USETW(req.wIndex, addr);
1447         USETW(req.wLength, len);
1448
1449         error = ural_do_request(sc, &req, buf);
1450         if (error != 0) {
1451                 device_printf(sc->sc_dev, "could not read EEPROM: %s\n",
1452                     usbd_errstr(error));
1453         }
1454 }
1455
1456 static uint16_t
1457 ural_read(struct ural_softc *sc, uint16_t reg)
1458 {
1459         struct usb_device_request req;
1460         usb_error_t error;
1461         uint16_t val;
1462
1463         req.bmRequestType = UT_READ_VENDOR_DEVICE;
1464         req.bRequest = RAL_READ_MAC;
1465         USETW(req.wValue, 0);
1466         USETW(req.wIndex, reg);
1467         USETW(req.wLength, sizeof (uint16_t));
1468
1469         error = ural_do_request(sc, &req, &val);
1470         if (error != 0) {
1471                 device_printf(sc->sc_dev, "could not read MAC register: %s\n",
1472                     usbd_errstr(error));
1473                 return 0;
1474         }
1475
1476         return le16toh(val);
1477 }
1478
1479 static void
1480 ural_read_multi(struct ural_softc *sc, uint16_t reg, void *buf, int len)
1481 {
1482         struct usb_device_request req;
1483         usb_error_t error;
1484
1485         req.bmRequestType = UT_READ_VENDOR_DEVICE;
1486         req.bRequest = RAL_READ_MULTI_MAC;
1487         USETW(req.wValue, 0);
1488         USETW(req.wIndex, reg);
1489         USETW(req.wLength, len);
1490
1491         error = ural_do_request(sc, &req, buf);
1492         if (error != 0) {
1493                 device_printf(sc->sc_dev, "could not read MAC register: %s\n",
1494                     usbd_errstr(error));
1495         }
1496 }
1497
1498 static void
1499 ural_write(struct ural_softc *sc, uint16_t reg, uint16_t val)
1500 {
1501         struct usb_device_request req;
1502         usb_error_t error;
1503
1504         req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1505         req.bRequest = RAL_WRITE_MAC;
1506         USETW(req.wValue, val);
1507         USETW(req.wIndex, reg);
1508         USETW(req.wLength, 0);
1509
1510         error = ural_do_request(sc, &req, NULL);
1511         if (error != 0) {
1512                 device_printf(sc->sc_dev, "could not write MAC register: %s\n",
1513                     usbd_errstr(error));
1514         }
1515 }
1516
1517 static void
1518 ural_write_multi(struct ural_softc *sc, uint16_t reg, void *buf, int len)
1519 {
1520         struct usb_device_request req;
1521         usb_error_t error;
1522
1523         req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1524         req.bRequest = RAL_WRITE_MULTI_MAC;
1525         USETW(req.wValue, 0);
1526         USETW(req.wIndex, reg);
1527         USETW(req.wLength, len);
1528
1529         error = ural_do_request(sc, &req, buf);
1530         if (error != 0) {
1531                 device_printf(sc->sc_dev, "could not write MAC register: %s\n",
1532                     usbd_errstr(error));
1533         }
1534 }
1535
1536 static void
1537 ural_bbp_write(struct ural_softc *sc, uint8_t reg, uint8_t val)
1538 {
1539         uint16_t tmp;
1540         int ntries;
1541
1542         for (ntries = 0; ntries < 100; ntries++) {
1543                 if (!(ural_read(sc, RAL_PHY_CSR8) & RAL_BBP_BUSY))
1544                         break;
1545                 if (ural_pause(sc, hz / 100))
1546                         break;
1547         }
1548         if (ntries == 100) {
1549                 device_printf(sc->sc_dev, "could not write to BBP\n");
1550                 return;
1551         }
1552
1553         tmp = reg << 8 | val;
1554         ural_write(sc, RAL_PHY_CSR7, tmp);
1555 }
1556
1557 static uint8_t
1558 ural_bbp_read(struct ural_softc *sc, uint8_t reg)
1559 {
1560         uint16_t val;
1561         int ntries;
1562
1563         val = RAL_BBP_WRITE | reg << 8;
1564         ural_write(sc, RAL_PHY_CSR7, val);
1565
1566         for (ntries = 0; ntries < 100; ntries++) {
1567                 if (!(ural_read(sc, RAL_PHY_CSR8) & RAL_BBP_BUSY))
1568                         break;
1569                 if (ural_pause(sc, hz / 100))
1570                         break;
1571         }
1572         if (ntries == 100) {
1573                 device_printf(sc->sc_dev, "could not read BBP\n");
1574                 return 0;
1575         }
1576
1577         return ural_read(sc, RAL_PHY_CSR7) & 0xff;
1578 }
1579
1580 static void
1581 ural_rf_write(struct ural_softc *sc, uint8_t reg, uint32_t val)
1582 {
1583         uint32_t tmp;
1584         int ntries;
1585
1586         for (ntries = 0; ntries < 100; ntries++) {
1587                 if (!(ural_read(sc, RAL_PHY_CSR10) & RAL_RF_LOBUSY))
1588                         break;
1589                 if (ural_pause(sc, hz / 100))
1590                         break;
1591         }
1592         if (ntries == 100) {
1593                 device_printf(sc->sc_dev, "could not write to RF\n");
1594                 return;
1595         }
1596
1597         tmp = RAL_RF_BUSY | RAL_RF_20BIT | (val & 0xfffff) << 2 | (reg & 0x3);
1598         ural_write(sc, RAL_PHY_CSR9,  tmp & 0xffff);
1599         ural_write(sc, RAL_PHY_CSR10, tmp >> 16);
1600
1601         /* remember last written value in sc */
1602         sc->rf_regs[reg] = val;
1603
1604         DPRINTFN(15, "RF R[%u] <- 0x%05x\n", reg & 0x3, val & 0xfffff);
1605 }
1606
1607 static void
1608 ural_scan_start(struct ieee80211com *ic)
1609 {
1610         struct ifnet *ifp = ic->ic_ifp;
1611         struct ural_softc *sc = ifp->if_softc;
1612
1613         RAL_LOCK(sc);
1614         ural_write(sc, RAL_TXRX_CSR19, 0);
1615         ural_set_bssid(sc, ifp->if_broadcastaddr);
1616         RAL_UNLOCK(sc);
1617 }
1618
1619 static void
1620 ural_scan_end(struct ieee80211com *ic)
1621 {
1622         struct ural_softc *sc = ic->ic_ifp->if_softc;
1623
1624         RAL_LOCK(sc);
1625         ural_enable_tsf_sync(sc);
1626         ural_set_bssid(sc, sc->sc_bssid);
1627         RAL_UNLOCK(sc);
1628
1629 }
1630
1631 static void
1632 ural_set_channel(struct ieee80211com *ic)
1633 {
1634         struct ural_softc *sc = ic->ic_ifp->if_softc;
1635
1636         RAL_LOCK(sc);
1637         ural_set_chan(sc, ic->ic_curchan);
1638         RAL_UNLOCK(sc);
1639 }
1640
1641 static void
1642 ural_set_chan(struct ural_softc *sc, struct ieee80211_channel *c)
1643 {
1644         struct ifnet *ifp = sc->sc_ifp;
1645         struct ieee80211com *ic = ifp->if_l2com;
1646         uint8_t power, tmp;
1647         int i, chan;
1648
1649         chan = ieee80211_chan2ieee(ic, c);
1650         if (chan == 0 || chan == IEEE80211_CHAN_ANY)
1651                 return;
1652
1653         if (IEEE80211_IS_CHAN_2GHZ(c))
1654                 power = min(sc->txpow[chan - 1], 31);
1655         else
1656                 power = 31;
1657
1658         /* adjust txpower using ifconfig settings */
1659         power -= (100 - ic->ic_txpowlimit) / 8;
1660
1661         DPRINTFN(2, "setting channel to %u, txpower to %u\n", chan, power);
1662
1663         switch (sc->rf_rev) {
1664         case RAL_RF_2522:
1665                 ural_rf_write(sc, RAL_RF1, 0x00814);
1666                 ural_rf_write(sc, RAL_RF2, ural_rf2522_r2[chan - 1]);
1667                 ural_rf_write(sc, RAL_RF3, power << 7 | 0x00040);
1668                 break;
1669
1670         case RAL_RF_2523:
1671                 ural_rf_write(sc, RAL_RF1, 0x08804);
1672                 ural_rf_write(sc, RAL_RF2, ural_rf2523_r2[chan - 1]);
1673                 ural_rf_write(sc, RAL_RF3, power << 7 | 0x38044);
1674                 ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
1675                 break;
1676
1677         case RAL_RF_2524:
1678                 ural_rf_write(sc, RAL_RF1, 0x0c808);
1679                 ural_rf_write(sc, RAL_RF2, ural_rf2524_r2[chan - 1]);
1680                 ural_rf_write(sc, RAL_RF3, power << 7 | 0x00040);
1681                 ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
1682                 break;
1683
1684         case RAL_RF_2525:
1685                 ural_rf_write(sc, RAL_RF1, 0x08808);
1686                 ural_rf_write(sc, RAL_RF2, ural_rf2525_hi_r2[chan - 1]);
1687                 ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
1688                 ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
1689
1690                 ural_rf_write(sc, RAL_RF1, 0x08808);
1691                 ural_rf_write(sc, RAL_RF2, ural_rf2525_r2[chan - 1]);
1692                 ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
1693                 ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
1694                 break;
1695
1696         case RAL_RF_2525E:
1697                 ural_rf_write(sc, RAL_RF1, 0x08808);
1698                 ural_rf_write(sc, RAL_RF2, ural_rf2525e_r2[chan - 1]);
1699                 ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
1700                 ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00286 : 0x00282);
1701                 break;
1702
1703         case RAL_RF_2526:
1704                 ural_rf_write(sc, RAL_RF2, ural_rf2526_hi_r2[chan - 1]);
1705                 ural_rf_write(sc, RAL_RF4, (chan & 1) ? 0x00386 : 0x00381);
1706                 ural_rf_write(sc, RAL_RF1, 0x08804);
1707
1708                 ural_rf_write(sc, RAL_RF2, ural_rf2526_r2[chan - 1]);
1709                 ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
1710                 ural_rf_write(sc, RAL_RF4, (chan & 1) ? 0x00386 : 0x00381);
1711                 break;
1712
1713         /* dual-band RF */
1714         case RAL_RF_5222:
1715                 for (i = 0; ural_rf5222[i].chan != chan; i++);
1716
1717                 ural_rf_write(sc, RAL_RF1, ural_rf5222[i].r1);
1718                 ural_rf_write(sc, RAL_RF2, ural_rf5222[i].r2);
1719                 ural_rf_write(sc, RAL_RF3, power << 7 | 0x00040);
1720                 ural_rf_write(sc, RAL_RF4, ural_rf5222[i].r4);
1721                 break;
1722         }
1723
1724         if (ic->ic_opmode != IEEE80211_M_MONITOR &&
1725             (ic->ic_flags & IEEE80211_F_SCAN) == 0) {
1726                 /* set Japan filter bit for channel 14 */
1727                 tmp = ural_bbp_read(sc, 70);
1728
1729                 tmp &= ~RAL_JAPAN_FILTER;
1730                 if (chan == 14)
1731                         tmp |= RAL_JAPAN_FILTER;
1732
1733                 ural_bbp_write(sc, 70, tmp);
1734
1735                 /* clear CRC errors */
1736                 ural_read(sc, RAL_STA_CSR0);
1737
1738                 ural_pause(sc, hz / 100);
1739                 ural_disable_rf_tune(sc);
1740         }
1741
1742         /* XXX doesn't belong here */
1743         /* update basic rate set */
1744         ural_set_basicrates(sc, c);
1745
1746         /* give the hardware some time to do the switchover */
1747         ural_pause(sc, hz / 100);
1748 }
1749
1750 /*
1751  * Disable RF auto-tuning.
1752  */
1753 static void
1754 ural_disable_rf_tune(struct ural_softc *sc)
1755 {
1756         uint32_t tmp;
1757
1758         if (sc->rf_rev != RAL_RF_2523) {
1759                 tmp = sc->rf_regs[RAL_RF1] & ~RAL_RF1_AUTOTUNE;
1760                 ural_rf_write(sc, RAL_RF1, tmp);
1761         }
1762
1763         tmp = sc->rf_regs[RAL_RF3] & ~RAL_RF3_AUTOTUNE;
1764         ural_rf_write(sc, RAL_RF3, tmp);
1765
1766         DPRINTFN(2, "disabling RF autotune\n");
1767 }
1768
1769 /*
1770  * Refer to IEEE Std 802.11-1999 pp. 123 for more information on TSF
1771  * synchronization.
1772  */
1773 static void
1774 ural_enable_tsf_sync(struct ural_softc *sc)
1775 {
1776         struct ifnet *ifp = sc->sc_ifp;
1777         struct ieee80211com *ic = ifp->if_l2com;
1778         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1779         uint16_t logcwmin, preload, tmp;
1780
1781         /* first, disable TSF synchronization */
1782         ural_write(sc, RAL_TXRX_CSR19, 0);
1783
1784         tmp = (16 * vap->iv_bss->ni_intval) << 4;
1785         ural_write(sc, RAL_TXRX_CSR18, tmp);
1786
1787         logcwmin = (ic->ic_opmode == IEEE80211_M_IBSS) ? 2 : 0;
1788         preload = (ic->ic_opmode == IEEE80211_M_IBSS) ? 320 : 6;
1789         tmp = logcwmin << 12 | preload;
1790         ural_write(sc, RAL_TXRX_CSR20, tmp);
1791
1792         /* finally, enable TSF synchronization */
1793         tmp = RAL_ENABLE_TSF | RAL_ENABLE_TBCN;
1794         if (ic->ic_opmode == IEEE80211_M_STA)
1795                 tmp |= RAL_ENABLE_TSF_SYNC(1);
1796         else
1797                 tmp |= RAL_ENABLE_TSF_SYNC(2) | RAL_ENABLE_BEACON_GENERATOR;
1798         ural_write(sc, RAL_TXRX_CSR19, tmp);
1799
1800         DPRINTF("enabling TSF synchronization\n");
1801 }
1802
1803 static void
1804 ural_enable_tsf(struct ural_softc *sc)
1805 {
1806         /* first, disable TSF synchronization */
1807         ural_write(sc, RAL_TXRX_CSR19, 0);
1808         ural_write(sc, RAL_TXRX_CSR19, RAL_ENABLE_TSF | RAL_ENABLE_TSF_SYNC(2));
1809 }
1810
1811 #define RAL_RXTX_TURNAROUND     5       /* us */
1812 static void
1813 ural_update_slot(struct ifnet *ifp)
1814 {
1815         struct ural_softc *sc = ifp->if_softc;
1816         struct ieee80211com *ic = ifp->if_l2com;
1817         uint16_t slottime, sifs, eifs;
1818
1819         slottime = (ic->ic_flags & IEEE80211_F_SHSLOT) ? 9 : 20;
1820
1821         /*
1822          * These settings may sound a bit inconsistent but this is what the
1823          * reference driver does.
1824          */
1825         if (ic->ic_curmode == IEEE80211_MODE_11B) {
1826                 sifs = 16 - RAL_RXTX_TURNAROUND;
1827                 eifs = 364;
1828         } else {
1829                 sifs = 10 - RAL_RXTX_TURNAROUND;
1830                 eifs = 64;
1831         }
1832
1833         ural_write(sc, RAL_MAC_CSR10, slottime);
1834         ural_write(sc, RAL_MAC_CSR11, sifs);
1835         ural_write(sc, RAL_MAC_CSR12, eifs);
1836 }
1837
1838 static void
1839 ural_set_txpreamble(struct ural_softc *sc)
1840 {
1841         struct ifnet *ifp = sc->sc_ifp;
1842         struct ieee80211com *ic = ifp->if_l2com;
1843         uint16_t tmp;
1844
1845         tmp = ural_read(sc, RAL_TXRX_CSR10);
1846
1847         tmp &= ~RAL_SHORT_PREAMBLE;
1848         if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
1849                 tmp |= RAL_SHORT_PREAMBLE;
1850
1851         ural_write(sc, RAL_TXRX_CSR10, tmp);
1852 }
1853
1854 static void
1855 ural_set_basicrates(struct ural_softc *sc, const struct ieee80211_channel *c)
1856 {
1857         /* XXX wrong, take from rate set */
1858         /* update basic rate set */
1859         if (IEEE80211_IS_CHAN_5GHZ(c)) {
1860                 /* 11a basic rates: 6, 12, 24Mbps */
1861                 ural_write(sc, RAL_TXRX_CSR11, 0x150);
1862         } else if (IEEE80211_IS_CHAN_ANYG(c)) {
1863                 /* 11g basic rates: 1, 2, 5.5, 11, 6, 12, 24Mbps */
1864                 ural_write(sc, RAL_TXRX_CSR11, 0x15f);
1865         } else {
1866                 /* 11b basic rates: 1, 2Mbps */
1867                 ural_write(sc, RAL_TXRX_CSR11, 0x3);
1868         }
1869 }
1870
1871 static void
1872 ural_set_bssid(struct ural_softc *sc, const uint8_t *bssid)
1873 {
1874         uint16_t tmp;
1875
1876         tmp = bssid[0] | bssid[1] << 8;
1877         ural_write(sc, RAL_MAC_CSR5, tmp);
1878
1879         tmp = bssid[2] | bssid[3] << 8;
1880         ural_write(sc, RAL_MAC_CSR6, tmp);
1881
1882         tmp = bssid[4] | bssid[5] << 8;
1883         ural_write(sc, RAL_MAC_CSR7, tmp);
1884
1885         DPRINTF("setting BSSID to %6D\n", bssid, ":");
1886 }
1887
1888 static void
1889 ural_set_macaddr(struct ural_softc *sc, uint8_t *addr)
1890 {
1891         uint16_t tmp;
1892
1893         tmp = addr[0] | addr[1] << 8;
1894         ural_write(sc, RAL_MAC_CSR2, tmp);
1895
1896         tmp = addr[2] | addr[3] << 8;
1897         ural_write(sc, RAL_MAC_CSR3, tmp);
1898
1899         tmp = addr[4] | addr[5] << 8;
1900         ural_write(sc, RAL_MAC_CSR4, tmp);
1901
1902         DPRINTF("setting MAC address to %6D\n", addr, ":");
1903 }
1904
1905 static void
1906 ural_setpromisc(struct ural_softc *sc)
1907 {
1908         struct ifnet *ifp = sc->sc_ifp;
1909         uint32_t tmp;
1910
1911         tmp = ural_read(sc, RAL_TXRX_CSR2);
1912
1913         tmp &= ~RAL_DROP_NOT_TO_ME;
1914         if (!(ifp->if_flags & IFF_PROMISC))
1915                 tmp |= RAL_DROP_NOT_TO_ME;
1916
1917         ural_write(sc, RAL_TXRX_CSR2, tmp);
1918
1919         DPRINTF("%s promiscuous mode\n", (ifp->if_flags & IFF_PROMISC) ?
1920             "entering" : "leaving");
1921 }
1922
1923 static void
1924 ural_update_promisc(struct ifnet *ifp)
1925 {
1926         struct ural_softc *sc = ifp->if_softc;
1927
1928         if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
1929                 return;
1930
1931         RAL_LOCK(sc);
1932         ural_setpromisc(sc);
1933         RAL_UNLOCK(sc);
1934 }
1935
1936 static const char *
1937 ural_get_rf(int rev)
1938 {
1939         switch (rev) {
1940         case RAL_RF_2522:       return "RT2522";
1941         case RAL_RF_2523:       return "RT2523";
1942         case RAL_RF_2524:       return "RT2524";
1943         case RAL_RF_2525:       return "RT2525";
1944         case RAL_RF_2525E:      return "RT2525e";
1945         case RAL_RF_2526:       return "RT2526";
1946         case RAL_RF_5222:       return "RT5222";
1947         default:                return "unknown";
1948         }
1949 }
1950
1951 static void
1952 ural_read_eeprom(struct ural_softc *sc)
1953 {
1954         uint16_t val;
1955
1956         ural_eeprom_read(sc, RAL_EEPROM_CONFIG0, &val, 2);
1957         val = le16toh(val);
1958         sc->rf_rev =   (val >> 11) & 0x7;
1959         sc->hw_radio = (val >> 10) & 0x1;
1960         sc->led_mode = (val >> 6)  & 0x7;
1961         sc->rx_ant =   (val >> 4)  & 0x3;
1962         sc->tx_ant =   (val >> 2)  & 0x3;
1963         sc->nb_ant =   val & 0x3;
1964
1965         /* read MAC address */
1966         ural_eeprom_read(sc, RAL_EEPROM_ADDRESS, sc->sc_bssid, 6);
1967
1968         /* read default values for BBP registers */
1969         ural_eeprom_read(sc, RAL_EEPROM_BBP_BASE, sc->bbp_prom, 2 * 16);
1970
1971         /* read Tx power for all b/g channels */
1972         ural_eeprom_read(sc, RAL_EEPROM_TXPOWER, sc->txpow, 14);
1973 }
1974
1975 static int
1976 ural_bbp_init(struct ural_softc *sc)
1977 {
1978 #define N(a)    ((int)(sizeof (a) / sizeof ((a)[0])))
1979         int i, ntries;
1980
1981         /* wait for BBP to be ready */
1982         for (ntries = 0; ntries < 100; ntries++) {
1983                 if (ural_bbp_read(sc, RAL_BBP_VERSION) != 0)
1984                         break;
1985                 if (ural_pause(sc, hz / 100))
1986                         break;
1987         }
1988         if (ntries == 100) {
1989                 device_printf(sc->sc_dev, "timeout waiting for BBP\n");
1990                 return EIO;
1991         }
1992
1993         /* initialize BBP registers to default values */
1994         for (i = 0; i < N(ural_def_bbp); i++)
1995                 ural_bbp_write(sc, ural_def_bbp[i].reg, ural_def_bbp[i].val);
1996
1997 #if 0
1998         /* initialize BBP registers to values stored in EEPROM */
1999         for (i = 0; i < 16; i++) {
2000                 if (sc->bbp_prom[i].reg == 0xff)
2001                         continue;
2002                 ural_bbp_write(sc, sc->bbp_prom[i].reg, sc->bbp_prom[i].val);
2003         }
2004 #endif
2005
2006         return 0;
2007 #undef N
2008 }
2009
2010 static void
2011 ural_set_txantenna(struct ural_softc *sc, int antenna)
2012 {
2013         uint16_t tmp;
2014         uint8_t tx;
2015
2016         tx = ural_bbp_read(sc, RAL_BBP_TX) & ~RAL_BBP_ANTMASK;
2017         if (antenna == 1)
2018                 tx |= RAL_BBP_ANTA;
2019         else if (antenna == 2)
2020                 tx |= RAL_BBP_ANTB;
2021         else
2022                 tx |= RAL_BBP_DIVERSITY;
2023
2024         /* need to force I/Q flip for RF 2525e, 2526 and 5222 */
2025         if (sc->rf_rev == RAL_RF_2525E || sc->rf_rev == RAL_RF_2526 ||
2026             sc->rf_rev == RAL_RF_5222)
2027                 tx |= RAL_BBP_FLIPIQ;
2028
2029         ural_bbp_write(sc, RAL_BBP_TX, tx);
2030
2031         /* update values in PHY_CSR5 and PHY_CSR6 */
2032         tmp = ural_read(sc, RAL_PHY_CSR5) & ~0x7;
2033         ural_write(sc, RAL_PHY_CSR5, tmp | (tx & 0x7));
2034
2035         tmp = ural_read(sc, RAL_PHY_CSR6) & ~0x7;
2036         ural_write(sc, RAL_PHY_CSR6, tmp | (tx & 0x7));
2037 }
2038
2039 static void
2040 ural_set_rxantenna(struct ural_softc *sc, int antenna)
2041 {
2042         uint8_t rx;
2043
2044         rx = ural_bbp_read(sc, RAL_BBP_RX) & ~RAL_BBP_ANTMASK;
2045         if (antenna == 1)
2046                 rx |= RAL_BBP_ANTA;
2047         else if (antenna == 2)
2048                 rx |= RAL_BBP_ANTB;
2049         else
2050                 rx |= RAL_BBP_DIVERSITY;
2051
2052         /* need to force no I/Q flip for RF 2525e and 2526 */
2053         if (sc->rf_rev == RAL_RF_2525E || sc->rf_rev == RAL_RF_2526)
2054                 rx &= ~RAL_BBP_FLIPIQ;
2055
2056         ural_bbp_write(sc, RAL_BBP_RX, rx);
2057 }
2058
2059 static void
2060 ural_init_locked(struct ural_softc *sc)
2061 {
2062 #define N(a)    ((int)(sizeof (a) / sizeof ((a)[0])))
2063         struct ifnet *ifp = sc->sc_ifp;
2064         struct ieee80211com *ic = ifp->if_l2com;
2065         uint16_t tmp;
2066         int i, ntries;
2067
2068         RAL_LOCK_ASSERT(sc, MA_OWNED);
2069
2070         ural_set_testmode(sc);
2071         ural_write(sc, 0x308, 0x00f0);  /* XXX magic */
2072
2073         ural_stop(sc);
2074
2075         /* initialize MAC registers to default values */
2076         for (i = 0; i < N(ural_def_mac); i++)
2077                 ural_write(sc, ural_def_mac[i].reg, ural_def_mac[i].val);
2078
2079         /* wait for BBP and RF to wake up (this can take a long time!) */
2080         for (ntries = 0; ntries < 100; ntries++) {
2081                 tmp = ural_read(sc, RAL_MAC_CSR17);
2082                 if ((tmp & (RAL_BBP_AWAKE | RAL_RF_AWAKE)) ==
2083                     (RAL_BBP_AWAKE | RAL_RF_AWAKE))
2084                         break;
2085                 if (ural_pause(sc, hz / 100))
2086                         break;
2087         }
2088         if (ntries == 100) {
2089                 device_printf(sc->sc_dev,
2090                     "timeout waiting for BBP/RF to wakeup\n");
2091                 goto fail;
2092         }
2093
2094         /* we're ready! */
2095         ural_write(sc, RAL_MAC_CSR1, RAL_HOST_READY);
2096
2097         /* set basic rate set (will be updated later) */
2098         ural_write(sc, RAL_TXRX_CSR11, 0x15f);
2099
2100         if (ural_bbp_init(sc) != 0)
2101                 goto fail;
2102
2103         ural_set_chan(sc, ic->ic_curchan);
2104
2105         /* clear statistic registers (STA_CSR0 to STA_CSR10) */
2106         ural_read_multi(sc, RAL_STA_CSR0, sc->sta, sizeof sc->sta);
2107
2108         ural_set_txantenna(sc, sc->tx_ant);
2109         ural_set_rxantenna(sc, sc->rx_ant);
2110
2111         ural_set_macaddr(sc, IF_LLADDR(ifp));
2112
2113         /*
2114          * Allocate Tx and Rx xfer queues.
2115          */
2116         ural_setup_tx_list(sc);
2117
2118         /* kick Rx */
2119         tmp = RAL_DROP_PHY | RAL_DROP_CRC;
2120         if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2121                 tmp |= RAL_DROP_CTL | RAL_DROP_BAD_VERSION;
2122                 if (ic->ic_opmode != IEEE80211_M_HOSTAP)
2123                         tmp |= RAL_DROP_TODS;
2124                 if (!(ifp->if_flags & IFF_PROMISC))
2125                         tmp |= RAL_DROP_NOT_TO_ME;
2126         }
2127         ural_write(sc, RAL_TXRX_CSR2, tmp);
2128
2129         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
2130         ifp->if_drv_flags |= IFF_DRV_RUNNING;
2131         usbd_xfer_set_stall(sc->sc_xfer[URAL_BULK_WR]);
2132         usbd_transfer_start(sc->sc_xfer[URAL_BULK_RD]);
2133         return;
2134
2135 fail:   ural_stop(sc);
2136 #undef N
2137 }
2138
2139 static void
2140 ural_init(void *priv)
2141 {
2142         struct ural_softc *sc = priv;
2143         struct ifnet *ifp = sc->sc_ifp;
2144         struct ieee80211com *ic = ifp->if_l2com;
2145
2146         RAL_LOCK(sc);
2147         ural_init_locked(sc);
2148         RAL_UNLOCK(sc);
2149
2150         if (ifp->if_drv_flags & IFF_DRV_RUNNING)
2151                 ieee80211_start_all(ic);                /* start all vap's */
2152 }
2153
2154 static void
2155 ural_stop(struct ural_softc *sc)
2156 {
2157         struct ifnet *ifp = sc->sc_ifp;
2158
2159         RAL_LOCK_ASSERT(sc, MA_OWNED);
2160
2161         ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
2162
2163         /*
2164          * Drain all the transfers, if not already drained:
2165          */
2166         RAL_UNLOCK(sc);
2167         usbd_transfer_drain(sc->sc_xfer[URAL_BULK_WR]);
2168         usbd_transfer_drain(sc->sc_xfer[URAL_BULK_RD]);
2169         RAL_LOCK(sc);
2170
2171         ural_unsetup_tx_list(sc);
2172
2173         /* disable Rx */
2174         ural_write(sc, RAL_TXRX_CSR2, RAL_DISABLE_RX);
2175         /* reset ASIC and BBP (but won't reset MAC registers!) */
2176         ural_write(sc, RAL_MAC_CSR1, RAL_RESET_ASIC | RAL_RESET_BBP);
2177         /* wait a little */
2178         ural_pause(sc, hz / 10);
2179         ural_write(sc, RAL_MAC_CSR1, 0);
2180         /* wait a little */
2181         ural_pause(sc, hz / 10);
2182 }
2183
2184 static int
2185 ural_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
2186         const struct ieee80211_bpf_params *params)
2187 {
2188         struct ieee80211com *ic = ni->ni_ic;
2189         struct ifnet *ifp = ic->ic_ifp;
2190         struct ural_softc *sc = ifp->if_softc;
2191
2192         RAL_LOCK(sc);
2193         /* prevent management frames from being sent if we're not ready */
2194         if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
2195                 RAL_UNLOCK(sc);
2196                 m_freem(m);
2197                 ieee80211_free_node(ni);
2198                 return ENETDOWN;
2199         }
2200         if (sc->tx_nfree < RAL_TX_MINFREE) {
2201                 ifp->if_drv_flags |= IFF_DRV_OACTIVE;
2202                 RAL_UNLOCK(sc);
2203                 m_freem(m);
2204                 ieee80211_free_node(ni);
2205                 return EIO;
2206         }
2207
2208         ifp->if_opackets++;
2209
2210         if (params == NULL) {
2211                 /*
2212                  * Legacy path; interpret frame contents to decide
2213                  * precisely how to send the frame.
2214                  */
2215                 if (ural_tx_mgt(sc, m, ni) != 0)
2216                         goto bad;
2217         } else {
2218                 /*
2219                  * Caller supplied explicit parameters to use in
2220                  * sending the frame.
2221                  */
2222                 if (ural_tx_raw(sc, m, ni, params) != 0)
2223                         goto bad;
2224         }
2225         RAL_UNLOCK(sc);
2226         return 0;
2227 bad:
2228         ifp->if_oerrors++;
2229         RAL_UNLOCK(sc);
2230         ieee80211_free_node(ni);
2231         return EIO;             /* XXX */
2232 }
2233
2234 static void
2235 ural_ratectl_start(struct ural_softc *sc, struct ieee80211_node *ni)
2236 {
2237         struct ieee80211vap *vap = ni->ni_vap;
2238         struct ural_vap *uvp = URAL_VAP(vap);
2239
2240         /* clear statistic registers (STA_CSR0 to STA_CSR10) */
2241         ural_read_multi(sc, RAL_STA_CSR0, sc->sta, sizeof sc->sta);
2242
2243         usb_callout_reset(&uvp->ratectl_ch, hz, ural_ratectl_timeout, uvp);
2244 }
2245
2246 static void
2247 ural_ratectl_timeout(void *arg)
2248 {
2249         struct ural_vap *uvp = arg;
2250         struct ieee80211vap *vap = &uvp->vap;
2251         struct ieee80211com *ic = vap->iv_ic;
2252
2253         ieee80211_runtask(ic, &uvp->ratectl_task);
2254 }
2255
2256 static void
2257 ural_ratectl_task(void *arg, int pending)
2258 {
2259         struct ural_vap *uvp = arg;
2260         struct ieee80211vap *vap = &uvp->vap;
2261         struct ieee80211com *ic = vap->iv_ic;
2262         struct ifnet *ifp = ic->ic_ifp;
2263         struct ural_softc *sc = ifp->if_softc;
2264         struct ieee80211_node *ni;
2265         int ok, fail;
2266         int sum, retrycnt;
2267
2268         ni = ieee80211_ref_node(vap->iv_bss);
2269         RAL_LOCK(sc);
2270         /* read and clear statistic registers (STA_CSR0 to STA_CSR10) */
2271         ural_read_multi(sc, RAL_STA_CSR0, sc->sta, sizeof(sc->sta));
2272
2273         ok = sc->sta[7] +               /* TX ok w/o retry */
2274              sc->sta[8];                /* TX ok w/ retry */
2275         fail = sc->sta[9];              /* TX retry-fail count */
2276         sum = ok+fail;
2277         retrycnt = sc->sta[8] + fail;
2278
2279         ieee80211_ratectl_tx_update(vap, ni, &sum, &ok, &retrycnt);
2280         (void) ieee80211_ratectl_rate(ni, NULL, 0);
2281
2282         ifp->if_oerrors += fail;        /* count TX retry-fail as Tx errors */
2283
2284         usb_callout_reset(&uvp->ratectl_ch, hz, ural_ratectl_timeout, uvp);
2285         RAL_UNLOCK(sc);
2286         ieee80211_free_node(ni);
2287 }
2288
2289 static int
2290 ural_pause(struct ural_softc *sc, int timeout)
2291 {
2292
2293         usb_pause_mtx(&sc->sc_mtx, timeout);
2294         return (0);
2295 }