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