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