d208a3ea85d088727ff9127db551bce7dec342ac
[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_RWTUN, &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 ieee80211com *);
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         DEVMETHOD_END
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, NULL);
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_softc = sc;
474         ic->ic_name = device_get_nameunit(dev);
475         ic->ic_phytype = IEEE80211_T_OFDM; /* not only, but not used */
476
477         /* set device capabilities */
478         ic->ic_caps =
479               IEEE80211_C_STA           /* station mode supported */
480             | IEEE80211_C_IBSS          /* IBSS mode supported */
481             | IEEE80211_C_MONITOR       /* monitor mode supported */
482             | IEEE80211_C_HOSTAP        /* HostAp mode supported */
483             | IEEE80211_C_TXPMGT        /* tx power management */
484             | IEEE80211_C_SHPREAMBLE    /* short preamble supported */
485             | IEEE80211_C_SHSLOT        /* short slot time supported */
486             | IEEE80211_C_BGSCAN        /* bg scanning supported */
487             | IEEE80211_C_WPA           /* 802.11i */
488             ;
489
490         bands = 0;
491         setbit(&bands, IEEE80211_MODE_11B);
492         setbit(&bands, IEEE80211_MODE_11G);
493         if (sc->rf_rev == RAL_RF_5222)
494                 setbit(&bands, IEEE80211_MODE_11A);
495         ieee80211_init_channels(ic, NULL, &bands);
496
497         ieee80211_ifattach(ic, sc->sc_bssid);
498         ic->ic_update_promisc = ural_update_promisc;
499         ic->ic_raw_xmit = ural_raw_xmit;
500         ic->ic_scan_start = ural_scan_start;
501         ic->ic_scan_end = ural_scan_end;
502         ic->ic_set_channel = ural_set_channel;
503
504         ic->ic_vap_create = ural_vap_create;
505         ic->ic_vap_delete = ural_vap_delete;
506
507         ieee80211_radiotap_attach(ic,
508             &sc->sc_txtap.wt_ihdr, sizeof(sc->sc_txtap),
509                 RAL_TX_RADIOTAP_PRESENT,
510             &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap),
511                 RAL_RX_RADIOTAP_PRESENT);
512
513         if (bootverbose)
514                 ieee80211_announce(ic);
515
516         return (0);
517
518 detach:
519         ural_detach(self);
520         return (ENXIO);                 /* failure */
521 }
522
523 static int
524 ural_detach(device_t self)
525 {
526         struct ural_softc *sc = device_get_softc(self);
527         struct ifnet *ifp = sc->sc_ifp;
528         struct ieee80211com *ic;
529
530         /* stop all USB transfers */
531         usbd_transfer_unsetup(sc->sc_xfer, URAL_N_TRANSFER);
532
533         /* free TX list, if any */
534         RAL_LOCK(sc);
535         ural_unsetup_tx_list(sc);
536         RAL_UNLOCK(sc);
537
538         if (ifp) {
539                 ic = ifp->if_l2com;
540                 ieee80211_ifdetach(ic);
541                 if_free(ifp);
542         }
543         mtx_destroy(&sc->sc_mtx);
544
545         return (0);
546 }
547
548 static usb_error_t
549 ural_do_request(struct ural_softc *sc,
550     struct usb_device_request *req, void *data)
551 {
552         usb_error_t err;
553         int ntries = 10;
554
555         while (ntries--) {
556                 err = usbd_do_request_flags(sc->sc_udev, &sc->sc_mtx,
557                     req, data, 0, NULL, 250 /* ms */);
558                 if (err == 0)
559                         break;
560
561                 DPRINTFN(1, "Control request failed, %s (retrying)\n",
562                     usbd_errstr(err));
563                 if (ural_pause(sc, hz / 100))
564                         break;
565         }
566         return (err);
567 }
568
569 static struct ieee80211vap *
570 ural_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
571     enum ieee80211_opmode opmode, int flags,
572     const uint8_t bssid[IEEE80211_ADDR_LEN],
573     const uint8_t mac[IEEE80211_ADDR_LEN])
574 {
575         struct ural_softc *sc = ic->ic_ifp->if_softc;
576         struct ural_vap *uvp;
577         struct ieee80211vap *vap;
578
579         if (!TAILQ_EMPTY(&ic->ic_vaps))         /* only one at a time */
580                 return NULL;
581         uvp = (struct ural_vap *) malloc(sizeof(struct ural_vap),
582             M_80211_VAP, M_WAITOK | M_ZERO);
583         if (uvp == NULL)
584                 return NULL;
585         vap = &uvp->vap;
586         /* enable s/w bmiss handling for sta mode */
587         ieee80211_vap_setup(ic, vap, name, unit, opmode,
588             flags | IEEE80211_CLONE_NOBEACONS, bssid, mac);
589
590         /* override state transition machine */
591         uvp->newstate = vap->iv_newstate;
592         vap->iv_newstate = ural_newstate;
593
594         usb_callout_init_mtx(&uvp->ratectl_ch, &sc->sc_mtx, 0);
595         TASK_INIT(&uvp->ratectl_task, 0, ural_ratectl_task, uvp);
596         ieee80211_ratectl_init(vap);
597         ieee80211_ratectl_setinterval(vap, 1000 /* 1 sec */);
598
599         /* complete setup */
600         ieee80211_vap_attach(vap, ieee80211_media_change, ieee80211_media_status);
601         ic->ic_opmode = opmode;
602         return vap;
603 }
604
605 static void
606 ural_vap_delete(struct ieee80211vap *vap)
607 {
608         struct ural_vap *uvp = URAL_VAP(vap);
609         struct ieee80211com *ic = vap->iv_ic;
610
611         usb_callout_drain(&uvp->ratectl_ch);
612         ieee80211_draintask(ic, &uvp->ratectl_task);
613         ieee80211_ratectl_deinit(vap);
614         ieee80211_vap_detach(vap);
615         free(uvp, M_80211_VAP);
616 }
617
618 static void
619 ural_tx_free(struct ural_tx_data *data, int txerr)
620 {
621         struct ural_softc *sc = data->sc;
622
623         if (data->m != NULL) {
624                 if (data->m->m_flags & M_TXCB)
625                         ieee80211_process_callback(data->ni, data->m,
626                             txerr ? ETIMEDOUT : 0);
627                 m_freem(data->m);
628                 data->m = NULL;
629
630                 ieee80211_free_node(data->ni);
631                 data->ni = NULL;
632         }
633         STAILQ_INSERT_TAIL(&sc->tx_free, data, next);
634         sc->tx_nfree++;
635 }
636
637 static void
638 ural_setup_tx_list(struct ural_softc *sc)
639 {
640         struct ural_tx_data *data;
641         int i;
642
643         sc->tx_nfree = 0;
644         STAILQ_INIT(&sc->tx_q);
645         STAILQ_INIT(&sc->tx_free);
646
647         for (i = 0; i < RAL_TX_LIST_COUNT; i++) {
648                 data = &sc->tx_data[i];
649
650                 data->sc = sc;
651                 STAILQ_INSERT_TAIL(&sc->tx_free, data, next);
652                 sc->tx_nfree++;
653         }
654 }
655
656 static void
657 ural_unsetup_tx_list(struct ural_softc *sc)
658 {
659         struct ural_tx_data *data;
660         int i;
661
662         /* make sure any subsequent use of the queues will fail */
663         sc->tx_nfree = 0;
664         STAILQ_INIT(&sc->tx_q);
665         STAILQ_INIT(&sc->tx_free);
666
667         /* free up all node references and mbufs */
668         for (i = 0; i < RAL_TX_LIST_COUNT; i++) {
669                 data = &sc->tx_data[i];
670
671                 if (data->m != NULL) {
672                         m_freem(data->m);
673                         data->m = NULL;
674                 }
675                 if (data->ni != NULL) {
676                         ieee80211_free_node(data->ni);
677                         data->ni = NULL;
678                 }
679         }
680 }
681
682 static int
683 ural_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
684 {
685         struct ural_vap *uvp = URAL_VAP(vap);
686         struct ieee80211com *ic = vap->iv_ic;
687         struct ural_softc *sc = ic->ic_ifp->if_softc;
688         const struct ieee80211_txparam *tp;
689         struct ieee80211_node *ni;
690         struct mbuf *m;
691
692         DPRINTF("%s -> %s\n",
693                 ieee80211_state_name[vap->iv_state],
694                 ieee80211_state_name[nstate]);
695
696         IEEE80211_UNLOCK(ic);
697         RAL_LOCK(sc);
698         usb_callout_stop(&uvp->ratectl_ch);
699
700         switch (nstate) {
701         case IEEE80211_S_INIT:
702                 if (vap->iv_state == IEEE80211_S_RUN) {
703                         /* abort TSF synchronization */
704                         ural_write(sc, RAL_TXRX_CSR19, 0);
705
706                         /* force tx led to stop blinking */
707                         ural_write(sc, RAL_MAC_CSR20, 0);
708                 }
709                 break;
710
711         case IEEE80211_S_RUN:
712                 ni = ieee80211_ref_node(vap->iv_bss);
713
714                 if (vap->iv_opmode != IEEE80211_M_MONITOR) {
715                         ural_update_slot(ic->ic_ifp);
716                         ural_set_txpreamble(sc);
717                         ural_set_basicrates(sc, ic->ic_bsschan);
718                         IEEE80211_ADDR_COPY(sc->sc_bssid, ni->ni_bssid);
719                         ural_set_bssid(sc, sc->sc_bssid);
720                 }
721
722                 if (vap->iv_opmode == IEEE80211_M_HOSTAP ||
723                     vap->iv_opmode == IEEE80211_M_IBSS) {
724                         m = ieee80211_beacon_alloc(ni, &uvp->bo);
725                         if (m == NULL) {
726                                 device_printf(sc->sc_dev,
727                                     "could not allocate beacon\n");
728                                 RAL_UNLOCK(sc);
729                                 IEEE80211_LOCK(ic);
730                                 ieee80211_free_node(ni);
731                                 return (-1);
732                         }
733                         ieee80211_ref_node(ni);
734                         if (ural_tx_bcn(sc, m, ni) != 0) {
735                                 device_printf(sc->sc_dev,
736                                     "could not send beacon\n");
737                                 RAL_UNLOCK(sc);
738                                 IEEE80211_LOCK(ic);
739                                 ieee80211_free_node(ni);
740                                 return (-1);
741                         }
742                 }
743
744                 /* make tx led blink on tx (controlled by ASIC) */
745                 ural_write(sc, RAL_MAC_CSR20, 1);
746
747                 if (vap->iv_opmode != IEEE80211_M_MONITOR)
748                         ural_enable_tsf_sync(sc);
749                 else
750                         ural_enable_tsf(sc);
751
752                 /* enable automatic rate adaptation */
753                 /* XXX should use ic_bsschan but not valid until after newstate call below */
754                 tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)];
755                 if (tp->ucastrate == IEEE80211_FIXED_RATE_NONE)
756                         ural_ratectl_start(sc, ni);
757                 ieee80211_free_node(ni);
758                 break;
759
760         default:
761                 break;
762         }
763         RAL_UNLOCK(sc);
764         IEEE80211_LOCK(ic);
765         return (uvp->newstate(vap, nstate, arg));
766 }
767
768
769 static void
770 ural_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error)
771 {
772         struct ural_softc *sc = usbd_xfer_softc(xfer);
773         struct ifnet *ifp = sc->sc_ifp;
774         struct ieee80211vap *vap;
775         struct ural_tx_data *data;
776         struct mbuf *m;
777         struct usb_page_cache *pc;
778         int len;
779
780         usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
781
782         switch (USB_GET_STATE(xfer)) {
783         case USB_ST_TRANSFERRED:
784                 DPRINTFN(11, "transfer complete, %d bytes\n", len);
785
786                 /* free resources */
787                 data = usbd_xfer_get_priv(xfer);
788                 ural_tx_free(data, 0);
789                 usbd_xfer_set_priv(xfer, NULL);
790
791                 ifp->if_opackets++;
792                 ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
793
794                 /* FALLTHROUGH */
795         case USB_ST_SETUP:
796 tr_setup:
797                 data = STAILQ_FIRST(&sc->tx_q);
798                 if (data) {
799                         STAILQ_REMOVE_HEAD(&sc->tx_q, next);
800                         m = data->m;
801
802                         if (m->m_pkthdr.len > (RAL_FRAME_SIZE + RAL_TX_DESC_SIZE)) {
803                                 DPRINTFN(0, "data overflow, %u bytes\n",
804                                     m->m_pkthdr.len);
805                                 m->m_pkthdr.len = (RAL_FRAME_SIZE + RAL_TX_DESC_SIZE);
806                         }
807                         pc = usbd_xfer_get_frame(xfer, 0);
808                         usbd_copy_in(pc, 0, &data->desc, RAL_TX_DESC_SIZE);
809                         usbd_m_copy_in(pc, RAL_TX_DESC_SIZE, m, 0,
810                             m->m_pkthdr.len);
811
812                         vap = data->ni->ni_vap;
813                         if (ieee80211_radiotap_active_vap(vap)) {
814                                 struct ural_tx_radiotap_header *tap = &sc->sc_txtap;
815
816                                 tap->wt_flags = 0;
817                                 tap->wt_rate = data->rate;
818                                 tap->wt_antenna = sc->tx_ant;
819
820                                 ieee80211_radiotap_tx(vap, m);
821                         }
822
823                         /* xfer length needs to be a multiple of two! */
824                         len = (RAL_TX_DESC_SIZE + m->m_pkthdr.len + 1) & ~1;
825                         if ((len % 64) == 0)
826                                 len += 2;
827
828                         DPRINTFN(11, "sending frame len=%u xferlen=%u\n",
829                             m->m_pkthdr.len, len);
830
831                         usbd_xfer_set_frame_len(xfer, 0, len);
832                         usbd_xfer_set_priv(xfer, data);
833
834                         usbd_transfer_submit(xfer);
835                 }
836                 RAL_UNLOCK(sc);
837                 ural_start(ifp);
838                 RAL_LOCK(sc);
839                 break;
840
841         default:                        /* Error */
842                 DPRINTFN(11, "transfer error, %s\n",
843                     usbd_errstr(error));
844
845                 ifp->if_oerrors++;
846                 data = usbd_xfer_get_priv(xfer);
847                 if (data != NULL) {
848                         ural_tx_free(data, error);
849                         usbd_xfer_set_priv(xfer, NULL);
850                 }
851
852                 if (error == USB_ERR_STALLED) {
853                         /* try to clear stall first */
854                         usbd_xfer_set_stall(xfer);
855                         goto tr_setup;
856                 }
857                 if (error == USB_ERR_TIMEOUT)
858                         device_printf(sc->sc_dev, "device timeout\n");
859                 break;
860         }
861 }
862
863 static void
864 ural_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error)
865 {
866         struct ural_softc *sc = usbd_xfer_softc(xfer);
867         struct ifnet *ifp = sc->sc_ifp;
868         struct ieee80211com *ic = ifp->if_l2com;
869         struct ieee80211_node *ni;
870         struct mbuf *m = NULL;
871         struct usb_page_cache *pc;
872         uint32_t flags;
873         int8_t rssi = 0, nf = 0;
874         int len;
875
876         usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
877
878         switch (USB_GET_STATE(xfer)) {
879         case USB_ST_TRANSFERRED:
880
881                 DPRINTFN(15, "rx done, actlen=%d\n", len);
882
883                 if (len < RAL_RX_DESC_SIZE + IEEE80211_MIN_LEN) {
884                         DPRINTF("%s: xfer too short %d\n",
885                             device_get_nameunit(sc->sc_dev), len);
886                         ifp->if_ierrors++;
887                         goto tr_setup;
888                 }
889
890                 len -= RAL_RX_DESC_SIZE;
891                 /* rx descriptor is located at the end */
892                 pc = usbd_xfer_get_frame(xfer, 0);
893                 usbd_copy_out(pc, len, &sc->sc_rx_desc, RAL_RX_DESC_SIZE);
894
895                 rssi = URAL_RSSI(sc->sc_rx_desc.rssi);
896                 nf = RAL_NOISE_FLOOR;
897                 flags = le32toh(sc->sc_rx_desc.flags);
898                 if (flags & (RAL_RX_PHY_ERROR | RAL_RX_CRC_ERROR)) {
899                         /*
900                          * This should not happen since we did not
901                          * request to receive those frames when we
902                          * filled RAL_TXRX_CSR2:
903                          */
904                         DPRINTFN(5, "PHY or CRC error\n");
905                         ifp->if_ierrors++;
906                         goto tr_setup;
907                 }
908
909                 m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
910                 if (m == NULL) {
911                         DPRINTF("could not allocate mbuf\n");
912                         ifp->if_ierrors++;
913                         goto tr_setup;
914                 }
915                 usbd_copy_out(pc, 0, mtod(m, uint8_t *), len);
916
917                 /* finalize mbuf */
918                 m->m_pkthdr.rcvif = ifp;
919                 m->m_pkthdr.len = m->m_len = (flags >> 16) & 0xfff;
920
921                 if (ieee80211_radiotap_active(ic)) {
922                         struct ural_rx_radiotap_header *tap = &sc->sc_rxtap;
923
924                         /* XXX set once */
925                         tap->wr_flags = 0;
926                         tap->wr_rate = ieee80211_plcp2rate(sc->sc_rx_desc.rate,
927                             (flags & RAL_RX_OFDM) ?
928                             IEEE80211_T_OFDM : IEEE80211_T_CCK);
929                         tap->wr_antenna = sc->rx_ant;
930                         tap->wr_antsignal = nf + rssi;
931                         tap->wr_antnoise = nf;
932                 }
933                 /* Strip trailing 802.11 MAC FCS. */
934                 m_adj(m, -IEEE80211_CRC_LEN);
935
936                 /* FALLTHROUGH */
937         case USB_ST_SETUP:
938 tr_setup:
939                 usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
940                 usbd_transfer_submit(xfer);
941
942                 /*
943                  * At the end of a USB callback it is always safe to unlock
944                  * the private mutex of a device! That is why we do the
945                  * "ieee80211_input" here, and not some lines up!
946                  */
947                 RAL_UNLOCK(sc);
948                 if (m) {
949                         ni = ieee80211_find_rxnode(ic,
950                             mtod(m, struct ieee80211_frame_min *));
951                         if (ni != NULL) {
952                                 (void) ieee80211_input(ni, m, rssi, nf);
953                                 ieee80211_free_node(ni);
954                         } else
955                                 (void) ieee80211_input_all(ic, m, rssi, nf);
956                 }
957                 if ((ifp->if_drv_flags & IFF_DRV_OACTIVE) == 0 &&
958                     !IFQ_IS_EMPTY(&ifp->if_snd))
959                         ural_start(ifp);
960                 RAL_LOCK(sc);
961                 return;
962
963         default:                        /* Error */
964                 if (error != USB_ERR_CANCELLED) {
965                         /* try to clear stall first */
966                         usbd_xfer_set_stall(xfer);
967                         goto tr_setup;
968                 }
969                 return;
970         }
971 }
972
973 static uint8_t
974 ural_plcp_signal(int rate)
975 {
976         switch (rate) {
977         /* OFDM rates (cf IEEE Std 802.11a-1999, pp. 14 Table 80) */
978         case 12:        return 0xb;
979         case 18:        return 0xf;
980         case 24:        return 0xa;
981         case 36:        return 0xe;
982         case 48:        return 0x9;
983         case 72:        return 0xd;
984         case 96:        return 0x8;
985         case 108:       return 0xc;
986
987         /* CCK rates (NB: not IEEE std, device-specific) */
988         case 2:         return 0x0;
989         case 4:         return 0x1;
990         case 11:        return 0x2;
991         case 22:        return 0x3;
992         }
993         return 0xff;            /* XXX unsupported/unknown rate */
994 }
995
996 static void
997 ural_setup_tx_desc(struct ural_softc *sc, struct ural_tx_desc *desc,
998     uint32_t flags, int len, int rate)
999 {
1000         struct ifnet *ifp = sc->sc_ifp;
1001         struct ieee80211com *ic = ifp->if_l2com;
1002         uint16_t plcp_length;
1003         int remainder;
1004
1005         desc->flags = htole32(flags);
1006         desc->flags |= htole32(RAL_TX_NEWSEQ);
1007         desc->flags |= htole32(len << 16);
1008
1009         desc->wme = htole16(RAL_AIFSN(2) | RAL_LOGCWMIN(3) | RAL_LOGCWMAX(5));
1010         desc->wme |= htole16(RAL_IVOFFSET(sizeof (struct ieee80211_frame)));
1011
1012         /* setup PLCP fields */
1013         desc->plcp_signal  = ural_plcp_signal(rate);
1014         desc->plcp_service = 4;
1015
1016         len += IEEE80211_CRC_LEN;
1017         if (ieee80211_rate2phytype(ic->ic_rt, rate) == IEEE80211_T_OFDM) {
1018                 desc->flags |= htole32(RAL_TX_OFDM);
1019
1020                 plcp_length = len & 0xfff;
1021                 desc->plcp_length_hi = plcp_length >> 6;
1022                 desc->plcp_length_lo = plcp_length & 0x3f;
1023         } else {
1024                 plcp_length = (16 * len + rate - 1) / rate;
1025                 if (rate == 22) {
1026                         remainder = (16 * len) % 22;
1027                         if (remainder != 0 && remainder < 7)
1028                                 desc->plcp_service |= RAL_PLCP_LENGEXT;
1029                 }
1030                 desc->plcp_length_hi = plcp_length >> 8;
1031                 desc->plcp_length_lo = plcp_length & 0xff;
1032
1033                 if (rate != 2 && (ic->ic_flags & IEEE80211_F_SHPREAMBLE))
1034                         desc->plcp_signal |= 0x08;
1035         }
1036
1037         desc->iv = 0;
1038         desc->eiv = 0;
1039 }
1040
1041 #define RAL_TX_TIMEOUT  5000
1042
1043 static int
1044 ural_tx_bcn(struct ural_softc *sc, struct mbuf *m0, struct ieee80211_node *ni)
1045 {
1046         struct ieee80211vap *vap = ni->ni_vap;
1047         struct ieee80211com *ic = ni->ni_ic;
1048         struct ifnet *ifp = sc->sc_ifp;
1049         const struct ieee80211_txparam *tp;
1050         struct ural_tx_data *data;
1051
1052         if (sc->tx_nfree == 0) {
1053                 ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1054                 m_freem(m0);
1055                 ieee80211_free_node(ni);
1056                 return EIO;
1057         }
1058         data = STAILQ_FIRST(&sc->tx_free);
1059         STAILQ_REMOVE_HEAD(&sc->tx_free, next);
1060         sc->tx_nfree--;
1061         tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_bsschan)];
1062
1063         data->m = m0;
1064         data->ni = ni;
1065         data->rate = tp->mgmtrate;
1066
1067         ural_setup_tx_desc(sc, &data->desc,
1068             RAL_TX_IFS_NEWBACKOFF | RAL_TX_TIMESTAMP, m0->m_pkthdr.len,
1069             tp->mgmtrate);
1070
1071         DPRINTFN(10, "sending beacon frame len=%u rate=%u\n",
1072             m0->m_pkthdr.len, tp->mgmtrate);
1073
1074         STAILQ_INSERT_TAIL(&sc->tx_q, data, next);
1075         usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]);
1076
1077         return (0);
1078 }
1079
1080 static int
1081 ural_tx_mgt(struct ural_softc *sc, struct mbuf *m0, struct ieee80211_node *ni)
1082 {
1083         struct ieee80211vap *vap = ni->ni_vap;
1084         struct ieee80211com *ic = ni->ni_ic;
1085         const struct ieee80211_txparam *tp;
1086         struct ural_tx_data *data;
1087         struct ieee80211_frame *wh;
1088         struct ieee80211_key *k;
1089         uint32_t flags;
1090         uint16_t dur;
1091
1092         RAL_LOCK_ASSERT(sc, MA_OWNED);
1093
1094         data = STAILQ_FIRST(&sc->tx_free);
1095         STAILQ_REMOVE_HEAD(&sc->tx_free, next);
1096         sc->tx_nfree--;
1097
1098         tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)];
1099
1100         wh = mtod(m0, struct ieee80211_frame *);
1101         if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
1102                 k = ieee80211_crypto_encap(ni, m0);
1103                 if (k == NULL) {
1104                         m_freem(m0);
1105                         return ENOBUFS;
1106                 }
1107                 wh = mtod(m0, struct ieee80211_frame *);
1108         }
1109
1110         data->m = m0;
1111         data->ni = ni;
1112         data->rate = tp->mgmtrate;
1113
1114         flags = 0;
1115         if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1116                 flags |= RAL_TX_ACK;
1117
1118                 dur = ieee80211_ack_duration(ic->ic_rt, tp->mgmtrate, 
1119                     ic->ic_flags & IEEE80211_F_SHPREAMBLE);
1120                 *(uint16_t *)wh->i_dur = htole16(dur);
1121
1122                 /* tell hardware to add timestamp for probe responses */
1123                 if ((wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) ==
1124                     IEEE80211_FC0_TYPE_MGT &&
1125                     (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) ==
1126                     IEEE80211_FC0_SUBTYPE_PROBE_RESP)
1127                         flags |= RAL_TX_TIMESTAMP;
1128         }
1129
1130         ural_setup_tx_desc(sc, &data->desc, flags, m0->m_pkthdr.len, tp->mgmtrate);
1131
1132         DPRINTFN(10, "sending mgt frame len=%u rate=%u\n",
1133             m0->m_pkthdr.len, tp->mgmtrate);
1134
1135         STAILQ_INSERT_TAIL(&sc->tx_q, data, next);
1136         usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]);
1137
1138         return 0;
1139 }
1140
1141 static int
1142 ural_sendprot(struct ural_softc *sc,
1143     const struct mbuf *m, struct ieee80211_node *ni, int prot, int rate)
1144 {
1145         struct ieee80211com *ic = ni->ni_ic;
1146         const struct ieee80211_frame *wh;
1147         struct ural_tx_data *data;
1148         struct mbuf *mprot;
1149         int protrate, ackrate, pktlen, flags, isshort;
1150         uint16_t dur;
1151
1152         KASSERT(prot == IEEE80211_PROT_RTSCTS || prot == IEEE80211_PROT_CTSONLY,
1153             ("protection %d", prot));
1154
1155         wh = mtod(m, const struct ieee80211_frame *);
1156         pktlen = m->m_pkthdr.len + IEEE80211_CRC_LEN;
1157
1158         protrate = ieee80211_ctl_rate(ic->ic_rt, rate);
1159         ackrate = ieee80211_ack_rate(ic->ic_rt, rate);
1160
1161         isshort = (ic->ic_flags & IEEE80211_F_SHPREAMBLE) != 0;
1162         dur = ieee80211_compute_duration(ic->ic_rt, pktlen, rate, isshort)
1163             + ieee80211_ack_duration(ic->ic_rt, rate, isshort);
1164         flags = RAL_TX_RETRY(7);
1165         if (prot == IEEE80211_PROT_RTSCTS) {
1166                 /* NB: CTS is the same size as an ACK */
1167                 dur += ieee80211_ack_duration(ic->ic_rt, rate, isshort);
1168                 flags |= RAL_TX_ACK;
1169                 mprot = ieee80211_alloc_rts(ic, wh->i_addr1, wh->i_addr2, dur);
1170         } else {
1171                 mprot = ieee80211_alloc_cts(ic, ni->ni_vap->iv_myaddr, dur);
1172         }
1173         if (mprot == NULL) {
1174                 /* XXX stat + msg */
1175                 return ENOBUFS;
1176         }
1177         data = STAILQ_FIRST(&sc->tx_free);
1178         STAILQ_REMOVE_HEAD(&sc->tx_free, next);
1179         sc->tx_nfree--;
1180
1181         data->m = mprot;
1182         data->ni = ieee80211_ref_node(ni);
1183         data->rate = protrate;
1184         ural_setup_tx_desc(sc, &data->desc, flags, mprot->m_pkthdr.len, protrate);
1185
1186         STAILQ_INSERT_TAIL(&sc->tx_q, data, next);
1187         usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]);
1188
1189         return 0;
1190 }
1191
1192 static int
1193 ural_tx_raw(struct ural_softc *sc, struct mbuf *m0, struct ieee80211_node *ni,
1194     const struct ieee80211_bpf_params *params)
1195 {
1196         struct ieee80211com *ic = ni->ni_ic;
1197         struct ural_tx_data *data;
1198         uint32_t flags;
1199         int error;
1200         int rate;
1201
1202         RAL_LOCK_ASSERT(sc, MA_OWNED);
1203         KASSERT(params != NULL, ("no raw xmit params"));
1204
1205         rate = params->ibp_rate0;
1206         if (!ieee80211_isratevalid(ic->ic_rt, rate)) {
1207                 m_freem(m0);
1208                 return EINVAL;
1209         }
1210         flags = 0;
1211         if ((params->ibp_flags & IEEE80211_BPF_NOACK) == 0)
1212                 flags |= RAL_TX_ACK;
1213         if (params->ibp_flags & (IEEE80211_BPF_RTS|IEEE80211_BPF_CTS)) {
1214                 error = ural_sendprot(sc, m0, ni,
1215                     params->ibp_flags & IEEE80211_BPF_RTS ?
1216                          IEEE80211_PROT_RTSCTS : IEEE80211_PROT_CTSONLY,
1217                     rate);
1218                 if (error || sc->tx_nfree == 0) {
1219                         m_freem(m0);
1220                         return ENOBUFS;
1221                 }
1222                 flags |= RAL_TX_IFS_SIFS;
1223         }
1224
1225         data = STAILQ_FIRST(&sc->tx_free);
1226         STAILQ_REMOVE_HEAD(&sc->tx_free, next);
1227         sc->tx_nfree--;
1228
1229         data->m = m0;
1230         data->ni = ni;
1231         data->rate = rate;
1232
1233         /* XXX need to setup descriptor ourself */
1234         ural_setup_tx_desc(sc, &data->desc, flags, m0->m_pkthdr.len, rate);
1235
1236         DPRINTFN(10, "sending raw frame len=%u rate=%u\n",
1237             m0->m_pkthdr.len, rate);
1238
1239         STAILQ_INSERT_TAIL(&sc->tx_q, data, next);
1240         usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]);
1241
1242         return 0;
1243 }
1244
1245 static int
1246 ural_tx_data(struct ural_softc *sc, struct mbuf *m0, struct ieee80211_node *ni)
1247 {
1248         struct ieee80211vap *vap = ni->ni_vap;
1249         struct ieee80211com *ic = ni->ni_ic;
1250         struct ural_tx_data *data;
1251         struct ieee80211_frame *wh;
1252         const struct ieee80211_txparam *tp;
1253         struct ieee80211_key *k;
1254         uint32_t flags = 0;
1255         uint16_t dur;
1256         int error, rate;
1257
1258         RAL_LOCK_ASSERT(sc, MA_OWNED);
1259
1260         wh = mtod(m0, struct ieee80211_frame *);
1261
1262         tp = &vap->iv_txparms[ieee80211_chan2mode(ni->ni_chan)];
1263         if (IEEE80211_IS_MULTICAST(wh->i_addr1))
1264                 rate = tp->mcastrate;
1265         else if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE)
1266                 rate = tp->ucastrate;
1267         else
1268                 rate = ni->ni_txrate;
1269
1270         if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
1271                 k = ieee80211_crypto_encap(ni, m0);
1272                 if (k == NULL) {
1273                         m_freem(m0);
1274                         return ENOBUFS;
1275                 }
1276                 /* packet header may have moved, reset our local pointer */
1277                 wh = mtod(m0, struct ieee80211_frame *);
1278         }
1279
1280         if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1281                 int prot = IEEE80211_PROT_NONE;
1282                 if (m0->m_pkthdr.len + IEEE80211_CRC_LEN > vap->iv_rtsthreshold)
1283                         prot = IEEE80211_PROT_RTSCTS;
1284                 else if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
1285                     ieee80211_rate2phytype(ic->ic_rt, rate) == IEEE80211_T_OFDM)
1286                         prot = ic->ic_protmode;
1287                 if (prot != IEEE80211_PROT_NONE) {
1288                         error = ural_sendprot(sc, m0, ni, prot, rate);
1289                         if (error || sc->tx_nfree == 0) {
1290                                 m_freem(m0);
1291                                 return ENOBUFS;
1292                         }
1293                         flags |= RAL_TX_IFS_SIFS;
1294                 }
1295         }
1296
1297         data = STAILQ_FIRST(&sc->tx_free);
1298         STAILQ_REMOVE_HEAD(&sc->tx_free, next);
1299         sc->tx_nfree--;
1300
1301         data->m = m0;
1302         data->ni = ni;
1303         data->rate = rate;
1304
1305         if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1306                 flags |= RAL_TX_ACK;
1307                 flags |= RAL_TX_RETRY(7);
1308
1309                 dur = ieee80211_ack_duration(ic->ic_rt, rate, 
1310                     ic->ic_flags & IEEE80211_F_SHPREAMBLE);
1311                 *(uint16_t *)wh->i_dur = htole16(dur);
1312         }
1313
1314         ural_setup_tx_desc(sc, &data->desc, flags, m0->m_pkthdr.len, rate);
1315
1316         DPRINTFN(10, "sending data frame len=%u rate=%u\n",
1317             m0->m_pkthdr.len, rate);
1318
1319         STAILQ_INSERT_TAIL(&sc->tx_q, data, next);
1320         usbd_transfer_start(sc->sc_xfer[URAL_BULK_WR]);
1321
1322         return 0;
1323 }
1324
1325 static void
1326 ural_start(struct ifnet *ifp)
1327 {
1328         struct ural_softc *sc = ifp->if_softc;
1329         struct ieee80211_node *ni;
1330         struct mbuf *m;
1331
1332         RAL_LOCK(sc);
1333         if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
1334                 RAL_UNLOCK(sc);
1335                 return;
1336         }
1337         for (;;) {
1338                 IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
1339                 if (m == NULL)
1340                         break;
1341                 if (sc->tx_nfree < RAL_TX_MINFREE) {
1342                         IFQ_DRV_PREPEND(&ifp->if_snd, m);
1343                         ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1344                         break;
1345                 }
1346                 ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
1347                 if (ural_tx_data(sc, m, ni) != 0) {
1348                         ieee80211_free_node(ni);
1349                         ifp->if_oerrors++;
1350                         break;
1351                 }
1352         }
1353         RAL_UNLOCK(sc);
1354 }
1355
1356 static int
1357 ural_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1358 {
1359         struct ural_softc *sc = ifp->if_softc;
1360         struct ieee80211com *ic = ifp->if_l2com;
1361         struct ifreq *ifr = (struct ifreq *) data;
1362         int error = 0, startall = 0;
1363
1364         switch (cmd) {
1365         case SIOCSIFFLAGS:
1366                 RAL_LOCK(sc);
1367                 if (ifp->if_flags & IFF_UP) {
1368                         if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
1369                                 ural_init_locked(sc);
1370                                 startall = 1;
1371                         } else
1372                                 ural_setpromisc(sc);
1373                 } else {
1374                         if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1375                                 ural_stop(sc);
1376                 }
1377                 RAL_UNLOCK(sc);
1378                 if (startall)
1379                         ieee80211_start_all(ic);
1380                 break;
1381         case SIOCGIFMEDIA:
1382         case SIOCSIFMEDIA:
1383                 error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
1384                 break;
1385         default:
1386                 error = ether_ioctl(ifp, cmd, data);
1387                 break;
1388         }
1389         return error;
1390 }
1391
1392 static void
1393 ural_set_testmode(struct ural_softc *sc)
1394 {
1395         struct usb_device_request req;
1396         usb_error_t error;
1397
1398         req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1399         req.bRequest = RAL_VENDOR_REQUEST;
1400         USETW(req.wValue, 4);
1401         USETW(req.wIndex, 1);
1402         USETW(req.wLength, 0);
1403
1404         error = ural_do_request(sc, &req, NULL);
1405         if (error != 0) {
1406                 device_printf(sc->sc_dev, "could not set test mode: %s\n",
1407                     usbd_errstr(error));
1408         }
1409 }
1410
1411 static void
1412 ural_eeprom_read(struct ural_softc *sc, uint16_t addr, void *buf, int len)
1413 {
1414         struct usb_device_request req;
1415         usb_error_t error;
1416
1417         req.bmRequestType = UT_READ_VENDOR_DEVICE;
1418         req.bRequest = RAL_READ_EEPROM;
1419         USETW(req.wValue, 0);
1420         USETW(req.wIndex, addr);
1421         USETW(req.wLength, len);
1422
1423         error = ural_do_request(sc, &req, buf);
1424         if (error != 0) {
1425                 device_printf(sc->sc_dev, "could not read EEPROM: %s\n",
1426                     usbd_errstr(error));
1427         }
1428 }
1429
1430 static uint16_t
1431 ural_read(struct ural_softc *sc, uint16_t reg)
1432 {
1433         struct usb_device_request req;
1434         usb_error_t error;
1435         uint16_t val;
1436
1437         req.bmRequestType = UT_READ_VENDOR_DEVICE;
1438         req.bRequest = RAL_READ_MAC;
1439         USETW(req.wValue, 0);
1440         USETW(req.wIndex, reg);
1441         USETW(req.wLength, sizeof (uint16_t));
1442
1443         error = ural_do_request(sc, &req, &val);
1444         if (error != 0) {
1445                 device_printf(sc->sc_dev, "could not read MAC register: %s\n",
1446                     usbd_errstr(error));
1447                 return 0;
1448         }
1449
1450         return le16toh(val);
1451 }
1452
1453 static void
1454 ural_read_multi(struct ural_softc *sc, uint16_t reg, void *buf, int len)
1455 {
1456         struct usb_device_request req;
1457         usb_error_t error;
1458
1459         req.bmRequestType = UT_READ_VENDOR_DEVICE;
1460         req.bRequest = RAL_READ_MULTI_MAC;
1461         USETW(req.wValue, 0);
1462         USETW(req.wIndex, reg);
1463         USETW(req.wLength, len);
1464
1465         error = ural_do_request(sc, &req, buf);
1466         if (error != 0) {
1467                 device_printf(sc->sc_dev, "could not read MAC register: %s\n",
1468                     usbd_errstr(error));
1469         }
1470 }
1471
1472 static void
1473 ural_write(struct ural_softc *sc, uint16_t reg, uint16_t val)
1474 {
1475         struct usb_device_request req;
1476         usb_error_t error;
1477
1478         req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1479         req.bRequest = RAL_WRITE_MAC;
1480         USETW(req.wValue, val);
1481         USETW(req.wIndex, reg);
1482         USETW(req.wLength, 0);
1483
1484         error = ural_do_request(sc, &req, NULL);
1485         if (error != 0) {
1486                 device_printf(sc->sc_dev, "could not write MAC register: %s\n",
1487                     usbd_errstr(error));
1488         }
1489 }
1490
1491 static void
1492 ural_write_multi(struct ural_softc *sc, uint16_t reg, void *buf, int len)
1493 {
1494         struct usb_device_request req;
1495         usb_error_t error;
1496
1497         req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1498         req.bRequest = RAL_WRITE_MULTI_MAC;
1499         USETW(req.wValue, 0);
1500         USETW(req.wIndex, reg);
1501         USETW(req.wLength, len);
1502
1503         error = ural_do_request(sc, &req, buf);
1504         if (error != 0) {
1505                 device_printf(sc->sc_dev, "could not write MAC register: %s\n",
1506                     usbd_errstr(error));
1507         }
1508 }
1509
1510 static void
1511 ural_bbp_write(struct ural_softc *sc, uint8_t reg, uint8_t val)
1512 {
1513         uint16_t tmp;
1514         int ntries;
1515
1516         for (ntries = 0; ntries < 100; ntries++) {
1517                 if (!(ural_read(sc, RAL_PHY_CSR8) & RAL_BBP_BUSY))
1518                         break;
1519                 if (ural_pause(sc, hz / 100))
1520                         break;
1521         }
1522         if (ntries == 100) {
1523                 device_printf(sc->sc_dev, "could not write to BBP\n");
1524                 return;
1525         }
1526
1527         tmp = reg << 8 | val;
1528         ural_write(sc, RAL_PHY_CSR7, tmp);
1529 }
1530
1531 static uint8_t
1532 ural_bbp_read(struct ural_softc *sc, uint8_t reg)
1533 {
1534         uint16_t val;
1535         int ntries;
1536
1537         val = RAL_BBP_WRITE | reg << 8;
1538         ural_write(sc, RAL_PHY_CSR7, val);
1539
1540         for (ntries = 0; ntries < 100; ntries++) {
1541                 if (!(ural_read(sc, RAL_PHY_CSR8) & RAL_BBP_BUSY))
1542                         break;
1543                 if (ural_pause(sc, hz / 100))
1544                         break;
1545         }
1546         if (ntries == 100) {
1547                 device_printf(sc->sc_dev, "could not read BBP\n");
1548                 return 0;
1549         }
1550
1551         return ural_read(sc, RAL_PHY_CSR7) & 0xff;
1552 }
1553
1554 static void
1555 ural_rf_write(struct ural_softc *sc, uint8_t reg, uint32_t val)
1556 {
1557         uint32_t tmp;
1558         int ntries;
1559
1560         for (ntries = 0; ntries < 100; ntries++) {
1561                 if (!(ural_read(sc, RAL_PHY_CSR10) & RAL_RF_LOBUSY))
1562                         break;
1563                 if (ural_pause(sc, hz / 100))
1564                         break;
1565         }
1566         if (ntries == 100) {
1567                 device_printf(sc->sc_dev, "could not write to RF\n");
1568                 return;
1569         }
1570
1571         tmp = RAL_RF_BUSY | RAL_RF_20BIT | (val & 0xfffff) << 2 | (reg & 0x3);
1572         ural_write(sc, RAL_PHY_CSR9,  tmp & 0xffff);
1573         ural_write(sc, RAL_PHY_CSR10, tmp >> 16);
1574
1575         /* remember last written value in sc */
1576         sc->rf_regs[reg] = val;
1577
1578         DPRINTFN(15, "RF R[%u] <- 0x%05x\n", reg & 0x3, val & 0xfffff);
1579 }
1580
1581 static void
1582 ural_scan_start(struct ieee80211com *ic)
1583 {
1584         struct ifnet *ifp = ic->ic_ifp;
1585         struct ural_softc *sc = ifp->if_softc;
1586
1587         RAL_LOCK(sc);
1588         ural_write(sc, RAL_TXRX_CSR19, 0);
1589         ural_set_bssid(sc, ifp->if_broadcastaddr);
1590         RAL_UNLOCK(sc);
1591 }
1592
1593 static void
1594 ural_scan_end(struct ieee80211com *ic)
1595 {
1596         struct ural_softc *sc = ic->ic_ifp->if_softc;
1597
1598         RAL_LOCK(sc);
1599         ural_enable_tsf_sync(sc);
1600         ural_set_bssid(sc, sc->sc_bssid);
1601         RAL_UNLOCK(sc);
1602
1603 }
1604
1605 static void
1606 ural_set_channel(struct ieee80211com *ic)
1607 {
1608         struct ural_softc *sc = ic->ic_ifp->if_softc;
1609
1610         RAL_LOCK(sc);
1611         ural_set_chan(sc, ic->ic_curchan);
1612         RAL_UNLOCK(sc);
1613 }
1614
1615 static void
1616 ural_set_chan(struct ural_softc *sc, struct ieee80211_channel *c)
1617 {
1618         struct ifnet *ifp = sc->sc_ifp;
1619         struct ieee80211com *ic = ifp->if_l2com;
1620         uint8_t power, tmp;
1621         int i, chan;
1622
1623         chan = ieee80211_chan2ieee(ic, c);
1624         if (chan == 0 || chan == IEEE80211_CHAN_ANY)
1625                 return;
1626
1627         if (IEEE80211_IS_CHAN_2GHZ(c))
1628                 power = min(sc->txpow[chan - 1], 31);
1629         else
1630                 power = 31;
1631
1632         /* adjust txpower using ifconfig settings */
1633         power -= (100 - ic->ic_txpowlimit) / 8;
1634
1635         DPRINTFN(2, "setting channel to %u, txpower to %u\n", chan, power);
1636
1637         switch (sc->rf_rev) {
1638         case RAL_RF_2522:
1639                 ural_rf_write(sc, RAL_RF1, 0x00814);
1640                 ural_rf_write(sc, RAL_RF2, ural_rf2522_r2[chan - 1]);
1641                 ural_rf_write(sc, RAL_RF3, power << 7 | 0x00040);
1642                 break;
1643
1644         case RAL_RF_2523:
1645                 ural_rf_write(sc, RAL_RF1, 0x08804);
1646                 ural_rf_write(sc, RAL_RF2, ural_rf2523_r2[chan - 1]);
1647                 ural_rf_write(sc, RAL_RF3, power << 7 | 0x38044);
1648                 ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
1649                 break;
1650
1651         case RAL_RF_2524:
1652                 ural_rf_write(sc, RAL_RF1, 0x0c808);
1653                 ural_rf_write(sc, RAL_RF2, ural_rf2524_r2[chan - 1]);
1654                 ural_rf_write(sc, RAL_RF3, power << 7 | 0x00040);
1655                 ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
1656                 break;
1657
1658         case RAL_RF_2525:
1659                 ural_rf_write(sc, RAL_RF1, 0x08808);
1660                 ural_rf_write(sc, RAL_RF2, ural_rf2525_hi_r2[chan - 1]);
1661                 ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
1662                 ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
1663
1664                 ural_rf_write(sc, RAL_RF1, 0x08808);
1665                 ural_rf_write(sc, RAL_RF2, ural_rf2525_r2[chan - 1]);
1666                 ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
1667                 ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00280 : 0x00286);
1668                 break;
1669
1670         case RAL_RF_2525E:
1671                 ural_rf_write(sc, RAL_RF1, 0x08808);
1672                 ural_rf_write(sc, RAL_RF2, ural_rf2525e_r2[chan - 1]);
1673                 ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
1674                 ural_rf_write(sc, RAL_RF4, (chan == 14) ? 0x00286 : 0x00282);
1675                 break;
1676
1677         case RAL_RF_2526:
1678                 ural_rf_write(sc, RAL_RF2, ural_rf2526_hi_r2[chan - 1]);
1679                 ural_rf_write(sc, RAL_RF4, (chan & 1) ? 0x00386 : 0x00381);
1680                 ural_rf_write(sc, RAL_RF1, 0x08804);
1681
1682                 ural_rf_write(sc, RAL_RF2, ural_rf2526_r2[chan - 1]);
1683                 ural_rf_write(sc, RAL_RF3, power << 7 | 0x18044);
1684                 ural_rf_write(sc, RAL_RF4, (chan & 1) ? 0x00386 : 0x00381);
1685                 break;
1686
1687         /* dual-band RF */
1688         case RAL_RF_5222:
1689                 for (i = 0; ural_rf5222[i].chan != chan; i++);
1690
1691                 ural_rf_write(sc, RAL_RF1, ural_rf5222[i].r1);
1692                 ural_rf_write(sc, RAL_RF2, ural_rf5222[i].r2);
1693                 ural_rf_write(sc, RAL_RF3, power << 7 | 0x00040);
1694                 ural_rf_write(sc, RAL_RF4, ural_rf5222[i].r4);
1695                 break;
1696         }
1697
1698         if (ic->ic_opmode != IEEE80211_M_MONITOR &&
1699             (ic->ic_flags & IEEE80211_F_SCAN) == 0) {
1700                 /* set Japan filter bit for channel 14 */
1701                 tmp = ural_bbp_read(sc, 70);
1702
1703                 tmp &= ~RAL_JAPAN_FILTER;
1704                 if (chan == 14)
1705                         tmp |= RAL_JAPAN_FILTER;
1706
1707                 ural_bbp_write(sc, 70, tmp);
1708
1709                 /* clear CRC errors */
1710                 ural_read(sc, RAL_STA_CSR0);
1711
1712                 ural_pause(sc, hz / 100);
1713                 ural_disable_rf_tune(sc);
1714         }
1715
1716         /* XXX doesn't belong here */
1717         /* update basic rate set */
1718         ural_set_basicrates(sc, c);
1719
1720         /* give the hardware some time to do the switchover */
1721         ural_pause(sc, hz / 100);
1722 }
1723
1724 /*
1725  * Disable RF auto-tuning.
1726  */
1727 static void
1728 ural_disable_rf_tune(struct ural_softc *sc)
1729 {
1730         uint32_t tmp;
1731
1732         if (sc->rf_rev != RAL_RF_2523) {
1733                 tmp = sc->rf_regs[RAL_RF1] & ~RAL_RF1_AUTOTUNE;
1734                 ural_rf_write(sc, RAL_RF1, tmp);
1735         }
1736
1737         tmp = sc->rf_regs[RAL_RF3] & ~RAL_RF3_AUTOTUNE;
1738         ural_rf_write(sc, RAL_RF3, tmp);
1739
1740         DPRINTFN(2, "disabling RF autotune\n");
1741 }
1742
1743 /*
1744  * Refer to IEEE Std 802.11-1999 pp. 123 for more information on TSF
1745  * synchronization.
1746  */
1747 static void
1748 ural_enable_tsf_sync(struct ural_softc *sc)
1749 {
1750         struct ifnet *ifp = sc->sc_ifp;
1751         struct ieee80211com *ic = ifp->if_l2com;
1752         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1753         uint16_t logcwmin, preload, tmp;
1754
1755         /* first, disable TSF synchronization */
1756         ural_write(sc, RAL_TXRX_CSR19, 0);
1757
1758         tmp = (16 * vap->iv_bss->ni_intval) << 4;
1759         ural_write(sc, RAL_TXRX_CSR18, tmp);
1760
1761         logcwmin = (ic->ic_opmode == IEEE80211_M_IBSS) ? 2 : 0;
1762         preload = (ic->ic_opmode == IEEE80211_M_IBSS) ? 320 : 6;
1763         tmp = logcwmin << 12 | preload;
1764         ural_write(sc, RAL_TXRX_CSR20, tmp);
1765
1766         /* finally, enable TSF synchronization */
1767         tmp = RAL_ENABLE_TSF | RAL_ENABLE_TBCN;
1768         if (ic->ic_opmode == IEEE80211_M_STA)
1769                 tmp |= RAL_ENABLE_TSF_SYNC(1);
1770         else
1771                 tmp |= RAL_ENABLE_TSF_SYNC(2) | RAL_ENABLE_BEACON_GENERATOR;
1772         ural_write(sc, RAL_TXRX_CSR19, tmp);
1773
1774         DPRINTF("enabling TSF synchronization\n");
1775 }
1776
1777 static void
1778 ural_enable_tsf(struct ural_softc *sc)
1779 {
1780         /* first, disable TSF synchronization */
1781         ural_write(sc, RAL_TXRX_CSR19, 0);
1782         ural_write(sc, RAL_TXRX_CSR19, RAL_ENABLE_TSF | RAL_ENABLE_TSF_SYNC(2));
1783 }
1784
1785 #define RAL_RXTX_TURNAROUND     5       /* us */
1786 static void
1787 ural_update_slot(struct ifnet *ifp)
1788 {
1789         struct ural_softc *sc = ifp->if_softc;
1790         struct ieee80211com *ic = ifp->if_l2com;
1791         uint16_t slottime, sifs, eifs;
1792
1793         slottime = (ic->ic_flags & IEEE80211_F_SHSLOT) ? 9 : 20;
1794
1795         /*
1796          * These settings may sound a bit inconsistent but this is what the
1797          * reference driver does.
1798          */
1799         if (ic->ic_curmode == IEEE80211_MODE_11B) {
1800                 sifs = 16 - RAL_RXTX_TURNAROUND;
1801                 eifs = 364;
1802         } else {
1803                 sifs = 10 - RAL_RXTX_TURNAROUND;
1804                 eifs = 64;
1805         }
1806
1807         ural_write(sc, RAL_MAC_CSR10, slottime);
1808         ural_write(sc, RAL_MAC_CSR11, sifs);
1809         ural_write(sc, RAL_MAC_CSR12, eifs);
1810 }
1811
1812 static void
1813 ural_set_txpreamble(struct ural_softc *sc)
1814 {
1815         struct ifnet *ifp = sc->sc_ifp;
1816         struct ieee80211com *ic = ifp->if_l2com;
1817         uint16_t tmp;
1818
1819         tmp = ural_read(sc, RAL_TXRX_CSR10);
1820
1821         tmp &= ~RAL_SHORT_PREAMBLE;
1822         if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
1823                 tmp |= RAL_SHORT_PREAMBLE;
1824
1825         ural_write(sc, RAL_TXRX_CSR10, tmp);
1826 }
1827
1828 static void
1829 ural_set_basicrates(struct ural_softc *sc, const struct ieee80211_channel *c)
1830 {
1831         /* XXX wrong, take from rate set */
1832         /* update basic rate set */
1833         if (IEEE80211_IS_CHAN_5GHZ(c)) {
1834                 /* 11a basic rates: 6, 12, 24Mbps */
1835                 ural_write(sc, RAL_TXRX_CSR11, 0x150);
1836         } else if (IEEE80211_IS_CHAN_ANYG(c)) {
1837                 /* 11g basic rates: 1, 2, 5.5, 11, 6, 12, 24Mbps */
1838                 ural_write(sc, RAL_TXRX_CSR11, 0x15f);
1839         } else {
1840                 /* 11b basic rates: 1, 2Mbps */
1841                 ural_write(sc, RAL_TXRX_CSR11, 0x3);
1842         }
1843 }
1844
1845 static void
1846 ural_set_bssid(struct ural_softc *sc, const uint8_t *bssid)
1847 {
1848         uint16_t tmp;
1849 #ifdef USB_DEBUG
1850         char ethstr[ETHER_ADDRSTRLEN + 1];
1851 #endif
1852
1853         tmp = bssid[0] | bssid[1] << 8;
1854         ural_write(sc, RAL_MAC_CSR5, tmp);
1855
1856         tmp = bssid[2] | bssid[3] << 8;
1857         ural_write(sc, RAL_MAC_CSR6, tmp);
1858
1859         tmp = bssid[4] | bssid[5] << 8;
1860         ural_write(sc, RAL_MAC_CSR7, tmp);
1861
1862         DPRINTF("setting BSSID to %s\n", kether_ntoa(bssid, ethstr));
1863 }
1864
1865 static void
1866 ural_set_macaddr(struct ural_softc *sc, uint8_t *addr)
1867 {
1868         uint16_t tmp;
1869 #ifdef USB_DEBUG
1870         char ethstr[ETHER_ADDRSTRLEN + 1];
1871 #endif
1872
1873         tmp = addr[0] | addr[1] << 8;
1874         ural_write(sc, RAL_MAC_CSR2, tmp);
1875
1876         tmp = addr[2] | addr[3] << 8;
1877         ural_write(sc, RAL_MAC_CSR3, tmp);
1878
1879         tmp = addr[4] | addr[5] << 8;
1880         ural_write(sc, RAL_MAC_CSR4, tmp);
1881
1882         DPRINTF("setting MAC address to %s\n", kether_ntoa(addr, ethstr));
1883 }
1884
1885 static void
1886 ural_setpromisc(struct ural_softc *sc)
1887 {
1888         struct ifnet *ifp = sc->sc_ifp;
1889         uint32_t tmp;
1890
1891         tmp = ural_read(sc, RAL_TXRX_CSR2);
1892
1893         tmp &= ~RAL_DROP_NOT_TO_ME;
1894         if (!(ifp->if_flags & IFF_PROMISC))
1895                 tmp |= RAL_DROP_NOT_TO_ME;
1896
1897         ural_write(sc, RAL_TXRX_CSR2, tmp);
1898
1899         DPRINTF("%s promiscuous mode\n", (ifp->if_flags & IFF_PROMISC) ?
1900             "entering" : "leaving");
1901 }
1902
1903 static void
1904 ural_update_promisc(struct ieee80211com *ic)
1905 {
1906         struct ural_softc *sc = ic->ic_softc;
1907
1908         if ((ic->ic_ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
1909                 return;
1910
1911         RAL_LOCK(sc);
1912         ural_setpromisc(sc);
1913         RAL_UNLOCK(sc);
1914 }
1915
1916 static const char *
1917 ural_get_rf(int rev)
1918 {
1919         switch (rev) {
1920         case RAL_RF_2522:       return "RT2522";
1921         case RAL_RF_2523:       return "RT2523";
1922         case RAL_RF_2524:       return "RT2524";
1923         case RAL_RF_2525:       return "RT2525";
1924         case RAL_RF_2525E:      return "RT2525e";
1925         case RAL_RF_2526:       return "RT2526";
1926         case RAL_RF_5222:       return "RT5222";
1927         default:                return "unknown";
1928         }
1929 }
1930
1931 static void
1932 ural_read_eeprom(struct ural_softc *sc)
1933 {
1934         uint16_t val;
1935
1936         ural_eeprom_read(sc, RAL_EEPROM_CONFIG0, &val, 2);
1937         val = le16toh(val);
1938         sc->rf_rev =   (val >> 11) & 0x7;
1939         sc->hw_radio = (val >> 10) & 0x1;
1940         sc->led_mode = (val >> 6)  & 0x7;
1941         sc->rx_ant =   (val >> 4)  & 0x3;
1942         sc->tx_ant =   (val >> 2)  & 0x3;
1943         sc->nb_ant =   val & 0x3;
1944
1945         /* read MAC address */
1946         ural_eeprom_read(sc, RAL_EEPROM_ADDRESS, sc->sc_bssid, 6);
1947
1948         /* read default values for BBP registers */
1949         ural_eeprom_read(sc, RAL_EEPROM_BBP_BASE, sc->bbp_prom, 2 * 16);
1950
1951         /* read Tx power for all b/g channels */
1952         ural_eeprom_read(sc, RAL_EEPROM_TXPOWER, sc->txpow, 14);
1953 }
1954
1955 static int
1956 ural_bbp_init(struct ural_softc *sc)
1957 {
1958 #define N(a)    (sizeof (a) / sizeof ((a)[0]))
1959         int i, ntries;
1960
1961         /* wait for BBP to be ready */
1962         for (ntries = 0; ntries < 100; ntries++) {
1963                 if (ural_bbp_read(sc, RAL_BBP_VERSION) != 0)
1964                         break;
1965                 if (ural_pause(sc, hz / 100))
1966                         break;
1967         }
1968         if (ntries == 100) {
1969                 device_printf(sc->sc_dev, "timeout waiting for BBP\n");
1970                 return EIO;
1971         }
1972
1973         /* initialize BBP registers to default values */
1974         for (i = 0; i < N(ural_def_bbp); i++)
1975                 ural_bbp_write(sc, ural_def_bbp[i].reg, ural_def_bbp[i].val);
1976
1977 #if 0
1978         /* initialize BBP registers to values stored in EEPROM */
1979         for (i = 0; i < 16; i++) {
1980                 if (sc->bbp_prom[i].reg == 0xff)
1981                         continue;
1982                 ural_bbp_write(sc, sc->bbp_prom[i].reg, sc->bbp_prom[i].val);
1983         }
1984 #endif
1985
1986         return 0;
1987 #undef N
1988 }
1989
1990 static void
1991 ural_set_txantenna(struct ural_softc *sc, int antenna)
1992 {
1993         uint16_t tmp;
1994         uint8_t tx;
1995
1996         tx = ural_bbp_read(sc, RAL_BBP_TX) & ~RAL_BBP_ANTMASK;
1997         if (antenna == 1)
1998                 tx |= RAL_BBP_ANTA;
1999         else if (antenna == 2)
2000                 tx |= RAL_BBP_ANTB;
2001         else
2002                 tx |= RAL_BBP_DIVERSITY;
2003
2004         /* need to force I/Q flip for RF 2525e, 2526 and 5222 */
2005         if (sc->rf_rev == RAL_RF_2525E || sc->rf_rev == RAL_RF_2526 ||
2006             sc->rf_rev == RAL_RF_5222)
2007                 tx |= RAL_BBP_FLIPIQ;
2008
2009         ural_bbp_write(sc, RAL_BBP_TX, tx);
2010
2011         /* update values in PHY_CSR5 and PHY_CSR6 */
2012         tmp = ural_read(sc, RAL_PHY_CSR5) & ~0x7;
2013         ural_write(sc, RAL_PHY_CSR5, tmp | (tx & 0x7));
2014
2015         tmp = ural_read(sc, RAL_PHY_CSR6) & ~0x7;
2016         ural_write(sc, RAL_PHY_CSR6, tmp | (tx & 0x7));
2017 }
2018
2019 static void
2020 ural_set_rxantenna(struct ural_softc *sc, int antenna)
2021 {
2022         uint8_t rx;
2023
2024         rx = ural_bbp_read(sc, RAL_BBP_RX) & ~RAL_BBP_ANTMASK;
2025         if (antenna == 1)
2026                 rx |= RAL_BBP_ANTA;
2027         else if (antenna == 2)
2028                 rx |= RAL_BBP_ANTB;
2029         else
2030                 rx |= RAL_BBP_DIVERSITY;
2031
2032         /* need to force no I/Q flip for RF 2525e and 2526 */
2033         if (sc->rf_rev == RAL_RF_2525E || sc->rf_rev == RAL_RF_2526)
2034                 rx &= ~RAL_BBP_FLIPIQ;
2035
2036         ural_bbp_write(sc, RAL_BBP_RX, rx);
2037 }
2038
2039 static void
2040 ural_init_locked(struct ural_softc *sc)
2041 {
2042 #define N(a)    (sizeof (a) / sizeof ((a)[0]))
2043         struct ifnet *ifp = sc->sc_ifp;
2044         struct ieee80211com *ic = ifp->if_l2com;
2045         uint16_t tmp;
2046         int i, ntries;
2047
2048         RAL_LOCK_ASSERT(sc, MA_OWNED);
2049
2050         ural_set_testmode(sc);
2051         ural_write(sc, 0x308, 0x00f0);  /* XXX magic */
2052
2053         ural_stop(sc);
2054
2055         /* initialize MAC registers to default values */
2056         for (i = 0; i < N(ural_def_mac); i++)
2057                 ural_write(sc, ural_def_mac[i].reg, ural_def_mac[i].val);
2058
2059         /* wait for BBP and RF to wake up (this can take a long time!) */
2060         for (ntries = 0; ntries < 100; ntries++) {
2061                 tmp = ural_read(sc, RAL_MAC_CSR17);
2062                 if ((tmp & (RAL_BBP_AWAKE | RAL_RF_AWAKE)) ==
2063                     (RAL_BBP_AWAKE | RAL_RF_AWAKE))
2064                         break;
2065                 if (ural_pause(sc, hz / 100))
2066                         break;
2067         }
2068         if (ntries == 100) {
2069                 device_printf(sc->sc_dev,
2070                     "timeout waiting for BBP/RF to wakeup\n");
2071                 goto fail;
2072         }
2073
2074         /* we're ready! */
2075         ural_write(sc, RAL_MAC_CSR1, RAL_HOST_READY);
2076
2077         /* set basic rate set (will be updated later) */
2078         ural_write(sc, RAL_TXRX_CSR11, 0x15f);
2079
2080         if (ural_bbp_init(sc) != 0)
2081                 goto fail;
2082
2083         ural_set_chan(sc, ic->ic_curchan);
2084
2085         /* clear statistic registers (STA_CSR0 to STA_CSR10) */
2086         ural_read_multi(sc, RAL_STA_CSR0, sc->sta, sizeof sc->sta);
2087
2088         ural_set_txantenna(sc, sc->tx_ant);
2089         ural_set_rxantenna(sc, sc->rx_ant);
2090
2091         ural_set_macaddr(sc, IF_LLADDR(ifp));
2092
2093         /*
2094          * Allocate Tx and Rx xfer queues.
2095          */
2096         ural_setup_tx_list(sc);
2097
2098         /* kick Rx */
2099         tmp = RAL_DROP_PHY | RAL_DROP_CRC;
2100         if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2101                 tmp |= RAL_DROP_CTL | RAL_DROP_BAD_VERSION;
2102                 if (ic->ic_opmode != IEEE80211_M_HOSTAP)
2103                         tmp |= RAL_DROP_TODS;
2104                 if (!(ifp->if_flags & IFF_PROMISC))
2105                         tmp |= RAL_DROP_NOT_TO_ME;
2106         }
2107         ural_write(sc, RAL_TXRX_CSR2, tmp);
2108
2109         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
2110         ifp->if_drv_flags |= IFF_DRV_RUNNING;
2111         usbd_xfer_set_stall(sc->sc_xfer[URAL_BULK_WR]);
2112         usbd_transfer_start(sc->sc_xfer[URAL_BULK_RD]);
2113         return;
2114
2115 fail:   ural_stop(sc);
2116 #undef N
2117 }
2118
2119 static void
2120 ural_init(void *priv)
2121 {
2122         struct ural_softc *sc = priv;
2123         struct ifnet *ifp = sc->sc_ifp;
2124         struct ieee80211com *ic = ifp->if_l2com;
2125
2126         RAL_LOCK(sc);
2127         ural_init_locked(sc);
2128         RAL_UNLOCK(sc);
2129
2130         if (ifp->if_drv_flags & IFF_DRV_RUNNING)
2131                 ieee80211_start_all(ic);                /* start all vap's */
2132 }
2133
2134 static void
2135 ural_stop(struct ural_softc *sc)
2136 {
2137         struct ifnet *ifp = sc->sc_ifp;
2138
2139         RAL_LOCK_ASSERT(sc, MA_OWNED);
2140
2141         ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
2142
2143         /*
2144          * Drain all the transfers, if not already drained:
2145          */
2146         RAL_UNLOCK(sc);
2147         usbd_transfer_drain(sc->sc_xfer[URAL_BULK_WR]);
2148         usbd_transfer_drain(sc->sc_xfer[URAL_BULK_RD]);
2149         RAL_LOCK(sc);
2150
2151         ural_unsetup_tx_list(sc);
2152
2153         /* disable Rx */
2154         ural_write(sc, RAL_TXRX_CSR2, RAL_DISABLE_RX);
2155         /* reset ASIC and BBP (but won't reset MAC registers!) */
2156         ural_write(sc, RAL_MAC_CSR1, RAL_RESET_ASIC | RAL_RESET_BBP);
2157         /* wait a little */
2158         ural_pause(sc, hz / 10);
2159         ural_write(sc, RAL_MAC_CSR1, 0);
2160         /* wait a little */
2161         ural_pause(sc, hz / 10);
2162 }
2163
2164 static int
2165 ural_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
2166         const struct ieee80211_bpf_params *params)
2167 {
2168         struct ieee80211com *ic = ni->ni_ic;
2169         struct ifnet *ifp = ic->ic_ifp;
2170         struct ural_softc *sc = ifp->if_softc;
2171
2172         RAL_LOCK(sc);
2173         /* prevent management frames from being sent if we're not ready */
2174         if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
2175                 RAL_UNLOCK(sc);
2176                 m_freem(m);
2177                 ieee80211_free_node(ni);
2178                 return ENETDOWN;
2179         }
2180         if (sc->tx_nfree < RAL_TX_MINFREE) {
2181                 ifp->if_drv_flags |= IFF_DRV_OACTIVE;
2182                 RAL_UNLOCK(sc);
2183                 m_freem(m);
2184                 ieee80211_free_node(ni);
2185                 return EIO;
2186         }
2187
2188         ifp->if_opackets++;
2189
2190         if (params == NULL) {
2191                 /*
2192                  * Legacy path; interpret frame contents to decide
2193                  * precisely how to send the frame.
2194                  */
2195                 if (ural_tx_mgt(sc, m, ni) != 0)
2196                         goto bad;
2197         } else {
2198                 /*
2199                  * Caller supplied explicit parameters to use in
2200                  * sending the frame.
2201                  */
2202                 if (ural_tx_raw(sc, m, ni, params) != 0)
2203                         goto bad;
2204         }
2205         RAL_UNLOCK(sc);
2206         return 0;
2207 bad:
2208         ifp->if_oerrors++;
2209         RAL_UNLOCK(sc);
2210         ieee80211_free_node(ni);
2211         return EIO;             /* XXX */
2212 }
2213
2214 static void
2215 ural_ratectl_start(struct ural_softc *sc, struct ieee80211_node *ni)
2216 {
2217         struct ieee80211vap *vap = ni->ni_vap;
2218         struct ural_vap *uvp = URAL_VAP(vap);
2219
2220         /* clear statistic registers (STA_CSR0 to STA_CSR10) */
2221         ural_read_multi(sc, RAL_STA_CSR0, sc->sta, sizeof sc->sta);
2222
2223         usb_callout_reset(&uvp->ratectl_ch, hz, ural_ratectl_timeout, uvp);
2224 }
2225
2226 static void
2227 ural_ratectl_timeout(void *arg)
2228 {
2229         struct ural_vap *uvp = arg;
2230         struct ieee80211vap *vap = &uvp->vap;
2231         struct ieee80211com *ic = vap->iv_ic;
2232
2233         ieee80211_runtask(ic, &uvp->ratectl_task);
2234 }
2235
2236 static void
2237 ural_ratectl_task(void *arg, int pending)
2238 {
2239         struct ural_vap *uvp = arg;
2240         struct ieee80211vap *vap = &uvp->vap;
2241         struct ieee80211com *ic = vap->iv_ic;
2242         struct ifnet *ifp = ic->ic_ifp;
2243         struct ural_softc *sc = ifp->if_softc;
2244         struct ieee80211_node *ni;
2245         int ok, fail;
2246         int sum, retrycnt;
2247
2248         ni = ieee80211_ref_node(vap->iv_bss);
2249         RAL_LOCK(sc);
2250         /* read and clear statistic registers (STA_CSR0 to STA_CSR10) */
2251         ural_read_multi(sc, RAL_STA_CSR0, sc->sta, sizeof(sc->sta));
2252
2253         ok = sc->sta[7] +               /* TX ok w/o retry */
2254              sc->sta[8];                /* TX ok w/ retry */
2255         fail = sc->sta[9];              /* TX retry-fail count */
2256         sum = ok+fail;
2257         retrycnt = sc->sta[8] + fail;
2258
2259         ieee80211_ratectl_tx_update(vap, ni, &sum, &ok, &retrycnt);
2260         (void) ieee80211_ratectl_rate(ni, NULL, 0);
2261
2262         ifp->if_oerrors += fail;        /* count TX retry-fail as Tx errors */
2263
2264         usb_callout_reset(&uvp->ratectl_ch, hz, ural_ratectl_timeout, uvp);
2265         RAL_UNLOCK(sc);
2266         ieee80211_free_node(ni);
2267 }
2268
2269 static int
2270 ural_pause(struct ural_softc *sc, int timeout)
2271 {
2272
2273         usb_pause_mtx(&sc->sc_mtx, timeout);
2274         return (0);
2275 }