]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/dev/usb/wlan/if_urtwn.c
MFC r281070:
[FreeBSD/stable/10.git] / sys / dev / usb / wlan / if_urtwn.c
1 /*      $OpenBSD: if_urtwn.c,v 1.16 2011/02/10 17:26:40 jakemsr Exp $   */
2
3 /*-
4  * Copyright (c) 2010 Damien Bergamini <damien.bergamini@free.fr>
5  * Copyright (c) 2014 Kevin Lo <kevlo@FreeBSD.org>
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  * Driver for Realtek RTL8188CE-VAU/RTL8188CUS/RTL8188EU/RTL8188RU/RTL8192CU.
25  */
26
27 #include <sys/param.h>
28 #include <sys/sockio.h>
29 #include <sys/sysctl.h>
30 #include <sys/lock.h>
31 #include <sys/mutex.h>
32 #include <sys/mbuf.h>
33 #include <sys/kernel.h>
34 #include <sys/socket.h>
35 #include <sys/systm.h>
36 #include <sys/malloc.h>
37 #include <sys/module.h>
38 #include <sys/bus.h>
39 #include <sys/endian.h>
40 #include <sys/linker.h>
41 #include <sys/firmware.h>
42 #include <sys/kdb.h>
43
44 #include <machine/bus.h>
45 #include <machine/resource.h>
46 #include <sys/rman.h>
47
48 #include <net/bpf.h>
49 #include <net/if.h>
50 #include <net/if_arp.h>
51 #include <net/ethernet.h>
52 #include <net/if_dl.h>
53 #include <net/if_media.h>
54 #include <net/if_types.h>
55
56 #include <netinet/in.h>
57 #include <netinet/in_systm.h>
58 #include <netinet/in_var.h>
59 #include <netinet/if_ether.h>
60 #include <netinet/ip.h>
61
62 #include <net80211/ieee80211_var.h>
63 #include <net80211/ieee80211_regdomain.h>
64 #include <net80211/ieee80211_radiotap.h>
65 #include <net80211/ieee80211_ratectl.h>
66
67 #include <dev/usb/usb.h>
68 #include <dev/usb/usbdi.h>
69 #include "usbdevs.h"
70
71 #define USB_DEBUG_VAR urtwn_debug
72 #include <dev/usb/usb_debug.h>
73
74 #include <dev/usb/wlan/if_urtwnreg.h>
75
76 #ifdef USB_DEBUG
77 static int urtwn_debug = 0;
78
79 SYSCTL_NODE(_hw_usb, OID_AUTO, urtwn, CTLFLAG_RW, 0, "USB urtwn");
80 SYSCTL_INT(_hw_usb_urtwn, OID_AUTO, debug, CTLFLAG_RW, &urtwn_debug, 0,
81     "Debug level");
82 #endif
83
84 #define URTWN_RSSI(r)  (r) - 110
85 #define IEEE80211_HAS_ADDR4(wh) \
86         (((wh)->i_fc[1] & IEEE80211_FC1_DIR_MASK) == IEEE80211_FC1_DIR_DSTODS)
87
88 /* various supported device vendors/products */
89 static const STRUCT_USB_HOST_ID urtwn_devs[] = {
90 #define URTWN_DEV(v,p)  { USB_VP(USB_VENDOR_##v, USB_PRODUCT_##v##_##p) }
91 #define URTWN_RTL8188E_DEV(v,p) \
92         { USB_VPI(USB_VENDOR_##v, USB_PRODUCT_##v##_##p, URTWN_RTL8188E) }
93 #define URTWN_RTL8188E  1
94         URTWN_DEV(ABOCOM,       RTL8188CU_1),
95         URTWN_DEV(ABOCOM,       RTL8188CU_2),
96         URTWN_DEV(ABOCOM,       RTL8192CU),
97         URTWN_DEV(ASUS,         RTL8192CU),
98         URTWN_DEV(ASUS,         USBN10NANO),
99         URTWN_DEV(AZUREWAVE,    RTL8188CE_1),
100         URTWN_DEV(AZUREWAVE,    RTL8188CE_2),
101         URTWN_DEV(AZUREWAVE,    RTL8188CU),
102         URTWN_DEV(BELKIN,       F7D2102),
103         URTWN_DEV(BELKIN,       RTL8188CU),
104         URTWN_DEV(BELKIN,       RTL8192CU),
105         URTWN_DEV(CHICONY,      RTL8188CUS_1),
106         URTWN_DEV(CHICONY,      RTL8188CUS_2),
107         URTWN_DEV(CHICONY,      RTL8188CUS_3),
108         URTWN_DEV(CHICONY,      RTL8188CUS_4),
109         URTWN_DEV(CHICONY,      RTL8188CUS_5),
110         URTWN_DEV(COREGA,       RTL8192CU),
111         URTWN_DEV(DLINK,        RTL8188CU),
112         URTWN_DEV(DLINK,        RTL8192CU_1),
113         URTWN_DEV(DLINK,        RTL8192CU_2),
114         URTWN_DEV(DLINK,        RTL8192CU_3),
115         URTWN_DEV(DLINK,        DWA131B),
116         URTWN_DEV(EDIMAX,       EW7811UN),
117         URTWN_DEV(EDIMAX,       RTL8192CU),
118         URTWN_DEV(FEIXUN,       RTL8188CU),
119         URTWN_DEV(FEIXUN,       RTL8192CU),
120         URTWN_DEV(GUILLEMOT,    HWNUP150),
121         URTWN_DEV(HAWKING,      RTL8192CU),
122         URTWN_DEV(HP3,          RTL8188CU),
123         URTWN_DEV(NETGEAR,      WNA1000M),
124         URTWN_DEV(NETGEAR,      RTL8192CU),
125         URTWN_DEV(NETGEAR4,     RTL8188CU),
126         URTWN_DEV(NOVATECH,     RTL8188CU),
127         URTWN_DEV(PLANEX2,      RTL8188CU_1),
128         URTWN_DEV(PLANEX2,      RTL8188CU_2),
129         URTWN_DEV(PLANEX2,      RTL8188CU_3),
130         URTWN_DEV(PLANEX2,      RTL8188CU_4),
131         URTWN_DEV(PLANEX2,      RTL8188CUS),
132         URTWN_DEV(PLANEX2,      RTL8192CU),
133         URTWN_DEV(REALTEK,      RTL8188CE_0),
134         URTWN_DEV(REALTEK,      RTL8188CE_1),
135         URTWN_DEV(REALTEK,      RTL8188CTV),
136         URTWN_DEV(REALTEK,      RTL8188CU_0),
137         URTWN_DEV(REALTEK,      RTL8188CU_1),
138         URTWN_DEV(REALTEK,      RTL8188CU_2),
139         URTWN_DEV(REALTEK,      RTL8188CU_COMBO),
140         URTWN_DEV(REALTEK,      RTL8188CUS),
141         URTWN_DEV(REALTEK,      RTL8188RU_1),
142         URTWN_DEV(REALTEK,      RTL8188RU_2),
143         URTWN_DEV(REALTEK,      RTL8188RU_3),
144         URTWN_DEV(REALTEK,      RTL8191CU),
145         URTWN_DEV(REALTEK,      RTL8192CE),
146         URTWN_DEV(REALTEK,      RTL8192CU),
147         URTWN_DEV(REALTEK,      RTL8188CU_0),
148         URTWN_DEV(SITECOMEU,    RTL8188CU_1),
149         URTWN_DEV(SITECOMEU,    RTL8188CU_2),
150         URTWN_DEV(SITECOMEU,    RTL8192CU),
151         URTWN_DEV(TRENDNET,     RTL8188CU),
152         URTWN_DEV(TRENDNET,     RTL8192CU),
153         URTWN_DEV(ZYXEL,        RTL8192CU),
154         /* URTWN_RTL8188E */
155         URTWN_RTL8188E_DEV(DLINK,       DWA125D1),
156         URTWN_RTL8188E_DEV(REALTEK,     RTL8188ETV),
157         URTWN_RTL8188E_DEV(REALTEK,     RTL8188EU),
158 #undef URTWN_RTL8188E_DEV
159 #undef URTWN_DEV
160 };
161
162 static device_probe_t   urtwn_match;
163 static device_attach_t  urtwn_attach;
164 static device_detach_t  urtwn_detach;
165
166 static usb_callback_t   urtwn_bulk_tx_callback;
167 static usb_callback_t   urtwn_bulk_rx_callback;
168
169 static usb_error_t      urtwn_do_request(struct urtwn_softc *sc,
170                             struct usb_device_request *req, void *data);
171 static struct ieee80211vap *urtwn_vap_create(struct ieee80211com *,
172                     const char [IFNAMSIZ], int, enum ieee80211_opmode, int,
173                     const uint8_t [IEEE80211_ADDR_LEN],
174                     const uint8_t [IEEE80211_ADDR_LEN]);
175 static void             urtwn_vap_delete(struct ieee80211vap *);
176 static struct mbuf *    urtwn_rx_frame(struct urtwn_softc *, uint8_t *, int, 
177                             int *);
178 static struct mbuf *    urtwn_rxeof(struct usb_xfer *, struct urtwn_data *, 
179                             int *, int8_t *);
180 static void             urtwn_txeof(struct usb_xfer *, struct urtwn_data *);
181 static int              urtwn_alloc_list(struct urtwn_softc *, 
182                             struct urtwn_data[], int, int);
183 static int              urtwn_alloc_rx_list(struct urtwn_softc *);
184 static int              urtwn_alloc_tx_list(struct urtwn_softc *);
185 static void             urtwn_free_tx_list(struct urtwn_softc *);
186 static void             urtwn_free_rx_list(struct urtwn_softc *);
187 static void             urtwn_free_list(struct urtwn_softc *,
188                             struct urtwn_data data[], int);
189 static struct urtwn_data *      _urtwn_getbuf(struct urtwn_softc *);
190 static struct urtwn_data *      urtwn_getbuf(struct urtwn_softc *);
191 static int              urtwn_write_region_1(struct urtwn_softc *, uint16_t, 
192                             uint8_t *, int);
193 static void             urtwn_write_1(struct urtwn_softc *, uint16_t, uint8_t);
194 static void             urtwn_write_2(struct urtwn_softc *, uint16_t, uint16_t);
195 static void             urtwn_write_4(struct urtwn_softc *, uint16_t, uint32_t);
196 static int              urtwn_read_region_1(struct urtwn_softc *, uint16_t, 
197                             uint8_t *, int);
198 static uint8_t          urtwn_read_1(struct urtwn_softc *, uint16_t);
199 static uint16_t         urtwn_read_2(struct urtwn_softc *, uint16_t);
200 static uint32_t         urtwn_read_4(struct urtwn_softc *, uint16_t);
201 static int              urtwn_fw_cmd(struct urtwn_softc *, uint8_t, 
202                             const void *, int);
203 static void             urtwn_r92c_rf_write(struct urtwn_softc *, int,
204                             uint8_t, uint32_t);
205 static void             urtwn_r88e_rf_write(struct urtwn_softc *, int, 
206                             uint8_t, uint32_t);
207 static uint32_t         urtwn_rf_read(struct urtwn_softc *, int, uint8_t);
208 static int              urtwn_llt_write(struct urtwn_softc *, uint32_t, 
209                             uint32_t);
210 static uint8_t          urtwn_efuse_read_1(struct urtwn_softc *, uint16_t);
211 static void             urtwn_efuse_read(struct urtwn_softc *);
212 static void             urtwn_efuse_switch_power(struct urtwn_softc *);
213 static int              urtwn_read_chipid(struct urtwn_softc *);
214 static void             urtwn_read_rom(struct urtwn_softc *);
215 static void             urtwn_r88e_read_rom(struct urtwn_softc *);
216 static int              urtwn_ra_init(struct urtwn_softc *);
217 static void             urtwn_tsf_sync_enable(struct urtwn_softc *);
218 static void             urtwn_set_led(struct urtwn_softc *, int, int);
219 static int              urtwn_newstate(struct ieee80211vap *, 
220                             enum ieee80211_state, int);
221 static void             urtwn_watchdog(void *);
222 static void             urtwn_update_avgrssi(struct urtwn_softc *, int, int8_t);
223 static int8_t           urtwn_get_rssi(struct urtwn_softc *, int, void *);
224 static int8_t           urtwn_r88e_get_rssi(struct urtwn_softc *, int, void *);
225 static int              urtwn_tx_start(struct urtwn_softc *,
226                             struct ieee80211_node *, struct mbuf *,
227                             struct urtwn_data *);
228 static void             urtwn_start(struct ifnet *);
229 static void             urtwn_start_locked(struct ifnet *,
230                             struct urtwn_softc *);
231 static int              urtwn_ioctl(struct ifnet *, u_long, caddr_t);
232 static int              urtwn_r92c_power_on(struct urtwn_softc *);
233 static int              urtwn_r88e_power_on(struct urtwn_softc *);
234 static int              urtwn_llt_init(struct urtwn_softc *);
235 static void             urtwn_fw_reset(struct urtwn_softc *);
236 static void             urtwn_r88e_fw_reset(struct urtwn_softc *);
237 static int              urtwn_fw_loadpage(struct urtwn_softc *, int, 
238                             const uint8_t *, int);
239 static int              urtwn_load_firmware(struct urtwn_softc *);
240 static int              urtwn_r92c_dma_init(struct urtwn_softc *);
241 static int              urtwn_r88e_dma_init(struct urtwn_softc *);
242 static void             urtwn_mac_init(struct urtwn_softc *);
243 static void             urtwn_bb_init(struct urtwn_softc *);
244 static void             urtwn_rf_init(struct urtwn_softc *);
245 static void             urtwn_cam_init(struct urtwn_softc *);
246 static void             urtwn_pa_bias_init(struct urtwn_softc *);
247 static void             urtwn_rxfilter_init(struct urtwn_softc *);
248 static void             urtwn_edca_init(struct urtwn_softc *);
249 static void             urtwn_write_txpower(struct urtwn_softc *, int, 
250                             uint16_t[]);
251 static void             urtwn_get_txpower(struct urtwn_softc *, int,
252                             struct ieee80211_channel *, 
253                             struct ieee80211_channel *, uint16_t[]);
254 static void             urtwn_r88e_get_txpower(struct urtwn_softc *, int,
255                             struct ieee80211_channel *, 
256                             struct ieee80211_channel *, uint16_t[]);
257 static void             urtwn_set_txpower(struct urtwn_softc *,
258                             struct ieee80211_channel *, 
259                             struct ieee80211_channel *);
260 static void             urtwn_scan_start(struct ieee80211com *);
261 static void             urtwn_scan_end(struct ieee80211com *);
262 static void             urtwn_set_channel(struct ieee80211com *);
263 static void             urtwn_set_chan(struct urtwn_softc *,
264                             struct ieee80211_channel *, 
265                             struct ieee80211_channel *);
266 static void             urtwn_update_mcast(struct ifnet *);
267 static void             urtwn_iq_calib(struct urtwn_softc *);
268 static void             urtwn_lc_calib(struct urtwn_softc *);
269 static void             urtwn_init(void *);
270 static void             urtwn_init_locked(void *);
271 static void             urtwn_stop(struct ifnet *);
272 static void             urtwn_stop_locked(struct ifnet *);
273 static void             urtwn_abort_xfers(struct urtwn_softc *);
274 static int              urtwn_raw_xmit(struct ieee80211_node *, struct mbuf *,
275                             const struct ieee80211_bpf_params *);
276 static void             urtwn_ms_delay(struct urtwn_softc *);
277
278 /* Aliases. */
279 #define urtwn_bb_write  urtwn_write_4
280 #define urtwn_bb_read   urtwn_read_4
281
282 static const struct usb_config urtwn_config[URTWN_N_TRANSFER] = {
283         [URTWN_BULK_RX] = {
284                 .type = UE_BULK,
285                 .endpoint = UE_ADDR_ANY,
286                 .direction = UE_DIR_IN,
287                 .bufsize = URTWN_RXBUFSZ,
288                 .flags = {
289                         .pipe_bof = 1,
290                         .short_xfer_ok = 1
291                 },
292                 .callback = urtwn_bulk_rx_callback,
293         },
294         [URTWN_BULK_TX_BE] = {
295                 .type = UE_BULK,
296                 .endpoint = 0x03,
297                 .direction = UE_DIR_OUT,
298                 .bufsize = URTWN_TXBUFSZ,
299                 .flags = {
300                         .ext_buffer = 1,
301                         .pipe_bof = 1,
302                         .force_short_xfer = 1
303                 },
304                 .callback = urtwn_bulk_tx_callback,
305                 .timeout = URTWN_TX_TIMEOUT,    /* ms */
306         },
307         [URTWN_BULK_TX_BK] = {
308                 .type = UE_BULK,
309                 .endpoint = 0x03,
310                 .direction = UE_DIR_OUT,
311                 .bufsize = URTWN_TXBUFSZ,
312                 .flags = {
313                         .ext_buffer = 1,
314                         .pipe_bof = 1,
315                         .force_short_xfer = 1,
316                 },
317                 .callback = urtwn_bulk_tx_callback,
318                 .timeout = URTWN_TX_TIMEOUT,    /* ms */
319         },
320         [URTWN_BULK_TX_VI] = {
321                 .type = UE_BULK,
322                 .endpoint = 0x02,
323                 .direction = UE_DIR_OUT,
324                 .bufsize = URTWN_TXBUFSZ,
325                 .flags = {
326                         .ext_buffer = 1,
327                         .pipe_bof = 1,
328                         .force_short_xfer = 1
329                 },
330                 .callback = urtwn_bulk_tx_callback,
331                 .timeout = URTWN_TX_TIMEOUT,    /* ms */
332         },
333         [URTWN_BULK_TX_VO] = {
334                 .type = UE_BULK,
335                 .endpoint = 0x02,
336                 .direction = UE_DIR_OUT,
337                 .bufsize = URTWN_TXBUFSZ,
338                 .flags = {
339                         .ext_buffer = 1,
340                         .pipe_bof = 1,
341                         .force_short_xfer = 1
342                 },
343                 .callback = urtwn_bulk_tx_callback,
344                 .timeout = URTWN_TX_TIMEOUT,    /* ms */
345         },
346 };
347
348 static int
349 urtwn_match(device_t self)
350 {
351         struct usb_attach_arg *uaa = device_get_ivars(self);
352
353         if (uaa->usb_mode != USB_MODE_HOST)
354                 return (ENXIO);
355         if (uaa->info.bConfigIndex != URTWN_CONFIG_INDEX)
356                 return (ENXIO);
357         if (uaa->info.bIfaceIndex != URTWN_IFACE_INDEX)
358                 return (ENXIO);
359
360         return (usbd_lookup_id_by_uaa(urtwn_devs, sizeof(urtwn_devs), uaa));
361 }
362
363 static int
364 urtwn_attach(device_t self)
365 {
366         struct usb_attach_arg *uaa = device_get_ivars(self);
367         struct urtwn_softc *sc = device_get_softc(self);
368         struct ifnet *ifp;
369         struct ieee80211com *ic;
370         uint8_t iface_index, bands;
371         int error;
372
373         device_set_usb_desc(self);
374         sc->sc_udev = uaa->device;
375         sc->sc_dev = self;
376         if (USB_GET_DRIVER_INFO(uaa) == URTWN_RTL8188E)
377                 sc->chip |= URTWN_CHIP_88E;
378
379         mtx_init(&sc->sc_mtx, device_get_nameunit(self),
380             MTX_NETWORK_LOCK, MTX_DEF);
381         callout_init(&sc->sc_watchdog_ch, 0);
382
383         iface_index = URTWN_IFACE_INDEX;
384         error = usbd_transfer_setup(uaa->device, &iface_index, sc->sc_xfer,
385             urtwn_config, URTWN_N_TRANSFER, sc, &sc->sc_mtx);
386         if (error) {
387                 device_printf(self, "could not allocate USB transfers, "
388                     "err=%s\n", usbd_errstr(error));
389                 goto detach;
390         }
391
392         URTWN_LOCK(sc);
393
394         error = urtwn_read_chipid(sc);
395         if (error) {
396                 device_printf(sc->sc_dev, "unsupported test chip\n");
397                 URTWN_UNLOCK(sc);
398                 goto detach;
399         }
400
401         /* Determine number of Tx/Rx chains. */
402         if (sc->chip & URTWN_CHIP_92C) {
403                 sc->ntxchains = (sc->chip & URTWN_CHIP_92C_1T2R) ? 1 : 2;
404                 sc->nrxchains = 2;
405         } else {
406                 sc->ntxchains = 1;
407                 sc->nrxchains = 1;
408         }
409
410         if (sc->chip & URTWN_CHIP_88E)
411                 urtwn_r88e_read_rom(sc);
412         else
413                 urtwn_read_rom(sc);
414
415         device_printf(sc->sc_dev, "MAC/BB RTL%s, RF 6052 %dT%dR\n",
416             (sc->chip & URTWN_CHIP_92C) ? "8192CU" :
417             (sc->chip & URTWN_CHIP_88E) ? "8188EU" :
418             (sc->board_type == R92C_BOARD_TYPE_HIGHPA) ? "8188RU" :
419             (sc->board_type == R92C_BOARD_TYPE_MINICARD) ? "8188CE-VAU" :
420             "8188CUS", sc->ntxchains, sc->nrxchains);
421
422         URTWN_UNLOCK(sc);
423
424         ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211);
425         if (ifp == NULL) {
426                 device_printf(sc->sc_dev, "can not if_alloc()\n");
427                 goto detach;
428         }
429         ic = ifp->if_l2com;
430
431         ifp->if_softc = sc;
432         if_initname(ifp, "urtwn", device_get_unit(sc->sc_dev));
433         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
434         ifp->if_init = urtwn_init;
435         ifp->if_ioctl = urtwn_ioctl;
436         ifp->if_start = urtwn_start;
437         IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
438         ifp->if_snd.ifq_drv_maxlen = ifqmaxlen;
439         IFQ_SET_READY(&ifp->if_snd);
440
441         ic->ic_ifp = ifp;
442         ic->ic_phytype = IEEE80211_T_OFDM;      /* not only, but not used */
443         ic->ic_opmode = IEEE80211_M_STA;        /* default to BSS mode */
444
445         /* set device capabilities */
446         ic->ic_caps =
447                   IEEE80211_C_STA               /* station mode */
448                 | IEEE80211_C_MONITOR           /* monitor mode */
449                 | IEEE80211_C_SHPREAMBLE        /* short preamble supported */
450                 | IEEE80211_C_SHSLOT            /* short slot time supported */
451                 | IEEE80211_C_BGSCAN            /* capable of bg scanning */
452                 | IEEE80211_C_WPA               /* 802.11i */
453                 ;
454
455         bands = 0;
456         setbit(&bands, IEEE80211_MODE_11B);
457         setbit(&bands, IEEE80211_MODE_11G);
458         ieee80211_init_channels(ic, NULL, &bands);
459
460         ieee80211_ifattach(ic, sc->sc_bssid);
461         ic->ic_raw_xmit = urtwn_raw_xmit;
462         ic->ic_scan_start = urtwn_scan_start;
463         ic->ic_scan_end = urtwn_scan_end;
464         ic->ic_set_channel = urtwn_set_channel;
465
466         ic->ic_vap_create = urtwn_vap_create;
467         ic->ic_vap_delete = urtwn_vap_delete;
468         ic->ic_update_mcast = urtwn_update_mcast;
469
470         ieee80211_radiotap_attach(ic, &sc->sc_txtap.wt_ihdr, 
471             sizeof(sc->sc_txtap), URTWN_TX_RADIOTAP_PRESENT,
472             &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap),
473             URTWN_RX_RADIOTAP_PRESENT);
474
475         if (bootverbose)
476                 ieee80211_announce(ic);
477
478         return (0);
479
480 detach:
481         urtwn_detach(self);
482         return (ENXIO);                 /* failure */
483 }
484
485 static int
486 urtwn_detach(device_t self)
487 {
488         struct urtwn_softc *sc = device_get_softc(self);
489         struct ifnet *ifp = sc->sc_ifp;
490         struct ieee80211com *ic = ifp->if_l2com;
491         unsigned int x;
492         
493         /* Prevent further ioctls. */
494         URTWN_LOCK(sc);
495         sc->sc_flags |= URTWN_DETACHED;
496         URTWN_UNLOCK(sc);
497
498         urtwn_stop(ifp);
499
500         callout_drain(&sc->sc_watchdog_ch);
501
502         /* Prevent further allocations from RX/TX data lists. */
503         URTWN_LOCK(sc);
504         STAILQ_INIT(&sc->sc_tx_active);
505         STAILQ_INIT(&sc->sc_tx_inactive);
506         STAILQ_INIT(&sc->sc_tx_pending);
507
508         STAILQ_INIT(&sc->sc_rx_active);
509         STAILQ_INIT(&sc->sc_rx_inactive);
510         URTWN_UNLOCK(sc);
511
512         /* drain USB transfers */
513         for (x = 0; x != URTWN_N_TRANSFER; x++)
514                 usbd_transfer_drain(sc->sc_xfer[x]);
515
516         /* Free data buffers. */
517         URTWN_LOCK(sc);
518         urtwn_free_tx_list(sc);
519         urtwn_free_rx_list(sc);
520         URTWN_UNLOCK(sc);
521
522         /* stop all USB transfers */
523         usbd_transfer_unsetup(sc->sc_xfer, URTWN_N_TRANSFER);
524         ieee80211_ifdetach(ic);
525
526         if_free(ifp);
527         mtx_destroy(&sc->sc_mtx);
528
529         return (0);
530 }
531
532 static void
533 urtwn_free_tx_list(struct urtwn_softc *sc)
534 {
535         urtwn_free_list(sc, sc->sc_tx, URTWN_TX_LIST_COUNT);
536 }
537
538 static void
539 urtwn_free_rx_list(struct urtwn_softc *sc)
540 {
541         urtwn_free_list(sc, sc->sc_rx, URTWN_RX_LIST_COUNT);
542 }
543
544 static void
545 urtwn_free_list(struct urtwn_softc *sc, struct urtwn_data data[], int ndata)
546 {
547         int i;
548
549         for (i = 0; i < ndata; i++) {
550                 struct urtwn_data *dp = &data[i];
551
552                 if (dp->buf != NULL) {
553                         free(dp->buf, M_USBDEV);
554                         dp->buf = NULL;
555                 }
556                 if (dp->ni != NULL) {
557                         ieee80211_free_node(dp->ni);
558                         dp->ni = NULL;
559                 }
560         }
561 }
562
563 static usb_error_t
564 urtwn_do_request(struct urtwn_softc *sc, struct usb_device_request *req,
565     void *data)
566 {
567         usb_error_t err;
568         int ntries = 10;
569
570         URTWN_ASSERT_LOCKED(sc);
571
572         while (ntries--) {
573                 err = usbd_do_request_flags(sc->sc_udev, &sc->sc_mtx,
574                     req, data, 0, NULL, 250 /* ms */);
575                 if (err == 0)
576                         break;
577
578                 DPRINTFN(1, "Control request failed, %s (retrying)\n",
579                     usbd_errstr(err));
580                 usb_pause_mtx(&sc->sc_mtx, hz / 100);
581         }
582         return (err);
583 }
584
585 static struct ieee80211vap *
586 urtwn_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
587     enum ieee80211_opmode opmode, int flags,
588     const uint8_t bssid[IEEE80211_ADDR_LEN],
589     const uint8_t mac[IEEE80211_ADDR_LEN])
590 {
591         struct urtwn_vap *uvp;
592         struct ieee80211vap *vap;
593
594         if (!TAILQ_EMPTY(&ic->ic_vaps))         /* only one at a time */
595                 return (NULL);
596
597         uvp = (struct urtwn_vap *) malloc(sizeof(struct urtwn_vap),
598             M_80211_VAP, M_NOWAIT | M_ZERO);
599         if (uvp == NULL)
600                 return (NULL);
601         vap = &uvp->vap;
602         /* enable s/w bmiss handling for sta mode */
603
604         if (ieee80211_vap_setup(ic, vap, name, unit, opmode, 
605             flags | IEEE80211_CLONE_NOBEACONS, bssid, mac) != 0) {
606                 /* out of memory */
607                 free(uvp, M_80211_VAP);
608                 return (NULL);
609         }
610
611         /* override state transition machine */
612         uvp->newstate = vap->iv_newstate;
613         vap->iv_newstate = urtwn_newstate;
614
615         /* complete setup */
616         ieee80211_vap_attach(vap, ieee80211_media_change,
617             ieee80211_media_status);
618         ic->ic_opmode = opmode;
619         return (vap);
620 }
621
622 static void
623 urtwn_vap_delete(struct ieee80211vap *vap)
624 {
625         struct urtwn_vap *uvp = URTWN_VAP(vap);
626
627         ieee80211_vap_detach(vap);
628         free(uvp, M_80211_VAP);
629 }
630
631 static struct mbuf *
632 urtwn_rx_frame(struct urtwn_softc *sc, uint8_t *buf, int pktlen, int *rssi_p)
633 {
634         struct ifnet *ifp = sc->sc_ifp;
635         struct ieee80211com *ic = ifp->if_l2com;
636         struct ieee80211_frame *wh;
637         struct mbuf *m;
638         struct r92c_rx_stat *stat;
639         uint32_t rxdw0, rxdw3;
640         uint8_t rate;
641         int8_t rssi = 0;
642         int infosz;
643
644         /*
645          * don't pass packets to the ieee80211 framework if the driver isn't
646          * RUNNING.
647          */
648         if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
649                 return (NULL);
650
651         stat = (struct r92c_rx_stat *)buf;
652         rxdw0 = le32toh(stat->rxdw0);
653         rxdw3 = le32toh(stat->rxdw3);
654
655         if (rxdw0 & (R92C_RXDW0_CRCERR | R92C_RXDW0_ICVERR)) {
656                 /*
657                  * This should not happen since we setup our Rx filter
658                  * to not receive these frames.
659                  */
660                 ifp->if_ierrors++;
661                 return (NULL);
662         }
663
664         rate = MS(rxdw3, R92C_RXDW3_RATE);
665         infosz = MS(rxdw0, R92C_RXDW0_INFOSZ) * 8;
666
667         /* Get RSSI from PHY status descriptor if present. */
668         if (infosz != 0 && (rxdw0 & R92C_RXDW0_PHYST)) {
669                 if (sc->chip & URTWN_CHIP_88E) 
670                         rssi = urtwn_r88e_get_rssi(sc, rate, &stat[1]);
671                 else
672                         rssi = urtwn_get_rssi(sc, rate, &stat[1]);
673                 /* Update our average RSSI. */
674                 urtwn_update_avgrssi(sc, rate, rssi);
675                 /*
676                  * Convert the RSSI to a range that will be accepted
677                  * by net80211.
678                  */
679                 rssi = URTWN_RSSI(rssi);
680         }
681
682         m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
683         if (m == NULL) {
684                 device_printf(sc->sc_dev, "could not create RX mbuf\n");
685                 return (NULL);
686         }
687
688         /* Finalize mbuf. */
689         m->m_pkthdr.rcvif = ifp;
690         wh = (struct ieee80211_frame *)((uint8_t *)&stat[1] + infosz);
691         memcpy(mtod(m, uint8_t *), wh, pktlen);
692         m->m_pkthdr.len = m->m_len = pktlen;
693
694         if (ieee80211_radiotap_active(ic)) {
695                 struct urtwn_rx_radiotap_header *tap = &sc->sc_rxtap;
696
697                 tap->wr_flags = 0;
698                 /* Map HW rate index to 802.11 rate. */
699                 if (!(rxdw3 & R92C_RXDW3_HT)) {
700                         switch (rate) {
701                         /* CCK. */
702                         case  0: tap->wr_rate =   2; break;
703                         case  1: tap->wr_rate =   4; break;
704                         case  2: tap->wr_rate =  11; break;
705                         case  3: tap->wr_rate =  22; break;
706                         /* OFDM. */
707                         case  4: tap->wr_rate =  12; break;
708                         case  5: tap->wr_rate =  18; break;
709                         case  6: tap->wr_rate =  24; break;
710                         case  7: tap->wr_rate =  36; break;
711                         case  8: tap->wr_rate =  48; break;
712                         case  9: tap->wr_rate =  72; break;
713                         case 10: tap->wr_rate =  96; break;
714                         case 11: tap->wr_rate = 108; break;
715                         }
716                 } else if (rate >= 12) {        /* MCS0~15. */
717                         /* Bit 7 set means HT MCS instead of rate. */
718                         tap->wr_rate = 0x80 | (rate - 12);
719                 }
720                 tap->wr_dbm_antsignal = rssi;
721                 tap->wr_chan_freq = htole16(ic->ic_curchan->ic_freq);
722                 tap->wr_chan_flags = htole16(ic->ic_curchan->ic_flags);
723         }
724
725         *rssi_p = rssi;
726
727         return (m);
728 }
729
730 static struct mbuf *
731 urtwn_rxeof(struct usb_xfer *xfer, struct urtwn_data *data, int *rssi,
732     int8_t *nf)
733 {
734         struct urtwn_softc *sc = data->sc;
735         struct ifnet *ifp = sc->sc_ifp;
736         struct r92c_rx_stat *stat;
737         struct mbuf *m, *m0 = NULL, *prevm = NULL;
738         uint32_t rxdw0;
739         uint8_t *buf;
740         int len, totlen, pktlen, infosz, npkts;
741
742         usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
743
744         if (len < sizeof(*stat)) {
745                 ifp->if_ierrors++;
746                 return (NULL);
747         }
748
749         buf = data->buf;
750         /* Get the number of encapsulated frames. */
751         stat = (struct r92c_rx_stat *)buf;
752         npkts = MS(le32toh(stat->rxdw2), R92C_RXDW2_PKTCNT);
753         DPRINTFN(6, "Rx %d frames in one chunk\n", npkts);
754
755         /* Process all of them. */
756         while (npkts-- > 0) {
757                 if (len < sizeof(*stat))
758                         break;
759                 stat = (struct r92c_rx_stat *)buf;
760                 rxdw0 = le32toh(stat->rxdw0);
761
762                 pktlen = MS(rxdw0, R92C_RXDW0_PKTLEN);
763                 if (pktlen == 0)
764                         break;
765
766                 infosz = MS(rxdw0, R92C_RXDW0_INFOSZ) * 8;
767
768                 /* Make sure everything fits in xfer. */
769                 totlen = sizeof(*stat) + infosz + pktlen;
770                 if (totlen > len)
771                         break;
772
773                 m = urtwn_rx_frame(sc, buf, pktlen, rssi);
774                 if (m0 == NULL)
775                         m0 = m;
776                 if (prevm == NULL)
777                         prevm = m;
778                 else {
779                         prevm->m_next = m;
780                         prevm = m;
781                 }
782
783                 /* Next chunk is 128-byte aligned. */
784                 totlen = (totlen + 127) & ~127;
785                 buf += totlen;
786                 len -= totlen;
787         }
788
789         return (m0);
790 }
791
792 static void
793 urtwn_bulk_rx_callback(struct usb_xfer *xfer, usb_error_t error)
794 {
795         struct urtwn_softc *sc = usbd_xfer_softc(xfer);
796         struct ifnet *ifp = sc->sc_ifp;
797         struct ieee80211com *ic = ifp->if_l2com;
798         struct ieee80211_frame *wh;
799         struct ieee80211_node *ni;
800         struct mbuf *m = NULL, *next;
801         struct urtwn_data *data;
802         int8_t nf;
803         int rssi = 1;
804
805         URTWN_ASSERT_LOCKED(sc);
806
807         switch (USB_GET_STATE(xfer)) {
808         case USB_ST_TRANSFERRED:
809                 data = STAILQ_FIRST(&sc->sc_rx_active);
810                 if (data == NULL)
811                         goto tr_setup;
812                 STAILQ_REMOVE_HEAD(&sc->sc_rx_active, next);
813                 m = urtwn_rxeof(xfer, data, &rssi, &nf);
814                 STAILQ_INSERT_TAIL(&sc->sc_rx_inactive, data, next);
815                 /* FALLTHROUGH */
816         case USB_ST_SETUP:
817 tr_setup:
818                 data = STAILQ_FIRST(&sc->sc_rx_inactive);
819                 if (data == NULL) {
820                         KASSERT(m == NULL, ("mbuf isn't NULL"));
821                         return;
822                 }
823                 STAILQ_REMOVE_HEAD(&sc->sc_rx_inactive, next);
824                 STAILQ_INSERT_TAIL(&sc->sc_rx_active, data, next);
825                 usbd_xfer_set_frame_data(xfer, 0, data->buf,
826                     usbd_xfer_max_len(xfer));
827                 usbd_transfer_submit(xfer);
828
829                 /*
830                  * To avoid LOR we should unlock our private mutex here to call
831                  * ieee80211_input() because here is at the end of a USB
832                  * callback and safe to unlock.
833                  */
834                 URTWN_UNLOCK(sc);
835                 while (m != NULL) {
836                         next = m->m_next;
837                         m->m_next = NULL;
838                         wh = mtod(m, struct ieee80211_frame *);
839                         ni = ieee80211_find_rxnode(ic,
840                             (struct ieee80211_frame_min *)wh);
841                         nf = URTWN_NOISE_FLOOR;
842                         if (ni != NULL) {
843                                 (void)ieee80211_input(ni, m, rssi, nf);
844                                 ieee80211_free_node(ni);
845                         } else
846                                 (void)ieee80211_input_all(ic, m, rssi, nf);
847                         m = next;
848                 }
849                 URTWN_LOCK(sc);
850                 break;
851         default:
852                 /* needs it to the inactive queue due to a error. */
853                 data = STAILQ_FIRST(&sc->sc_rx_active);
854                 if (data != NULL) {
855                         STAILQ_REMOVE_HEAD(&sc->sc_rx_active, next);
856                         STAILQ_INSERT_TAIL(&sc->sc_rx_inactive, data, next);
857                 }
858                 if (error != USB_ERR_CANCELLED) {
859                         usbd_xfer_set_stall(xfer);
860                         ifp->if_ierrors++;
861                         goto tr_setup;
862                 }
863                 break;
864         }
865 }
866
867 static void
868 urtwn_txeof(struct usb_xfer *xfer, struct urtwn_data *data)
869 {
870         struct urtwn_softc *sc = usbd_xfer_softc(xfer);
871         struct ifnet *ifp = sc->sc_ifp;
872         struct mbuf *m;
873
874         URTWN_ASSERT_LOCKED(sc);
875
876         /*
877          * Do any tx complete callback.  Note this must be done before releasing
878          * the node reference.
879          */
880         if (data->m) {
881                 m = data->m;
882                 if (m->m_flags & M_TXCB) {
883                         /* XXX status? */
884                         ieee80211_process_callback(data->ni, m, 0);
885                 }
886                 m_freem(m);
887                 data->m = NULL;
888         }
889         if (data->ni) {
890                 ieee80211_free_node(data->ni);
891                 data->ni = NULL;
892         }
893         sc->sc_txtimer = 0;
894         ifp->if_opackets++;
895         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
896 }
897
898 static void
899 urtwn_bulk_tx_callback(struct usb_xfer *xfer, usb_error_t error)
900 {
901         struct urtwn_softc *sc = usbd_xfer_softc(xfer);
902         struct ifnet *ifp = sc->sc_ifp;
903         struct urtwn_data *data;
904
905         URTWN_ASSERT_LOCKED(sc);
906
907         switch (USB_GET_STATE(xfer)){
908         case USB_ST_TRANSFERRED:
909                 data = STAILQ_FIRST(&sc->sc_tx_active);
910                 if (data == NULL)
911                         goto tr_setup;
912                 STAILQ_REMOVE_HEAD(&sc->sc_tx_active, next);
913                 urtwn_txeof(xfer, data);
914                 STAILQ_INSERT_TAIL(&sc->sc_tx_inactive, data, next);
915                 /* FALLTHROUGH */
916         case USB_ST_SETUP:
917 tr_setup:
918                 data = STAILQ_FIRST(&sc->sc_tx_pending);
919                 if (data == NULL) {
920                         DPRINTF("%s: empty pending queue\n", __func__);
921                         return;
922                 }
923                 STAILQ_REMOVE_HEAD(&sc->sc_tx_pending, next);
924                 STAILQ_INSERT_TAIL(&sc->sc_tx_active, data, next);
925                 usbd_xfer_set_frame_data(xfer, 0, data->buf, data->buflen);
926                 usbd_transfer_submit(xfer);
927                 urtwn_start_locked(ifp, sc);
928                 break;
929         default:
930                 data = STAILQ_FIRST(&sc->sc_tx_active);
931                 if (data == NULL)
932                         goto tr_setup;
933                 if (data->ni != NULL) {
934                         ieee80211_free_node(data->ni);
935                         data->ni = NULL;
936                         ifp->if_oerrors++;
937                 }
938                 if (error != USB_ERR_CANCELLED) {
939                         usbd_xfer_set_stall(xfer);
940                         goto tr_setup;
941                 }
942                 break;
943         }
944 }
945
946 static struct urtwn_data *
947 _urtwn_getbuf(struct urtwn_softc *sc)
948 {
949         struct urtwn_data *bf;
950
951         bf = STAILQ_FIRST(&sc->sc_tx_inactive);
952         if (bf != NULL)
953                 STAILQ_REMOVE_HEAD(&sc->sc_tx_inactive, next);
954         else
955                 bf = NULL;
956         if (bf == NULL)
957                 DPRINTF("%s: %s\n", __func__, "out of xmit buffers");
958         return (bf);
959 }
960
961 static struct urtwn_data *
962 urtwn_getbuf(struct urtwn_softc *sc)
963 {
964         struct urtwn_data *bf;
965
966         URTWN_ASSERT_LOCKED(sc);
967
968         bf = _urtwn_getbuf(sc);
969         if (bf == NULL) {
970                 struct ifnet *ifp = sc->sc_ifp;
971                 DPRINTF("%s: stop queue\n", __func__);
972                 ifp->if_drv_flags |= IFF_DRV_OACTIVE;
973         }
974         return (bf);
975 }
976
977 static int
978 urtwn_write_region_1(struct urtwn_softc *sc, uint16_t addr, uint8_t *buf,
979     int len)
980 {
981         usb_device_request_t req;
982
983         req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
984         req.bRequest = R92C_REQ_REGS;
985         USETW(req.wValue, addr);
986         USETW(req.wIndex, 0);
987         USETW(req.wLength, len);
988         return (urtwn_do_request(sc, &req, buf));
989 }
990
991 static void
992 urtwn_write_1(struct urtwn_softc *sc, uint16_t addr, uint8_t val)
993 {
994         urtwn_write_region_1(sc, addr, &val, 1);
995 }
996
997
998 static void
999 urtwn_write_2(struct urtwn_softc *sc, uint16_t addr, uint16_t val)
1000 {
1001         val = htole16(val);
1002         urtwn_write_region_1(sc, addr, (uint8_t *)&val, 2);
1003 }
1004
1005 static void
1006 urtwn_write_4(struct urtwn_softc *sc, uint16_t addr, uint32_t val)
1007 {
1008         val = htole32(val);
1009         urtwn_write_region_1(sc, addr, (uint8_t *)&val, 4);
1010 }
1011
1012 static int
1013 urtwn_read_region_1(struct urtwn_softc *sc, uint16_t addr, uint8_t *buf,
1014     int len)
1015 {
1016         usb_device_request_t req;
1017
1018         req.bmRequestType = UT_READ_VENDOR_DEVICE;
1019         req.bRequest = R92C_REQ_REGS;
1020         USETW(req.wValue, addr);
1021         USETW(req.wIndex, 0);
1022         USETW(req.wLength, len);
1023         return (urtwn_do_request(sc, &req, buf));
1024 }
1025
1026 static uint8_t
1027 urtwn_read_1(struct urtwn_softc *sc, uint16_t addr)
1028 {
1029         uint8_t val;
1030
1031         if (urtwn_read_region_1(sc, addr, &val, 1) != 0)
1032                 return (0xff);
1033         return (val);
1034 }
1035
1036 static uint16_t
1037 urtwn_read_2(struct urtwn_softc *sc, uint16_t addr)
1038 {
1039         uint16_t val;
1040
1041         if (urtwn_read_region_1(sc, addr, (uint8_t *)&val, 2) != 0)
1042                 return (0xffff);
1043         return (le16toh(val));
1044 }
1045
1046 static uint32_t
1047 urtwn_read_4(struct urtwn_softc *sc, uint16_t addr)
1048 {
1049         uint32_t val;
1050
1051         if (urtwn_read_region_1(sc, addr, (uint8_t *)&val, 4) != 0)
1052                 return (0xffffffff);
1053         return (le32toh(val));
1054 }
1055
1056 static int
1057 urtwn_fw_cmd(struct urtwn_softc *sc, uint8_t id, const void *buf, int len)
1058 {
1059         struct r92c_fw_cmd cmd;
1060         int ntries;
1061
1062         /* Wait for current FW box to be empty. */
1063         for (ntries = 0; ntries < 100; ntries++) {
1064                 if (!(urtwn_read_1(sc, R92C_HMETFR) & (1 << sc->fwcur)))
1065                         break;
1066                 urtwn_ms_delay(sc);
1067         }
1068         if (ntries == 100) {
1069                 device_printf(sc->sc_dev,
1070                     "could not send firmware command\n");
1071                 return (ETIMEDOUT);
1072         }
1073         memset(&cmd, 0, sizeof(cmd));
1074         cmd.id = id;
1075         if (len > 3)
1076                 cmd.id |= R92C_CMD_FLAG_EXT;
1077         KASSERT(len <= sizeof(cmd.msg), ("urtwn_fw_cmd\n"));
1078         memcpy(cmd.msg, buf, len);
1079
1080         /* Write the first word last since that will trigger the FW. */
1081         urtwn_write_region_1(sc, R92C_HMEBOX_EXT(sc->fwcur),
1082             (uint8_t *)&cmd + 4, 2);
1083         urtwn_write_region_1(sc, R92C_HMEBOX(sc->fwcur),
1084             (uint8_t *)&cmd + 0, 4);
1085
1086         sc->fwcur = (sc->fwcur + 1) % R92C_H2C_NBOX;
1087         return (0);
1088 }
1089
1090 static __inline void
1091 urtwn_rf_write(struct urtwn_softc *sc, int chain, uint8_t addr, uint32_t val)
1092 {
1093
1094         sc->sc_rf_write(sc, chain, addr, val);
1095 }
1096
1097 static void
1098 urtwn_r92c_rf_write(struct urtwn_softc *sc, int chain, uint8_t addr,
1099     uint32_t val)
1100 {
1101         urtwn_bb_write(sc, R92C_LSSI_PARAM(chain),
1102             SM(R92C_LSSI_PARAM_ADDR, addr) |
1103             SM(R92C_LSSI_PARAM_DATA, val));
1104 }
1105
1106 static void
1107 urtwn_r88e_rf_write(struct urtwn_softc *sc, int chain, uint8_t addr,
1108 uint32_t val)
1109 {
1110         urtwn_bb_write(sc, R92C_LSSI_PARAM(chain),
1111             SM(R88E_LSSI_PARAM_ADDR, addr) |
1112             SM(R92C_LSSI_PARAM_DATA, val));
1113 }
1114
1115 static uint32_t
1116 urtwn_rf_read(struct urtwn_softc *sc, int chain, uint8_t addr)
1117 {
1118         uint32_t reg[R92C_MAX_CHAINS], val;
1119
1120         reg[0] = urtwn_bb_read(sc, R92C_HSSI_PARAM2(0));
1121         if (chain != 0)
1122                 reg[chain] = urtwn_bb_read(sc, R92C_HSSI_PARAM2(chain));
1123
1124         urtwn_bb_write(sc, R92C_HSSI_PARAM2(0),
1125             reg[0] & ~R92C_HSSI_PARAM2_READ_EDGE);
1126         urtwn_ms_delay(sc);
1127
1128         urtwn_bb_write(sc, R92C_HSSI_PARAM2(chain),
1129             RW(reg[chain], R92C_HSSI_PARAM2_READ_ADDR, addr) |
1130             R92C_HSSI_PARAM2_READ_EDGE);
1131         urtwn_ms_delay(sc);
1132
1133         urtwn_bb_write(sc, R92C_HSSI_PARAM2(0),
1134             reg[0] | R92C_HSSI_PARAM2_READ_EDGE);
1135         urtwn_ms_delay(sc);
1136
1137         if (urtwn_bb_read(sc, R92C_HSSI_PARAM1(chain)) & R92C_HSSI_PARAM1_PI)
1138                 val = urtwn_bb_read(sc, R92C_HSPI_READBACK(chain));
1139         else
1140                 val = urtwn_bb_read(sc, R92C_LSSI_READBACK(chain));
1141         return (MS(val, R92C_LSSI_READBACK_DATA));
1142 }
1143
1144 static int
1145 urtwn_llt_write(struct urtwn_softc *sc, uint32_t addr, uint32_t data)
1146 {
1147         int ntries;
1148
1149         urtwn_write_4(sc, R92C_LLT_INIT,
1150             SM(R92C_LLT_INIT_OP, R92C_LLT_INIT_OP_WRITE) |
1151             SM(R92C_LLT_INIT_ADDR, addr) |
1152             SM(R92C_LLT_INIT_DATA, data));
1153         /* Wait for write operation to complete. */
1154         for (ntries = 0; ntries < 20; ntries++) {
1155                 if (MS(urtwn_read_4(sc, R92C_LLT_INIT), R92C_LLT_INIT_OP) ==
1156                     R92C_LLT_INIT_OP_NO_ACTIVE)
1157                         return (0);
1158                 urtwn_ms_delay(sc);
1159         }
1160         return (ETIMEDOUT);
1161 }
1162
1163 static uint8_t
1164 urtwn_efuse_read_1(struct urtwn_softc *sc, uint16_t addr)
1165 {
1166         uint32_t reg;
1167         int ntries;
1168
1169         reg = urtwn_read_4(sc, R92C_EFUSE_CTRL);
1170         reg = RW(reg, R92C_EFUSE_CTRL_ADDR, addr);
1171         reg &= ~R92C_EFUSE_CTRL_VALID;
1172         urtwn_write_4(sc, R92C_EFUSE_CTRL, reg);
1173         /* Wait for read operation to complete. */
1174         for (ntries = 0; ntries < 100; ntries++) {
1175                 reg = urtwn_read_4(sc, R92C_EFUSE_CTRL);
1176                 if (reg & R92C_EFUSE_CTRL_VALID)
1177                         return (MS(reg, R92C_EFUSE_CTRL_DATA));
1178                 urtwn_ms_delay(sc);
1179         }
1180         device_printf(sc->sc_dev, 
1181             "could not read efuse byte at address 0x%x\n", addr);
1182         return (0xff);
1183 }
1184
1185 static void
1186 urtwn_efuse_read(struct urtwn_softc *sc)
1187 {
1188         uint8_t *rom = (uint8_t *)&sc->rom;
1189         uint16_t addr = 0;
1190         uint32_t reg;
1191         uint8_t off, msk;
1192         int i;
1193
1194         urtwn_efuse_switch_power(sc);
1195
1196         memset(&sc->rom, 0xff, sizeof(sc->rom));
1197         while (addr < 512) {
1198                 reg = urtwn_efuse_read_1(sc, addr);
1199                 if (reg == 0xff)
1200                         break;
1201                 addr++;
1202                 off = reg >> 4;
1203                 msk = reg & 0xf;
1204                 for (i = 0; i < 4; i++) {
1205                         if (msk & (1 << i))
1206                                 continue;
1207                         rom[off * 8 + i * 2 + 0] =
1208                             urtwn_efuse_read_1(sc, addr);
1209                         addr++;
1210                         rom[off * 8 + i * 2 + 1] =
1211                             urtwn_efuse_read_1(sc, addr);
1212                         addr++;
1213                 }
1214         }
1215 #ifdef URTWN_DEBUG
1216         if (urtwn_debug >= 2) {
1217                 /* Dump ROM content. */
1218                 printf("\n");
1219                 for (i = 0; i < sizeof(sc->rom); i++)
1220                         printf("%02x:", rom[i]);
1221                 printf("\n");
1222         }
1223 #endif
1224 }
1225 static void
1226 urtwn_efuse_switch_power(struct urtwn_softc *sc)
1227 {
1228         uint32_t reg;
1229
1230         reg = urtwn_read_2(sc, R92C_SYS_ISO_CTRL);
1231         if (!(reg & R92C_SYS_ISO_CTRL_PWC_EV12V)) {
1232                 urtwn_write_2(sc, R92C_SYS_ISO_CTRL,
1233                     reg | R92C_SYS_ISO_CTRL_PWC_EV12V);
1234         }
1235         reg = urtwn_read_2(sc, R92C_SYS_FUNC_EN);
1236         if (!(reg & R92C_SYS_FUNC_EN_ELDR)) {
1237                 urtwn_write_2(sc, R92C_SYS_FUNC_EN,
1238                     reg | R92C_SYS_FUNC_EN_ELDR);
1239         }
1240         reg = urtwn_read_2(sc, R92C_SYS_CLKR);
1241         if ((reg & (R92C_SYS_CLKR_LOADER_EN | R92C_SYS_CLKR_ANA8M)) !=
1242             (R92C_SYS_CLKR_LOADER_EN | R92C_SYS_CLKR_ANA8M)) {
1243                 urtwn_write_2(sc, R92C_SYS_CLKR,
1244                     reg | R92C_SYS_CLKR_LOADER_EN | R92C_SYS_CLKR_ANA8M);
1245         }
1246 }
1247
1248 static int
1249 urtwn_read_chipid(struct urtwn_softc *sc)
1250 {
1251         uint32_t reg;
1252
1253         if (sc->chip & URTWN_CHIP_88E)
1254                 return (0);
1255
1256         reg = urtwn_read_4(sc, R92C_SYS_CFG);
1257         if (reg & R92C_SYS_CFG_TRP_VAUX_EN)
1258                 return (EIO);
1259
1260         if (reg & R92C_SYS_CFG_TYPE_92C) {
1261                 sc->chip |= URTWN_CHIP_92C;
1262                 /* Check if it is a castrated 8192C. */
1263                 if (MS(urtwn_read_4(sc, R92C_HPON_FSM),
1264                     R92C_HPON_FSM_CHIP_BONDING_ID) ==
1265                     R92C_HPON_FSM_CHIP_BONDING_ID_92C_1T2R)
1266                         sc->chip |= URTWN_CHIP_92C_1T2R;
1267         }
1268         if (reg & R92C_SYS_CFG_VENDOR_UMC) {
1269                 sc->chip |= URTWN_CHIP_UMC;
1270                 if (MS(reg, R92C_SYS_CFG_CHIP_VER_RTL) == 0)
1271                         sc->chip |= URTWN_CHIP_UMC_A_CUT;
1272         }
1273         return (0);
1274 }
1275
1276 static void
1277 urtwn_read_rom(struct urtwn_softc *sc)
1278 {
1279         struct r92c_rom *rom = &sc->rom;
1280
1281         /* Read full ROM image. */
1282         urtwn_efuse_read(sc);
1283
1284         /* XXX Weird but this is what the vendor driver does. */
1285         sc->pa_setting = urtwn_efuse_read_1(sc, 0x1fa);
1286         DPRINTF("PA setting=0x%x\n", sc->pa_setting);
1287
1288         sc->board_type = MS(rom->rf_opt1, R92C_ROM_RF1_BOARD_TYPE);
1289
1290         sc->regulatory = MS(rom->rf_opt1, R92C_ROM_RF1_REGULATORY);
1291         DPRINTF("regulatory type=%d\n", sc->regulatory);
1292         IEEE80211_ADDR_COPY(sc->sc_bssid, rom->macaddr);
1293
1294         sc->sc_rf_write = urtwn_r92c_rf_write;
1295         sc->sc_power_on = urtwn_r92c_power_on;
1296         sc->sc_dma_init = urtwn_r92c_dma_init;
1297 }
1298
1299 static void
1300 urtwn_r88e_read_rom(struct urtwn_softc *sc)
1301 {
1302         uint8_t *rom = sc->r88e_rom;
1303         uint16_t addr = 0;
1304         uint32_t reg;
1305         uint8_t off, msk, tmp;
1306         int i;
1307
1308         off = 0;
1309         urtwn_efuse_switch_power(sc);
1310
1311         /* Read full ROM image. */
1312         memset(&sc->r88e_rom, 0xff, sizeof(sc->r88e_rom));
1313         while (addr < 1024) {
1314                 reg = urtwn_efuse_read_1(sc, addr);
1315                 if (reg == 0xff)
1316                         break;
1317                 addr++;
1318                 if ((reg & 0x1f) == 0x0f) {
1319                         tmp = (reg & 0xe0) >> 5;
1320                         reg = urtwn_efuse_read_1(sc, addr);
1321                         if ((reg & 0x0f) != 0x0f)
1322                                 off = ((reg & 0xf0) >> 1) | tmp;
1323                         addr++;
1324                 } else
1325                         off = reg >> 4;
1326                 msk = reg & 0xf;
1327                 for (i = 0; i < 4; i++) {
1328                         if (msk & (1 << i))
1329                                 continue;
1330                         rom[off * 8 + i * 2 + 0] =
1331                             urtwn_efuse_read_1(sc, addr);
1332                         addr++;
1333                         rom[off * 8 + i * 2 + 1] =
1334                             urtwn_efuse_read_1(sc, addr);
1335                         addr++;
1336                 }
1337         }
1338
1339         addr = 0x10;
1340         for (i = 0; i < 6; i++)
1341                 sc->cck_tx_pwr[i] = sc->r88e_rom[addr++];
1342         for (i = 0; i < 5; i++)
1343                 sc->ht40_tx_pwr[i] = sc->r88e_rom[addr++];
1344         sc->bw20_tx_pwr_diff = (sc->r88e_rom[addr] & 0xf0) >> 4;
1345         if (sc->bw20_tx_pwr_diff & 0x08)
1346                 sc->bw20_tx_pwr_diff |= 0xf0;
1347         sc->ofdm_tx_pwr_diff = (sc->r88e_rom[addr] & 0xf);
1348         if (sc->ofdm_tx_pwr_diff & 0x08)
1349                 sc->ofdm_tx_pwr_diff |= 0xf0;
1350         sc->regulatory = MS(sc->r88e_rom[0xc1], R92C_ROM_RF1_REGULATORY);
1351         IEEE80211_ADDR_COPY(sc->sc_bssid, &sc->r88e_rom[0xd7]);
1352
1353         sc->sc_rf_write = urtwn_r88e_rf_write;
1354         sc->sc_power_on = urtwn_r88e_power_on;
1355         sc->sc_dma_init = urtwn_r88e_dma_init;
1356 }
1357
1358 /*
1359  * Initialize rate adaptation in firmware.
1360  */
1361 static int
1362 urtwn_ra_init(struct urtwn_softc *sc)
1363 {
1364         static const uint8_t map[] =
1365             { 2, 4, 11, 22, 12, 18, 24, 36, 48, 72, 96, 108 };
1366         struct ieee80211com *ic = sc->sc_ifp->if_l2com;
1367         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1368         struct ieee80211_node *ni;
1369         struct ieee80211_rateset *rs;
1370         struct r92c_fw_cmd_macid_cfg cmd;
1371         uint32_t rates, basicrates;
1372         uint8_t mode;
1373         int maxrate, maxbasicrate, error, i, j;
1374
1375         ni = ieee80211_ref_node(vap->iv_bss);
1376         rs = &ni->ni_rates;
1377
1378         /* Get normal and basic rates mask. */
1379         rates = basicrates = 0;
1380         maxrate = maxbasicrate = 0;
1381         for (i = 0; i < rs->rs_nrates; i++) {
1382                 /* Convert 802.11 rate to HW rate index. */
1383                 for (j = 0; j < nitems(map); j++)
1384                         if ((rs->rs_rates[i] & IEEE80211_RATE_VAL) == map[j])
1385                                 break;
1386                 if (j == nitems(map))   /* Unknown rate, skip. */
1387                         continue;
1388                 rates |= 1 << j;
1389                 if (j > maxrate)
1390                         maxrate = j;
1391                 if (rs->rs_rates[i] & IEEE80211_RATE_BASIC) {
1392                         basicrates |= 1 << j;
1393                         if (j > maxbasicrate)
1394                                 maxbasicrate = j;
1395                 }
1396         }
1397         if (ic->ic_curmode == IEEE80211_MODE_11B)
1398                 mode = R92C_RAID_11B;
1399         else
1400                 mode = R92C_RAID_11BG;
1401         DPRINTF("mode=0x%x rates=0x%08x, basicrates=0x%08x\n",
1402             mode, rates, basicrates);
1403
1404         /* Set rates mask for group addressed frames. */
1405         cmd.macid = URTWN_MACID_BC | URTWN_MACID_VALID;
1406         cmd.mask = htole32(mode << 28 | basicrates);
1407         error = urtwn_fw_cmd(sc, R92C_CMD_MACID_CONFIG, &cmd, sizeof(cmd));
1408         if (error != 0) {
1409                 ieee80211_free_node(ni);
1410                 device_printf(sc->sc_dev,
1411                     "could not add broadcast station\n");
1412                 return (error);
1413         }
1414         /* Set initial MRR rate. */
1415         DPRINTF("maxbasicrate=%d\n", maxbasicrate);
1416         urtwn_write_1(sc, R92C_INIDATA_RATE_SEL(URTWN_MACID_BC),
1417             maxbasicrate);
1418
1419         /* Set rates mask for unicast frames. */
1420         cmd.macid = URTWN_MACID_BSS | URTWN_MACID_VALID;
1421         cmd.mask = htole32(mode << 28 | rates);
1422         error = urtwn_fw_cmd(sc, R92C_CMD_MACID_CONFIG, &cmd, sizeof(cmd));
1423         if (error != 0) {
1424                 ieee80211_free_node(ni);
1425                 device_printf(sc->sc_dev, "could not add BSS station\n");
1426                 return (error);
1427         }
1428         /* Set initial MRR rate. */
1429         DPRINTF("maxrate=%d\n", maxrate);
1430         urtwn_write_1(sc, R92C_INIDATA_RATE_SEL(URTWN_MACID_BSS),
1431             maxrate);
1432
1433         /* Indicate highest supported rate. */
1434         ni->ni_txrate = rs->rs_rates[rs->rs_nrates - 1];
1435         ieee80211_free_node(ni);
1436
1437         return (0);
1438 }
1439
1440 void
1441 urtwn_tsf_sync_enable(struct urtwn_softc *sc)
1442 {
1443         struct ifnet *ifp = sc->sc_ifp;
1444         struct ieee80211com *ic = ifp->if_l2com;
1445         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1446         struct ieee80211_node *ni = vap->iv_bss;
1447
1448         uint64_t tsf;
1449
1450         /* Enable TSF synchronization. */
1451         urtwn_write_1(sc, R92C_BCN_CTRL,
1452             urtwn_read_1(sc, R92C_BCN_CTRL) & ~R92C_BCN_CTRL_DIS_TSF_UDT0);
1453
1454         urtwn_write_1(sc, R92C_BCN_CTRL,
1455             urtwn_read_1(sc, R92C_BCN_CTRL) & ~R92C_BCN_CTRL_EN_BCN);
1456
1457         /* Set initial TSF. */
1458         memcpy(&tsf, ni->ni_tstamp.data, 8);
1459         tsf = le64toh(tsf);
1460         tsf = tsf - (tsf % (vap->iv_bss->ni_intval * IEEE80211_DUR_TU));
1461         tsf -= IEEE80211_DUR_TU;
1462         urtwn_write_4(sc, R92C_TSFTR + 0, tsf);
1463         urtwn_write_4(sc, R92C_TSFTR + 4, tsf >> 32);
1464
1465         urtwn_write_1(sc, R92C_BCN_CTRL,
1466             urtwn_read_1(sc, R92C_BCN_CTRL) | R92C_BCN_CTRL_EN_BCN);
1467 }
1468
1469 static void
1470 urtwn_set_led(struct urtwn_softc *sc, int led, int on)
1471 {
1472         uint8_t reg;
1473         
1474         if (led == URTWN_LED_LINK) {
1475                 if (sc->chip & URTWN_CHIP_88E) {
1476                         reg = urtwn_read_1(sc, R92C_LEDCFG2) & 0xf0;
1477                         urtwn_write_1(sc, R92C_LEDCFG2, reg | 0x60);
1478                         if (!on) {
1479                                 reg = urtwn_read_1(sc, R92C_LEDCFG2) & 0x90;
1480                                 urtwn_write_1(sc, R92C_LEDCFG2,
1481                                     reg | R92C_LEDCFG0_DIS);
1482                                 urtwn_write_1(sc, R92C_MAC_PINMUX_CFG,
1483                                     urtwn_read_1(sc, R92C_MAC_PINMUX_CFG) &
1484                                     0xfe);
1485                         }
1486                 } else {
1487                         reg = urtwn_read_1(sc, R92C_LEDCFG0) & 0x70;
1488                         if (!on)
1489                                 reg |= R92C_LEDCFG0_DIS;
1490                         urtwn_write_1(sc, R92C_LEDCFG0, reg);
1491                 }
1492                 sc->ledlink = on;       /* Save LED state. */
1493         }
1494 }
1495
1496 static int
1497 urtwn_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
1498 {
1499         struct urtwn_vap *uvp = URTWN_VAP(vap);
1500         struct ieee80211com *ic = vap->iv_ic;
1501         struct urtwn_softc *sc = ic->ic_ifp->if_softc;
1502         struct ieee80211_node *ni;
1503         enum ieee80211_state ostate;
1504         uint32_t reg;
1505
1506         ostate = vap->iv_state;
1507         DPRINTF("%s -> %s\n", ieee80211_state_name[ostate],
1508             ieee80211_state_name[nstate]);
1509
1510         IEEE80211_UNLOCK(ic);
1511         URTWN_LOCK(sc);
1512         callout_stop(&sc->sc_watchdog_ch);
1513
1514         if (ostate == IEEE80211_S_RUN) {
1515                 /* Turn link LED off. */
1516                 urtwn_set_led(sc, URTWN_LED_LINK, 0);
1517
1518                 /* Set media status to 'No Link'. */
1519                 reg = urtwn_read_4(sc, R92C_CR);
1520                 reg = RW(reg, R92C_CR_NETTYPE, R92C_CR_NETTYPE_NOLINK);
1521                 urtwn_write_4(sc, R92C_CR, reg);
1522
1523                 /* Stop Rx of data frames. */
1524                 urtwn_write_2(sc, R92C_RXFLTMAP2, 0);
1525
1526                 /* Rest TSF. */
1527                 urtwn_write_1(sc, R92C_DUAL_TSF_RST, 0x03);
1528
1529                 /* Disable TSF synchronization. */
1530                 urtwn_write_1(sc, R92C_BCN_CTRL,
1531                     urtwn_read_1(sc, R92C_BCN_CTRL) |
1532                     R92C_BCN_CTRL_DIS_TSF_UDT0);
1533
1534                 /* Reset EDCA parameters. */
1535                 urtwn_write_4(sc, R92C_EDCA_VO_PARAM, 0x002f3217);
1536                 urtwn_write_4(sc, R92C_EDCA_VI_PARAM, 0x005e4317);
1537                 urtwn_write_4(sc, R92C_EDCA_BE_PARAM, 0x00105320);
1538                 urtwn_write_4(sc, R92C_EDCA_BK_PARAM, 0x0000a444);
1539         }
1540
1541         switch (nstate) {
1542         case IEEE80211_S_INIT:
1543                 /* Turn link LED off. */
1544                 urtwn_set_led(sc, URTWN_LED_LINK, 0);
1545                 break;
1546         case IEEE80211_S_SCAN:
1547                 if (ostate != IEEE80211_S_SCAN) {
1548                         /* Allow Rx from any BSSID. */
1549                         urtwn_write_4(sc, R92C_RCR,
1550                             urtwn_read_4(sc, R92C_RCR) &
1551                             ~(R92C_RCR_CBSSID_DATA | R92C_RCR_CBSSID_BCN));
1552
1553                         /* Set gain for scanning. */
1554                         reg = urtwn_bb_read(sc, R92C_OFDM0_AGCCORE1(0));
1555                         reg = RW(reg, R92C_OFDM0_AGCCORE1_GAIN, 0x20);
1556                         urtwn_bb_write(sc, R92C_OFDM0_AGCCORE1(0), reg);
1557
1558                         if (!(sc->chip & URTWN_CHIP_88E)) {
1559                                 reg = urtwn_bb_read(sc, R92C_OFDM0_AGCCORE1(1));
1560                                 reg = RW(reg, R92C_OFDM0_AGCCORE1_GAIN, 0x20);
1561                                 urtwn_bb_write(sc, R92C_OFDM0_AGCCORE1(1), reg);
1562                         }
1563                 }
1564                 /* Pause AC Tx queues. */
1565                 urtwn_write_1(sc, R92C_TXPAUSE,
1566                     urtwn_read_1(sc, R92C_TXPAUSE) | 0x0f);
1567                 break;
1568         case IEEE80211_S_AUTH:
1569                 /* Set initial gain under link. */
1570                 reg = urtwn_bb_read(sc, R92C_OFDM0_AGCCORE1(0));
1571                 reg = RW(reg, R92C_OFDM0_AGCCORE1_GAIN, 0x32);
1572                 urtwn_bb_write(sc, R92C_OFDM0_AGCCORE1(0), reg);
1573
1574                 if (!(sc->chip & URTWN_CHIP_88E)) {
1575                         reg = urtwn_bb_read(sc, R92C_OFDM0_AGCCORE1(1));
1576                         reg = RW(reg, R92C_OFDM0_AGCCORE1_GAIN, 0x32);
1577                         urtwn_bb_write(sc, R92C_OFDM0_AGCCORE1(1), reg);
1578                 }
1579                 urtwn_set_chan(sc, ic->ic_curchan, NULL);
1580                 break;
1581         case IEEE80211_S_RUN:
1582                 if (vap->iv_opmode == IEEE80211_M_MONITOR) {
1583                         /* Enable Rx of data frames. */
1584                         urtwn_write_2(sc, R92C_RXFLTMAP2, 0xffff);
1585
1586                         /* Turn link LED on. */
1587                         urtwn_set_led(sc, URTWN_LED_LINK, 1);
1588                         break;
1589                 }
1590
1591                 ni = ieee80211_ref_node(vap->iv_bss);
1592                 /* Set media status to 'Associated'. */
1593                 reg = urtwn_read_4(sc, R92C_CR);
1594                 reg = RW(reg, R92C_CR_NETTYPE, R92C_CR_NETTYPE_INFRA);
1595                 urtwn_write_4(sc, R92C_CR, reg);
1596
1597                 /* Set BSSID. */
1598                 urtwn_write_4(sc, R92C_BSSID + 0, LE_READ_4(&ni->ni_bssid[0]));
1599                 urtwn_write_4(sc, R92C_BSSID + 4, LE_READ_2(&ni->ni_bssid[4]));
1600
1601                 if (ic->ic_curmode == IEEE80211_MODE_11B)
1602                         urtwn_write_1(sc, R92C_INIRTS_RATE_SEL, 0);
1603                 else    /* 802.11b/g */
1604                         urtwn_write_1(sc, R92C_INIRTS_RATE_SEL, 3);
1605
1606                 /* Enable Rx of data frames. */
1607                 urtwn_write_2(sc, R92C_RXFLTMAP2, 0xffff);
1608
1609                 /* Flush all AC queues. */
1610                 urtwn_write_1(sc, R92C_TXPAUSE, 0);
1611
1612                 /* Set beacon interval. */
1613                 urtwn_write_2(sc, R92C_BCN_INTERVAL, ni->ni_intval);
1614
1615                 /* Allow Rx from our BSSID only. */
1616                 urtwn_write_4(sc, R92C_RCR,
1617                     urtwn_read_4(sc, R92C_RCR) |
1618                     R92C_RCR_CBSSID_DATA | R92C_RCR_CBSSID_BCN);
1619
1620                 /* Enable TSF synchronization. */
1621                 urtwn_tsf_sync_enable(sc);
1622
1623                 urtwn_write_1(sc, R92C_SIFS_CCK + 1, 10);
1624                 urtwn_write_1(sc, R92C_SIFS_OFDM + 1, 10);
1625                 urtwn_write_1(sc, R92C_SPEC_SIFS + 1, 10);
1626                 urtwn_write_1(sc, R92C_MAC_SPEC_SIFS + 1, 10);
1627                 urtwn_write_1(sc, R92C_R2T_SIFS + 1, 10);
1628                 urtwn_write_1(sc, R92C_T2T_SIFS + 1, 10);
1629
1630                 /* Intialize rate adaptation. */
1631                 if (sc->chip & URTWN_CHIP_88E)
1632                         ni->ni_txrate =
1633                             ni->ni_rates.rs_rates[ni->ni_rates.rs_nrates-1];
1634                 else 
1635                         urtwn_ra_init(sc);
1636                 /* Turn link LED on. */
1637                 urtwn_set_led(sc, URTWN_LED_LINK, 1);
1638
1639                 sc->avg_pwdb = -1;      /* Reset average RSSI. */
1640                 /* Reset temperature calibration state machine. */
1641                 sc->thcal_state = 0;
1642                 sc->thcal_lctemp = 0;
1643                 ieee80211_free_node(ni);
1644                 break;
1645         default:
1646                 break;
1647         }
1648         URTWN_UNLOCK(sc);
1649         IEEE80211_LOCK(ic);
1650         return(uvp->newstate(vap, nstate, arg));
1651 }
1652
1653 static void
1654 urtwn_watchdog(void *arg)
1655 {
1656         struct urtwn_softc *sc = arg;
1657         struct ifnet *ifp = sc->sc_ifp;
1658
1659         if (sc->sc_txtimer > 0) {
1660                 if (--sc->sc_txtimer == 0) {
1661                         device_printf(sc->sc_dev, "device timeout\n");
1662                         ifp->if_oerrors++;
1663                         return;
1664                 }
1665                 callout_reset(&sc->sc_watchdog_ch, hz, urtwn_watchdog, sc);
1666         }
1667 }
1668
1669 static void
1670 urtwn_update_avgrssi(struct urtwn_softc *sc, int rate, int8_t rssi)
1671 {
1672         int pwdb;
1673
1674         /* Convert antenna signal to percentage. */
1675         if (rssi <= -100 || rssi >= 20)
1676                 pwdb = 0;
1677         else if (rssi >= 0)
1678                 pwdb = 100;
1679         else
1680                 pwdb = 100 + rssi;
1681         if (!(sc->chip & URTWN_CHIP_88E)) {
1682                 if (rate <= 3) {
1683                         /* CCK gain is smaller than OFDM/MCS gain. */
1684                         pwdb += 6;
1685                         if (pwdb > 100)
1686                                 pwdb = 100;
1687                         if (pwdb <= 14)
1688                                 pwdb -= 4;
1689                         else if (pwdb <= 26)
1690                                 pwdb -= 8;
1691                         else if (pwdb <= 34)
1692                                 pwdb -= 6;
1693                         else if (pwdb <= 42)
1694                                 pwdb -= 2;
1695                 }
1696         }
1697         if (sc->avg_pwdb == -1) /* Init. */
1698                 sc->avg_pwdb = pwdb;
1699         else if (sc->avg_pwdb < pwdb)
1700                 sc->avg_pwdb = ((sc->avg_pwdb * 19 + pwdb) / 20) + 1;
1701         else
1702                 sc->avg_pwdb = ((sc->avg_pwdb * 19 + pwdb) / 20);
1703         DPRINTFN(4, "PWDB=%d EMA=%d\n", pwdb, sc->avg_pwdb);
1704 }
1705
1706 static int8_t
1707 urtwn_get_rssi(struct urtwn_softc *sc, int rate, void *physt)
1708 {
1709         static const int8_t cckoff[] = { 16, -12, -26, -46 };
1710         struct r92c_rx_phystat *phy;
1711         struct r92c_rx_cck *cck;
1712         uint8_t rpt;
1713         int8_t rssi;
1714
1715         if (rate <= 3) {
1716                 cck = (struct r92c_rx_cck *)physt;
1717                 if (sc->sc_flags & URTWN_FLAG_CCK_HIPWR) {
1718                         rpt = (cck->agc_rpt >> 5) & 0x3;
1719                         rssi = (cck->agc_rpt & 0x1f) << 1;
1720                 } else {
1721                         rpt = (cck->agc_rpt >> 6) & 0x3;
1722                         rssi = cck->agc_rpt & 0x3e;
1723                 }
1724                 rssi = cckoff[rpt] - rssi;
1725         } else {        /* OFDM/HT. */
1726                 phy = (struct r92c_rx_phystat *)physt;
1727                 rssi = ((le32toh(phy->phydw1) >> 1) & 0x7f) - 110;
1728         }
1729         return (rssi);
1730 }
1731
1732 static int8_t
1733 urtwn_r88e_get_rssi(struct urtwn_softc *sc, int rate, void *physt)
1734 {
1735         struct r92c_rx_phystat *phy;
1736         struct r88e_rx_cck *cck;
1737         uint8_t cck_agc_rpt, lna_idx, vga_idx;
1738         int8_t rssi;
1739
1740         rssi = 0;
1741         if (rate <= 3) {
1742                 cck = (struct r88e_rx_cck *)physt;
1743                 cck_agc_rpt = cck->agc_rpt;
1744                 lna_idx = (cck_agc_rpt & 0xe0) >> 5;
1745                 vga_idx = cck_agc_rpt & 0x1f; 
1746                 switch (lna_idx) {
1747                 case 7:
1748                         if (vga_idx <= 27)
1749                                 rssi = -100 + 2* (27 - vga_idx);
1750                         else
1751                                 rssi = -100;
1752                         break;
1753                 case 6:
1754                         rssi = -48 + 2 * (2 - vga_idx);
1755                         break;
1756                 case 5:
1757                         rssi = -42 + 2 * (7 - vga_idx);
1758                         break;
1759                 case 4:
1760                         rssi = -36 + 2 * (7 - vga_idx);
1761                         break;
1762                 case 3:
1763                         rssi = -24 + 2 * (7 - vga_idx);
1764                         break;
1765                 case 2:
1766                         rssi = -12 + 2 * (5 - vga_idx);
1767                         break;
1768                 case 1:
1769                         rssi = 8 - (2 * vga_idx);
1770                         break;
1771                 case 0:
1772                         rssi = 14 - (2 * vga_idx);
1773                         break;
1774                 }
1775                 rssi += 6;
1776         } else {        /* OFDM/HT. */
1777                 phy = (struct r92c_rx_phystat *)physt;
1778                 rssi = ((le32toh(phy->phydw1) >> 1) & 0x7f) - 110;
1779         }
1780         return (rssi);
1781 }
1782
1783
1784 static int
1785 urtwn_tx_start(struct urtwn_softc *sc, struct ieee80211_node *ni, 
1786     struct mbuf *m0, struct urtwn_data *data)
1787 {
1788         struct ifnet *ifp = sc->sc_ifp;
1789         struct ieee80211_frame *wh;
1790         struct ieee80211_key *k;
1791         struct ieee80211com *ic = ifp->if_l2com;
1792         struct ieee80211vap *vap = ni->ni_vap;
1793         struct usb_xfer *xfer;
1794         struct r92c_tx_desc *txd;
1795         uint8_t raid, type;
1796         uint16_t sum;
1797         int i, hasqos, xferlen;
1798         struct usb_xfer *urtwn_pipes[4] = {
1799                 sc->sc_xfer[URTWN_BULK_TX_BE],
1800                 sc->sc_xfer[URTWN_BULK_TX_BK],
1801                 sc->sc_xfer[URTWN_BULK_TX_VI],
1802                 sc->sc_xfer[URTWN_BULK_TX_VO]
1803         };
1804
1805         URTWN_ASSERT_LOCKED(sc);
1806
1807         /*
1808          * Software crypto.
1809          */
1810         wh = mtod(m0, struct ieee80211_frame *);
1811         type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
1812
1813         if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
1814                 k = ieee80211_crypto_encap(ni, m0);
1815                 if (k == NULL) {
1816                         device_printf(sc->sc_dev,
1817                             "ieee80211_crypto_encap returns NULL.\n");
1818                         /* XXX we don't expect the fragmented frames */
1819                         m_freem(m0);
1820                         return (ENOBUFS);
1821                 }
1822
1823                 /* in case packet header moved, reset pointer */
1824                 wh = mtod(m0, struct ieee80211_frame *);
1825         }
1826         
1827         switch (type) {
1828         case IEEE80211_FC0_TYPE_CTL:
1829         case IEEE80211_FC0_TYPE_MGT:
1830                 xfer = sc->sc_xfer[URTWN_BULK_TX_VO];
1831                 break;
1832         default:
1833                 KASSERT(M_WME_GETAC(m0) < 4,
1834                     ("unsupported WME pipe %d", M_WME_GETAC(m0)));
1835                 xfer = urtwn_pipes[M_WME_GETAC(m0)];
1836                 break;
1837         }
1838                             
1839         hasqos = 0;
1840
1841         /* Fill Tx descriptor. */
1842         txd = (struct r92c_tx_desc *)data->buf;
1843         memset(txd, 0, sizeof(*txd));
1844
1845         txd->txdw0 |= htole32(
1846             SM(R92C_TXDW0_PKTLEN, m0->m_pkthdr.len) |
1847             SM(R92C_TXDW0_OFFSET, sizeof(*txd)) |
1848             R92C_TXDW0_OWN | R92C_TXDW0_FSG | R92C_TXDW0_LSG);
1849         if (IEEE80211_IS_MULTICAST(wh->i_addr1))
1850                 txd->txdw0 |= htole32(R92C_TXDW0_BMCAST);
1851         if (!IEEE80211_IS_MULTICAST(wh->i_addr1) &&
1852             type == IEEE80211_FC0_TYPE_DATA) {
1853                 if (ic->ic_curmode == IEEE80211_MODE_11B)
1854                         raid = R92C_RAID_11B;
1855                 else
1856                         raid = R92C_RAID_11BG;
1857                 if (sc->chip & URTWN_CHIP_88E) {
1858                         txd->txdw1 |= htole32(
1859                             SM(R88E_TXDW1_MACID, URTWN_MACID_BSS) |
1860                             SM(R92C_TXDW1_QSEL, R92C_TXDW1_QSEL_BE) |
1861                             SM(R92C_TXDW1_RAID, raid));
1862                         txd->txdw2 |= htole32(R88E_TXDW2_AGGBK);
1863                 } else {
1864                         txd->txdw1 |= htole32(
1865                             SM(R92C_TXDW1_MACID, URTWN_MACID_BSS) |
1866                             SM(R92C_TXDW1_QSEL, R92C_TXDW1_QSEL_BE) |
1867                             SM(R92C_TXDW1_RAID, raid) | R92C_TXDW1_AGGBK);
1868                 }
1869                 if (ic->ic_flags & IEEE80211_F_USEPROT) {
1870                         if (ic->ic_protmode == IEEE80211_PROT_CTSONLY) {
1871                                 txd->txdw4 |= htole32(R92C_TXDW4_CTS2SELF |
1872                                     R92C_TXDW4_HWRTSEN);
1873                         } else if (ic->ic_protmode == IEEE80211_PROT_RTSCTS) {
1874                                 txd->txdw4 |= htole32(R92C_TXDW4_RTSEN |
1875                                     R92C_TXDW4_HWRTSEN);
1876                         }
1877                 }
1878                 /* Send RTS at OFDM24. */
1879                 txd->txdw4 |= htole32(SM(R92C_TXDW4_RTSRATE, 8));
1880                 txd->txdw5 |= htole32(0x0001ff00);
1881                 /* Send data at OFDM54. */
1882                 if (sc->chip & URTWN_CHIP_88E)
1883                         txd->txdw5 |= htole32(0x13 & 0x3f);
1884                 else
1885                         txd->txdw5 |= htole32(SM(R92C_TXDW5_DATARATE, 11));
1886         } else {
1887                 txd->txdw1 |= htole32(
1888                     SM(R92C_TXDW1_MACID, 0) |
1889                     SM(R92C_TXDW1_QSEL, R92C_TXDW1_QSEL_MGNT) |
1890                     SM(R92C_TXDW1_RAID, R92C_RAID_11B));
1891
1892                 /* Force CCK1. */
1893                 txd->txdw4 |= htole32(R92C_TXDW4_DRVRATE);
1894                 txd->txdw5 |= htole32(SM(R92C_TXDW5_DATARATE, 0));
1895         }
1896         /* Set sequence number (already little endian). */
1897         txd->txdseq |= *(uint16_t *)wh->i_seq;
1898
1899         if (!hasqos) {
1900                 /* Use HW sequence numbering for non-QoS frames. */
1901                 txd->txdw4  |= htole32(R92C_TXDW4_HWSEQ);
1902                 txd->txdseq |= htole16(0x8000);
1903         } else
1904                 txd->txdw4 |= htole32(R92C_TXDW4_QOS);
1905
1906         /* Compute Tx descriptor checksum. */
1907         sum = 0;
1908         for (i = 0; i < sizeof(*txd) / 2; i++)
1909                 sum ^= ((uint16_t *)txd)[i];
1910         txd->txdsum = sum;      /* NB: already little endian. */
1911
1912         if (ieee80211_radiotap_active_vap(vap)) {
1913                 struct urtwn_tx_radiotap_header *tap = &sc->sc_txtap;
1914
1915                 tap->wt_flags = 0;
1916                 tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
1917                 tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
1918                 ieee80211_radiotap_tx(vap, m0);
1919         }
1920
1921         xferlen = sizeof(*txd) + m0->m_pkthdr.len;
1922         m_copydata(m0, 0, m0->m_pkthdr.len, (caddr_t)&txd[1]);
1923
1924         data->buflen = xferlen;
1925         data->ni = ni;
1926         data->m = m0;
1927
1928         STAILQ_INSERT_TAIL(&sc->sc_tx_pending, data, next);
1929         usbd_transfer_start(xfer);
1930         return (0);
1931 }
1932
1933 static void
1934 urtwn_start(struct ifnet *ifp)
1935 {
1936         struct urtwn_softc *sc = ifp->if_softc;
1937
1938         if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
1939                 return;
1940         URTWN_LOCK(sc);
1941         urtwn_start_locked(ifp, sc);
1942         URTWN_UNLOCK(sc);
1943 }
1944
1945 static void
1946 urtwn_start_locked(struct ifnet *ifp, struct urtwn_softc *sc)
1947 {
1948         struct ieee80211_node *ni;
1949         struct mbuf *m;
1950         struct urtwn_data *bf;
1951
1952         URTWN_ASSERT_LOCKED(sc);
1953         for (;;) {
1954                 IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
1955                 if (m == NULL)
1956                         break;
1957                 bf = urtwn_getbuf(sc);
1958                 if (bf == NULL) {
1959                         IFQ_DRV_PREPEND(&ifp->if_snd, m);
1960                         break;
1961                 }
1962                 ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
1963                 m->m_pkthdr.rcvif = NULL;
1964
1965                 if (urtwn_tx_start(sc, ni, m, bf) != 0) {
1966                         ifp->if_oerrors++;
1967                         STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, bf, next);
1968                         ieee80211_free_node(ni);
1969                         break;
1970                 }
1971
1972                 sc->sc_txtimer = 5;
1973                 callout_reset(&sc->sc_watchdog_ch, hz, urtwn_watchdog, sc);
1974         }
1975 }
1976
1977 static int
1978 urtwn_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1979 {
1980         struct urtwn_softc *sc = ifp->if_softc;
1981         struct ieee80211com *ic = ifp->if_l2com;
1982         struct ifreq *ifr = (struct ifreq *) data;
1983         int error = 0, startall = 0;
1984
1985         URTWN_LOCK(sc);
1986         error = (sc->sc_flags & URTWN_DETACHED) ? ENXIO : 0;
1987         URTWN_UNLOCK(sc);
1988         if (error != 0)
1989                 return (error);
1990
1991         switch (cmd) {
1992         case SIOCSIFFLAGS:
1993                 if (ifp->if_flags & IFF_UP) {
1994                         if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
1995                                 urtwn_init(ifp->if_softc);
1996                                 startall = 1;
1997                         }
1998                 } else {
1999                         if (ifp->if_drv_flags & IFF_DRV_RUNNING)
2000                                 urtwn_stop(ifp);
2001                 }
2002                 if (startall)
2003                         ieee80211_start_all(ic);
2004                 break;
2005         case SIOCGIFMEDIA:
2006                 error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
2007                 break;
2008         case SIOCGIFADDR:
2009                 error = ether_ioctl(ifp, cmd, data);
2010                 break;
2011         default:
2012                 error = EINVAL;
2013                 break;
2014         }
2015         return (error);
2016 }
2017
2018 static int
2019 urtwn_alloc_list(struct urtwn_softc *sc, struct urtwn_data data[],
2020     int ndata, int maxsz)
2021 {
2022         int i, error;
2023
2024         for (i = 0; i < ndata; i++) {
2025                 struct urtwn_data *dp = &data[i];
2026                 dp->sc = sc;
2027                 dp->m = NULL;
2028                 dp->buf = malloc(maxsz, M_USBDEV, M_NOWAIT);
2029                 if (dp->buf == NULL) {
2030                         device_printf(sc->sc_dev,
2031                             "could not allocate buffer\n");
2032                         error = ENOMEM;
2033                         goto fail;
2034                 }
2035                 dp->ni = NULL;
2036         }
2037
2038         return (0);
2039 fail:
2040         urtwn_free_list(sc, data, ndata);
2041         return (error);
2042 }
2043
2044 static int
2045 urtwn_alloc_rx_list(struct urtwn_softc *sc)
2046 {
2047         int error, i;
2048
2049         error = urtwn_alloc_list(sc, sc->sc_rx, URTWN_RX_LIST_COUNT,
2050             URTWN_RXBUFSZ);
2051         if (error != 0)
2052                 return (error);
2053
2054         STAILQ_INIT(&sc->sc_rx_active);
2055         STAILQ_INIT(&sc->sc_rx_inactive);
2056
2057         for (i = 0; i < URTWN_RX_LIST_COUNT; i++)
2058                 STAILQ_INSERT_HEAD(&sc->sc_rx_inactive, &sc->sc_rx[i], next);
2059
2060         return (0);
2061 }
2062
2063 static int
2064 urtwn_alloc_tx_list(struct urtwn_softc *sc)
2065 {
2066         int error, i;
2067
2068         error = urtwn_alloc_list(sc, sc->sc_tx, URTWN_TX_LIST_COUNT,
2069             URTWN_TXBUFSZ);
2070         if (error != 0)
2071                 return (error);
2072
2073         STAILQ_INIT(&sc->sc_tx_active);
2074         STAILQ_INIT(&sc->sc_tx_inactive);
2075         STAILQ_INIT(&sc->sc_tx_pending);
2076
2077         for (i = 0; i < URTWN_TX_LIST_COUNT; i++)
2078                 STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, &sc->sc_tx[i], next);
2079
2080         return (0);
2081 }
2082
2083 static __inline int
2084 urtwn_power_on(struct urtwn_softc *sc)
2085 {
2086
2087         return sc->sc_power_on(sc);
2088 }
2089
2090 static int
2091 urtwn_r92c_power_on(struct urtwn_softc *sc)
2092 {
2093         uint32_t reg;
2094         int ntries;
2095
2096         /* Wait for autoload done bit. */
2097         for (ntries = 0; ntries < 1000; ntries++) {
2098                 if (urtwn_read_1(sc, R92C_APS_FSMCO) & R92C_APS_FSMCO_PFM_ALDN)
2099                         break;
2100                 urtwn_ms_delay(sc);
2101         }
2102         if (ntries == 1000) {
2103                 device_printf(sc->sc_dev,
2104                     "timeout waiting for chip autoload\n");
2105                 return (ETIMEDOUT);
2106         }
2107
2108         /* Unlock ISO/CLK/Power control register. */
2109         urtwn_write_1(sc, R92C_RSV_CTRL, 0);
2110         /* Move SPS into PWM mode. */
2111         urtwn_write_1(sc, R92C_SPS0_CTRL, 0x2b);
2112         urtwn_ms_delay(sc);
2113
2114         reg = urtwn_read_1(sc, R92C_LDOV12D_CTRL);
2115         if (!(reg & R92C_LDOV12D_CTRL_LDV12_EN)) {
2116                 urtwn_write_1(sc, R92C_LDOV12D_CTRL,
2117                     reg | R92C_LDOV12D_CTRL_LDV12_EN);
2118                 urtwn_ms_delay(sc);
2119                 urtwn_write_1(sc, R92C_SYS_ISO_CTRL,
2120                     urtwn_read_1(sc, R92C_SYS_ISO_CTRL) &
2121                     ~R92C_SYS_ISO_CTRL_MD2PP);
2122         }
2123
2124         /* Auto enable WLAN. */
2125         urtwn_write_2(sc, R92C_APS_FSMCO,
2126             urtwn_read_2(sc, R92C_APS_FSMCO) | R92C_APS_FSMCO_APFM_ONMAC);
2127         for (ntries = 0; ntries < 1000; ntries++) {
2128                 if (!(urtwn_read_2(sc, R92C_APS_FSMCO) &
2129                     R92C_APS_FSMCO_APFM_ONMAC))
2130                         break;
2131                 urtwn_ms_delay(sc);
2132         }
2133         if (ntries == 1000) {
2134                 device_printf(sc->sc_dev,
2135                     "timeout waiting for MAC auto ON\n");
2136                 return (ETIMEDOUT);
2137         }
2138
2139         /* Enable radio, GPIO and LED functions. */
2140         urtwn_write_2(sc, R92C_APS_FSMCO,
2141             R92C_APS_FSMCO_AFSM_HSUS |
2142             R92C_APS_FSMCO_PDN_EN |
2143             R92C_APS_FSMCO_PFM_ALDN);
2144         /* Release RF digital isolation. */
2145         urtwn_write_2(sc, R92C_SYS_ISO_CTRL,
2146             urtwn_read_2(sc, R92C_SYS_ISO_CTRL) & ~R92C_SYS_ISO_CTRL_DIOR);
2147
2148         /* Initialize MAC. */
2149         urtwn_write_1(sc, R92C_APSD_CTRL,
2150             urtwn_read_1(sc, R92C_APSD_CTRL) & ~R92C_APSD_CTRL_OFF);
2151         for (ntries = 0; ntries < 200; ntries++) {
2152                 if (!(urtwn_read_1(sc, R92C_APSD_CTRL) &
2153                     R92C_APSD_CTRL_OFF_STATUS))
2154                         break;
2155                 urtwn_ms_delay(sc);
2156         }
2157         if (ntries == 200) {
2158                 device_printf(sc->sc_dev,
2159                     "timeout waiting for MAC initialization\n");
2160                 return (ETIMEDOUT);
2161         }
2162
2163         /* Enable MAC DMA/WMAC/SCHEDULE/SEC blocks. */
2164         reg = urtwn_read_2(sc, R92C_CR);
2165         reg |= R92C_CR_HCI_TXDMA_EN | R92C_CR_HCI_RXDMA_EN |
2166             R92C_CR_TXDMA_EN | R92C_CR_RXDMA_EN | R92C_CR_PROTOCOL_EN |
2167             R92C_CR_SCHEDULE_EN | R92C_CR_MACTXEN | R92C_CR_MACRXEN |
2168             R92C_CR_ENSEC;
2169         urtwn_write_2(sc, R92C_CR, reg);
2170
2171         urtwn_write_1(sc, 0xfe10, 0x19);
2172         return (0);
2173 }
2174
2175 static int
2176 urtwn_r88e_power_on(struct urtwn_softc *sc)
2177 {
2178         uint8_t val;
2179         uint32_t reg;
2180         int ntries;
2181
2182         /* Wait for power ready bit. */
2183         for (ntries = 0; ntries < 5000; ntries++) {
2184                 val = urtwn_read_1(sc, 0x6) & 0x2;
2185                 if (val == 0x2)
2186                         break;
2187                 urtwn_ms_delay(sc);
2188         }
2189         if (ntries == 5000) {
2190                 device_printf(sc->sc_dev,
2191                     "timeout waiting for chip power up\n");
2192                 return (ETIMEDOUT);
2193         }
2194
2195         /* Reset BB. */
2196         urtwn_write_1(sc, R92C_SYS_FUNC_EN,
2197             urtwn_read_1(sc, R92C_SYS_FUNC_EN) & ~(R92C_SYS_FUNC_EN_BBRSTB |
2198             R92C_SYS_FUNC_EN_BB_GLB_RST));
2199
2200         urtwn_write_1(sc, 0x26, urtwn_read_1(sc, 0x26) | 0x80);
2201
2202         /* Disable HWPDN. */
2203         urtwn_write_1(sc, 0x5, urtwn_read_1(sc, 0x5) & ~0x80);
2204
2205         /* Disable WL suspend. */
2206         urtwn_write_1(sc, 0x5, urtwn_read_1(sc, 0x5) & ~0x18);
2207
2208         urtwn_write_1(sc, 0x5, urtwn_read_1(sc, 0x5) | 0x1);
2209         for (ntries = 0; ntries < 5000; ntries++) {
2210                 if (!(urtwn_read_1(sc, 0x5) & 0x1))
2211                         break;
2212                 urtwn_ms_delay(sc);
2213         }
2214         if (ntries == 5000)
2215                 return (ETIMEDOUT);
2216
2217         /* Enable LDO normal mode. */
2218         urtwn_write_1(sc, 0x23, urtwn_read_1(sc, 0x23) & ~0x10);
2219
2220         /* Enable MAC DMA/WMAC/SCHEDULE/SEC blocks. */
2221         urtwn_write_2(sc, R92C_CR, 0);
2222         reg = urtwn_read_2(sc, R92C_CR);
2223         reg |= R92C_CR_HCI_TXDMA_EN | R92C_CR_HCI_RXDMA_EN |
2224             R92C_CR_TXDMA_EN | R92C_CR_RXDMA_EN | R92C_CR_PROTOCOL_EN |
2225             R92C_CR_SCHEDULE_EN | R92C_CR_ENSEC | R92C_CR_CALTMR_EN;
2226         urtwn_write_2(sc, R92C_CR, reg);
2227
2228         return (0);
2229 }
2230
2231 static int
2232 urtwn_llt_init(struct urtwn_softc *sc)
2233 {
2234         int i, error, page_count, pktbuf_count;
2235
2236         page_count = (sc->chip & URTWN_CHIP_88E) ?
2237             R88E_TX_PAGE_COUNT : R92C_TX_PAGE_COUNT;
2238         pktbuf_count = (sc->chip & URTWN_CHIP_88E) ?
2239             R88E_TXPKTBUF_COUNT : R92C_TXPKTBUF_COUNT;
2240
2241         /* Reserve pages [0; page_count]. */
2242         for (i = 0; i < page_count; i++) {
2243                 if ((error = urtwn_llt_write(sc, i, i + 1)) != 0)
2244                         return (error);
2245         }
2246         /* NB: 0xff indicates end-of-list. */
2247         if ((error = urtwn_llt_write(sc, i, 0xff)) != 0)
2248                 return (error);
2249         /*
2250          * Use pages [page_count + 1; pktbuf_count - 1]
2251          * as ring buffer.
2252          */
2253         for (++i; i < pktbuf_count - 1; i++) {
2254                 if ((error = urtwn_llt_write(sc, i, i + 1)) != 0)
2255                         return (error);
2256         }
2257         /* Make the last page point to the beginning of the ring buffer. */
2258         error = urtwn_llt_write(sc, i, page_count + 1);
2259         return (error);
2260 }
2261
2262 static void
2263 urtwn_fw_reset(struct urtwn_softc *sc)
2264 {
2265         uint16_t reg;
2266         int ntries;
2267
2268         /* Tell 8051 to reset itself. */
2269         urtwn_write_1(sc, R92C_HMETFR + 3, 0x20);
2270
2271         /* Wait until 8051 resets by itself. */
2272         for (ntries = 0; ntries < 100; ntries++) {
2273                 reg = urtwn_read_2(sc, R92C_SYS_FUNC_EN);
2274                 if (!(reg & R92C_SYS_FUNC_EN_CPUEN))
2275                         return;
2276                 urtwn_ms_delay(sc);
2277         }
2278         /* Force 8051 reset. */
2279         urtwn_write_2(sc, R92C_SYS_FUNC_EN, reg & ~R92C_SYS_FUNC_EN_CPUEN);
2280 }
2281
2282 static void
2283 urtwn_r88e_fw_reset(struct urtwn_softc *sc)
2284 {
2285         uint16_t reg;
2286
2287         reg = urtwn_read_2(sc, R92C_SYS_FUNC_EN);
2288         urtwn_write_2(sc, R92C_SYS_FUNC_EN, reg & ~R92C_SYS_FUNC_EN_CPUEN);
2289         urtwn_write_2(sc, R92C_SYS_FUNC_EN, reg | R92C_SYS_FUNC_EN_CPUEN);
2290 }
2291
2292 static int
2293 urtwn_fw_loadpage(struct urtwn_softc *sc, int page, const uint8_t *buf, int len)
2294 {
2295         uint32_t reg;
2296         int off, mlen, error = 0;
2297
2298         reg = urtwn_read_4(sc, R92C_MCUFWDL);
2299         reg = RW(reg, R92C_MCUFWDL_PAGE, page);
2300         urtwn_write_4(sc, R92C_MCUFWDL, reg);
2301
2302         off = R92C_FW_START_ADDR;
2303         while (len > 0) {
2304                 if (len > 196)
2305                         mlen = 196;
2306                 else if (len > 4)
2307                         mlen = 4;
2308                 else
2309                         mlen = 1;
2310                 /* XXX fix this deconst */
2311                 error = urtwn_write_region_1(sc, off, 
2312                     __DECONST(uint8_t *, buf), mlen);
2313                 if (error != 0)
2314                         break;
2315                 off += mlen;
2316                 buf += mlen;
2317                 len -= mlen;
2318         }
2319         return (error);
2320 }
2321
2322 static int
2323 urtwn_load_firmware(struct urtwn_softc *sc)
2324 {
2325         const struct firmware *fw;
2326         const struct r92c_fw_hdr *hdr;
2327         const char *imagename;
2328         const u_char *ptr;
2329         size_t len;
2330         uint32_t reg;
2331         int mlen, ntries, page, error;
2332
2333         URTWN_UNLOCK(sc);
2334         /* Read firmware image from the filesystem. */
2335         if (sc->chip & URTWN_CHIP_88E)
2336                 imagename = "urtwn-rtl8188eufw";
2337         else if ((sc->chip & (URTWN_CHIP_UMC_A_CUT | URTWN_CHIP_92C)) ==
2338                     URTWN_CHIP_UMC_A_CUT)
2339                 imagename = "urtwn-rtl8192cfwU";
2340         else
2341                 imagename = "urtwn-rtl8192cfwT";
2342
2343         fw = firmware_get(imagename);
2344         URTWN_LOCK(sc);
2345         if (fw == NULL) {
2346                 device_printf(sc->sc_dev,
2347                     "failed loadfirmware of file %s\n", imagename);
2348                 return (ENOENT);
2349         }
2350
2351         len = fw->datasize;
2352
2353         if (len < sizeof(*hdr)) {
2354                 device_printf(sc->sc_dev, "firmware too short\n");
2355                 error = EINVAL;
2356                 goto fail;
2357         }
2358         ptr = fw->data;
2359         hdr = (const struct r92c_fw_hdr *)ptr;
2360         /* Check if there is a valid FW header and skip it. */
2361         if ((le16toh(hdr->signature) >> 4) == 0x88c ||
2362             (le16toh(hdr->signature) >> 4) == 0x88e ||
2363             (le16toh(hdr->signature) >> 4) == 0x92c) {
2364                 DPRINTF("FW V%d.%d %02d-%02d %02d:%02d\n",
2365                     le16toh(hdr->version), le16toh(hdr->subversion),
2366                     hdr->month, hdr->date, hdr->hour, hdr->minute);
2367                 ptr += sizeof(*hdr);
2368                 len -= sizeof(*hdr);
2369         }
2370
2371         if (urtwn_read_1(sc, R92C_MCUFWDL) & R92C_MCUFWDL_RAM_DL_SEL) {
2372                 if (sc->chip & URTWN_CHIP_88E)
2373                         urtwn_r88e_fw_reset(sc);
2374                 else
2375                         urtwn_fw_reset(sc);
2376                 urtwn_write_1(sc, R92C_MCUFWDL, 0);
2377         }
2378
2379         if (!(sc->chip & URTWN_CHIP_88E)) {
2380                 urtwn_write_2(sc, R92C_SYS_FUNC_EN,
2381                     urtwn_read_2(sc, R92C_SYS_FUNC_EN) |
2382                     R92C_SYS_FUNC_EN_CPUEN);
2383         }
2384         urtwn_write_1(sc, R92C_MCUFWDL,
2385             urtwn_read_1(sc, R92C_MCUFWDL) | R92C_MCUFWDL_EN);
2386         urtwn_write_1(sc, R92C_MCUFWDL + 2,
2387             urtwn_read_1(sc, R92C_MCUFWDL + 2) & ~0x08);
2388
2389         /* Reset the FWDL checksum. */
2390         urtwn_write_1(sc, R92C_MCUFWDL,
2391             urtwn_read_1(sc, R92C_MCUFWDL) | R92C_MCUFWDL_CHKSUM_RPT);
2392
2393         for (page = 0; len > 0; page++) {
2394                 mlen = min(len, R92C_FW_PAGE_SIZE);
2395                 error = urtwn_fw_loadpage(sc, page, ptr, mlen);
2396                 if (error != 0) {
2397                         device_printf(sc->sc_dev,
2398                             "could not load firmware page\n");
2399                         goto fail;
2400                 }
2401                 ptr += mlen;
2402                 len -= mlen;
2403         }
2404         urtwn_write_1(sc, R92C_MCUFWDL,
2405             urtwn_read_1(sc, R92C_MCUFWDL) & ~R92C_MCUFWDL_EN);
2406         urtwn_write_1(sc, R92C_MCUFWDL + 1, 0);
2407
2408         /* Wait for checksum report. */
2409         for (ntries = 0; ntries < 1000; ntries++) {
2410                 if (urtwn_read_4(sc, R92C_MCUFWDL) & R92C_MCUFWDL_CHKSUM_RPT)
2411                         break;
2412                 urtwn_ms_delay(sc);
2413         }
2414         if (ntries == 1000) {
2415                 device_printf(sc->sc_dev,
2416                     "timeout waiting for checksum report\n");
2417                 error = ETIMEDOUT;
2418                 goto fail;
2419         }
2420
2421         reg = urtwn_read_4(sc, R92C_MCUFWDL);
2422         reg = (reg & ~R92C_MCUFWDL_WINTINI_RDY) | R92C_MCUFWDL_RDY;
2423         urtwn_write_4(sc, R92C_MCUFWDL, reg);
2424         if (sc->chip & URTWN_CHIP_88E)
2425                 urtwn_r88e_fw_reset(sc);
2426         /* Wait for firmware readiness. */
2427         for (ntries = 0; ntries < 1000; ntries++) {
2428                 if (urtwn_read_4(sc, R92C_MCUFWDL) & R92C_MCUFWDL_WINTINI_RDY)
2429                         break;
2430                 urtwn_ms_delay(sc);
2431         }
2432         if (ntries == 1000) {
2433                 device_printf(sc->sc_dev,
2434                     "timeout waiting for firmware readiness\n");
2435                 error = ETIMEDOUT;
2436                 goto fail;
2437         }
2438 fail:
2439         firmware_put(fw, FIRMWARE_UNLOAD);
2440         return (error);
2441 }
2442
2443 static __inline int
2444 urtwn_dma_init(struct urtwn_softc *sc)
2445 {
2446             
2447         return sc->sc_dma_init(sc);
2448 }
2449
2450 static int
2451 urtwn_r92c_dma_init(struct urtwn_softc *sc)
2452 {
2453         int hashq, hasnq, haslq, nqueues, nqpages, nrempages;
2454         uint32_t reg;
2455         int error;
2456
2457         /* Initialize LLT table. */
2458         error = urtwn_llt_init(sc);
2459         if (error != 0)
2460                 return (error);
2461
2462         /* Get Tx queues to USB endpoints mapping. */
2463         hashq = hasnq = haslq = 0;
2464         reg = urtwn_read_2(sc, R92C_USB_EP + 1);
2465         DPRINTFN(2, "USB endpoints mapping 0x%x\n", reg);
2466         if (MS(reg, R92C_USB_EP_HQ) != 0)
2467                 hashq = 1;
2468         if (MS(reg, R92C_USB_EP_NQ) != 0)
2469                 hasnq = 1;
2470         if (MS(reg, R92C_USB_EP_LQ) != 0)
2471                 haslq = 1;
2472         nqueues = hashq + hasnq + haslq;
2473         if (nqueues == 0)
2474                 return (EIO);
2475         /* Get the number of pages for each queue. */
2476         nqpages = (R92C_TX_PAGE_COUNT - R92C_PUBQ_NPAGES) / nqueues;
2477         /* The remaining pages are assigned to the high priority queue. */
2478         nrempages = (R92C_TX_PAGE_COUNT - R92C_PUBQ_NPAGES) % nqueues;
2479
2480         /* Set number of pages for normal priority queue. */
2481         urtwn_write_1(sc, R92C_RQPN_NPQ, hasnq ? nqpages : 0);
2482         urtwn_write_4(sc, R92C_RQPN,
2483             /* Set number of pages for public queue. */
2484             SM(R92C_RQPN_PUBQ, R92C_PUBQ_NPAGES) |
2485             /* Set number of pages for high priority queue. */
2486             SM(R92C_RQPN_HPQ, hashq ? nqpages + nrempages : 0) |
2487             /* Set number of pages for low priority queue. */
2488             SM(R92C_RQPN_LPQ, haslq ? nqpages : 0) |
2489             /* Load values. */
2490             R92C_RQPN_LD);
2491
2492         urtwn_write_1(sc, R92C_TXPKTBUF_BCNQ_BDNY, R92C_TX_PAGE_BOUNDARY);
2493         urtwn_write_1(sc, R92C_TXPKTBUF_MGQ_BDNY, R92C_TX_PAGE_BOUNDARY);
2494         urtwn_write_1(sc, R92C_TXPKTBUF_WMAC_LBK_BF_HD, R92C_TX_PAGE_BOUNDARY);
2495         urtwn_write_1(sc, R92C_TRXFF_BNDY, R92C_TX_PAGE_BOUNDARY);
2496         urtwn_write_1(sc, R92C_TDECTRL + 1, R92C_TX_PAGE_BOUNDARY);
2497
2498         /* Set queue to USB pipe mapping. */
2499         reg = urtwn_read_2(sc, R92C_TRXDMA_CTRL);
2500         reg &= ~R92C_TRXDMA_CTRL_QMAP_M;
2501         if (nqueues == 1) {
2502                 if (hashq)
2503                         reg |= R92C_TRXDMA_CTRL_QMAP_HQ;
2504                 else if (hasnq)
2505                         reg |= R92C_TRXDMA_CTRL_QMAP_NQ;
2506                 else
2507                         reg |= R92C_TRXDMA_CTRL_QMAP_LQ;
2508         } else if (nqueues == 2) {
2509                 /* All 2-endpoints configs have a high priority queue. */
2510                 if (!hashq)
2511                         return (EIO);
2512                 if (hasnq)
2513                         reg |= R92C_TRXDMA_CTRL_QMAP_HQ_NQ;
2514                 else
2515                         reg |= R92C_TRXDMA_CTRL_QMAP_HQ_LQ;
2516         } else
2517                 reg |= R92C_TRXDMA_CTRL_QMAP_3EP;
2518         urtwn_write_2(sc, R92C_TRXDMA_CTRL, reg);
2519
2520         /* Set Tx/Rx transfer page boundary. */
2521         urtwn_write_2(sc, R92C_TRXFF_BNDY + 2, 0x27ff);
2522
2523         /* Set Tx/Rx transfer page size. */
2524         urtwn_write_1(sc, R92C_PBP,
2525             SM(R92C_PBP_PSRX, R92C_PBP_128) |
2526             SM(R92C_PBP_PSTX, R92C_PBP_128));
2527         return (0);
2528 }
2529
2530 static int
2531 urtwn_r88e_dma_init(struct urtwn_softc *sc)
2532 {
2533         struct usb_interface *iface;
2534         uint32_t reg;
2535         int nqueues;
2536         int error;
2537
2538         /* Initialize LLT table. */
2539         error = urtwn_llt_init(sc);
2540         if (error != 0)
2541                 return (error);
2542
2543         /* Get Tx queues to USB endpoints mapping. */
2544         iface = usbd_get_iface(sc->sc_udev, 0);
2545         nqueues = iface->idesc->bNumEndpoints - 1;
2546         if (nqueues == 0)
2547                 return (EIO);
2548
2549         /* Set number of pages for normal priority queue. */
2550         urtwn_write_2(sc, R92C_RQPN_NPQ, 0);
2551         urtwn_write_2(sc, R92C_RQPN_NPQ, 0x000d);
2552         urtwn_write_4(sc, R92C_RQPN, 0x808e000d);
2553
2554         urtwn_write_1(sc, R92C_TXPKTBUF_BCNQ_BDNY, R88E_TX_PAGE_BOUNDARY);
2555         urtwn_write_1(sc, R92C_TXPKTBUF_MGQ_BDNY, R88E_TX_PAGE_BOUNDARY);
2556         urtwn_write_1(sc, R92C_TXPKTBUF_WMAC_LBK_BF_HD, R88E_TX_PAGE_BOUNDARY);
2557         urtwn_write_1(sc, R92C_TRXFF_BNDY, R88E_TX_PAGE_BOUNDARY);
2558         urtwn_write_1(sc, R92C_TDECTRL + 1, R88E_TX_PAGE_BOUNDARY);
2559
2560         /* Set queue to USB pipe mapping. */
2561         reg = urtwn_read_2(sc, R92C_TRXDMA_CTRL);
2562         reg &= ~R92C_TRXDMA_CTRL_QMAP_M;
2563         if (nqueues == 1)
2564                 reg |= R92C_TRXDMA_CTRL_QMAP_LQ;
2565         else if (nqueues == 2)
2566                 reg |= R92C_TRXDMA_CTRL_QMAP_HQ_NQ;
2567         else
2568                 reg |= R92C_TRXDMA_CTRL_QMAP_3EP;
2569         urtwn_write_2(sc, R92C_TRXDMA_CTRL, reg);
2570
2571         /* Set Tx/Rx transfer page boundary. */
2572         urtwn_write_2(sc, R92C_TRXFF_BNDY + 2, 0x23ff);
2573
2574         /* Set Tx/Rx transfer page size. */
2575         urtwn_write_1(sc, R92C_PBP,
2576             SM(R92C_PBP_PSRX, R92C_PBP_128) |
2577             SM(R92C_PBP_PSTX, R92C_PBP_128));
2578
2579         return (0);
2580 }
2581
2582 static void
2583 urtwn_mac_init(struct urtwn_softc *sc)
2584 {
2585         int i;
2586
2587         /* Write MAC initialization values. */
2588         if (sc->chip & URTWN_CHIP_88E) {
2589                 for (i = 0; i < nitems(rtl8188eu_mac); i++) {
2590                         urtwn_write_1(sc, rtl8188eu_mac[i].reg,
2591                             rtl8188eu_mac[i].val);
2592                 }
2593                 urtwn_write_1(sc, R92C_MAX_AGGR_NUM, 0x07);
2594         } else {
2595                 for (i = 0; i < nitems(rtl8192cu_mac); i++)
2596                         urtwn_write_1(sc, rtl8192cu_mac[i].reg,
2597                             rtl8192cu_mac[i].val);
2598         }
2599 }
2600
2601 static void
2602 urtwn_bb_init(struct urtwn_softc *sc)
2603 {
2604         const struct urtwn_bb_prog *prog;
2605         uint32_t reg;
2606         uint8_t crystalcap;
2607         int i;
2608
2609         /* Enable BB and RF. */
2610         urtwn_write_2(sc, R92C_SYS_FUNC_EN,
2611             urtwn_read_2(sc, R92C_SYS_FUNC_EN) |
2612             R92C_SYS_FUNC_EN_BBRSTB | R92C_SYS_FUNC_EN_BB_GLB_RST |
2613             R92C_SYS_FUNC_EN_DIO_RF);
2614
2615         if (!(sc->chip & URTWN_CHIP_88E))
2616                 urtwn_write_2(sc, R92C_AFE_PLL_CTRL, 0xdb83);
2617
2618         urtwn_write_1(sc, R92C_RF_CTRL,
2619             R92C_RF_CTRL_EN | R92C_RF_CTRL_RSTB | R92C_RF_CTRL_SDMRSTB);
2620         urtwn_write_1(sc, R92C_SYS_FUNC_EN,
2621             R92C_SYS_FUNC_EN_USBA | R92C_SYS_FUNC_EN_USBD |
2622             R92C_SYS_FUNC_EN_BB_GLB_RST | R92C_SYS_FUNC_EN_BBRSTB);
2623
2624         if (!(sc->chip & URTWN_CHIP_88E)) {
2625                 urtwn_write_1(sc, R92C_LDOHCI12_CTRL, 0x0f);
2626                 urtwn_write_1(sc, 0x15, 0xe9);
2627                 urtwn_write_1(sc, R92C_AFE_XTAL_CTRL + 1, 0x80);
2628         }
2629
2630         /* Select BB programming based on board type. */
2631         if (sc->chip & URTWN_CHIP_88E)
2632                 prog = &rtl8188eu_bb_prog;
2633         else if (!(sc->chip & URTWN_CHIP_92C)) {
2634                 if (sc->board_type == R92C_BOARD_TYPE_MINICARD)
2635                         prog = &rtl8188ce_bb_prog;
2636                 else if (sc->board_type == R92C_BOARD_TYPE_HIGHPA)
2637                         prog = &rtl8188ru_bb_prog;
2638                 else
2639                         prog = &rtl8188cu_bb_prog;
2640         } else {
2641                 if (sc->board_type == R92C_BOARD_TYPE_MINICARD)
2642                         prog = &rtl8192ce_bb_prog;
2643                 else
2644                         prog = &rtl8192cu_bb_prog;
2645         }
2646         /* Write BB initialization values. */
2647         for (i = 0; i < prog->count; i++) {
2648                 urtwn_bb_write(sc, prog->regs[i], prog->vals[i]);
2649                 urtwn_ms_delay(sc);
2650         }
2651
2652         if (sc->chip & URTWN_CHIP_92C_1T2R) {
2653                 /* 8192C 1T only configuration. */
2654                 reg = urtwn_bb_read(sc, R92C_FPGA0_TXINFO);
2655                 reg = (reg & ~0x00000003) | 0x2;
2656                 urtwn_bb_write(sc, R92C_FPGA0_TXINFO, reg);
2657
2658                 reg = urtwn_bb_read(sc, R92C_FPGA1_TXINFO);
2659                 reg = (reg & ~0x00300033) | 0x00200022;
2660                 urtwn_bb_write(sc, R92C_FPGA1_TXINFO, reg);
2661
2662                 reg = urtwn_bb_read(sc, R92C_CCK0_AFESETTING);
2663                 reg = (reg & ~0xff000000) | 0x45 << 24;
2664                 urtwn_bb_write(sc, R92C_CCK0_AFESETTING, reg);
2665
2666                 reg = urtwn_bb_read(sc, R92C_OFDM0_TRXPATHENA);
2667                 reg = (reg & ~0x000000ff) | 0x23;
2668                 urtwn_bb_write(sc, R92C_OFDM0_TRXPATHENA, reg);
2669
2670                 reg = urtwn_bb_read(sc, R92C_OFDM0_AGCPARAM1);
2671                 reg = (reg & ~0x00000030) | 1 << 4;
2672                 urtwn_bb_write(sc, R92C_OFDM0_AGCPARAM1, reg);
2673
2674                 reg = urtwn_bb_read(sc, 0xe74);
2675                 reg = (reg & ~0x0c000000) | 2 << 26;
2676                 urtwn_bb_write(sc, 0xe74, reg);
2677                 reg = urtwn_bb_read(sc, 0xe78);
2678                 reg = (reg & ~0x0c000000) | 2 << 26;
2679                 urtwn_bb_write(sc, 0xe78, reg);
2680                 reg = urtwn_bb_read(sc, 0xe7c);
2681                 reg = (reg & ~0x0c000000) | 2 << 26;
2682                 urtwn_bb_write(sc, 0xe7c, reg);
2683                 reg = urtwn_bb_read(sc, 0xe80);
2684                 reg = (reg & ~0x0c000000) | 2 << 26;
2685                 urtwn_bb_write(sc, 0xe80, reg);
2686                 reg = urtwn_bb_read(sc, 0xe88);
2687                 reg = (reg & ~0x0c000000) | 2 << 26;
2688                 urtwn_bb_write(sc, 0xe88, reg);
2689         }
2690
2691         /* Write AGC values. */
2692         for (i = 0; i < prog->agccount; i++) {
2693                 urtwn_bb_write(sc, R92C_OFDM0_AGCRSSITABLE,
2694                     prog->agcvals[i]);
2695                 urtwn_ms_delay(sc);
2696         }
2697
2698         if (sc->chip & URTWN_CHIP_88E) {
2699                 urtwn_bb_write(sc, R92C_OFDM0_AGCCORE1(0), 0x69553422);
2700                 urtwn_ms_delay(sc);
2701                 urtwn_bb_write(sc, R92C_OFDM0_AGCCORE1(0), 0x69553420);
2702                 urtwn_ms_delay(sc);
2703
2704                 crystalcap = sc->r88e_rom[0xb9];
2705                 if (crystalcap == 0xff)
2706                         crystalcap = 0x20;
2707                 crystalcap &= 0x3f;
2708                 reg = urtwn_bb_read(sc, R92C_AFE_XTAL_CTRL);
2709                 urtwn_bb_write(sc, R92C_AFE_XTAL_CTRL,
2710                     RW(reg, R92C_AFE_XTAL_CTRL_ADDR,
2711                     crystalcap | crystalcap << 6));
2712         } else {
2713                 if (urtwn_bb_read(sc, R92C_HSSI_PARAM2(0)) &
2714                     R92C_HSSI_PARAM2_CCK_HIPWR)
2715                         sc->sc_flags |= URTWN_FLAG_CCK_HIPWR;
2716         }
2717 }
2718
2719 void
2720 urtwn_rf_init(struct urtwn_softc *sc)
2721 {
2722         const struct urtwn_rf_prog *prog;
2723         uint32_t reg, type;
2724         int i, j, idx, off;
2725
2726         /* Select RF programming based on board type. */
2727         if (sc->chip & URTWN_CHIP_88E)
2728                 prog = rtl8188eu_rf_prog;
2729         else if (!(sc->chip & URTWN_CHIP_92C)) {
2730                 if (sc->board_type == R92C_BOARD_TYPE_MINICARD)
2731                         prog = rtl8188ce_rf_prog;
2732                 else if (sc->board_type == R92C_BOARD_TYPE_HIGHPA)
2733                         prog = rtl8188ru_rf_prog;
2734                 else
2735                         prog = rtl8188cu_rf_prog;
2736         } else
2737                 prog = rtl8192ce_rf_prog;
2738
2739         for (i = 0; i < sc->nrxchains; i++) {
2740                 /* Save RF_ENV control type. */
2741                 idx = i / 2;
2742                 off = (i % 2) * 16;
2743                 reg = urtwn_bb_read(sc, R92C_FPGA0_RFIFACESW(idx));
2744                 type = (reg >> off) & 0x10;
2745
2746                 /* Set RF_ENV enable. */
2747                 reg = urtwn_bb_read(sc, R92C_FPGA0_RFIFACEOE(i));
2748                 reg |= 0x100000;
2749                 urtwn_bb_write(sc, R92C_FPGA0_RFIFACEOE(i), reg);
2750                 urtwn_ms_delay(sc);
2751                 /* Set RF_ENV output high. */
2752                 reg = urtwn_bb_read(sc, R92C_FPGA0_RFIFACEOE(i));
2753                 reg |= 0x10;
2754                 urtwn_bb_write(sc, R92C_FPGA0_RFIFACEOE(i), reg);
2755                 urtwn_ms_delay(sc);
2756                 /* Set address and data lengths of RF registers. */
2757                 reg = urtwn_bb_read(sc, R92C_HSSI_PARAM2(i));
2758                 reg &= ~R92C_HSSI_PARAM2_ADDR_LENGTH;
2759                 urtwn_bb_write(sc, R92C_HSSI_PARAM2(i), reg);
2760                 urtwn_ms_delay(sc);
2761                 reg = urtwn_bb_read(sc, R92C_HSSI_PARAM2(i));
2762                 reg &= ~R92C_HSSI_PARAM2_DATA_LENGTH;
2763                 urtwn_bb_write(sc, R92C_HSSI_PARAM2(i), reg);
2764                 urtwn_ms_delay(sc);
2765
2766                 /* Write RF initialization values for this chain. */
2767                 for (j = 0; j < prog[i].count; j++) {
2768                         if (prog[i].regs[j] >= 0xf9 &&
2769                             prog[i].regs[j] <= 0xfe) {
2770                                 /*
2771                                  * These are fake RF registers offsets that
2772                                  * indicate a delay is required.
2773                                  */
2774                                 usb_pause_mtx(&sc->sc_mtx, hz / 20);    /* 50ms */
2775                                 continue;
2776                         }
2777                         urtwn_rf_write(sc, i, prog[i].regs[j],
2778                             prog[i].vals[j]);
2779                         urtwn_ms_delay(sc);
2780                 }
2781
2782                 /* Restore RF_ENV control type. */
2783                 reg = urtwn_bb_read(sc, R92C_FPGA0_RFIFACESW(idx));
2784                 reg &= ~(0x10 << off) | (type << off);
2785                 urtwn_bb_write(sc, R92C_FPGA0_RFIFACESW(idx), reg);
2786
2787                 /* Cache RF register CHNLBW. */
2788                 sc->rf_chnlbw[i] = urtwn_rf_read(sc, i, R92C_RF_CHNLBW);
2789         }
2790
2791         if ((sc->chip & (URTWN_CHIP_UMC_A_CUT | URTWN_CHIP_92C)) ==
2792             URTWN_CHIP_UMC_A_CUT) {
2793                 urtwn_rf_write(sc, 0, R92C_RF_RX_G1, 0x30255);
2794                 urtwn_rf_write(sc, 0, R92C_RF_RX_G2, 0x50a00);
2795         }
2796 }
2797
2798 static void
2799 urtwn_cam_init(struct urtwn_softc *sc)
2800 {
2801         /* Invalidate all CAM entries. */
2802         urtwn_write_4(sc, R92C_CAMCMD,
2803             R92C_CAMCMD_POLLING | R92C_CAMCMD_CLR);
2804 }
2805
2806 static void
2807 urtwn_pa_bias_init(struct urtwn_softc *sc)
2808 {
2809         uint8_t reg;
2810         int i;
2811
2812         for (i = 0; i < sc->nrxchains; i++) {
2813                 if (sc->pa_setting & (1 << i))
2814                         continue;
2815                 urtwn_rf_write(sc, i, R92C_RF_IPA, 0x0f406);
2816                 urtwn_rf_write(sc, i, R92C_RF_IPA, 0x4f406);
2817                 urtwn_rf_write(sc, i, R92C_RF_IPA, 0x8f406);
2818                 urtwn_rf_write(sc, i, R92C_RF_IPA, 0xcf406);
2819         }
2820         if (!(sc->pa_setting & 0x10)) {
2821                 reg = urtwn_read_1(sc, 0x16);
2822                 reg = (reg & ~0xf0) | 0x90;
2823                 urtwn_write_1(sc, 0x16, reg);
2824         }
2825 }
2826
2827 static void
2828 urtwn_rxfilter_init(struct urtwn_softc *sc)
2829 {
2830         /* Initialize Rx filter. */
2831         /* TODO: use better filter for monitor mode. */
2832         urtwn_write_4(sc, R92C_RCR,
2833             R92C_RCR_AAP | R92C_RCR_APM | R92C_RCR_AM | R92C_RCR_AB |
2834             R92C_RCR_APP_ICV | R92C_RCR_AMF | R92C_RCR_HTC_LOC_CTRL |
2835             R92C_RCR_APP_MIC | R92C_RCR_APP_PHYSTS);
2836         /* Accept all multicast frames. */
2837         urtwn_write_4(sc, R92C_MAR + 0, 0xffffffff);
2838         urtwn_write_4(sc, R92C_MAR + 4, 0xffffffff);
2839         /* Accept all management frames. */
2840         urtwn_write_2(sc, R92C_RXFLTMAP0, 0xffff);
2841         /* Reject all control frames. */
2842         urtwn_write_2(sc, R92C_RXFLTMAP1, 0x0000);
2843         /* Accept all data frames. */
2844         urtwn_write_2(sc, R92C_RXFLTMAP2, 0xffff);
2845 }
2846
2847 static void
2848 urtwn_edca_init(struct urtwn_softc *sc)
2849 {
2850         urtwn_write_2(sc, R92C_SPEC_SIFS, 0x100a);
2851         urtwn_write_2(sc, R92C_MAC_SPEC_SIFS, 0x100a);
2852         urtwn_write_2(sc, R92C_SIFS_CCK, 0x100a);
2853         urtwn_write_2(sc, R92C_SIFS_OFDM, 0x100a);
2854         urtwn_write_4(sc, R92C_EDCA_BE_PARAM, 0x005ea42b);
2855         urtwn_write_4(sc, R92C_EDCA_BK_PARAM, 0x0000a44f);
2856         urtwn_write_4(sc, R92C_EDCA_VI_PARAM, 0x005ea324);
2857         urtwn_write_4(sc, R92C_EDCA_VO_PARAM, 0x002fa226);
2858 }
2859
2860 void
2861 urtwn_write_txpower(struct urtwn_softc *sc, int chain,
2862     uint16_t power[URTWN_RIDX_COUNT])
2863 {
2864         uint32_t reg;
2865
2866         /* Write per-CCK rate Tx power. */
2867         if (chain == 0) {
2868                 reg = urtwn_bb_read(sc, R92C_TXAGC_A_CCK1_MCS32);
2869                 reg = RW(reg, R92C_TXAGC_A_CCK1,  power[0]);
2870                 urtwn_bb_write(sc, R92C_TXAGC_A_CCK1_MCS32, reg);
2871                 reg = urtwn_bb_read(sc, R92C_TXAGC_B_CCK11_A_CCK2_11);
2872                 reg = RW(reg, R92C_TXAGC_A_CCK2,  power[1]);
2873                 reg = RW(reg, R92C_TXAGC_A_CCK55, power[2]);
2874                 reg = RW(reg, R92C_TXAGC_A_CCK11, power[3]);
2875                 urtwn_bb_write(sc, R92C_TXAGC_B_CCK11_A_CCK2_11, reg);
2876         } else {
2877                 reg = urtwn_bb_read(sc, R92C_TXAGC_B_CCK1_55_MCS32);
2878                 reg = RW(reg, R92C_TXAGC_B_CCK1,  power[0]);
2879                 reg = RW(reg, R92C_TXAGC_B_CCK2,  power[1]);
2880                 reg = RW(reg, R92C_TXAGC_B_CCK55, power[2]);
2881                 urtwn_bb_write(sc, R92C_TXAGC_B_CCK1_55_MCS32, reg);
2882                 reg = urtwn_bb_read(sc, R92C_TXAGC_B_CCK11_A_CCK2_11);
2883                 reg = RW(reg, R92C_TXAGC_B_CCK11, power[3]);
2884                 urtwn_bb_write(sc, R92C_TXAGC_B_CCK11_A_CCK2_11, reg);
2885         }
2886         /* Write per-OFDM rate Tx power. */
2887         urtwn_bb_write(sc, R92C_TXAGC_RATE18_06(chain),
2888             SM(R92C_TXAGC_RATE06, power[ 4]) |
2889             SM(R92C_TXAGC_RATE09, power[ 5]) |
2890             SM(R92C_TXAGC_RATE12, power[ 6]) |
2891             SM(R92C_TXAGC_RATE18, power[ 7]));
2892         urtwn_bb_write(sc, R92C_TXAGC_RATE54_24(chain),
2893             SM(R92C_TXAGC_RATE24, power[ 8]) |
2894             SM(R92C_TXAGC_RATE36, power[ 9]) |
2895             SM(R92C_TXAGC_RATE48, power[10]) |
2896             SM(R92C_TXAGC_RATE54, power[11]));
2897         /* Write per-MCS Tx power. */
2898         urtwn_bb_write(sc, R92C_TXAGC_MCS03_MCS00(chain),
2899             SM(R92C_TXAGC_MCS00,  power[12]) |
2900             SM(R92C_TXAGC_MCS01,  power[13]) |
2901             SM(R92C_TXAGC_MCS02,  power[14]) |
2902             SM(R92C_TXAGC_MCS03,  power[15]));
2903         urtwn_bb_write(sc, R92C_TXAGC_MCS07_MCS04(chain),
2904             SM(R92C_TXAGC_MCS04,  power[16]) |
2905             SM(R92C_TXAGC_MCS05,  power[17]) |
2906             SM(R92C_TXAGC_MCS06,  power[18]) |
2907             SM(R92C_TXAGC_MCS07,  power[19]));
2908         urtwn_bb_write(sc, R92C_TXAGC_MCS11_MCS08(chain),
2909             SM(R92C_TXAGC_MCS08,  power[20]) |
2910             SM(R92C_TXAGC_MCS09,  power[21]) |
2911             SM(R92C_TXAGC_MCS10,  power[22]) |
2912             SM(R92C_TXAGC_MCS11,  power[23]));
2913         urtwn_bb_write(sc, R92C_TXAGC_MCS15_MCS12(chain),
2914             SM(R92C_TXAGC_MCS12,  power[24]) |
2915             SM(R92C_TXAGC_MCS13,  power[25]) |
2916             SM(R92C_TXAGC_MCS14,  power[26]) |
2917             SM(R92C_TXAGC_MCS15,  power[27]));
2918 }
2919
2920 void
2921 urtwn_get_txpower(struct urtwn_softc *sc, int chain,
2922     struct ieee80211_channel *c, struct ieee80211_channel *extc,
2923     uint16_t power[URTWN_RIDX_COUNT])
2924 {
2925         struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2926         struct r92c_rom *rom = &sc->rom;
2927         uint16_t cckpow, ofdmpow, htpow, diff, max;
2928         const struct urtwn_txpwr *base;
2929         int ridx, chan, group;
2930
2931         /* Determine channel group. */
2932         chan = ieee80211_chan2ieee(ic, c);      /* XXX center freq! */
2933         if (chan <= 3)
2934                 group = 0;
2935         else if (chan <= 9)
2936                 group = 1;
2937         else
2938                 group = 2;
2939
2940         /* Get original Tx power based on board type and RF chain. */
2941         if (!(sc->chip & URTWN_CHIP_92C)) {
2942                 if (sc->board_type == R92C_BOARD_TYPE_HIGHPA)
2943                         base = &rtl8188ru_txagc[chain];
2944                 else
2945                         base = &rtl8192cu_txagc[chain];
2946         } else
2947                 base = &rtl8192cu_txagc[chain];
2948
2949         memset(power, 0, URTWN_RIDX_COUNT * sizeof(power[0]));
2950         if (sc->regulatory == 0) {
2951                 for (ridx = 0; ridx <= 3; ridx++)
2952                         power[ridx] = base->pwr[0][ridx];
2953         }
2954         for (ridx = 4; ridx < URTWN_RIDX_COUNT; ridx++) {
2955                 if (sc->regulatory == 3) {
2956                         power[ridx] = base->pwr[0][ridx];
2957                         /* Apply vendor limits. */
2958                         if (extc != NULL)
2959                                 max = rom->ht40_max_pwr[group];
2960                         else
2961                                 max = rom->ht20_max_pwr[group];
2962                         max = (max >> (chain * 4)) & 0xf;
2963                         if (power[ridx] > max)
2964                                 power[ridx] = max;
2965                 } else if (sc->regulatory == 1) {
2966                         if (extc == NULL)
2967                                 power[ridx] = base->pwr[group][ridx];
2968                 } else if (sc->regulatory != 2)
2969                         power[ridx] = base->pwr[0][ridx];
2970         }
2971
2972         /* Compute per-CCK rate Tx power. */
2973         cckpow = rom->cck_tx_pwr[chain][group];
2974         for (ridx = 0; ridx <= 3; ridx++) {
2975                 power[ridx] += cckpow;
2976                 if (power[ridx] > R92C_MAX_TX_PWR)
2977                         power[ridx] = R92C_MAX_TX_PWR;
2978         }
2979
2980         htpow = rom->ht40_1s_tx_pwr[chain][group];
2981         if (sc->ntxchains > 1) {
2982                 /* Apply reduction for 2 spatial streams. */
2983                 diff = rom->ht40_2s_tx_pwr_diff[group];
2984                 diff = (diff >> (chain * 4)) & 0xf;
2985                 htpow = (htpow > diff) ? htpow - diff : 0;
2986         }
2987
2988         /* Compute per-OFDM rate Tx power. */
2989         diff = rom->ofdm_tx_pwr_diff[group];
2990         diff = (diff >> (chain * 4)) & 0xf;
2991         ofdmpow = htpow + diff; /* HT->OFDM correction. */
2992         for (ridx = 4; ridx <= 11; ridx++) {
2993                 power[ridx] += ofdmpow;
2994                 if (power[ridx] > R92C_MAX_TX_PWR)
2995                         power[ridx] = R92C_MAX_TX_PWR;
2996         }
2997
2998         /* Compute per-MCS Tx power. */
2999         if (extc == NULL) {
3000                 diff = rom->ht20_tx_pwr_diff[group];
3001                 diff = (diff >> (chain * 4)) & 0xf;
3002                 htpow += diff;  /* HT40->HT20 correction. */
3003         }
3004         for (ridx = 12; ridx <= 27; ridx++) {
3005                 power[ridx] += htpow;
3006                 if (power[ridx] > R92C_MAX_TX_PWR)
3007                         power[ridx] = R92C_MAX_TX_PWR;
3008         }
3009 #ifdef URTWN_DEBUG
3010         if (urtwn_debug >= 4) {
3011                 /* Dump per-rate Tx power values. */
3012                 printf("Tx power for chain %d:\n", chain);
3013                 for (ridx = 0; ridx < URTWN_RIDX_COUNT; ridx++)
3014                         printf("Rate %d = %u\n", ridx, power[ridx]);
3015         }
3016 #endif
3017 }
3018
3019 void
3020 urtwn_r88e_get_txpower(struct urtwn_softc *sc, int chain,
3021     struct ieee80211_channel *c, struct ieee80211_channel *extc,
3022     uint16_t power[URTWN_RIDX_COUNT])
3023 {
3024         struct ieee80211com *ic = sc->sc_ifp->if_l2com;
3025         uint16_t cckpow, ofdmpow, bw20pow, htpow;
3026         const struct urtwn_r88e_txpwr *base;
3027         int ridx, chan, group;
3028
3029         /* Determine channel group. */
3030         chan = ieee80211_chan2ieee(ic, c);      /* XXX center freq! */
3031         if (chan <= 2)
3032                 group = 0;
3033         else if (chan <= 5)
3034                 group = 1;
3035         else if (chan <= 8)
3036                 group = 2;
3037         else if (chan <= 11)
3038                 group = 3;
3039         else if (chan <= 13)
3040                 group = 4;
3041         else
3042                 group = 5;
3043
3044         /* Get original Tx power based on board type and RF chain. */
3045         base = &rtl8188eu_txagc[chain];
3046
3047         memset(power, 0, URTWN_RIDX_COUNT * sizeof(power[0]));
3048         if (sc->regulatory == 0) {
3049                 for (ridx = 0; ridx <= 3; ridx++)
3050                         power[ridx] = base->pwr[0][ridx];
3051         }
3052         for (ridx = 4; ridx < URTWN_RIDX_COUNT; ridx++) {
3053                 if (sc->regulatory == 3)
3054                         power[ridx] = base->pwr[0][ridx];
3055                 else if (sc->regulatory == 1) {
3056                         if (extc == NULL)
3057                                 power[ridx] = base->pwr[group][ridx];
3058                 } else if (sc->regulatory != 2)
3059                         power[ridx] = base->pwr[0][ridx];
3060         }
3061
3062         /* Compute per-CCK rate Tx power. */
3063         cckpow = sc->cck_tx_pwr[group];
3064         for (ridx = 0; ridx <= 3; ridx++) {
3065                 power[ridx] += cckpow;
3066                 if (power[ridx] > R92C_MAX_TX_PWR)
3067                         power[ridx] = R92C_MAX_TX_PWR;
3068         }
3069
3070         htpow = sc->ht40_tx_pwr[group];
3071
3072         /* Compute per-OFDM rate Tx power. */
3073         ofdmpow = htpow + sc->ofdm_tx_pwr_diff;
3074         for (ridx = 4; ridx <= 11; ridx++) {
3075                 power[ridx] += ofdmpow;
3076                 if (power[ridx] > R92C_MAX_TX_PWR)
3077                         power[ridx] = R92C_MAX_TX_PWR;
3078         }
3079
3080         bw20pow = htpow + sc->bw20_tx_pwr_diff;
3081         for (ridx = 12; ridx <= 27; ridx++) {
3082                 power[ridx] += bw20pow;
3083                 if (power[ridx] > R92C_MAX_TX_PWR)
3084                         power[ridx] = R92C_MAX_TX_PWR;
3085         }
3086 }
3087
3088 void
3089 urtwn_set_txpower(struct urtwn_softc *sc, struct ieee80211_channel *c,
3090     struct ieee80211_channel *extc)
3091 {
3092         uint16_t power[URTWN_RIDX_COUNT];
3093         int i;
3094
3095         for (i = 0; i < sc->ntxchains; i++) {
3096                 /* Compute per-rate Tx power values. */
3097                 if (sc->chip & URTWN_CHIP_88E)
3098                         urtwn_r88e_get_txpower(sc, i, c, extc, power);
3099                 else
3100                         urtwn_get_txpower(sc, i, c, extc, power);
3101                 /* Write per-rate Tx power values to hardware. */
3102                 urtwn_write_txpower(sc, i, power);
3103         }
3104 }
3105
3106 static void
3107 urtwn_scan_start(struct ieee80211com *ic)
3108 {
3109         /* XXX do nothing?  */
3110 }
3111
3112 static void
3113 urtwn_scan_end(struct ieee80211com *ic)
3114 {
3115         /* XXX do nothing?  */
3116 }
3117
3118 static void
3119 urtwn_set_channel(struct ieee80211com *ic)
3120 {
3121         struct urtwn_softc *sc = ic->ic_ifp->if_softc;
3122         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3123
3124         URTWN_LOCK(sc);
3125         if (vap->iv_state == IEEE80211_S_SCAN) {
3126                 /* Make link LED blink during scan. */
3127                 urtwn_set_led(sc, URTWN_LED_LINK, !sc->ledlink);
3128         }
3129         urtwn_set_chan(sc, ic->ic_curchan, NULL);
3130         URTWN_UNLOCK(sc);
3131 }
3132
3133 static void
3134 urtwn_update_mcast(struct ifnet *ifp)
3135 {
3136         /* XXX do nothing?  */
3137 }
3138
3139 static void
3140 urtwn_set_chan(struct urtwn_softc *sc, struct ieee80211_channel *c,
3141     struct ieee80211_channel *extc)
3142 {
3143         struct ieee80211com *ic = sc->sc_ifp->if_l2com;
3144         uint32_t reg;
3145         u_int chan;
3146         int i;
3147
3148         chan = ieee80211_chan2ieee(ic, c);      /* XXX center freq! */
3149         if (chan == 0 || chan == IEEE80211_CHAN_ANY) {
3150                 device_printf(sc->sc_dev,
3151                     "%s: invalid channel %x\n", __func__, chan);
3152                 return;
3153         }
3154
3155         /* Set Tx power for this new channel. */
3156         urtwn_set_txpower(sc, c, extc);
3157
3158         for (i = 0; i < sc->nrxchains; i++) {
3159                 urtwn_rf_write(sc, i, R92C_RF_CHNLBW,
3160                     RW(sc->rf_chnlbw[i], R92C_RF_CHNLBW_CHNL, chan));
3161         }
3162 #ifndef IEEE80211_NO_HT
3163         if (extc != NULL) {
3164                 /* Is secondary channel below or above primary? */
3165                 int prichlo = c->ic_freq < extc->ic_freq;
3166
3167                 urtwn_write_1(sc, R92C_BWOPMODE,
3168                     urtwn_read_1(sc, R92C_BWOPMODE) & ~R92C_BWOPMODE_20MHZ);
3169
3170                 reg = urtwn_read_1(sc, R92C_RRSR + 2);
3171                 reg = (reg & ~0x6f) | (prichlo ? 1 : 2) << 5;
3172                 urtwn_write_1(sc, R92C_RRSR + 2, reg);
3173
3174                 urtwn_bb_write(sc, R92C_FPGA0_RFMOD,
3175                     urtwn_bb_read(sc, R92C_FPGA0_RFMOD) | R92C_RFMOD_40MHZ);
3176                 urtwn_bb_write(sc, R92C_FPGA1_RFMOD,
3177                     urtwn_bb_read(sc, R92C_FPGA1_RFMOD) | R92C_RFMOD_40MHZ);
3178
3179                 /* Set CCK side band. */
3180                 reg = urtwn_bb_read(sc, R92C_CCK0_SYSTEM);
3181                 reg = (reg & ~0x00000010) | (prichlo ? 0 : 1) << 4;
3182                 urtwn_bb_write(sc, R92C_CCK0_SYSTEM, reg);
3183
3184                 reg = urtwn_bb_read(sc, R92C_OFDM1_LSTF);
3185                 reg = (reg & ~0x00000c00) | (prichlo ? 1 : 2) << 10;
3186                 urtwn_bb_write(sc, R92C_OFDM1_LSTF, reg);
3187
3188                 urtwn_bb_write(sc, R92C_FPGA0_ANAPARAM2,
3189                     urtwn_bb_read(sc, R92C_FPGA0_ANAPARAM2) &
3190                     ~R92C_FPGA0_ANAPARAM2_CBW20);
3191
3192                 reg = urtwn_bb_read(sc, 0x818);
3193                 reg = (reg & ~0x0c000000) | (prichlo ? 2 : 1) << 26;
3194                 urtwn_bb_write(sc, 0x818, reg);
3195
3196                 /* Select 40MHz bandwidth. */
3197                 urtwn_rf_write(sc, 0, R92C_RF_CHNLBW,
3198                     (sc->rf_chnlbw[0] & ~0xfff) | chan);
3199         } else
3200 #endif
3201         {
3202                 urtwn_write_1(sc, R92C_BWOPMODE,
3203                     urtwn_read_1(sc, R92C_BWOPMODE) | R92C_BWOPMODE_20MHZ);
3204
3205                 urtwn_bb_write(sc, R92C_FPGA0_RFMOD,
3206                     urtwn_bb_read(sc, R92C_FPGA0_RFMOD) & ~R92C_RFMOD_40MHZ);
3207                 urtwn_bb_write(sc, R92C_FPGA1_RFMOD,
3208                     urtwn_bb_read(sc, R92C_FPGA1_RFMOD) & ~R92C_RFMOD_40MHZ);
3209
3210                 if (!(sc->chip & URTWN_CHIP_88E)) {
3211                         urtwn_bb_write(sc, R92C_FPGA0_ANAPARAM2,
3212                             urtwn_bb_read(sc, R92C_FPGA0_ANAPARAM2) |
3213                             R92C_FPGA0_ANAPARAM2_CBW20);
3214                 }
3215                         
3216                 /* Select 20MHz bandwidth. */
3217                 urtwn_rf_write(sc, 0, R92C_RF_CHNLBW,
3218                     (sc->rf_chnlbw[0] & ~0xfff) | chan | 
3219                     ((sc->chip & URTWN_CHIP_88E) ? R88E_RF_CHNLBW_BW20 :
3220                     R92C_RF_CHNLBW_BW20));
3221         }
3222 }
3223
3224 static void
3225 urtwn_iq_calib(struct urtwn_softc *sc)
3226 {
3227         /* TODO */
3228 }
3229
3230 static void
3231 urtwn_lc_calib(struct urtwn_softc *sc)
3232 {
3233         uint32_t rf_ac[2];
3234         uint8_t txmode;
3235         int i;
3236
3237         txmode = urtwn_read_1(sc, R92C_OFDM1_LSTF + 3);
3238         if ((txmode & 0x70) != 0) {
3239                 /* Disable all continuous Tx. */
3240                 urtwn_write_1(sc, R92C_OFDM1_LSTF + 3, txmode & ~0x70);
3241
3242                 /* Set RF mode to standby mode. */
3243                 for (i = 0; i < sc->nrxchains; i++) {
3244                         rf_ac[i] = urtwn_rf_read(sc, i, R92C_RF_AC);
3245                         urtwn_rf_write(sc, i, R92C_RF_AC,
3246                             RW(rf_ac[i], R92C_RF_AC_MODE,
3247                                 R92C_RF_AC_MODE_STANDBY));
3248                 }
3249         } else {
3250                 /* Block all Tx queues. */
3251                 urtwn_write_1(sc, R92C_TXPAUSE, 0xff);
3252         }
3253         /* Start calibration. */
3254         urtwn_rf_write(sc, 0, R92C_RF_CHNLBW,
3255             urtwn_rf_read(sc, 0, R92C_RF_CHNLBW) | R92C_RF_CHNLBW_LCSTART);
3256
3257         /* Give calibration the time to complete. */
3258         usb_pause_mtx(&sc->sc_mtx, hz / 10);            /* 100ms */
3259
3260         /* Restore configuration. */
3261         if ((txmode & 0x70) != 0) {
3262                 /* Restore Tx mode. */
3263                 urtwn_write_1(sc, R92C_OFDM1_LSTF + 3, txmode);
3264                 /* Restore RF mode. */
3265                 for (i = 0; i < sc->nrxchains; i++)
3266                         urtwn_rf_write(sc, i, R92C_RF_AC, rf_ac[i]);
3267         } else {
3268                 /* Unblock all Tx queues. */
3269                 urtwn_write_1(sc, R92C_TXPAUSE, 0x00);
3270         }
3271 }
3272
3273 static void
3274 urtwn_init_locked(void *arg)
3275 {
3276         struct urtwn_softc *sc = arg;
3277         struct ifnet *ifp = sc->sc_ifp;
3278         uint32_t reg;
3279         int error;
3280
3281         URTWN_ASSERT_LOCKED(sc);
3282
3283         if (ifp->if_drv_flags & IFF_DRV_RUNNING)
3284                 urtwn_stop_locked(ifp);
3285
3286         /* Init firmware commands ring. */
3287         sc->fwcur = 0;
3288
3289         /* Allocate Tx/Rx buffers. */
3290         error = urtwn_alloc_rx_list(sc);
3291         if (error != 0)
3292                 goto fail;
3293         
3294         error = urtwn_alloc_tx_list(sc);
3295         if (error != 0)
3296                 goto fail;
3297
3298         /* Power on adapter. */
3299         error = urtwn_power_on(sc);
3300         if (error != 0)
3301                 goto fail;
3302
3303         /* Initialize DMA. */
3304         error = urtwn_dma_init(sc);
3305         if (error != 0)
3306                 goto fail;
3307
3308         /* Set info size in Rx descriptors (in 64-bit words). */
3309         urtwn_write_1(sc, R92C_RX_DRVINFO_SZ, 4);
3310
3311         /* Init interrupts. */
3312         if (sc->chip & URTWN_CHIP_88E) {
3313                 urtwn_write_4(sc, R88E_HISR, 0xffffffff);
3314                 urtwn_write_4(sc, R88E_HIMR, R88E_HIMR_CPWM | R88E_HIMR_CPWM2 |
3315                     R88E_HIMR_TBDER | R88E_HIMR_PSTIMEOUT);
3316                 urtwn_write_4(sc, R88E_HIMRE, R88E_HIMRE_RXFOVW |
3317                     R88E_HIMRE_TXFOVW | R88E_HIMRE_RXERR | R88E_HIMRE_TXERR);
3318                 urtwn_write_1(sc, R92C_USB_SPECIAL_OPTION,
3319                     urtwn_read_1(sc, R92C_USB_SPECIAL_OPTION) |
3320                     R92C_USB_SPECIAL_OPTION_INT_BULK_SEL);
3321         } else {
3322                 urtwn_write_4(sc, R92C_HISR, 0xffffffff);
3323                 urtwn_write_4(sc, R92C_HIMR, 0xffffffff);
3324         }
3325
3326         /* Set MAC address. */
3327         urtwn_write_region_1(sc, R92C_MACID, IF_LLADDR(ifp),
3328             IEEE80211_ADDR_LEN);
3329
3330         /* Set initial network type. */
3331         reg = urtwn_read_4(sc, R92C_CR);
3332         reg = RW(reg, R92C_CR_NETTYPE, R92C_CR_NETTYPE_INFRA);
3333         urtwn_write_4(sc, R92C_CR, reg);
3334
3335         urtwn_rxfilter_init(sc);
3336
3337         reg = urtwn_read_4(sc, R92C_RRSR);
3338         reg = RW(reg, R92C_RRSR_RATE_BITMAP, R92C_RRSR_RATE_CCK_ONLY_1M);
3339         urtwn_write_4(sc, R92C_RRSR, reg);
3340
3341         /* Set short/long retry limits. */
3342         urtwn_write_2(sc, R92C_RL,
3343             SM(R92C_RL_SRL, 0x30) | SM(R92C_RL_LRL, 0x30));
3344
3345         /* Initialize EDCA parameters. */
3346         urtwn_edca_init(sc);
3347
3348         /* Setup rate fallback. */
3349         if (!(sc->chip & URTWN_CHIP_88E)) {
3350                 urtwn_write_4(sc, R92C_DARFRC + 0, 0x00000000);
3351                 urtwn_write_4(sc, R92C_DARFRC + 4, 0x10080404);
3352                 urtwn_write_4(sc, R92C_RARFRC + 0, 0x04030201);
3353                 urtwn_write_4(sc, R92C_RARFRC + 4, 0x08070605);
3354         }
3355
3356         urtwn_write_1(sc, R92C_FWHW_TXQ_CTRL,
3357             urtwn_read_1(sc, R92C_FWHW_TXQ_CTRL) |
3358             R92C_FWHW_TXQ_CTRL_AMPDU_RTY_NEW);
3359         /* Set ACK timeout. */
3360         urtwn_write_1(sc, R92C_ACKTO, 0x40);
3361
3362         /* Setup USB aggregation. */
3363         reg = urtwn_read_4(sc, R92C_TDECTRL);
3364         reg = RW(reg, R92C_TDECTRL_BLK_DESC_NUM, 6);
3365         urtwn_write_4(sc, R92C_TDECTRL, reg);
3366         urtwn_write_1(sc, R92C_TRXDMA_CTRL,
3367             urtwn_read_1(sc, R92C_TRXDMA_CTRL) |
3368             R92C_TRXDMA_CTRL_RXDMA_AGG_EN);
3369         urtwn_write_1(sc, R92C_USB_SPECIAL_OPTION,
3370             urtwn_read_1(sc, R92C_USB_SPECIAL_OPTION) |
3371             R92C_USB_SPECIAL_OPTION_AGG_EN);
3372         urtwn_write_1(sc, R92C_RXDMA_AGG_PG_TH, 48);
3373         if (sc->chip & URTWN_CHIP_88E)
3374                 urtwn_write_1(sc, R92C_RXDMA_AGG_PG_TH + 1, 4);
3375         else
3376                 urtwn_write_1(sc, R92C_USB_DMA_AGG_TO, 4);
3377         urtwn_write_1(sc, R92C_USB_AGG_TH, 8);
3378         urtwn_write_1(sc, R92C_USB_AGG_TO, 6);
3379
3380         /* Initialize beacon parameters. */
3381         urtwn_write_2(sc, R92C_BCN_CTRL, 0x1010);
3382         urtwn_write_2(sc, R92C_TBTT_PROHIBIT, 0x6404);
3383         urtwn_write_1(sc, R92C_DRVERLYINT, 0x05);
3384         urtwn_write_1(sc, R92C_BCNDMATIM, 0x02);
3385         urtwn_write_2(sc, R92C_BCNTCFG, 0x660f);
3386
3387         if (!(sc->chip & URTWN_CHIP_88E)) {
3388                 /* Setup AMPDU aggregation. */
3389                 urtwn_write_4(sc, R92C_AGGLEN_LMT, 0x99997631); /* MCS7~0 */
3390                 urtwn_write_1(sc, R92C_AGGR_BREAK_TIME, 0x16);
3391                 urtwn_write_2(sc, R92C_MAX_AGGR_NUM, 0x0708);
3392
3393                 urtwn_write_1(sc, R92C_BCN_MAX_ERR, 0xff);
3394         }
3395
3396         /* Load 8051 microcode. */
3397         error = urtwn_load_firmware(sc);
3398         if (error != 0)
3399                 goto fail;
3400
3401         /* Initialize MAC/BB/RF blocks. */
3402         urtwn_mac_init(sc);
3403         urtwn_bb_init(sc);
3404         urtwn_rf_init(sc);
3405
3406         if (sc->chip & URTWN_CHIP_88E) {
3407                 urtwn_write_2(sc, R92C_CR,
3408                     urtwn_read_2(sc, R92C_CR) | R92C_CR_MACTXEN |
3409                     R92C_CR_MACRXEN);
3410         }
3411
3412         /* Turn CCK and OFDM blocks on. */
3413         reg = urtwn_bb_read(sc, R92C_FPGA0_RFMOD);
3414         reg |= R92C_RFMOD_CCK_EN;
3415         urtwn_bb_write(sc, R92C_FPGA0_RFMOD, reg);
3416         reg = urtwn_bb_read(sc, R92C_FPGA0_RFMOD);
3417         reg |= R92C_RFMOD_OFDM_EN;
3418         urtwn_bb_write(sc, R92C_FPGA0_RFMOD, reg);
3419
3420         /* Clear per-station keys table. */
3421         urtwn_cam_init(sc);
3422
3423         /* Enable hardware sequence numbering. */
3424         urtwn_write_1(sc, R92C_HWSEQ_CTRL, 0xff);
3425
3426         /* Perform LO and IQ calibrations. */
3427         urtwn_iq_calib(sc);
3428         /* Perform LC calibration. */
3429         urtwn_lc_calib(sc);
3430
3431         /* Fix USB interference issue. */
3432         if (!(sc->chip & URTWN_CHIP_88E)) {
3433                 urtwn_write_1(sc, 0xfe40, 0xe0);
3434                 urtwn_write_1(sc, 0xfe41, 0x8d);
3435                 urtwn_write_1(sc, 0xfe42, 0x80);
3436
3437                 urtwn_pa_bias_init(sc);
3438         }
3439
3440         /* Initialize GPIO setting. */
3441         urtwn_write_1(sc, R92C_GPIO_MUXCFG,
3442             urtwn_read_1(sc, R92C_GPIO_MUXCFG) & ~R92C_GPIO_MUXCFG_ENBT);
3443
3444         /* Fix for lower temperature. */
3445         if (!(sc->chip & URTWN_CHIP_88E))
3446                 urtwn_write_1(sc, 0x15, 0xe9);
3447
3448         usbd_transfer_start(sc->sc_xfer[URTWN_BULK_RX]);
3449
3450         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3451         ifp->if_drv_flags |= IFF_DRV_RUNNING;
3452
3453         callout_reset(&sc->sc_watchdog_ch, hz, urtwn_watchdog, sc);
3454 fail:
3455         return;
3456 }
3457
3458 static void
3459 urtwn_init(void *arg)
3460 {
3461         struct urtwn_softc *sc = arg;
3462
3463         URTWN_LOCK(sc);
3464         urtwn_init_locked(arg);
3465         URTWN_UNLOCK(sc);
3466 }
3467
3468 static void
3469 urtwn_stop_locked(struct ifnet *ifp)
3470 {
3471         struct urtwn_softc *sc = ifp->if_softc;
3472
3473         URTWN_ASSERT_LOCKED(sc);
3474
3475         ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
3476
3477         callout_stop(&sc->sc_watchdog_ch);
3478         urtwn_abort_xfers(sc);
3479 }
3480
3481 static void
3482 urtwn_stop(struct ifnet *ifp)
3483 {
3484         struct urtwn_softc *sc = ifp->if_softc;
3485
3486         URTWN_LOCK(sc);
3487         urtwn_stop_locked(ifp);
3488         URTWN_UNLOCK(sc);
3489 }
3490
3491 static void
3492 urtwn_abort_xfers(struct urtwn_softc *sc)
3493 {
3494         int i;
3495
3496         URTWN_ASSERT_LOCKED(sc);
3497
3498         /* abort any pending transfers */
3499         for (i = 0; i < URTWN_N_TRANSFER; i++)
3500                 usbd_transfer_stop(sc->sc_xfer[i]);
3501 }
3502
3503 static int
3504 urtwn_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
3505     const struct ieee80211_bpf_params *params)
3506 {
3507         struct ieee80211com *ic = ni->ni_ic;
3508         struct ifnet *ifp = ic->ic_ifp;
3509         struct urtwn_softc *sc = ifp->if_softc;
3510         struct urtwn_data *bf;
3511
3512         /* prevent management frames from being sent if we're not ready */
3513         if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
3514                 m_freem(m);
3515                 ieee80211_free_node(ni);
3516                 return (ENETDOWN);
3517         }
3518         URTWN_LOCK(sc);
3519         bf = urtwn_getbuf(sc);
3520         if (bf == NULL) {
3521                 ieee80211_free_node(ni);
3522                 m_freem(m);
3523                 URTWN_UNLOCK(sc);
3524                 return (ENOBUFS);
3525         }
3526
3527         ifp->if_opackets++;
3528         if (urtwn_tx_start(sc, ni, m, bf) != 0) {
3529                 ieee80211_free_node(ni);
3530                 ifp->if_oerrors++;
3531                 STAILQ_INSERT_HEAD(&sc->sc_tx_inactive, bf, next);
3532                 URTWN_UNLOCK(sc);
3533                 return (EIO);
3534         }
3535         URTWN_UNLOCK(sc);
3536
3537         sc->sc_txtimer = 5;
3538         return (0);
3539 }
3540
3541 static void
3542 urtwn_ms_delay(struct urtwn_softc *sc)
3543 {
3544         usb_pause_mtx(&sc->sc_mtx, hz / 1000);
3545 }
3546
3547 static device_method_t urtwn_methods[] = {
3548         /* Device interface */
3549         DEVMETHOD(device_probe,         urtwn_match),
3550         DEVMETHOD(device_attach,        urtwn_attach),
3551         DEVMETHOD(device_detach,        urtwn_detach),
3552
3553         DEVMETHOD_END
3554 };
3555
3556 static driver_t urtwn_driver = {
3557         "urtwn",
3558         urtwn_methods,
3559         sizeof(struct urtwn_softc)
3560 };
3561
3562 static devclass_t urtwn_devclass;
3563
3564 DRIVER_MODULE(urtwn, uhub, urtwn_driver, urtwn_devclass, NULL, NULL);
3565 MODULE_DEPEND(urtwn, usb, 1, 1, 1);
3566 MODULE_DEPEND(urtwn, wlan, 1, 1, 1);
3567 MODULE_DEPEND(urtwn, firmware, 1, 1, 1);
3568 MODULE_VERSION(urtwn, 1);