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