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