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