xref: /openbsd-src/sys/dev/usb/if_urtwn.c (revision d13be5d47e4149db2549a9828e244d59dbc43f15)
1 /*	$OpenBSD: if_urtwn.c,v 1.18 2011/07/03 15:47:17 matthew Exp $	*/
2 
3 /*-
4  * Copyright (c) 2010 Damien Bergamini <damien.bergamini@free.fr>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 /*
20  * Driver for Realtek RTL8188CE-VAU/RTL8188CUS/RTL8188RU/RTL8192CU.
21  */
22 
23 #include "bpfilter.h"
24 
25 #include <sys/param.h>
26 #include <sys/sockio.h>
27 #include <sys/mbuf.h>
28 #include <sys/kernel.h>
29 #include <sys/socket.h>
30 #include <sys/systm.h>
31 #include <sys/timeout.h>
32 #include <sys/conf.h>
33 #include <sys/device.h>
34 
35 #include <machine/bus.h>
36 #include <machine/endian.h>
37 #include <machine/intr.h>
38 
39 #if NBPFILTER > 0
40 #include <net/bpf.h>
41 #endif
42 #include <net/if.h>
43 #include <net/if_arp.h>
44 #include <net/if_dl.h>
45 #include <net/if_media.h>
46 #include <net/if_types.h>
47 
48 #include <netinet/in.h>
49 #include <netinet/in_systm.h>
50 #include <netinet/in_var.h>
51 #include <netinet/if_ether.h>
52 #include <netinet/ip.h>
53 
54 #include <net80211/ieee80211_var.h>
55 #include <net80211/ieee80211_radiotap.h>
56 
57 #include <dev/usb/usb.h>
58 #include <dev/usb/usbdi.h>
59 #include <dev/usb/usbdi_util.h>
60 #include <dev/usb/usbdevs.h>
61 
62 #include <dev/usb/if_urtwnreg.h>
63 
64 #ifdef USB_DEBUG
65 #define URTWN_DEBUG
66 #endif
67 
68 #ifdef URTWN_DEBUG
69 #define DPRINTF(x)	do { if (urtwn_debug) printf x; } while (0)
70 #define DPRINTFN(n, x)	do { if (urtwn_debug >= (n)) printf x; } while (0)
71 int urtwn_debug = 4;
72 #else
73 #define DPRINTF(x)
74 #define DPRINTFN(n, x)
75 #endif
76 
77 static const struct usb_devno urtwn_devs[] = {
78 	{ USB_VENDOR_ABOCOM,	USB_PRODUCT_ABOCOM_RTL8188CU_1 },
79 	{ USB_VENDOR_ABOCOM,	USB_PRODUCT_ABOCOM_RTL8188CU_2 },
80 	{ USB_VENDOR_ABOCOM,	USB_PRODUCT_ABOCOM_RTL8192CU },
81 	{ USB_VENDOR_AZUREWAVE,	USB_PRODUCT_AZUREWAVE_RTL8188CE_1 },
82 	{ USB_VENDOR_AZUREWAVE,	USB_PRODUCT_AZUREWAVE_RTL8188CE_2 },
83 	{ USB_VENDOR_BELKIN,	USB_PRODUCT_BELKIN_RTL8188CU },
84 	{ USB_VENDOR_COREGA,	USB_PRODUCT_COREGA_RTL8192CU },
85 	{ USB_VENDOR_DLINK,	USB_PRODUCT_DLINK_RTL8188CU },
86 	{ USB_VENDOR_DLINK,	USB_PRODUCT_DLINK_RTL8192CU_1 },
87 	{ USB_VENDOR_DLINK,	USB_PRODUCT_DLINK_RTL8192CU_2 },
88 	{ USB_VENDOR_DLINK,	USB_PRODUCT_DLINK_RTL8192CU_3 },
89 	{ USB_VENDOR_EDIMAX,	USB_PRODUCT_EDIMAX_RTL8188CU },
90 	{ USB_VENDOR_EDIMAX,	USB_PRODUCT_EDIMAX_RTL8192CU },
91 	{ USB_VENDOR_FEIXUN,	USB_PRODUCT_FEIXUN_RTL8188CU },
92 	{ USB_VENDOR_FEIXUN,	USB_PRODUCT_FEIXUN_RTL8192CU },
93 	{ USB_VENDOR_GUILLEMOT,	USB_PRODUCT_GUILLEMOT_HWNUP150 },
94 	{ USB_VENDOR_HP3,	USB_PRODUCT_HP3_RTL8188CU },
95 	{ USB_VENDOR_NOVATECH,	USB_PRODUCT_NOVATECH_RTL8188CU },
96 	{ USB_VENDOR_PLANEX2,	USB_PRODUCT_PLANEX2_RTL8188CU_1 },
97 	{ USB_VENDOR_PLANEX2,	USB_PRODUCT_PLANEX2_RTL8188CU_2 },
98 	{ USB_VENDOR_PLANEX2,	USB_PRODUCT_PLANEX2_RTL8192CU },
99 	{ USB_VENDOR_REALTEK,	USB_PRODUCT_REALTEK_RTL8188CE_0 },
100 	{ USB_VENDOR_REALTEK,	USB_PRODUCT_REALTEK_RTL8188CE_1 },
101 	{ USB_VENDOR_REALTEK,	USB_PRODUCT_REALTEK_RTL8188CU_0 },
102 	{ USB_VENDOR_REALTEK,	USB_PRODUCT_REALTEK_RTL8188CU_1 },
103 	{ USB_VENDOR_REALTEK,	USB_PRODUCT_REALTEK_RTL8188CU_2 },
104 	{ USB_VENDOR_REALTEK,	USB_PRODUCT_REALTEK_RTL8188RU },
105 	{ USB_VENDOR_REALTEK,	USB_PRODUCT_REALTEK_RTL8191CU },
106 	{ USB_VENDOR_REALTEK,	USB_PRODUCT_REALTEK_RTL8192CE },
107 	{ USB_VENDOR_REALTEK,	USB_PRODUCT_REALTEK_RTL8192CU },
108 	{ USB_VENDOR_SITECOMEU,	USB_PRODUCT_SITECOMEU_RTL8188CU },
109 	{ USB_VENDOR_TRENDNET,	USB_PRODUCT_TRENDNET_RTL8188CU },
110 	{ USB_VENDOR_ZYXEL,	USB_PRODUCT_ZYXEL_RTL8192CU }
111 };
112 
113 int		urtwn_match(struct device *, void *, void *);
114 void		urtwn_attach(struct device *, struct device *, void *);
115 int		urtwn_detach(struct device *, int);
116 int		urtwn_activate(struct device *, int);
117 int		urtwn_open_pipes(struct urtwn_softc *);
118 void		urtwn_close_pipes(struct urtwn_softc *);
119 int		urtwn_alloc_rx_list(struct urtwn_softc *);
120 void		urtwn_free_rx_list(struct urtwn_softc *);
121 int		urtwn_alloc_tx_list(struct urtwn_softc *);
122 void		urtwn_free_tx_list(struct urtwn_softc *);
123 void		urtwn_task(void *);
124 void		urtwn_do_async(struct urtwn_softc *,
125 		    void (*)(struct urtwn_softc *, void *), void *, int);
126 void		urtwn_wait_async(struct urtwn_softc *);
127 int		urtwn_write_region_1(struct urtwn_softc *, uint16_t, uint8_t *,
128 		    int);
129 void		urtwn_write_1(struct urtwn_softc *, uint16_t, uint8_t);
130 void		urtwn_write_2(struct urtwn_softc *, uint16_t, uint16_t);
131 void		urtwn_write_4(struct urtwn_softc *, uint16_t, uint32_t);
132 int		urtwn_read_region_1(struct urtwn_softc *, uint16_t, uint8_t *,
133 		    int);
134 uint8_t		urtwn_read_1(struct urtwn_softc *, uint16_t);
135 uint16_t	urtwn_read_2(struct urtwn_softc *, uint16_t);
136 uint32_t	urtwn_read_4(struct urtwn_softc *, uint16_t);
137 int		urtwn_fw_cmd(struct urtwn_softc *, uint8_t, const void *, int);
138 void		urtwn_rf_write(struct urtwn_softc *, int, uint8_t, uint32_t);
139 uint32_t	urtwn_rf_read(struct urtwn_softc *, int, uint8_t);
140 void		urtwn_cam_write(struct urtwn_softc *, uint32_t, uint32_t);
141 int		urtwn_llt_write(struct urtwn_softc *, uint32_t, uint32_t);
142 uint8_t		urtwn_efuse_read_1(struct urtwn_softc *, uint16_t);
143 void		urtwn_efuse_read(struct urtwn_softc *);
144 int		urtwn_read_chipid(struct urtwn_softc *);
145 void		urtwn_read_rom(struct urtwn_softc *);
146 int		urtwn_media_change(struct ifnet *);
147 int		urtwn_ra_init(struct urtwn_softc *);
148 void		urtwn_tsf_sync_enable(struct urtwn_softc *);
149 void		urtwn_set_led(struct urtwn_softc *, int, int);
150 void		urtwn_calib_to(void *);
151 void		urtwn_calib_cb(struct urtwn_softc *, void *);
152 void		urtwn_next_scan(void *);
153 int		urtwn_newstate(struct ieee80211com *, enum ieee80211_state,
154 		    int);
155 void		urtwn_newstate_cb(struct urtwn_softc *, void *);
156 void		urtwn_updateedca(struct ieee80211com *);
157 void		urtwn_updateedca_cb(struct urtwn_softc *, void *);
158 int		urtwn_set_key(struct ieee80211com *, struct ieee80211_node *,
159 		    struct ieee80211_key *);
160 void		urtwn_set_key_cb(struct urtwn_softc *, void *);
161 void		urtwn_delete_key(struct ieee80211com *,
162 		    struct ieee80211_node *, struct ieee80211_key *);
163 void		urtwn_delete_key_cb(struct urtwn_softc *, void *);
164 void		urtwn_update_avgrssi(struct urtwn_softc *, int, int8_t);
165 int8_t		urtwn_get_rssi(struct urtwn_softc *, int, void *);
166 void		urtwn_rx_frame(struct urtwn_softc *, uint8_t *, int);
167 void		urtwn_rxeof(usbd_xfer_handle, usbd_private_handle,
168 		    usbd_status);
169 void		urtwn_txeof(usbd_xfer_handle, usbd_private_handle,
170 		    usbd_status);
171 int		urtwn_tx(struct urtwn_softc *, struct mbuf *,
172 		    struct ieee80211_node *);
173 void		urtwn_start(struct ifnet *);
174 void		urtwn_watchdog(struct ifnet *);
175 int		urtwn_ioctl(struct ifnet *, u_long, caddr_t);
176 int		urtwn_power_on(struct urtwn_softc *);
177 int		urtwn_llt_init(struct urtwn_softc *);
178 void		urtwn_fw_reset(struct urtwn_softc *);
179 int		urtwn_fw_loadpage(struct urtwn_softc *, int, uint8_t *, int);
180 int		urtwn_load_firmware(struct urtwn_softc *);
181 int		urtwn_dma_init(struct urtwn_softc *);
182 void		urtwn_mac_init(struct urtwn_softc *);
183 void		urtwn_bb_init(struct urtwn_softc *);
184 void		urtwn_rf_init(struct urtwn_softc *);
185 void		urtwn_cam_init(struct urtwn_softc *);
186 void		urtwn_pa_bias_init(struct urtwn_softc *);
187 void		urtwn_rxfilter_init(struct urtwn_softc *);
188 void		urtwn_edca_init(struct urtwn_softc *);
189 void		urtwn_write_txpower(struct urtwn_softc *, int, uint16_t[]);
190 void		urtwn_get_txpower(struct urtwn_softc *, int,
191 		    struct ieee80211_channel *, struct ieee80211_channel *,
192 		    uint16_t[]);
193 void		urtwn_set_txpower(struct urtwn_softc *,
194 		    struct ieee80211_channel *, struct ieee80211_channel *);
195 void		urtwn_set_chan(struct urtwn_softc *,
196 		    struct ieee80211_channel *, struct ieee80211_channel *);
197 int		urtwn_iq_calib_chain(struct urtwn_softc *, int, uint16_t[],
198 		    uint16_t[]);
199 void		urtwn_iq_calib(struct urtwn_softc *);
200 void		urtwn_lc_calib(struct urtwn_softc *);
201 void		urtwn_temp_calib(struct urtwn_softc *);
202 int		urtwn_init(struct ifnet *);
203 void		urtwn_stop(struct ifnet *);
204 
205 /* Aliases. */
206 #define	urtwn_bb_write	urtwn_write_4
207 #define urtwn_bb_read	urtwn_read_4
208 
209 struct cfdriver urtwn_cd = {
210 	NULL, "urtwn", DV_IFNET
211 };
212 
213 const struct cfattach urtwn_ca = {
214 	sizeof(struct urtwn_softc),
215 	urtwn_match,
216 	urtwn_attach,
217 	urtwn_detach,
218 	urtwn_activate
219 };
220 
221 int
222 urtwn_match(struct device *parent, void *match, void *aux)
223 {
224 	struct usb_attach_arg *uaa = aux;
225 
226 	if (uaa->iface != NULL)
227 		return (UMATCH_NONE);
228 
229 	return ((usb_lookup(urtwn_devs, uaa->vendor, uaa->product) != NULL) ?
230 	    UMATCH_VENDOR_PRODUCT : UMATCH_NONE);
231 }
232 
233 void
234 urtwn_attach(struct device *parent, struct device *self, void *aux)
235 {
236 	struct urtwn_softc *sc = (struct urtwn_softc *)self;
237 	struct usb_attach_arg *uaa = aux;
238 	struct ieee80211com *ic = &sc->sc_ic;
239 	struct ifnet *ifp = &ic->ic_if;
240 	int i, error;
241 
242 	sc->sc_udev = uaa->device;
243 
244 	usb_init_task(&sc->sc_task, urtwn_task, sc, USB_TASK_TYPE_GENERIC);
245 	timeout_set(&sc->scan_to, urtwn_next_scan, sc);
246 	timeout_set(&sc->calib_to, urtwn_calib_to, sc);
247 
248 	if (usbd_set_config_no(sc->sc_udev, 1, 0) != 0) {
249 		printf("%s: could not set configuration no\n",
250 		    sc->sc_dev.dv_xname);
251 		return;
252 	}
253 
254 	/* Get the first interface handle. */
255 	error = usbd_device2interface_handle(sc->sc_udev, 0, &sc->sc_iface);
256 	if (error != 0) {
257 		printf("%s: could not get interface handle\n",
258 		    sc->sc_dev.dv_xname);
259 		return;
260 	}
261 
262 	error = urtwn_read_chipid(sc);
263 	if (error != 0) {
264 		printf("%s: unsupported test chip\n", sc->sc_dev.dv_xname);
265 		return;
266 	}
267 
268 	/* Determine number of Tx/Rx chains. */
269 	if (sc->chip & URTWN_CHIP_92C) {
270 		sc->ntxchains = (sc->chip & URTWN_CHIP_92C_1T2R) ? 1 : 2;
271 		sc->nrxchains = 2;
272 	} else {
273 		sc->ntxchains = 1;
274 		sc->nrxchains = 1;
275 	}
276 	urtwn_read_rom(sc);
277 
278 	printf("%s: MAC/BB RTL%s, RF 6052 %dT%dR, address %s\n",
279 	    sc->sc_dev.dv_xname,
280 	    (sc->chip & URTWN_CHIP_92C) ? "8192CU" :
281 	    (sc->board_type == R92C_BOARD_TYPE_HIGHPA) ? "8188RU" :
282 	    (sc->board_type == R92C_BOARD_TYPE_MINICARD) ? "8188CE-VAU" :
283 	    "8188CUS", sc->ntxchains, sc->nrxchains,
284 	    ether_sprintf(ic->ic_myaddr));
285 
286 	if (urtwn_open_pipes(sc) != 0)
287 		return;
288 
289 	ic->ic_phytype = IEEE80211_T_OFDM;	/* Not only, but not used. */
290 	ic->ic_opmode = IEEE80211_M_STA;	/* Default to BSS mode. */
291 	ic->ic_state = IEEE80211_S_INIT;
292 
293 	/* Set device capabilities. */
294 	ic->ic_caps =
295 	    IEEE80211_C_MONITOR |	/* Monitor mode supported. */
296 	    IEEE80211_C_SHPREAMBLE |	/* Short preamble supported. */
297 	    IEEE80211_C_SHSLOT |	/* Short slot time supported. */
298 	    IEEE80211_C_WEP |		/* WEP. */
299 	    IEEE80211_C_RSN;		/* WPA/RSN. */
300 
301 #ifndef IEEE80211_NO_HT
302 	/* Set HT capabilities. */
303 	ic->ic_htcaps =
304 	    IEEE80211_HTCAP_CBW20_40 |
305 	    IEEE80211_HTCAP_DSSSCCK40;
306 	/* Set supported HT rates. */
307 	for (i = 0; i < sc->nrxchains; i++)
308 		ic->ic_sup_mcs[i] = 0xff;
309 #endif
310 
311 	/* Set supported .11b and .11g rates. */
312 	ic->ic_sup_rates[IEEE80211_MODE_11B] = ieee80211_std_rateset_11b;
313 	ic->ic_sup_rates[IEEE80211_MODE_11G] = ieee80211_std_rateset_11g;
314 
315 	/* Set supported .11b and .11g channels (1 through 14). */
316 	for (i = 1; i <= 14; i++) {
317 		ic->ic_channels[i].ic_freq =
318 		    ieee80211_ieee2mhz(i, IEEE80211_CHAN_2GHZ);
319 		ic->ic_channels[i].ic_flags =
320 		    IEEE80211_CHAN_CCK | IEEE80211_CHAN_OFDM |
321 		    IEEE80211_CHAN_DYN | IEEE80211_CHAN_2GHZ;
322 	}
323 	/*
324 	 * The number of STAs that we can support is limited by the number
325 	 * of CAM entries used for hardware crypto.
326 	 */
327 	ic->ic_max_nnodes = R92C_CAM_ENTRY_COUNT - 4;
328 	if (ic->ic_max_nnodes > IEEE80211_CACHE_SIZE)
329 		ic->ic_max_nnodes = IEEE80211_CACHE_SIZE;
330 
331 	ifp->if_softc = sc;
332 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
333 	ifp->if_ioctl = urtwn_ioctl;
334 	ifp->if_start = urtwn_start;
335 	ifp->if_watchdog = urtwn_watchdog;
336 	IFQ_SET_READY(&ifp->if_snd);
337 	memcpy(ifp->if_xname, sc->sc_dev.dv_xname, IFNAMSIZ);
338 
339 	if_attach(ifp);
340 	ieee80211_ifattach(ifp);
341 	ic->ic_updateedca = urtwn_updateedca;
342 #ifdef notyet
343 	ic->ic_set_key = urtwn_set_key;
344 	ic->ic_delete_key = urtwn_delete_key;
345 #endif
346 	/* Override state transition machine. */
347 	sc->sc_newstate = ic->ic_newstate;
348 	ic->ic_newstate = urtwn_newstate;
349 	ieee80211_media_init(ifp, urtwn_media_change, ieee80211_media_status);
350 
351 #if NBPFILTER > 0
352 	bpfattach(&sc->sc_drvbpf, ifp, DLT_IEEE802_11_RADIO,
353 	    sizeof(struct ieee80211_frame) + IEEE80211_RADIOTAP_HDRLEN);
354 
355 	sc->sc_rxtap_len = sizeof(sc->sc_rxtapu);
356 	sc->sc_rxtap.wr_ihdr.it_len = htole16(sc->sc_rxtap_len);
357 	sc->sc_rxtap.wr_ihdr.it_present = htole32(URTWN_RX_RADIOTAP_PRESENT);
358 
359 	sc->sc_txtap_len = sizeof(sc->sc_txtapu);
360 	sc->sc_txtap.wt_ihdr.it_len = htole16(sc->sc_txtap_len);
361 	sc->sc_txtap.wt_ihdr.it_present = htole32(URTWN_TX_RADIOTAP_PRESENT);
362 #endif
363 }
364 
365 int
366 urtwn_detach(struct device *self, int flags)
367 {
368 	struct urtwn_softc *sc = (struct urtwn_softc *)self;
369 	struct ifnet *ifp = &sc->sc_ic.ic_if;
370 	int s;
371 
372 	s = splusb();
373 
374 	if (timeout_initialized(&sc->scan_to))
375 		timeout_del(&sc->scan_to);
376 	if (timeout_initialized(&sc->calib_to))
377 		timeout_del(&sc->calib_to);
378 
379 	/* Wait for all async commands to complete. */
380 	usb_rem_wait_task(sc->sc_udev, &sc->sc_task);
381 
382 	usbd_ref_wait(sc->sc_udev);
383 
384 	if (ifp->if_softc != NULL) {
385 		ieee80211_ifdetach(ifp);
386 		if_detach(ifp);
387 	}
388 
389 	/* Abort and close Tx/Rx pipes. */
390 	urtwn_close_pipes(sc);
391 
392 	/* Free Tx/Rx buffers. */
393 	urtwn_free_tx_list(sc);
394 	urtwn_free_rx_list(sc);
395 	splx(s);
396 
397 	return (0);
398 }
399 
400 int
401 urtwn_activate(struct device *self, int act)
402 {
403 	struct urtwn_softc *sc = (struct urtwn_softc *)self;
404 
405 	switch (act) {
406 	case DVACT_DEACTIVATE:
407 		usbd_deactivate(sc->sc_udev);
408 		break;
409 	}
410 	return (0);
411 }
412 
413 int
414 urtwn_open_pipes(struct urtwn_softc *sc)
415 {
416 	/* Bulk-out endpoints addresses (from highest to lowest prio). */
417 	const uint8_t epaddr[] = { 0x02, 0x03, 0x05 };
418 	usb_interface_descriptor_t *id;
419 	usb_endpoint_descriptor_t *ed;
420 	int i, ntx = 0, error;
421 
422 	/* Determine the number of bulk-out pipes. */
423 	id = usbd_get_interface_descriptor(sc->sc_iface);
424 	for (i = 0; i < id->bNumEndpoints; i++) {
425 		ed = usbd_interface2endpoint_descriptor(sc->sc_iface, i);
426 		if (ed != NULL &&
427 		    UE_GET_XFERTYPE(ed->bmAttributes) == UE_BULK &&
428 		    UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_OUT)
429 			ntx++;
430 	}
431 	DPRINTF(("found %d bulk-out pipes\n", ntx));
432 	if (ntx == 0 || ntx > R92C_MAX_EPOUT) {
433 		printf("%s: %d: invalid number of Tx bulk pipes\n",
434 		    sc->sc_dev.dv_xname, ntx);
435 		return (EIO);
436 	}
437 
438 	/* Open bulk-in pipe at address 0x81. */
439 	error = usbd_open_pipe(sc->sc_iface, 0x81, 0, &sc->rx_pipe);
440 	if (error != 0) {
441 		printf("%s: could not open Rx bulk pipe\n",
442 		    sc->sc_dev.dv_xname);
443 		goto fail;
444 	}
445 
446 	/* Open bulk-out pipes (up to 3). */
447 	for (i = 0; i < ntx; i++) {
448 		error = usbd_open_pipe(sc->sc_iface, epaddr[i], 0,
449 		    &sc->tx_pipe[i]);
450 		if (error != 0) {
451 			printf("%s: could not open Tx bulk pipe 0x%02x\n",
452 			    sc->sc_dev.dv_xname, epaddr[i]);
453 			goto fail;
454 		}
455 	}
456 
457 	/* Map 802.11 access categories to USB pipes. */
458 	sc->ac2idx[EDCA_AC_BK] =
459 	sc->ac2idx[EDCA_AC_BE] = (ntx == 3) ? 2 : ((ntx == 2) ? 1 : 0);
460 	sc->ac2idx[EDCA_AC_VI] = (ntx == 3) ? 1 : 0;
461 	sc->ac2idx[EDCA_AC_VO] = 0;	/* Always use highest prio. */
462 
463 	if (error != 0)
464  fail:		urtwn_close_pipes(sc);
465 	return (error);
466 }
467 
468 void
469 urtwn_close_pipes(struct urtwn_softc *sc)
470 {
471 	int i;
472 
473 	/* Close Rx pipe. */
474 	if (sc->rx_pipe != NULL) {
475 		usbd_abort_pipe(sc->rx_pipe);
476 		usbd_close_pipe(sc->rx_pipe);
477 	}
478 	/* Close Tx pipes. */
479 	for (i = 0; i < R92C_MAX_EPOUT; i++) {
480 		if (sc->tx_pipe[i] == NULL)
481 			continue;
482 		usbd_abort_pipe(sc->tx_pipe[i]);
483 		usbd_close_pipe(sc->tx_pipe[i]);
484 	}
485 }
486 
487 int
488 urtwn_alloc_rx_list(struct urtwn_softc *sc)
489 {
490 	struct urtwn_rx_data *data;
491 	int i, error = 0;
492 
493 	for (i = 0; i < URTWN_RX_LIST_COUNT; i++) {
494 		data = &sc->rx_data[i];
495 
496 		data->sc = sc;	/* Backpointer for callbacks. */
497 
498 		data->xfer = usbd_alloc_xfer(sc->sc_udev);
499 		if (data->xfer == NULL) {
500 			printf("%s: could not allocate xfer\n",
501 			    sc->sc_dev.dv_xname);
502 			error = ENOMEM;
503 			break;
504 		}
505 		data->buf = usbd_alloc_buffer(data->xfer, URTWN_RXBUFSZ);
506 		if (data->buf == NULL) {
507 			printf("%s: could not allocate xfer buffer\n",
508 			    sc->sc_dev.dv_xname);
509 			error = ENOMEM;
510 			break;
511 		}
512 	}
513 	if (error != 0)
514 		urtwn_free_rx_list(sc);
515 	return (error);
516 }
517 
518 void
519 urtwn_free_rx_list(struct urtwn_softc *sc)
520 {
521 	int i;
522 
523 	/* NB: Caller must abort pipe first. */
524 	for (i = 0; i < URTWN_RX_LIST_COUNT; i++) {
525 		if (sc->rx_data[i].xfer != NULL)
526 			usbd_free_xfer(sc->rx_data[i].xfer);
527 		sc->rx_data[i].xfer = NULL;
528 	}
529 }
530 
531 int
532 urtwn_alloc_tx_list(struct urtwn_softc *sc)
533 {
534 	struct urtwn_tx_data *data;
535 	int i, error = 0;
536 
537 	TAILQ_INIT(&sc->tx_free_list);
538 	for (i = 0; i < URTWN_TX_LIST_COUNT; i++) {
539 		data = &sc->tx_data[i];
540 
541 		data->sc = sc;	/* Backpointer for callbacks. */
542 
543 		data->xfer = usbd_alloc_xfer(sc->sc_udev);
544 		if (data->xfer == NULL) {
545 			printf("%s: could not allocate xfer\n",
546 			    sc->sc_dev.dv_xname);
547 			error = ENOMEM;
548 			break;
549 		}
550 		data->buf = usbd_alloc_buffer(data->xfer, URTWN_TXBUFSZ);
551 		if (data->buf == NULL) {
552 			printf("%s: could not allocate xfer buffer\n",
553 			    sc->sc_dev.dv_xname);
554 			error = ENOMEM;
555 			break;
556 		}
557 		/* Append this Tx buffer to our free list. */
558 		TAILQ_INSERT_TAIL(&sc->tx_free_list, data, next);
559 	}
560 	if (error != 0)
561 		urtwn_free_tx_list(sc);
562 	return (error);
563 }
564 
565 void
566 urtwn_free_tx_list(struct urtwn_softc *sc)
567 {
568 	int i;
569 
570 	/* NB: Caller must abort pipe first. */
571 	for (i = 0; i < URTWN_TX_LIST_COUNT; i++) {
572 		if (sc->tx_data[i].xfer != NULL)
573 			usbd_free_xfer(sc->tx_data[i].xfer);
574 		sc->tx_data[i].xfer = NULL;
575 	}
576 }
577 
578 void
579 urtwn_task(void *arg)
580 {
581 	struct urtwn_softc *sc = arg;
582 	struct urtwn_host_cmd_ring *ring = &sc->cmdq;
583 	struct urtwn_host_cmd *cmd;
584 	int s;
585 
586 	/* Process host commands. */
587 	s = splusb();
588 	while (ring->next != ring->cur) {
589 		cmd = &ring->cmd[ring->next];
590 		splx(s);
591 		/* Invoke callback. */
592 		cmd->cb(sc, cmd->data);
593 		s = splusb();
594 		ring->queued--;
595 		ring->next = (ring->next + 1) % URTWN_HOST_CMD_RING_COUNT;
596 	}
597 	splx(s);
598 }
599 
600 void
601 urtwn_do_async(struct urtwn_softc *sc,
602     void (*cb)(struct urtwn_softc *, void *), void *arg, int len)
603 {
604 	struct urtwn_host_cmd_ring *ring = &sc->cmdq;
605 	struct urtwn_host_cmd *cmd;
606 	int s;
607 
608 	s = splusb();
609 	cmd = &ring->cmd[ring->cur];
610 	cmd->cb = cb;
611 	KASSERT(len <= sizeof(cmd->data));
612 	memcpy(cmd->data, arg, len);
613 	ring->cur = (ring->cur + 1) % URTWN_HOST_CMD_RING_COUNT;
614 
615 	/* If there is no pending command already, schedule a task. */
616 	if (++ring->queued == 1)
617 		usb_add_task(sc->sc_udev, &sc->sc_task);
618 	splx(s);
619 }
620 
621 void
622 urtwn_wait_async(struct urtwn_softc *sc)
623 {
624 	/* Wait for all queued asynchronous commands to complete. */
625 	usb_wait_task(sc->sc_udev, &sc->sc_task);
626 }
627 
628 int
629 urtwn_write_region_1(struct urtwn_softc *sc, uint16_t addr, uint8_t *buf,
630     int len)
631 {
632 	usb_device_request_t req;
633 
634 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
635 	req.bRequest = R92C_REQ_REGS;
636 	USETW(req.wValue, addr);
637 	USETW(req.wIndex, 0);
638 	USETW(req.wLength, len);
639 	return (usbd_do_request(sc->sc_udev, &req, buf));
640 }
641 
642 void
643 urtwn_write_1(struct urtwn_softc *sc, uint16_t addr, uint8_t val)
644 {
645 	urtwn_write_region_1(sc, addr, &val, 1);
646 }
647 
648 void
649 urtwn_write_2(struct urtwn_softc *sc, uint16_t addr, uint16_t val)
650 {
651 	val = htole16(val);
652 	urtwn_write_region_1(sc, addr, (uint8_t *)&val, 2);
653 }
654 
655 void
656 urtwn_write_4(struct urtwn_softc *sc, uint16_t addr, uint32_t val)
657 {
658 	val = htole32(val);
659 	urtwn_write_region_1(sc, addr, (uint8_t *)&val, 4);
660 }
661 
662 int
663 urtwn_read_region_1(struct urtwn_softc *sc, uint16_t addr, uint8_t *buf,
664     int len)
665 {
666 	usb_device_request_t req;
667 
668 	req.bmRequestType = UT_READ_VENDOR_DEVICE;
669 	req.bRequest = R92C_REQ_REGS;
670 	USETW(req.wValue, addr);
671 	USETW(req.wIndex, 0);
672 	USETW(req.wLength, len);
673 	return (usbd_do_request(sc->sc_udev, &req, buf));
674 }
675 
676 uint8_t
677 urtwn_read_1(struct urtwn_softc *sc, uint16_t addr)
678 {
679 	uint8_t val;
680 
681 	if (urtwn_read_region_1(sc, addr, &val, 1) != 0)
682 		return (0xff);
683 	return (val);
684 }
685 
686 uint16_t
687 urtwn_read_2(struct urtwn_softc *sc, uint16_t addr)
688 {
689 	uint16_t val;
690 
691 	if (urtwn_read_region_1(sc, addr, (uint8_t *)&val, 2) != 0)
692 		return (0xffff);
693 	return (letoh16(val));
694 }
695 
696 uint32_t
697 urtwn_read_4(struct urtwn_softc *sc, uint16_t addr)
698 {
699 	uint32_t val;
700 
701 	if (urtwn_read_region_1(sc, addr, (uint8_t *)&val, 4) != 0)
702 		return (0xffffffff);
703 	return (letoh32(val));
704 }
705 
706 int
707 urtwn_fw_cmd(struct urtwn_softc *sc, uint8_t id, const void *buf, int len)
708 {
709 	struct r92c_fw_cmd cmd;
710 	int ntries;
711 
712 	/* Wait for current FW box to be empty. */
713 	for (ntries = 0; ntries < 100; ntries++) {
714 		if (!(urtwn_read_1(sc, R92C_HMETFR) & (1 << sc->fwcur)))
715 			break;
716 		DELAY(1);
717 	}
718 	if (ntries == 100) {
719 		printf("%s: could not send firmware command %d\n",
720 		    sc->sc_dev.dv_xname, id);
721 		return (ETIMEDOUT);
722 	}
723 	memset(&cmd, 0, sizeof(cmd));
724 	cmd.id = id;
725 	if (len > 3)
726 		cmd.id |= R92C_CMD_FLAG_EXT;
727 	KASSERT(len <= sizeof(cmd.msg));
728 	memcpy(cmd.msg, buf, len);
729 
730 	/* Write the first word last since that will trigger the FW. */
731 	urtwn_write_region_1(sc, R92C_HMEBOX_EXT(sc->fwcur),
732 	    (uint8_t *)&cmd + 4, 2);
733 	urtwn_write_region_1(sc, R92C_HMEBOX(sc->fwcur),
734 	    (uint8_t *)&cmd + 0, 4);
735 
736 	sc->fwcur = (sc->fwcur + 1) % R92C_H2C_NBOX;
737 	return (0);
738 }
739 
740 void
741 urtwn_rf_write(struct urtwn_softc *sc, int chain, uint8_t addr, uint32_t val)
742 {
743 	urtwn_bb_write(sc, R92C_LSSI_PARAM(chain),
744 	    SM(R92C_LSSI_PARAM_ADDR, addr) |
745 	    SM(R92C_LSSI_PARAM_DATA, val));
746 }
747 
748 uint32_t
749 urtwn_rf_read(struct urtwn_softc *sc, int chain, uint8_t addr)
750 {
751 	uint32_t reg[R92C_MAX_CHAINS], val;
752 
753 	reg[0] = urtwn_bb_read(sc, R92C_HSSI_PARAM2(0));
754 	if (chain != 0)
755 		reg[chain] = urtwn_bb_read(sc, R92C_HSSI_PARAM2(chain));
756 
757 	urtwn_bb_write(sc, R92C_HSSI_PARAM2(0),
758 	    reg[0] & ~R92C_HSSI_PARAM2_READ_EDGE);
759 	DELAY(1000);
760 
761 	urtwn_bb_write(sc, R92C_HSSI_PARAM2(chain),
762 	    RW(reg[chain], R92C_HSSI_PARAM2_READ_ADDR, addr) |
763 	    R92C_HSSI_PARAM2_READ_EDGE);
764 	DELAY(1000);
765 
766 	urtwn_bb_write(sc, R92C_HSSI_PARAM2(0),
767 	    reg[0] | R92C_HSSI_PARAM2_READ_EDGE);
768 	DELAY(1000);
769 
770 	if (urtwn_bb_read(sc, R92C_HSSI_PARAM1(chain)) & R92C_HSSI_PARAM1_PI)
771 		val = urtwn_bb_read(sc, R92C_HSPI_READBACK(chain));
772 	else
773 		val = urtwn_bb_read(sc, R92C_LSSI_READBACK(chain));
774 	return (MS(val, R92C_LSSI_READBACK_DATA));
775 }
776 
777 void
778 urtwn_cam_write(struct urtwn_softc *sc, uint32_t addr, uint32_t data)
779 {
780 	urtwn_write_4(sc, R92C_CAMWRITE, data);
781 	urtwn_write_4(sc, R92C_CAMCMD,
782 	    R92C_CAMCMD_POLLING | R92C_CAMCMD_WRITE |
783 	    SM(R92C_CAMCMD_ADDR, addr));
784 }
785 
786 int
787 urtwn_llt_write(struct urtwn_softc *sc, uint32_t addr, uint32_t data)
788 {
789 	int ntries;
790 
791 	urtwn_write_4(sc, R92C_LLT_INIT,
792 	    SM(R92C_LLT_INIT_OP, R92C_LLT_INIT_OP_WRITE) |
793 	    SM(R92C_LLT_INIT_ADDR, addr) |
794 	    SM(R92C_LLT_INIT_DATA, data));
795 	/* Wait for write operation to complete. */
796 	for (ntries = 0; ntries < 20; ntries++) {
797 		if (MS(urtwn_read_4(sc, R92C_LLT_INIT), R92C_LLT_INIT_OP) ==
798 		    R92C_LLT_INIT_OP_NO_ACTIVE)
799 			return (0);
800 		DELAY(5);
801 	}
802 	return (ETIMEDOUT);
803 }
804 
805 uint8_t
806 urtwn_efuse_read_1(struct urtwn_softc *sc, uint16_t addr)
807 {
808 	uint32_t reg;
809 	int ntries;
810 
811 	reg = urtwn_read_4(sc, R92C_EFUSE_CTRL);
812 	reg = RW(reg, R92C_EFUSE_CTRL_ADDR, addr);
813 	reg &= ~R92C_EFUSE_CTRL_VALID;
814 	urtwn_write_4(sc, R92C_EFUSE_CTRL, reg);
815 	/* Wait for read operation to complete. */
816 	for (ntries = 0; ntries < 100; ntries++) {
817 		reg = urtwn_read_4(sc, R92C_EFUSE_CTRL);
818 		if (reg & R92C_EFUSE_CTRL_VALID)
819 			return (MS(reg, R92C_EFUSE_CTRL_DATA));
820 		DELAY(5);
821 	}
822 	printf("%s: could not read efuse byte at address 0x%x\n",
823 	    sc->sc_dev.dv_xname, addr);
824 	return (0xff);
825 }
826 
827 void
828 urtwn_efuse_read(struct urtwn_softc *sc)
829 {
830 	uint8_t *rom = (uint8_t *)&sc->rom;
831 	uint16_t addr = 0;
832 	uint32_t reg;
833 	uint8_t off, msk;
834 	int i;
835 
836 	reg = urtwn_read_2(sc, R92C_SYS_ISO_CTRL);
837 	if (!(reg & R92C_SYS_ISO_CTRL_PWC_EV12V)) {
838 		urtwn_write_2(sc, R92C_SYS_ISO_CTRL,
839 		    reg | R92C_SYS_ISO_CTRL_PWC_EV12V);
840 	}
841 	reg = urtwn_read_2(sc, R92C_SYS_FUNC_EN);
842 	if (!(reg & R92C_SYS_FUNC_EN_ELDR)) {
843 		urtwn_write_2(sc, R92C_SYS_FUNC_EN,
844 		    reg | R92C_SYS_FUNC_EN_ELDR);
845 	}
846 	reg = urtwn_read_2(sc, R92C_SYS_CLKR);
847 	if ((reg & (R92C_SYS_CLKR_LOADER_EN | R92C_SYS_CLKR_ANA8M)) !=
848 	    (R92C_SYS_CLKR_LOADER_EN | R92C_SYS_CLKR_ANA8M)) {
849 		urtwn_write_2(sc, R92C_SYS_CLKR,
850 		    reg | R92C_SYS_CLKR_LOADER_EN | R92C_SYS_CLKR_ANA8M);
851 	}
852 	memset(&sc->rom, 0xff, sizeof(sc->rom));
853 	while (addr < 512) {
854 		reg = urtwn_efuse_read_1(sc, addr);
855 		if (reg == 0xff)
856 			break;
857 		addr++;
858 		off = reg >> 4;
859 		msk = reg & 0xf;
860 		for (i = 0; i < 4; i++) {
861 			if (msk & (1 << i))
862 				continue;
863 			rom[off * 8 + i * 2 + 0] =
864 			    urtwn_efuse_read_1(sc, addr);
865 			addr++;
866 			rom[off * 8 + i * 2 + 1] =
867 			    urtwn_efuse_read_1(sc, addr);
868 			addr++;
869 		}
870 	}
871 #ifdef URTWN_DEBUG
872 	if (urtwn_debug >= 2) {
873 		/* Dump ROM content. */
874 		printf("\n");
875 		for (i = 0; i < sizeof(sc->rom); i++)
876 			printf("%02x:", rom[i]);
877 		printf("\n");
878 	}
879 #endif
880 }
881 
882 int
883 urtwn_read_chipid(struct urtwn_softc *sc)
884 {
885 	uint32_t reg;
886 
887 	reg = urtwn_read_4(sc, R92C_SYS_CFG);
888 	if (reg & R92C_SYS_CFG_TRP_VAUX_EN)
889 		return (EIO);
890 
891 	if (reg & R92C_SYS_CFG_TYPE_92C) {
892 		sc->chip |= URTWN_CHIP_92C;
893 		/* Check if it is a castrated 8192C. */
894 		if (MS(urtwn_read_4(sc, R92C_HPON_FSM),
895 		    R92C_HPON_FSM_CHIP_BONDING_ID) ==
896 		    R92C_HPON_FSM_CHIP_BONDING_ID_92C_1T2R)
897 			sc->chip |= URTWN_CHIP_92C_1T2R;
898 	}
899 	if (reg & R92C_SYS_CFG_VENDOR_UMC) {
900 		sc->chip |= URTWN_CHIP_UMC;
901 		if (MS(reg, R92C_SYS_CFG_CHIP_VER_RTL) == 0)
902 			sc->chip |= URTWN_CHIP_UMC_A_CUT;
903 	}
904 	return (0);
905 }
906 
907 void
908 urtwn_read_rom(struct urtwn_softc *sc)
909 {
910 	struct ieee80211com *ic = &sc->sc_ic;
911 	struct r92c_rom *rom = &sc->rom;
912 
913 	/* Read full ROM image. */
914 	urtwn_efuse_read(sc);
915 
916 	/* XXX Weird but this is what the vendor driver does. */
917 	sc->pa_setting = urtwn_efuse_read_1(sc, 0x1fa);
918 	DPRINTF(("PA setting=0x%x\n", sc->pa_setting));
919 
920 	sc->board_type = MS(rom->rf_opt1, R92C_ROM_RF1_BOARD_TYPE);
921 
922 	sc->regulatory = MS(rom->rf_opt1, R92C_ROM_RF1_REGULATORY);
923 	DPRINTF(("regulatory type=%d\n", sc->regulatory));
924 
925 	IEEE80211_ADDR_COPY(ic->ic_myaddr, rom->macaddr);
926 }
927 
928 int
929 urtwn_media_change(struct ifnet *ifp)
930 {
931 	int error;
932 
933 	error = ieee80211_media_change(ifp);
934 	if (error != ENETRESET)
935 		return (error);
936 
937 	if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
938 	    (IFF_UP | IFF_RUNNING)) {
939 		urtwn_stop(ifp);
940 		urtwn_init(ifp);
941 	}
942 	return (0);
943 }
944 
945 /*
946  * Initialize rate adaptation in firmware.
947  */
948 int
949 urtwn_ra_init(struct urtwn_softc *sc)
950 {
951 	static const uint8_t map[] =
952 	    { 2, 4, 11, 22, 12, 18, 24, 36, 48, 72, 96, 108 };
953 	struct ieee80211com *ic = &sc->sc_ic;
954 	struct ieee80211_node *ni = ic->ic_bss;
955 	struct ieee80211_rateset *rs = &ni->ni_rates;
956 	struct r92c_fw_cmd_macid_cfg cmd;
957 	uint32_t rates, basicrates;
958 	uint8_t mode;
959 	int maxrate, maxbasicrate, error, i, j;
960 
961 	/* Get normal and basic rates mask. */
962 	rates = basicrates = 0;
963 	maxrate = maxbasicrate = 0;
964 	for (i = 0; i < rs->rs_nrates; i++) {
965 		/* Convert 802.11 rate to HW rate index. */
966 		for (j = 0; j < nitems(map); j++)
967 			if ((rs->rs_rates[i] & IEEE80211_RATE_VAL) == map[j])
968 				break;
969 		if (j == nitems(map))	/* Unknown rate, skip. */
970 			continue;
971 		rates |= 1 << j;
972 		if (j > maxrate)
973 			maxrate = j;
974 		if (rs->rs_rates[i] & IEEE80211_RATE_BASIC) {
975 			basicrates |= 1 << j;
976 			if (j > maxbasicrate)
977 				maxbasicrate = j;
978 		}
979 	}
980 	if (ic->ic_curmode == IEEE80211_MODE_11B)
981 		mode = R92C_RAID_11B;
982 	else
983 		mode = R92C_RAID_11BG;
984 	DPRINTF(("mode=0x%x rates=0x%08x, basicrates=0x%08x\n",
985 	    mode, rates, basicrates));
986 
987 	/* Set rates mask for group addressed frames. */
988 	cmd.macid = URTWN_MACID_BC | URTWN_MACID_VALID;
989 	cmd.mask = htole32(mode << 28 | basicrates);
990 	error = urtwn_fw_cmd(sc, R92C_CMD_MACID_CONFIG, &cmd, sizeof(cmd));
991 	if (error != 0) {
992 		printf("%s: could not add broadcast station\n",
993 		    sc->sc_dev.dv_xname);
994 		return (error);
995 	}
996 	/* Set initial MRR rate. */
997 	DPRINTF(("maxbasicrate=%d\n", maxbasicrate));
998 	urtwn_write_1(sc, R92C_INIDATA_RATE_SEL(URTWN_MACID_BC),
999 	    maxbasicrate);
1000 
1001 	/* Set rates mask for unicast frames. */
1002 	cmd.macid = URTWN_MACID_BSS | URTWN_MACID_VALID;
1003 	cmd.mask = htole32(mode << 28 | rates);
1004 	error = urtwn_fw_cmd(sc, R92C_CMD_MACID_CONFIG, &cmd, sizeof(cmd));
1005 	if (error != 0) {
1006 		printf("%s: could not add BSS station\n",
1007 		    sc->sc_dev.dv_xname);
1008 		return (error);
1009 	}
1010 	/* Set initial MRR rate. */
1011 	DPRINTF(("maxrate=%d\n", maxrate));
1012 	urtwn_write_1(sc, R92C_INIDATA_RATE_SEL(URTWN_MACID_BSS),
1013 	    maxrate);
1014 
1015 	/* Indicate highest supported rate. */
1016 	ni->ni_txrate = rs->rs_nrates - 1;
1017 	return (0);
1018 }
1019 
1020 void
1021 urtwn_tsf_sync_enable(struct urtwn_softc *sc)
1022 {
1023 	struct ieee80211_node *ni = sc->sc_ic.ic_bss;
1024 	uint64_t tsf;
1025 
1026 	/* Enable TSF synchronization. */
1027 	urtwn_write_1(sc, R92C_BCN_CTRL,
1028 	    urtwn_read_1(sc, R92C_BCN_CTRL) & ~R92C_BCN_CTRL_DIS_TSF_UDT0);
1029 
1030 	urtwn_write_1(sc, R92C_BCN_CTRL,
1031 	    urtwn_read_1(sc, R92C_BCN_CTRL) & ~R92C_BCN_CTRL_EN_BCN);
1032 
1033 	/* Set initial TSF. */
1034 	memcpy(&tsf, ni->ni_tstamp, 8);
1035 	tsf = letoh64(tsf);
1036 	tsf = tsf - (tsf % (ni->ni_intval * IEEE80211_DUR_TU));
1037 	tsf -= IEEE80211_DUR_TU;
1038 	urtwn_write_4(sc, R92C_TSFTR + 0, tsf);
1039 	urtwn_write_4(sc, R92C_TSFTR + 4, tsf >> 32);
1040 
1041 	urtwn_write_1(sc, R92C_BCN_CTRL,
1042 	    urtwn_read_1(sc, R92C_BCN_CTRL) | R92C_BCN_CTRL_EN_BCN);
1043 }
1044 
1045 void
1046 urtwn_set_led(struct urtwn_softc *sc, int led, int on)
1047 {
1048 	uint8_t reg;
1049 
1050 	if (led == URTWN_LED_LINK) {
1051 		reg = urtwn_read_1(sc, R92C_LEDCFG0) & 0x70;
1052 		if (!on)
1053 			reg |= R92C_LEDCFG0_DIS;
1054 		urtwn_write_1(sc, R92C_LEDCFG0, reg);
1055 		sc->ledlink = on;	/* Save LED state. */
1056 	}
1057 }
1058 
1059 void
1060 urtwn_calib_to(void *arg)
1061 {
1062 	struct urtwn_softc *sc = arg;
1063 
1064 	if (usbd_is_dying(sc->sc_udev))
1065 		return;
1066 
1067 	usbd_ref_incr(sc->sc_udev);
1068 
1069 	/* Do it in a process context. */
1070 	urtwn_do_async(sc, urtwn_calib_cb, NULL, 0);
1071 
1072 	usbd_ref_decr(sc->sc_udev);
1073 }
1074 
1075 /* ARGSUSED */
1076 void
1077 urtwn_calib_cb(struct urtwn_softc *sc, void *arg)
1078 {
1079 	struct r92c_fw_cmd_rssi cmd;
1080 
1081 	if (sc->avg_pwdb != -1) {
1082 		/* Indicate Rx signal strength to FW for rate adaptation. */
1083 		memset(&cmd, 0, sizeof(cmd));
1084 		cmd.macid = 0;	/* BSS. */
1085 		cmd.pwdb = sc->avg_pwdb;
1086 		DPRINTFN(3, ("sending RSSI command avg=%d\n", sc->avg_pwdb));
1087 		urtwn_fw_cmd(sc, R92C_CMD_RSSI_SETTING, &cmd, sizeof(cmd));
1088 	}
1089 
1090 	/* Do temperature compensation. */
1091 	urtwn_temp_calib(sc);
1092 
1093 	if (!usbd_is_dying(sc->sc_udev))
1094 		timeout_add_sec(&sc->calib_to, 2);
1095 }
1096 
1097 void
1098 urtwn_next_scan(void *arg)
1099 {
1100 	struct urtwn_softc *sc = arg;
1101 	struct ieee80211com *ic = &sc->sc_ic;
1102 	int s;
1103 
1104 	if (usbd_is_dying(sc->sc_udev))
1105 		return;
1106 
1107 	usbd_ref_incr(sc->sc_udev);
1108 
1109 	s = splnet();
1110 	if (ic->ic_state == IEEE80211_S_SCAN)
1111 		ieee80211_next_scan(&ic->ic_if);
1112 	splx(s);
1113 
1114 	usbd_ref_decr(sc->sc_udev);
1115 }
1116 
1117 int
1118 urtwn_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
1119 {
1120 	struct urtwn_softc *sc = ic->ic_softc;
1121 	struct urtwn_cmd_newstate cmd;
1122 
1123 	/* Do it in a process context. */
1124 	cmd.state = nstate;
1125 	cmd.arg = arg;
1126 	urtwn_do_async(sc, urtwn_newstate_cb, &cmd, sizeof(cmd));
1127 	return (0);
1128 }
1129 
1130 void
1131 urtwn_newstate_cb(struct urtwn_softc *sc, void *arg)
1132 {
1133 	struct urtwn_cmd_newstate *cmd = arg;
1134 	struct ieee80211com *ic = &sc->sc_ic;
1135 	struct ieee80211_node *ni;
1136 	enum ieee80211_state ostate;
1137 	uint32_t reg;
1138 	int s;
1139 
1140 	s = splnet();
1141 	ostate = ic->ic_state;
1142 	DPRINTF(("newstate %d -> %d\n", ostate, cmd->state));
1143 
1144 	if (ostate == IEEE80211_S_RUN) {
1145 		/* Stop calibration. */
1146 		timeout_del(&sc->calib_to);
1147 
1148 		/* Turn link LED off. */
1149 		urtwn_set_led(sc, URTWN_LED_LINK, 0);
1150 
1151 		/* Set media status to 'No Link'. */
1152 		reg = urtwn_read_4(sc, R92C_CR);
1153 		reg = RW(reg, R92C_CR_NETTYPE, R92C_CR_NETTYPE_NOLINK);
1154 		urtwn_write_4(sc, R92C_CR, reg);
1155 
1156 		/* Stop Rx of data frames. */
1157 		urtwn_write_2(sc, R92C_RXFLTMAP2, 0);
1158 
1159 		/* Rest TSF. */
1160 		urtwn_write_1(sc, R92C_DUAL_TSF_RST, 0x03);
1161 
1162 		/* Disable TSF synchronization. */
1163 		urtwn_write_1(sc, R92C_BCN_CTRL,
1164 		    urtwn_read_1(sc, R92C_BCN_CTRL) |
1165 		    R92C_BCN_CTRL_DIS_TSF_UDT0);
1166 
1167 		/* Reset EDCA parameters. */
1168 		urtwn_write_4(sc, R92C_EDCA_VO_PARAM, 0x002f3217);
1169 		urtwn_write_4(sc, R92C_EDCA_VI_PARAM, 0x005e4317);
1170 		urtwn_write_4(sc, R92C_EDCA_BE_PARAM, 0x00105320);
1171 		urtwn_write_4(sc, R92C_EDCA_BK_PARAM, 0x0000a444);
1172 	}
1173 	switch (cmd->state) {
1174 	case IEEE80211_S_INIT:
1175 		/* Turn link LED off. */
1176 		urtwn_set_led(sc, URTWN_LED_LINK, 0);
1177 		break;
1178 	case IEEE80211_S_SCAN:
1179 		if (ostate != IEEE80211_S_SCAN) {
1180 			/* Allow Rx from any BSSID. */
1181 			urtwn_write_4(sc, R92C_RCR,
1182 			    urtwn_read_4(sc, R92C_RCR) &
1183 			    ~(R92C_RCR_CBSSID_DATA | R92C_RCR_CBSSID_BCN));
1184 
1185 			/* Set gain for scanning. */
1186 			reg = urtwn_bb_read(sc, R92C_OFDM0_AGCCORE1(0));
1187 			reg = RW(reg, R92C_OFDM0_AGCCORE1_GAIN, 0x20);
1188 			urtwn_bb_write(sc, R92C_OFDM0_AGCCORE1(0), reg);
1189 
1190 			reg = urtwn_bb_read(sc, R92C_OFDM0_AGCCORE1(1));
1191 			reg = RW(reg, R92C_OFDM0_AGCCORE1_GAIN, 0x20);
1192 			urtwn_bb_write(sc, R92C_OFDM0_AGCCORE1(1), reg);
1193 		}
1194 
1195 		/* Make link LED blink during scan. */
1196 		urtwn_set_led(sc, URTWN_LED_LINK, !sc->ledlink);
1197 
1198 		/* Pause AC Tx queues. */
1199 		urtwn_write_1(sc, R92C_TXPAUSE,
1200 		    urtwn_read_1(sc, R92C_TXPAUSE) | 0x0f);
1201 
1202 		urtwn_set_chan(sc, ic->ic_bss->ni_chan, NULL);
1203 		if (!usbd_is_dying(sc->sc_udev))
1204 			timeout_add_msec(&sc->scan_to, 200);
1205 		break;
1206 
1207 	case IEEE80211_S_AUTH:
1208 		/* Set initial gain under link. */
1209 		reg = urtwn_bb_read(sc, R92C_OFDM0_AGCCORE1(0));
1210 		reg = RW(reg, R92C_OFDM0_AGCCORE1_GAIN, 0x32);
1211 		urtwn_bb_write(sc, R92C_OFDM0_AGCCORE1(0), reg);
1212 
1213 		reg = urtwn_bb_read(sc, R92C_OFDM0_AGCCORE1(1));
1214 		reg = RW(reg, R92C_OFDM0_AGCCORE1_GAIN, 0x32);
1215 		urtwn_bb_write(sc, R92C_OFDM0_AGCCORE1(1), reg);
1216 
1217 		urtwn_set_chan(sc, ic->ic_bss->ni_chan, NULL);
1218 		break;
1219 	case IEEE80211_S_ASSOC:
1220 		break;
1221 	case IEEE80211_S_RUN:
1222 		if (ic->ic_opmode == IEEE80211_M_MONITOR) {
1223 			urtwn_set_chan(sc, ic->ic_ibss_chan, NULL);
1224 
1225 			/* Enable Rx of data frames. */
1226 			urtwn_write_2(sc, R92C_RXFLTMAP2, 0xffff);
1227 
1228 			/* Turn link LED on. */
1229 			urtwn_set_led(sc, URTWN_LED_LINK, 1);
1230 			break;
1231 		}
1232 		ni = ic->ic_bss;
1233 
1234 		/* Set media status to 'Associated'. */
1235 		reg = urtwn_read_4(sc, R92C_CR);
1236 		reg = RW(reg, R92C_CR_NETTYPE, R92C_CR_NETTYPE_INFRA);
1237 		urtwn_write_4(sc, R92C_CR, reg);
1238 
1239 		/* Set BSSID. */
1240 		urtwn_write_4(sc, R92C_BSSID + 0, LE_READ_4(&ni->ni_bssid[0]));
1241 		urtwn_write_4(sc, R92C_BSSID + 4, LE_READ_2(&ni->ni_bssid[4]));
1242 
1243 		if (ic->ic_curmode == IEEE80211_MODE_11B)
1244 			urtwn_write_1(sc, R92C_INIRTS_RATE_SEL, 0);
1245 		else	/* 802.11b/g */
1246 			urtwn_write_1(sc, R92C_INIRTS_RATE_SEL, 3);
1247 
1248 		/* Enable Rx of data frames. */
1249 		urtwn_write_2(sc, R92C_RXFLTMAP2, 0xffff);
1250 
1251 		/* Flush all AC queues. */
1252 		urtwn_write_1(sc, R92C_TXPAUSE, 0);
1253 
1254 		/* Set beacon interval. */
1255 		urtwn_write_2(sc, R92C_BCN_INTERVAL, ni->ni_intval);
1256 
1257 		/* Allow Rx from our BSSID only. */
1258 		urtwn_write_4(sc, R92C_RCR,
1259 		    urtwn_read_4(sc, R92C_RCR) |
1260 		    R92C_RCR_CBSSID_DATA | R92C_RCR_CBSSID_BCN);
1261 
1262 		/* Enable TSF synchronization. */
1263 		urtwn_tsf_sync_enable(sc);
1264 
1265 		urtwn_write_1(sc, R92C_SIFS_CCK + 1, 10);
1266 		urtwn_write_1(sc, R92C_SIFS_OFDM + 1, 10);
1267 		urtwn_write_1(sc, R92C_SPEC_SIFS + 1, 10);
1268 		urtwn_write_1(sc, R92C_MAC_SPEC_SIFS + 1, 10);
1269 		urtwn_write_1(sc, R92C_R2T_SIFS + 1, 10);
1270 		urtwn_write_1(sc, R92C_T2T_SIFS + 1, 10);
1271 
1272 		/* Intialize rate adaptation. */
1273 		urtwn_ra_init(sc);
1274 		/* Turn link LED on. */
1275 		urtwn_set_led(sc, URTWN_LED_LINK, 1);
1276 
1277 		sc->avg_pwdb = -1;	/* Reset average RSSI. */
1278 		/* Reset temperature calibration state machine. */
1279 		sc->thcal_state = 0;
1280 		sc->thcal_lctemp = 0;
1281 		/* Start periodic calibration. */
1282 		if (!usbd_is_dying(sc->sc_udev))
1283 			timeout_add_sec(&sc->calib_to, 2);
1284 		break;
1285 	}
1286 	(void)sc->sc_newstate(ic, cmd->state, cmd->arg);
1287 	splx(s);
1288 }
1289 
1290 void
1291 urtwn_updateedca(struct ieee80211com *ic)
1292 {
1293 	/* Do it in a process context. */
1294 	urtwn_do_async(ic->ic_softc, urtwn_updateedca_cb, NULL, 0);
1295 }
1296 
1297 /* ARGSUSED */
1298 void
1299 urtwn_updateedca_cb(struct urtwn_softc *sc, void *arg)
1300 {
1301 	const uint16_t aci2reg[EDCA_NUM_AC] = {
1302 		R92C_EDCA_BE_PARAM,
1303 		R92C_EDCA_BK_PARAM,
1304 		R92C_EDCA_VI_PARAM,
1305 		R92C_EDCA_VO_PARAM
1306 	};
1307 	struct ieee80211com *ic = &sc->sc_ic;
1308 	struct ieee80211_edca_ac_params *ac;
1309 	int s, aci, aifs, slottime;
1310 
1311 	s = splnet();
1312 	slottime = (ic->ic_flags & IEEE80211_F_SHSLOT) ? 9 : 20;
1313 	for (aci = 0; aci < EDCA_NUM_AC; aci++) {
1314 		ac = &ic->ic_edca_ac[aci];
1315 		/* AIFS[AC] = AIFSN[AC] * aSlotTime + aSIFSTime. */
1316 		aifs = ac->ac_aifsn * slottime + 10;
1317 		urtwn_write_4(sc, aci2reg[aci],
1318 		    SM(R92C_EDCA_PARAM_TXOP, ac->ac_txoplimit) |
1319 		    SM(R92C_EDCA_PARAM_ECWMIN, ac->ac_ecwmin) |
1320 		    SM(R92C_EDCA_PARAM_ECWMAX, ac->ac_ecwmax) |
1321 		    SM(R92C_EDCA_PARAM_AIFS, aifs));
1322 	}
1323 	splx(s);
1324 }
1325 
1326 int
1327 urtwn_set_key(struct ieee80211com *ic, struct ieee80211_node *ni,
1328     struct ieee80211_key *k)
1329 {
1330 	struct urtwn_softc *sc = ic->ic_softc;
1331 	struct urtwn_cmd_key cmd;
1332 
1333 	/* Defer setting of WEP keys until interface is brought up. */
1334 	if ((ic->ic_if.if_flags & (IFF_UP | IFF_RUNNING)) !=
1335 	    (IFF_UP | IFF_RUNNING))
1336 		return (0);
1337 
1338 	/* Do it in a process context. */
1339 	cmd.key = *k;
1340 	cmd.associd = (ni != NULL) ? ni->ni_associd : 0;
1341 	urtwn_do_async(sc, urtwn_set_key_cb, &cmd, sizeof(cmd));
1342 	return (0);
1343 }
1344 
1345 void
1346 urtwn_set_key_cb(struct urtwn_softc *sc, void *arg)
1347 {
1348 	static const uint8_t etherzeroaddr[6] = { 0 };
1349 	struct ieee80211com *ic = &sc->sc_ic;
1350 	struct urtwn_cmd_key *cmd = arg;
1351 	struct ieee80211_key *k = &cmd->key;
1352 	const uint8_t *macaddr;
1353 	uint8_t keybuf[16], algo;
1354 	int i, entry;
1355 
1356 	/* Map net80211 cipher to HW crypto algorithm. */
1357 	switch (k->k_cipher) {
1358 	case IEEE80211_CIPHER_WEP40:
1359 		algo = R92C_CAM_ALGO_WEP40;
1360 		break;
1361 	case IEEE80211_CIPHER_WEP104:
1362 		algo = R92C_CAM_ALGO_WEP104;
1363 		break;
1364 	case IEEE80211_CIPHER_TKIP:
1365 		algo = R92C_CAM_ALGO_TKIP;
1366 		break;
1367 	case IEEE80211_CIPHER_CCMP:
1368 		algo = R92C_CAM_ALGO_AES;
1369 		break;
1370 	default:
1371 		return;
1372 	}
1373 	if (k->k_flags & IEEE80211_KEY_GROUP) {
1374 		macaddr = etherzeroaddr;
1375 		entry = k->k_id;
1376 	} else {
1377 		macaddr = ic->ic_bss->ni_macaddr;
1378 		entry = 4;
1379 	}
1380 	/* Write key. */
1381 	memset(keybuf, 0, sizeof(keybuf));
1382 	memcpy(keybuf, k->k_key, MIN(k->k_len, sizeof(keybuf)));
1383 	for (i = 0; i < 4; i++) {
1384 		urtwn_cam_write(sc, R92C_CAM_KEY(entry, i),
1385 		    LE_READ_4(&keybuf[i * 4]));
1386 	}
1387 	/* Write CTL0 last since that will validate the CAM entry. */
1388 	urtwn_cam_write(sc, R92C_CAM_CTL1(entry),
1389 	    LE_READ_4(&macaddr[2]));
1390 	urtwn_cam_write(sc, R92C_CAM_CTL0(entry),
1391 	    SM(R92C_CAM_ALGO, algo) |
1392 	    SM(R92C_CAM_KEYID, k->k_id) |
1393 	    SM(R92C_CAM_MACLO, LE_READ_2(&macaddr[0])) |
1394 	    R92C_CAM_VALID);
1395 }
1396 
1397 void
1398 urtwn_delete_key(struct ieee80211com *ic, struct ieee80211_node *ni,
1399     struct ieee80211_key *k)
1400 {
1401 	struct urtwn_softc *sc = ic->ic_softc;
1402 	struct urtwn_cmd_key cmd;
1403 
1404 	if (!(ic->ic_if.if_flags & IFF_RUNNING) ||
1405 	    ic->ic_state != IEEE80211_S_RUN)
1406 		return;	/* Nothing to do. */
1407 
1408 	/* Do it in a process context. */
1409 	cmd.key = *k;
1410 	cmd.associd = (ni != NULL) ? ni->ni_associd : 0;
1411 	urtwn_do_async(sc, urtwn_delete_key_cb, &cmd, sizeof(cmd));
1412 }
1413 
1414 void
1415 urtwn_delete_key_cb(struct urtwn_softc *sc, void *arg)
1416 {
1417 	struct urtwn_cmd_key *cmd = arg;
1418 	struct ieee80211_key *k = &cmd->key;
1419 	int i, entry;
1420 
1421 	if (k->k_flags & IEEE80211_KEY_GROUP)
1422 		entry = k->k_id;
1423 	else
1424 		entry = 4;
1425 	urtwn_cam_write(sc, R92C_CAM_CTL0(entry), 0);
1426 	urtwn_cam_write(sc, R92C_CAM_CTL1(entry), 0);
1427 	/* Clear key. */
1428 	for (i = 0; i < 4; i++)
1429 		urtwn_cam_write(sc, R92C_CAM_KEY(entry, i), 0);
1430 }
1431 
1432 void
1433 urtwn_update_avgrssi(struct urtwn_softc *sc, int rate, int8_t rssi)
1434 {
1435 	int pwdb;
1436 
1437 	/* Convert antenna signal to percentage. */
1438 	if (rssi <= -100 || rssi >= 20)
1439 		pwdb = 0;
1440 	else if (rssi >= 0)
1441 		pwdb = 100;
1442 	else
1443 		pwdb = 100 + rssi;
1444 	if (rate <= 3) {
1445 		/* CCK gain is smaller than OFDM/MCS gain. */
1446 		pwdb += 6;
1447 		if (pwdb > 100)
1448 			pwdb = 100;
1449 		if (pwdb <= 14)
1450 			pwdb -= 4;
1451 		else if (pwdb <= 26)
1452 			pwdb -= 8;
1453 		else if (pwdb <= 34)
1454 			pwdb -= 6;
1455 		else if (pwdb <= 42)
1456 			pwdb -= 2;
1457 	}
1458 	if (sc->avg_pwdb == -1)	/* Init. */
1459 		sc->avg_pwdb = pwdb;
1460 	else if (sc->avg_pwdb < pwdb)
1461 		sc->avg_pwdb = ((sc->avg_pwdb * 19 + pwdb) / 20) + 1;
1462 	else
1463 		sc->avg_pwdb = ((sc->avg_pwdb * 19 + pwdb) / 20);
1464 	DPRINTFN(4, ("PWDB=%d EMA=%d\n", pwdb, sc->avg_pwdb));
1465 }
1466 
1467 int8_t
1468 urtwn_get_rssi(struct urtwn_softc *sc, int rate, void *physt)
1469 {
1470 	static const int8_t cckoff[] = { 16, -12, -26, -46 };
1471 	struct r92c_rx_phystat *phy;
1472 	struct r92c_rx_cck *cck;
1473 	uint8_t rpt;
1474 	int8_t rssi;
1475 
1476 	if (rate <= 3) {
1477 		cck = (struct r92c_rx_cck *)physt;
1478 		if (sc->sc_flags & URTWN_FLAG_CCK_HIPWR) {
1479 			rpt = (cck->agc_rpt >> 5) & 0x3;
1480 			rssi = (cck->agc_rpt & 0x1f) << 1;
1481 		} else {
1482 			rpt = (cck->agc_rpt >> 6) & 0x3;
1483 			rssi = cck->agc_rpt & 0x3e;
1484 		}
1485 		rssi = cckoff[rpt] - rssi;
1486 	} else {	/* OFDM/HT. */
1487 		phy = (struct r92c_rx_phystat *)physt;
1488 		rssi = ((letoh32(phy->phydw1) >> 1) & 0x7f) - 110;
1489 	}
1490 	return (rssi);
1491 }
1492 
1493 void
1494 urtwn_rx_frame(struct urtwn_softc *sc, uint8_t *buf, int pktlen)
1495 {
1496 	struct ieee80211com *ic = &sc->sc_ic;
1497 	struct ifnet *ifp = &ic->ic_if;
1498 	struct ieee80211_rxinfo rxi;
1499 	struct ieee80211_frame *wh;
1500 	struct ieee80211_node *ni;
1501 	struct r92c_rx_stat *stat;
1502 	uint32_t rxdw0, rxdw3;
1503 	struct mbuf *m;
1504 	uint8_t rate;
1505 	int8_t rssi = 0;
1506 	int s, infosz;
1507 
1508 	stat = (struct r92c_rx_stat *)buf;
1509 	rxdw0 = letoh32(stat->rxdw0);
1510 	rxdw3 = letoh32(stat->rxdw3);
1511 
1512 	if (__predict_false(rxdw0 & (R92C_RXDW0_CRCERR | R92C_RXDW0_ICVERR))) {
1513 		/*
1514 		 * This should not happen since we setup our Rx filter
1515 		 * to not receive these frames.
1516 		 */
1517 		ifp->if_ierrors++;
1518 		return;
1519 	}
1520 	if (__predict_false(pktlen < sizeof(*wh) || pktlen > MCLBYTES)) {
1521 		ifp->if_ierrors++;
1522 		return;
1523 	}
1524 
1525 	rate = MS(rxdw3, R92C_RXDW3_RATE);
1526 	infosz = MS(rxdw0, R92C_RXDW0_INFOSZ) * 8;
1527 
1528 	/* Get RSSI from PHY status descriptor if present. */
1529 	if (infosz != 0 && (rxdw0 & R92C_RXDW0_PHYST)) {
1530 		rssi = urtwn_get_rssi(sc, rate, &stat[1]);
1531 		/* Update our average RSSI. */
1532 		urtwn_update_avgrssi(sc, rate, rssi);
1533 	}
1534 
1535 	DPRINTFN(5, ("Rx frame len=%d rate=%d infosz=%d rssi=%d\n",
1536 	    pktlen, rate, infosz, rssi));
1537 
1538 	MGETHDR(m, M_DONTWAIT, MT_DATA);
1539 	if (__predict_false(m == NULL)) {
1540 		ifp->if_ierrors++;
1541 		return;
1542 	}
1543 	if (pktlen > MHLEN) {
1544 		MCLGET(m, M_DONTWAIT);
1545 		if (__predict_false(!(m->m_flags & M_EXT))) {
1546 			ifp->if_ierrors++;
1547 			m_freem(m);
1548 			return;
1549 		}
1550 	}
1551 	/* Finalize mbuf. */
1552 	m->m_pkthdr.rcvif = ifp;
1553 	wh = (struct ieee80211_frame *)((uint8_t *)&stat[1] + infosz);
1554 	memcpy(mtod(m, uint8_t *), wh, pktlen);
1555 	m->m_pkthdr.len = m->m_len = pktlen;
1556 
1557 	s = splnet();
1558 #if NBPFILTER > 0
1559 	if (__predict_false(sc->sc_drvbpf != NULL)) {
1560 		struct urtwn_rx_radiotap_header *tap = &sc->sc_rxtap;
1561 		struct mbuf mb;
1562 
1563 		tap->wr_flags = 0;
1564 		/* Map HW rate index to 802.11 rate. */
1565 		tap->wr_flags = 2;
1566 		if (!(rxdw3 & R92C_RXDW3_HT)) {
1567 			switch (rate) {
1568 			/* CCK. */
1569 			case  0: tap->wr_rate =   2; break;
1570 			case  1: tap->wr_rate =   4; break;
1571 			case  2: tap->wr_rate =  11; break;
1572 			case  3: tap->wr_rate =  22; break;
1573 			/* OFDM. */
1574 			case  4: tap->wr_rate =  12; break;
1575 			case  5: tap->wr_rate =  18; break;
1576 			case  6: tap->wr_rate =  24; break;
1577 			case  7: tap->wr_rate =  36; break;
1578 			case  8: tap->wr_rate =  48; break;
1579 			case  9: tap->wr_rate =  72; break;
1580 			case 10: tap->wr_rate =  96; break;
1581 			case 11: tap->wr_rate = 108; break;
1582 			}
1583 		} else if (rate >= 12) {	/* MCS0~15. */
1584 			/* Bit 7 set means HT MCS instead of rate. */
1585 			tap->wr_rate = 0x80 | (rate - 12);
1586 		}
1587 		tap->wr_dbm_antsignal = rssi;
1588 		tap->wr_chan_freq = htole16(ic->ic_ibss_chan->ic_freq);
1589 		tap->wr_chan_flags = htole16(ic->ic_ibss_chan->ic_flags);
1590 
1591 		mb.m_data = (caddr_t)tap;
1592 		mb.m_len = sc->sc_rxtap_len;
1593 		mb.m_next = m;
1594 		mb.m_nextpkt = NULL;
1595 		mb.m_type = 0;
1596 		mb.m_flags = 0;
1597 		bpf_mtap(sc->sc_drvbpf, &mb, BPF_DIRECTION_IN);
1598 	}
1599 #endif
1600 
1601 	ni = ieee80211_find_rxnode(ic, wh);
1602 	rxi.rxi_flags = 0;
1603 	rxi.rxi_rssi = rssi;
1604 	rxi.rxi_tstamp = 0;	/* Unused. */
1605 	ieee80211_input(ifp, m, ni, &rxi);
1606 	/* Node is no longer needed. */
1607 	ieee80211_release_node(ic, ni);
1608 	splx(s);
1609 }
1610 
1611 void
1612 urtwn_rxeof(usbd_xfer_handle xfer, usbd_private_handle priv,
1613     usbd_status status)
1614 {
1615 	struct urtwn_rx_data *data = priv;
1616 	struct urtwn_softc *sc = data->sc;
1617 	struct r92c_rx_stat *stat;
1618 	uint32_t rxdw0;
1619 	uint8_t *buf;
1620 	int len, totlen, pktlen, infosz, npkts;
1621 
1622 	if (__predict_false(status != USBD_NORMAL_COMPLETION)) {
1623 		DPRINTF(("RX status=%d\n", status));
1624 		if (status == USBD_STALLED)
1625 			usbd_clear_endpoint_stall_async(sc->rx_pipe);
1626 		if (status != USBD_CANCELLED)
1627 			goto resubmit;
1628 		return;
1629 	}
1630 	usbd_get_xfer_status(xfer, NULL, NULL, &len, NULL);
1631 
1632 	if (__predict_false(len < sizeof(*stat))) {
1633 		DPRINTF(("xfer too short %d\n", len));
1634 		goto resubmit;
1635 	}
1636 	buf = data->buf;
1637 
1638 	/* Get the number of encapsulated frames. */
1639 	stat = (struct r92c_rx_stat *)buf;
1640 	npkts = MS(letoh32(stat->rxdw2), R92C_RXDW2_PKTCNT);
1641 	DPRINTFN(6, ("Rx %d frames in one chunk\n", npkts));
1642 
1643 	/* Process all of them. */
1644 	while (npkts-- > 0) {
1645 		if (__predict_false(len < sizeof(*stat)))
1646 			break;
1647 		stat = (struct r92c_rx_stat *)buf;
1648 		rxdw0 = letoh32(stat->rxdw0);
1649 
1650 		pktlen = MS(rxdw0, R92C_RXDW0_PKTLEN);
1651 		if (__predict_false(pktlen == 0))
1652 			break;
1653 
1654 		infosz = MS(rxdw0, R92C_RXDW0_INFOSZ) * 8;
1655 
1656 		/* Make sure everything fits in xfer. */
1657 		totlen = sizeof(*stat) + infosz + pktlen;
1658 		if (__predict_false(totlen > len))
1659 			break;
1660 
1661 		/* Process 802.11 frame. */
1662 		urtwn_rx_frame(sc, buf, pktlen);
1663 
1664 		/* Next chunk is 128-byte aligned. */
1665 		totlen = (totlen + 127) & ~127;
1666 		buf += totlen;
1667 		len -= totlen;
1668 	}
1669 
1670  resubmit:
1671 	/* Setup a new transfer. */
1672 	usbd_setup_xfer(xfer, sc->rx_pipe, data, data->buf, URTWN_RXBUFSZ,
1673 	    USBD_SHORT_XFER_OK | USBD_NO_COPY, USBD_NO_TIMEOUT, urtwn_rxeof);
1674 	(void)usbd_transfer(xfer);
1675 }
1676 
1677 void
1678 urtwn_txeof(usbd_xfer_handle xfer, usbd_private_handle priv,
1679     usbd_status status)
1680 {
1681 	struct urtwn_tx_data *data = priv;
1682 	struct urtwn_softc *sc = data->sc;
1683 	struct ifnet *ifp = &sc->sc_ic.ic_if;
1684 	int s;
1685 
1686 	s = splnet();
1687 	/* Put this Tx buffer back to our free list. */
1688 	TAILQ_INSERT_TAIL(&sc->tx_free_list, data, next);
1689 
1690 	if (__predict_false(status != USBD_NORMAL_COMPLETION)) {
1691 		DPRINTF(("TX status=%d\n", status));
1692 		if (status == USBD_STALLED)
1693 			usbd_clear_endpoint_stall_async(data->pipe);
1694 		ifp->if_oerrors++;
1695 		splx(s);
1696 		return;
1697 	}
1698 	sc->sc_tx_timer = 0;
1699 	ifp->if_opackets++;
1700 
1701 	/* We just released a Tx buffer, notify Tx. */
1702 	if (ifp->if_flags & IFF_OACTIVE) {
1703 		ifp->if_flags &= ~IFF_OACTIVE;
1704 		urtwn_start(ifp);
1705 	}
1706 	splx(s);
1707 }
1708 
1709 int
1710 urtwn_tx(struct urtwn_softc *sc, struct mbuf *m, struct ieee80211_node *ni)
1711 {
1712 	struct ieee80211com *ic = &sc->sc_ic;
1713 	struct ieee80211_frame *wh;
1714 	struct ieee80211_key *k = NULL;
1715 	struct urtwn_tx_data *data;
1716 	struct r92c_tx_desc *txd;
1717 	usbd_pipe_handle pipe;
1718 	uint16_t qos, sum;
1719 	uint8_t raid, type, tid, qid;
1720 	int i, hasqos, xferlen, error;
1721 
1722 	wh = mtod(m, struct ieee80211_frame *);
1723 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
1724 
1725 	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
1726 		k = ieee80211_get_txkey(ic, wh, ni);
1727 		if ((m = ieee80211_encrypt(ic, m, k)) == NULL)
1728 			return (ENOBUFS);
1729 		wh = mtod(m, struct ieee80211_frame *);
1730 	}
1731 
1732 	if ((hasqos = ieee80211_has_qos(wh))) {
1733 		qos = ieee80211_get_qos(wh);
1734 		tid = qos & IEEE80211_QOS_TID;
1735 		qid = ieee80211_up_to_ac(ic, tid);
1736 	} else if (type != IEEE80211_FC0_TYPE_DATA) {
1737 		/* Use AC VO for management frames. */
1738 		qid = EDCA_AC_VO;
1739 	} else
1740 		qid = EDCA_AC_BE;
1741 
1742 	/* Get the USB pipe to use for this AC. */
1743 	pipe = sc->tx_pipe[sc->ac2idx[qid]];
1744 
1745 	/* Grab a Tx buffer from our free list. */
1746 	data = TAILQ_FIRST(&sc->tx_free_list);
1747 	TAILQ_REMOVE(&sc->tx_free_list, data, next);
1748 
1749 	/* Fill Tx descriptor. */
1750 	txd = (struct r92c_tx_desc *)data->buf;
1751 	memset(txd, 0, sizeof(*txd));
1752 
1753 	txd->txdw0 |= htole32(
1754 	    SM(R92C_TXDW0_PKTLEN, m->m_pkthdr.len) |
1755 	    SM(R92C_TXDW0_OFFSET, sizeof(*txd)) |
1756 	    R92C_TXDW0_OWN | R92C_TXDW0_FSG | R92C_TXDW0_LSG);
1757 	if (IEEE80211_IS_MULTICAST(wh->i_addr1))
1758 		txd->txdw0 |= htole32(R92C_TXDW0_BMCAST);
1759 
1760 #ifdef notyet
1761 	if (k != NULL) {
1762 		switch (k->k_cipher) {
1763 		case IEEE80211_CIPHER_WEP40:
1764 		case IEEE80211_CIPHER_WEP104:
1765 		case IEEE80211_CIPHER_TKIP:
1766 			cipher = R92C_TXDW1_CIPHER_RC4;
1767 			break;
1768 		case IEEE80211_CIPHER_CCMP:
1769 			cipher = R92C_TXDW1_CIPHER_AES;
1770 			break;
1771 		default:
1772 			cipher = R92C_TXDW1_CIPHER_NONE;
1773 		}
1774 		txd->txdw1 |= htole32(SM(R92C_TXDW1_CIPHER, cipher));
1775 	}
1776 #endif
1777 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1) &&
1778 	    type == IEEE80211_FC0_TYPE_DATA) {
1779 		if (ic->ic_curmode == IEEE80211_MODE_11B)
1780 			raid = R92C_RAID_11B;
1781 		else
1782 			raid = R92C_RAID_11BG;
1783 		txd->txdw1 |= htole32(
1784 		    SM(R92C_TXDW1_MACID, URTWN_MACID_BSS) |
1785 		    SM(R92C_TXDW1_QSEL, R92C_TXDW1_QSEL_BE) |
1786 		    SM(R92C_TXDW1_RAID, raid) |
1787 		    R92C_TXDW1_AGGBK);
1788 
1789 		if (ic->ic_flags & IEEE80211_F_USEPROT) {
1790 			if (ic->ic_protmode == IEEE80211_PROT_CTSONLY) {
1791 				txd->txdw4 |= htole32(R92C_TXDW4_CTS2SELF |
1792 				    R92C_TXDW4_HWRTSEN);
1793 			} else if (ic->ic_protmode == IEEE80211_PROT_RTSCTS) {
1794 				txd->txdw4 |= htole32(R92C_TXDW4_RTSEN |
1795 				    R92C_TXDW4_HWRTSEN);
1796 			}
1797 		}
1798 		/* Send RTS at OFDM24. */
1799 		txd->txdw4 |= htole32(SM(R92C_TXDW4_RTSRATE, 8));
1800 		txd->txdw5 |= htole32(0x0001ff00);
1801 		/* Send data at OFDM54. */
1802 		txd->txdw5 |= htole32(SM(R92C_TXDW5_DATARATE, 11));
1803 
1804 	} else {
1805 		txd->txdw1 |= htole32(
1806 		    SM(R92C_TXDW1_MACID, 0) |
1807 		    SM(R92C_TXDW1_QSEL, R92C_TXDW1_QSEL_MGNT) |
1808 		    SM(R92C_TXDW1_RAID, R92C_RAID_11B));
1809 
1810 		/* Force CCK1. */
1811 		txd->txdw4 |= htole32(R92C_TXDW4_DRVRATE);
1812 		txd->txdw5 |= htole32(SM(R92C_TXDW5_DATARATE, 0));
1813 	}
1814 	/* Set sequence number (already little endian). */
1815 	txd->txdseq |= *(uint16_t *)wh->i_seq;
1816 
1817 	if (!hasqos) {
1818 		/* Use HW sequence numbering for non-QoS frames. */
1819 		txd->txdw4  |= htole32(R92C_TXDW4_HWSEQ);
1820 		txd->txdseq |= htole16(0x8000);		/* WTF? */
1821 	} else
1822 		txd->txdw4 |= htole32(R92C_TXDW4_QOS);
1823 
1824 	/* Compute Tx descriptor checksum. */
1825 	sum = 0;
1826 	for (i = 0; i < sizeof(*txd) / 2; i++)
1827 		sum ^= ((uint16_t *)txd)[i];
1828 	txd->txdsum = sum;	/* NB: already little endian. */
1829 
1830 #if NBPFILTER > 0
1831 	if (__predict_false(sc->sc_drvbpf != NULL)) {
1832 		struct urtwn_tx_radiotap_header *tap = &sc->sc_txtap;
1833 		struct mbuf mb;
1834 
1835 		tap->wt_flags = 0;
1836 		tap->wt_chan_freq = htole16(ic->ic_bss->ni_chan->ic_freq);
1837 		tap->wt_chan_flags = htole16(ic->ic_bss->ni_chan->ic_flags);
1838 
1839 		mb.m_data = (caddr_t)tap;
1840 		mb.m_len = sc->sc_txtap_len;
1841 		mb.m_next = m;
1842 		mb.m_nextpkt = NULL;
1843 		mb.m_type = 0;
1844 		mb.m_flags = 0;
1845 		bpf_mtap(sc->sc_drvbpf, &mb, BPF_DIRECTION_OUT);
1846 	}
1847 #endif
1848 
1849 	xferlen = sizeof(*txd) + m->m_pkthdr.len;
1850 	m_copydata(m, 0, m->m_pkthdr.len, (caddr_t)&txd[1]);
1851 	m_freem(m);
1852 
1853 	data->pipe = pipe;
1854 	usbd_setup_xfer(data->xfer, pipe, data, data->buf, xferlen,
1855 	    USBD_FORCE_SHORT_XFER | USBD_NO_COPY, URTWN_TX_TIMEOUT,
1856 	    urtwn_txeof);
1857 	error = usbd_transfer(data->xfer);
1858 	if (__predict_false(error != USBD_IN_PROGRESS && error != 0)) {
1859 		/* Put this Tx buffer back to our free list. */
1860 		TAILQ_INSERT_TAIL(&sc->tx_free_list, data, next);
1861 		return (error);
1862 	}
1863 	ieee80211_release_node(ic, ni);
1864 	return (0);
1865 }
1866 
1867 void
1868 urtwn_start(struct ifnet *ifp)
1869 {
1870 	struct urtwn_softc *sc = ifp->if_softc;
1871 	struct ieee80211com *ic = &sc->sc_ic;
1872 	struct ieee80211_node *ni;
1873 	struct mbuf *m;
1874 
1875 	if ((ifp->if_flags & (IFF_RUNNING | IFF_OACTIVE)) != IFF_RUNNING)
1876 		return;
1877 
1878 	for (;;) {
1879 		if (TAILQ_EMPTY(&sc->tx_free_list)) {
1880 			ifp->if_flags |= IFF_OACTIVE;
1881 			break;
1882 		}
1883 		/* Send pending management frames first. */
1884 		IF_DEQUEUE(&ic->ic_mgtq, m);
1885 		if (m != NULL) {
1886 			ni = (void *)m->m_pkthdr.rcvif;
1887 			goto sendit;
1888 		}
1889 		if (ic->ic_state != IEEE80211_S_RUN)
1890 			break;
1891 
1892 		/* Encapsulate and send data frames. */
1893 		IFQ_DEQUEUE(&ifp->if_snd, m);
1894 		if (m == NULL)
1895 			break;
1896 #if NBPFILTER > 0
1897 		if (ifp->if_bpf != NULL)
1898 			bpf_mtap(ifp->if_bpf, m, BPF_DIRECTION_OUT);
1899 #endif
1900 		if ((m = ieee80211_encap(ifp, m, &ni)) == NULL)
1901 			continue;
1902 sendit:
1903 #if NBPFILTER > 0
1904 		if (ic->ic_rawbpf != NULL)
1905 			bpf_mtap(ic->ic_rawbpf, m, BPF_DIRECTION_OUT);
1906 #endif
1907 		if (urtwn_tx(sc, m, ni) != 0) {
1908 			ieee80211_release_node(ic, ni);
1909 			ifp->if_oerrors++;
1910 			continue;
1911 		}
1912 
1913 		sc->sc_tx_timer = 5;
1914 		ifp->if_timer = 1;
1915 	}
1916 }
1917 
1918 void
1919 urtwn_watchdog(struct ifnet *ifp)
1920 {
1921 	struct urtwn_softc *sc = ifp->if_softc;
1922 
1923 	ifp->if_timer = 0;
1924 
1925 	if (sc->sc_tx_timer > 0) {
1926 		if (--sc->sc_tx_timer == 0) {
1927 			printf("%s: device timeout\n", sc->sc_dev.dv_xname);
1928 			/* urtwn_init(ifp); XXX needs a process context! */
1929 			ifp->if_oerrors++;
1930 			return;
1931 		}
1932 		ifp->if_timer = 1;
1933 	}
1934 	ieee80211_watchdog(ifp);
1935 }
1936 
1937 int
1938 urtwn_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1939 {
1940 	struct urtwn_softc *sc = ifp->if_softc;
1941 	struct ieee80211com *ic = &sc->sc_ic;
1942 	struct ifaddr *ifa;
1943 	struct ifreq *ifr;
1944 	int s, error = 0;
1945 
1946 	if (usbd_is_dying(sc->sc_udev))
1947 		return ENXIO;
1948 
1949 	usbd_ref_incr(sc->sc_udev);
1950 
1951 	s = splnet();
1952 
1953 	switch (cmd) {
1954 	case SIOCSIFADDR:
1955 		ifa = (struct ifaddr *)data;
1956 		ifp->if_flags |= IFF_UP;
1957 #ifdef INET
1958 		if (ifa->ifa_addr->sa_family == AF_INET)
1959 			arp_ifinit(&ic->ic_ac, ifa);
1960 #endif
1961 		/* FALLTHROUGH */
1962 	case SIOCSIFFLAGS:
1963 		if (ifp->if_flags & IFF_UP) {
1964 			if (!(ifp->if_flags & IFF_RUNNING))
1965 				urtwn_init(ifp);
1966 		} else {
1967 			if (ifp->if_flags & IFF_RUNNING)
1968 				urtwn_stop(ifp);
1969 		}
1970 		break;
1971 	case SIOCADDMULTI:
1972 	case SIOCDELMULTI:
1973 		ifr = (struct ifreq *)data;
1974 		error = (cmd == SIOCADDMULTI) ?
1975 		    ether_addmulti(ifr, &ic->ic_ac) :
1976 		    ether_delmulti(ifr, &ic->ic_ac);
1977 		if (error == ENETRESET)
1978 			error = 0;
1979 		break;
1980 	case SIOCS80211CHANNEL:
1981 		error = ieee80211_ioctl(ifp, cmd, data);
1982 		if (error == ENETRESET &&
1983 		    ic->ic_opmode == IEEE80211_M_MONITOR) {
1984 			if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
1985 			    (IFF_UP | IFF_RUNNING))
1986 				urtwn_set_chan(sc, ic->ic_ibss_chan, NULL);
1987 			error = 0;
1988 		}
1989 		break;
1990 	default:
1991 		error = ieee80211_ioctl(ifp, cmd, data);
1992 	}
1993 
1994 	if (error == ENETRESET) {
1995 		if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
1996 		    (IFF_UP | IFF_RUNNING)) {
1997 			urtwn_stop(ifp);
1998 			urtwn_init(ifp);
1999 		}
2000 		error = 0;
2001 	}
2002 	splx(s);
2003 
2004 	usbd_ref_decr(sc->sc_udev);
2005 
2006 	return (error);
2007 }
2008 
2009 int
2010 urtwn_power_on(struct urtwn_softc *sc)
2011 {
2012 	uint32_t reg;
2013 	int ntries;
2014 
2015 	/* Wait for autoload done bit. */
2016 	for (ntries = 0; ntries < 1000; ntries++) {
2017 		if (urtwn_read_1(sc, R92C_APS_FSMCO) & R92C_APS_FSMCO_PFM_ALDN)
2018 			break;
2019 		DELAY(5);
2020 	}
2021 	if (ntries == 1000) {
2022 		printf("%s: timeout waiting for chip autoload\n",
2023 		    sc->sc_dev.dv_xname);
2024 		return (ETIMEDOUT);
2025 	}
2026 
2027 	/* Unlock ISO/CLK/Power control register. */
2028 	urtwn_write_1(sc, R92C_RSV_CTRL, 0);
2029 	/* Move SPS into PWM mode. */
2030 	urtwn_write_1(sc, R92C_SPS0_CTRL, 0x2b);
2031 	DELAY(100);
2032 
2033 	reg = urtwn_read_1(sc, R92C_LDOV12D_CTRL);
2034 	if (!(reg & R92C_LDOV12D_CTRL_LDV12_EN)) {
2035 		urtwn_write_1(sc, R92C_LDOV12D_CTRL,
2036 		    reg | R92C_LDOV12D_CTRL_LDV12_EN);
2037 		DELAY(100);
2038 		urtwn_write_1(sc, R92C_SYS_ISO_CTRL,
2039 		    urtwn_read_1(sc, R92C_SYS_ISO_CTRL) &
2040 		    ~R92C_SYS_ISO_CTRL_MD2PP);
2041 	}
2042 
2043 	/* Auto enable WLAN. */
2044 	urtwn_write_2(sc, R92C_APS_FSMCO,
2045 	    urtwn_read_2(sc, R92C_APS_FSMCO) | R92C_APS_FSMCO_APFM_ONMAC);
2046 	for (ntries = 0; ntries < 1000; ntries++) {
2047 		if (urtwn_read_2(sc, R92C_APS_FSMCO) &
2048 		    R92C_APS_FSMCO_APFM_ONMAC)
2049 			break;
2050 		DELAY(5);
2051 	}
2052 	if (ntries == 1000) {
2053 		printf("%s: timeout waiting for MAC auto ON\n",
2054 		    sc->sc_dev.dv_xname);
2055 		return (ETIMEDOUT);
2056 	}
2057 
2058 	/* Enable radio, GPIO and LED functions. */
2059 	urtwn_write_2(sc, R92C_APS_FSMCO,
2060 	    R92C_APS_FSMCO_AFSM_HSUS |
2061 	    R92C_APS_FSMCO_PDN_EN |
2062 	    R92C_APS_FSMCO_PFM_ALDN);
2063 	/* Release RF digital isolation. */
2064 	urtwn_write_2(sc, R92C_SYS_ISO_CTRL,
2065 	    urtwn_read_2(sc, R92C_SYS_ISO_CTRL) & ~R92C_SYS_ISO_CTRL_DIOR);
2066 
2067 	/* Initialize MAC. */
2068 	urtwn_write_1(sc, R92C_APSD_CTRL,
2069 	    urtwn_read_1(sc, R92C_APSD_CTRL) & ~R92C_APSD_CTRL_OFF);
2070 	for (ntries = 0; ntries < 200; ntries++) {
2071 		if (!(urtwn_read_1(sc, R92C_APSD_CTRL) &
2072 		    R92C_APSD_CTRL_OFF_STATUS))
2073 			break;
2074 		DELAY(5);
2075 	}
2076 	if (ntries == 200) {
2077 		printf("%s: timeout waiting for MAC initialization\n",
2078 		    sc->sc_dev.dv_xname);
2079 		return (ETIMEDOUT);
2080 	}
2081 
2082 	/* Enable MAC DMA/WMAC/SCHEDULE/SEC blocks. */
2083 	reg = urtwn_read_2(sc, R92C_CR);
2084 	reg |= R92C_CR_HCI_TXDMA_EN | R92C_CR_HCI_RXDMA_EN |
2085 	    R92C_CR_TXDMA_EN | R92C_CR_RXDMA_EN | R92C_CR_PROTOCOL_EN |
2086 	    R92C_CR_SCHEDULE_EN | R92C_CR_MACTXEN | R92C_CR_MACRXEN |
2087 	    R92C_CR_ENSEC;
2088 	urtwn_write_2(sc, R92C_CR, reg);
2089 
2090 	urtwn_write_1(sc, 0xfe10, 0x19);
2091 	return (0);
2092 }
2093 
2094 int
2095 urtwn_llt_init(struct urtwn_softc *sc)
2096 {
2097 	int i, error;
2098 
2099 	/* Reserve pages [0; R92C_TX_PAGE_COUNT]. */
2100 	for (i = 0; i < R92C_TX_PAGE_COUNT; i++) {
2101 		if ((error = urtwn_llt_write(sc, i, i + 1)) != 0)
2102 			return (error);
2103 	}
2104 	/* NB: 0xff indicates end-of-list. */
2105 	if ((error = urtwn_llt_write(sc, i, 0xff)) != 0)
2106 		return (error);
2107 	/*
2108 	 * Use pages [R92C_TX_PAGE_COUNT + 1; R92C_TXPKTBUF_COUNT - 1]
2109 	 * as ring buffer.
2110 	 */
2111 	for (++i; i < R92C_TXPKTBUF_COUNT - 1; i++) {
2112 		if ((error = urtwn_llt_write(sc, i, i + 1)) != 0)
2113 			return (error);
2114 	}
2115 	/* Make the last page point to the beginning of the ring buffer. */
2116 	error = urtwn_llt_write(sc, i, R92C_TX_PAGE_COUNT + 1);
2117 	return (error);
2118 }
2119 
2120 void
2121 urtwn_fw_reset(struct urtwn_softc *sc)
2122 {
2123 	uint16_t reg;
2124 	int ntries;
2125 
2126 	/* Tell 8051 to reset itself. */
2127 	urtwn_write_1(sc, R92C_HMETFR + 3, 0x20);
2128 
2129 	/* Wait until 8051 resets by itself. */
2130 	for (ntries = 0; ntries < 100; ntries++) {
2131 		reg = urtwn_read_2(sc, R92C_SYS_FUNC_EN);
2132 		if (!(reg & R92C_SYS_FUNC_EN_CPUEN))
2133 			return;
2134 		DELAY(50);
2135 	}
2136 	/* Force 8051 reset. */
2137 	urtwn_write_2(sc, R92C_SYS_FUNC_EN, reg & ~R92C_SYS_FUNC_EN_CPUEN);
2138 }
2139 
2140 int
2141 urtwn_fw_loadpage(struct urtwn_softc *sc, int page, uint8_t *buf, int len)
2142 {
2143 	uint32_t reg;
2144 	int off, mlen, error = 0;
2145 
2146 	reg = urtwn_read_4(sc, R92C_MCUFWDL);
2147 	reg = RW(reg, R92C_MCUFWDL_PAGE, page);
2148 	urtwn_write_4(sc, R92C_MCUFWDL, reg);
2149 
2150 	off = R92C_FW_START_ADDR;
2151 	while (len > 0) {
2152 		if (len > 196)
2153 			mlen = 196;
2154 		else if (len > 4)
2155 			mlen = 4;
2156 		else
2157 			mlen = 1;
2158 		error = urtwn_write_region_1(sc, off, buf, mlen);
2159 		if (error != 0)
2160 			break;
2161 		off += mlen;
2162 		buf += mlen;
2163 		len -= mlen;
2164 	}
2165 	return (error);
2166 }
2167 
2168 int
2169 urtwn_load_firmware(struct urtwn_softc *sc)
2170 {
2171 	const struct r92c_fw_hdr *hdr;
2172 	const char *name;
2173 	u_char *fw, *ptr;
2174 	size_t len;
2175 	uint32_t reg;
2176 	int mlen, ntries, page, error;
2177 
2178 	/* Read firmware image from the filesystem. */
2179 	if ((sc->chip & (URTWN_CHIP_UMC_A_CUT | URTWN_CHIP_92C)) ==
2180 	    URTWN_CHIP_UMC_A_CUT)
2181 		name = "urtwn-rtl8192cfwU";
2182 	else
2183 		name = "urtwn-rtl8192cfwT";
2184 	if ((error = loadfirmware(name, &fw, &len)) != 0) {
2185 		printf("%s: failed loadfirmware of file %s (error %d)\n",
2186 		    sc->sc_dev.dv_xname, name, error);
2187 		return (error);
2188 	}
2189 	if (len < sizeof(*hdr)) {
2190 		printf("%s: firmware too short\n", sc->sc_dev.dv_xname);
2191 		error = EINVAL;
2192 		goto fail;
2193 	}
2194 	ptr = fw;
2195 	hdr = (const struct r92c_fw_hdr *)ptr;
2196 	/* Check if there is a valid FW header and skip it. */
2197 	if ((letoh16(hdr->signature) >> 4) == 0x88c ||
2198 	    (letoh16(hdr->signature) >> 4) == 0x92c) {
2199 		DPRINTF(("FW V%d.%d %02d-%02d %02d:%02d\n",
2200 		    letoh16(hdr->version), letoh16(hdr->subversion),
2201 		    hdr->month, hdr->date, hdr->hour, hdr->minute));
2202 		ptr += sizeof(*hdr);
2203 		len -= sizeof(*hdr);
2204 	}
2205 
2206 	if (urtwn_read_1(sc, R92C_MCUFWDL) & 0x80) {
2207 		urtwn_fw_reset(sc);
2208 		urtwn_write_1(sc, R92C_MCUFWDL, 0);
2209 	}
2210 	urtwn_write_2(sc, R92C_SYS_FUNC_EN,
2211 	    urtwn_read_2(sc, R92C_SYS_FUNC_EN) |
2212 	    R92C_SYS_FUNC_EN_CPUEN);
2213 	urtwn_write_1(sc, R92C_MCUFWDL,
2214 	    urtwn_read_1(sc, R92C_MCUFWDL) | R92C_MCUFWDL_EN);
2215 	urtwn_write_1(sc, R92C_MCUFWDL + 2,
2216 	    urtwn_read_1(sc, R92C_MCUFWDL + 2) & ~0x08);
2217 
2218 	for (page = 0; len > 0; page++) {
2219 		mlen = MIN(len, R92C_FW_PAGE_SIZE);
2220 		error = urtwn_fw_loadpage(sc, page, ptr, mlen);
2221 		if (error != 0) {
2222 			printf("%s: could not load firmware page %d\n",
2223 			    sc->sc_dev.dv_xname, page);
2224 			goto fail;
2225 		}
2226 		ptr += mlen;
2227 		len -= mlen;
2228 	}
2229 	urtwn_write_1(sc, R92C_MCUFWDL,
2230 	    urtwn_read_1(sc, R92C_MCUFWDL) & ~R92C_MCUFWDL_EN);
2231 	urtwn_write_1(sc, R92C_MCUFWDL + 1, 0);
2232 
2233 	/* Wait for checksum report. */
2234 	for (ntries = 0; ntries < 1000; ntries++) {
2235 		if (urtwn_read_4(sc, R92C_MCUFWDL) & R92C_MCUFWDL_CHKSUM_RPT)
2236 			break;
2237 		DELAY(5);
2238 	}
2239 	if (ntries == 1000) {
2240 		printf("%s: timeout waiting for checksum report\n",
2241 		    sc->sc_dev.dv_xname);
2242 		error = ETIMEDOUT;
2243 		goto fail;
2244 	}
2245 
2246 	reg = urtwn_read_4(sc, R92C_MCUFWDL);
2247 	reg = (reg & ~R92C_MCUFWDL_WINTINI_RDY) | R92C_MCUFWDL_RDY;
2248 	urtwn_write_4(sc, R92C_MCUFWDL, reg);
2249 	/* Wait for firmware readiness. */
2250 	for (ntries = 0; ntries < 1000; ntries++) {
2251 		if (urtwn_read_4(sc, R92C_MCUFWDL) & R92C_MCUFWDL_WINTINI_RDY)
2252 			break;
2253 		DELAY(5);
2254 	}
2255 	if (ntries == 1000) {
2256 		printf("%s: timeout waiting for firmware readiness\n",
2257 		    sc->sc_dev.dv_xname);
2258 		error = ETIMEDOUT;
2259 		goto fail;
2260 	}
2261  fail:
2262 	free(fw, M_DEVBUF);
2263 	return (error);
2264 }
2265 
2266 int
2267 urtwn_dma_init(struct urtwn_softc *sc)
2268 {
2269 	int hashq, hasnq, haslq, nqueues, nqpages, nrempages;
2270 	uint32_t reg;
2271 	int error;
2272 
2273 	/* Initialize LLT table. */
2274 	error = urtwn_llt_init(sc);
2275 	if (error != 0)
2276 		return (error);
2277 
2278 	/* Get Tx queues to USB endpoints mapping. */
2279 	hashq = hasnq = haslq = 0;
2280 	reg = urtwn_read_2(sc, R92C_USB_EP + 1);
2281 	DPRINTFN(2, ("USB endpoints mapping 0x%x\n", reg));
2282 	if (MS(reg, R92C_USB_EP_HQ) != 0)
2283 		hashq = 1;
2284 	if (MS(reg, R92C_USB_EP_NQ) != 0)
2285 		hasnq = 1;
2286 	if (MS(reg, R92C_USB_EP_LQ) != 0)
2287 		haslq = 1;
2288 	nqueues = hashq + hasnq + haslq;
2289 	if (nqueues == 0)
2290 		return (EIO);
2291 	/* Get the number of pages for each queue. */
2292 	nqpages = (R92C_TX_PAGE_COUNT - R92C_PUBQ_NPAGES) / nqueues;
2293 	/* The remaining pages are assigned to the high priority queue. */
2294 	nrempages = (R92C_TX_PAGE_COUNT - R92C_PUBQ_NPAGES) % nqueues;
2295 
2296 	/* Set number of pages for normal priority queue. */
2297 	urtwn_write_1(sc, R92C_RQPN_NPQ, hasnq ? nqpages : 0);
2298 	urtwn_write_4(sc, R92C_RQPN,
2299 	    /* Set number of pages for public queue. */
2300 	    SM(R92C_RQPN_PUBQ, R92C_PUBQ_NPAGES) |
2301 	    /* Set number of pages for high priority queue. */
2302 	    SM(R92C_RQPN_HPQ, hashq ? nqpages + nrempages : 0) |
2303 	    /* Set number of pages for low priority queue. */
2304 	    SM(R92C_RQPN_LPQ, haslq ? nqpages : 0) |
2305 	    /* Load values. */
2306 	    R92C_RQPN_LD);
2307 
2308 	urtwn_write_1(sc, R92C_TXPKTBUF_BCNQ_BDNY, R92C_TX_PAGE_BOUNDARY);
2309 	urtwn_write_1(sc, R92C_TXPKTBUF_MGQ_BDNY, R92C_TX_PAGE_BOUNDARY);
2310 	urtwn_write_1(sc, R92C_TXPKTBUF_WMAC_LBK_BF_HD, R92C_TX_PAGE_BOUNDARY);
2311 	urtwn_write_1(sc, R92C_TRXFF_BNDY, R92C_TX_PAGE_BOUNDARY);
2312 	urtwn_write_1(sc, R92C_TDECTRL + 1, R92C_TX_PAGE_BOUNDARY);
2313 
2314 	/* Set queue to USB pipe mapping. */
2315 	reg = urtwn_read_2(sc, R92C_TRXDMA_CTRL);
2316 	reg &= ~R92C_TRXDMA_CTRL_QMAP_M;
2317 	if (nqueues == 1) {
2318 		if (hashq)
2319 			reg |= R92C_TRXDMA_CTRL_QMAP_HQ;
2320 		else if (hasnq)
2321 			reg |= R92C_TRXDMA_CTRL_QMAP_NQ;
2322 		else
2323 			reg |= R92C_TRXDMA_CTRL_QMAP_LQ;
2324 	} else if (nqueues == 2) {
2325 		/* All 2-endpoints configs have a high priority queue. */
2326 		if (!hashq)
2327 			return (EIO);
2328 		if (hasnq)
2329 			reg |= R92C_TRXDMA_CTRL_QMAP_HQ_NQ;
2330 		else
2331 			reg |= R92C_TRXDMA_CTRL_QMAP_HQ_LQ;
2332 	} else
2333 		reg |= R92C_TRXDMA_CTRL_QMAP_3EP;
2334 	urtwn_write_2(sc, R92C_TRXDMA_CTRL, reg);
2335 
2336 	/* Set Tx/Rx transfer page boundary. */
2337 	urtwn_write_2(sc, R92C_TRXFF_BNDY + 2, 0x27ff);
2338 
2339 	/* Set Tx/Rx transfer page size. */
2340 	urtwn_write_1(sc, R92C_PBP,
2341 	    SM(R92C_PBP_PSRX, R92C_PBP_128) |
2342 	    SM(R92C_PBP_PSTX, R92C_PBP_128));
2343 	return (0);
2344 }
2345 
2346 void
2347 urtwn_mac_init(struct urtwn_softc *sc)
2348 {
2349 	int i;
2350 
2351 	/* Write MAC initialization values. */
2352 	for (i = 0; i < nitems(rtl8192cu_mac); i++)
2353 		urtwn_write_1(sc, rtl8192cu_mac[i].reg, rtl8192cu_mac[i].val);
2354 }
2355 
2356 void
2357 urtwn_bb_init(struct urtwn_softc *sc)
2358 {
2359 	const struct urtwn_bb_prog *prog;
2360 	uint32_t reg;
2361 	int i;
2362 
2363 	/* Enable BB and RF. */
2364 	urtwn_write_2(sc, R92C_SYS_FUNC_EN,
2365 	    urtwn_read_2(sc, R92C_SYS_FUNC_EN) |
2366 	    R92C_SYS_FUNC_EN_BBRSTB | R92C_SYS_FUNC_EN_BB_GLB_RST |
2367 	    R92C_SYS_FUNC_EN_DIO_RF);
2368 
2369 	urtwn_write_2(sc, R92C_AFE_PLL_CTRL, 0xdb83);
2370 
2371 	urtwn_write_1(sc, R92C_RF_CTRL,
2372 	    R92C_RF_CTRL_EN | R92C_RF_CTRL_RSTB | R92C_RF_CTRL_SDMRSTB);
2373 	urtwn_write_1(sc, R92C_SYS_FUNC_EN,
2374 	    R92C_SYS_FUNC_EN_USBA | R92C_SYS_FUNC_EN_USBD |
2375 	    R92C_SYS_FUNC_EN_BB_GLB_RST | R92C_SYS_FUNC_EN_BBRSTB);
2376 
2377 	urtwn_write_1(sc, R92C_LDOHCI12_CTRL, 0x0f);
2378 	urtwn_write_1(sc, 0x15, 0xe9);
2379 	urtwn_write_1(sc, R92C_AFE_XTAL_CTRL + 1, 0x80);
2380 
2381 	/* Select BB programming based on board type. */
2382 	if (!(sc->chip & URTWN_CHIP_92C)) {
2383 		if (sc->board_type == R92C_BOARD_TYPE_MINICARD)
2384 			prog = &rtl8188ce_bb_prog;
2385 		else if (sc->board_type == R92C_BOARD_TYPE_HIGHPA)
2386 			prog = &rtl8188ru_bb_prog;
2387 		else
2388 			prog = &rtl8188cu_bb_prog;
2389 	} else {
2390 		if (sc->board_type == R92C_BOARD_TYPE_MINICARD)
2391 			prog = &rtl8192ce_bb_prog;
2392 		else
2393 			prog = &rtl8192cu_bb_prog;
2394 	}
2395 	/* Write BB initialization values. */
2396 	for (i = 0; i < prog->count; i++) {
2397 		urtwn_bb_write(sc, prog->regs[i], prog->vals[i]);
2398 		DELAY(1);
2399 	}
2400 
2401 	if (sc->chip & URTWN_CHIP_92C_1T2R) {
2402 		/* 8192C 1T only configuration. */
2403 		reg = urtwn_bb_read(sc, R92C_FPGA0_TXINFO);
2404 		reg = (reg & ~0x00000003) | 0x2;
2405 		urtwn_bb_write(sc, R92C_FPGA0_TXINFO, reg);
2406 
2407 		reg = urtwn_bb_read(sc, R92C_FPGA1_TXINFO);
2408 		reg = (reg & ~0x00300033) | 0x00200022;
2409 		urtwn_bb_write(sc, R92C_FPGA1_TXINFO, reg);
2410 
2411 		reg = urtwn_bb_read(sc, R92C_CCK0_AFESETTING);
2412 		reg = (reg & ~0xff000000) | 0x45 << 24;
2413 		urtwn_bb_write(sc, R92C_CCK0_AFESETTING, reg);
2414 
2415 		reg = urtwn_bb_read(sc, R92C_OFDM0_TRXPATHENA);
2416 		reg = (reg & ~0x000000ff) | 0x23;
2417 		urtwn_bb_write(sc, R92C_OFDM0_TRXPATHENA, reg);
2418 
2419 		reg = urtwn_bb_read(sc, R92C_OFDM0_AGCPARAM1);
2420 		reg = (reg & ~0x00000030) | 1 << 4;
2421 		urtwn_bb_write(sc, R92C_OFDM0_AGCPARAM1, reg);
2422 
2423 		reg = urtwn_bb_read(sc, 0xe74);
2424 		reg = (reg & ~0x0c000000) | 2 << 26;
2425 		urtwn_bb_write(sc, 0xe74, reg);
2426 		reg = urtwn_bb_read(sc, 0xe78);
2427 		reg = (reg & ~0x0c000000) | 2 << 26;
2428 		urtwn_bb_write(sc, 0xe78, reg);
2429 		reg = urtwn_bb_read(sc, 0xe7c);
2430 		reg = (reg & ~0x0c000000) | 2 << 26;
2431 		urtwn_bb_write(sc, 0xe7c, reg);
2432 		reg = urtwn_bb_read(sc, 0xe80);
2433 		reg = (reg & ~0x0c000000) | 2 << 26;
2434 		urtwn_bb_write(sc, 0xe80, reg);
2435 		reg = urtwn_bb_read(sc, 0xe88);
2436 		reg = (reg & ~0x0c000000) | 2 << 26;
2437 		urtwn_bb_write(sc, 0xe88, reg);
2438 	}
2439 
2440 	/* Write AGC values. */
2441 	for (i = 0; i < prog->agccount; i++) {
2442 		urtwn_bb_write(sc, R92C_OFDM0_AGCRSSITABLE,
2443 		    prog->agcvals[i]);
2444 		DELAY(1);
2445 	}
2446 
2447 	if (urtwn_bb_read(sc, R92C_HSSI_PARAM2(0)) &
2448 	    R92C_HSSI_PARAM2_CCK_HIPWR)
2449 		sc->sc_flags |= URTWN_FLAG_CCK_HIPWR;
2450 }
2451 
2452 void
2453 urtwn_rf_init(struct urtwn_softc *sc)
2454 {
2455 	const struct urtwn_rf_prog *prog;
2456 	uint32_t reg, type;
2457 	int i, j, idx, off;
2458 
2459 	/* Select RF programming based on board type. */
2460 	if (!(sc->chip & URTWN_CHIP_92C)) {
2461 		if (sc->board_type == R92C_BOARD_TYPE_MINICARD)
2462 			prog = rtl8188ce_rf_prog;
2463 		else if (sc->board_type == R92C_BOARD_TYPE_HIGHPA)
2464 			prog = rtl8188ru_rf_prog;
2465 		else
2466 			prog = rtl8188cu_rf_prog;
2467 	} else
2468 		prog = rtl8192ce_rf_prog;
2469 
2470 	for (i = 0; i < sc->nrxchains; i++) {
2471 		/* Save RF_ENV control type. */
2472 		idx = i / 2;
2473 		off = (i % 2) * 16;
2474 		reg = urtwn_bb_read(sc, R92C_FPGA0_RFIFACESW(idx));
2475 		type = (reg >> off) & 0x10;
2476 
2477 		/* Set RF_ENV enable. */
2478 		reg = urtwn_bb_read(sc, R92C_FPGA0_RFIFACEOE(i));
2479 		reg |= 0x100000;
2480 		urtwn_bb_write(sc, R92C_FPGA0_RFIFACEOE(i), reg);
2481 		DELAY(1);
2482 		/* Set RF_ENV output high. */
2483 		reg = urtwn_bb_read(sc, R92C_FPGA0_RFIFACEOE(i));
2484 		reg |= 0x10;
2485 		urtwn_bb_write(sc, R92C_FPGA0_RFIFACEOE(i), reg);
2486 		DELAY(1);
2487 		/* Set address and data lengths of RF registers. */
2488 		reg = urtwn_bb_read(sc, R92C_HSSI_PARAM2(i));
2489 		reg &= ~R92C_HSSI_PARAM2_ADDR_LENGTH;
2490 		urtwn_bb_write(sc, R92C_HSSI_PARAM2(i), reg);
2491 		DELAY(1);
2492 		reg = urtwn_bb_read(sc, R92C_HSSI_PARAM2(i));
2493 		reg &= ~R92C_HSSI_PARAM2_DATA_LENGTH;
2494 		urtwn_bb_write(sc, R92C_HSSI_PARAM2(i), reg);
2495 		DELAY(1);
2496 
2497 		/* Write RF initialization values for this chain. */
2498 		for (j = 0; j < prog[i].count; j++) {
2499 			if (prog[i].regs[j] >= 0xf9 &&
2500 			    prog[i].regs[j] <= 0xfe) {
2501 				/*
2502 				 * These are fake RF registers offsets that
2503 				 * indicate a delay is required.
2504 				 */
2505 				usbd_delay_ms(sc->sc_udev, 50);
2506 				continue;
2507 			}
2508 			urtwn_rf_write(sc, i, prog[i].regs[j],
2509 			    prog[i].vals[j]);
2510 			DELAY(1);
2511 		}
2512 
2513 		/* Restore RF_ENV control type. */
2514 		reg = urtwn_bb_read(sc, R92C_FPGA0_RFIFACESW(idx));
2515 		reg &= ~(0x10 << off) | (type << off);
2516 		urtwn_bb_write(sc, R92C_FPGA0_RFIFACESW(idx), reg);
2517 
2518 		/* Cache RF register CHNLBW. */
2519 		sc->rf_chnlbw[i] = urtwn_rf_read(sc, i, R92C_RF_CHNLBW);
2520 	}
2521 
2522 	if ((sc->chip & (URTWN_CHIP_UMC_A_CUT | URTWN_CHIP_92C)) ==
2523 	    URTWN_CHIP_UMC_A_CUT) {
2524 		urtwn_rf_write(sc, 0, R92C_RF_RX_G1, 0x30255);
2525 		urtwn_rf_write(sc, 0, R92C_RF_RX_G2, 0x50a00);
2526 	}
2527 }
2528 
2529 void
2530 urtwn_cam_init(struct urtwn_softc *sc)
2531 {
2532 	/* Invalidate all CAM entries. */
2533 	urtwn_write_4(sc, R92C_CAMCMD,
2534 	    R92C_CAMCMD_POLLING | R92C_CAMCMD_CLR);
2535 }
2536 
2537 void
2538 urtwn_pa_bias_init(struct urtwn_softc *sc)
2539 {
2540 	uint8_t reg;
2541 	int i;
2542 
2543 	for (i = 0; i < sc->nrxchains; i++) {
2544 		if (sc->pa_setting & (1 << i))
2545 			continue;
2546 		urtwn_rf_write(sc, i, R92C_RF_IPA, 0x0f406);
2547 		urtwn_rf_write(sc, i, R92C_RF_IPA, 0x4f406);
2548 		urtwn_rf_write(sc, i, R92C_RF_IPA, 0x8f406);
2549 		urtwn_rf_write(sc, i, R92C_RF_IPA, 0xcf406);
2550 	}
2551 	if (!(sc->pa_setting & 0x10)) {
2552 		reg = urtwn_read_1(sc, 0x16);
2553 		reg = (reg & ~0xf0) | 0x90;
2554 		urtwn_write_1(sc, 0x16, reg);
2555 	}
2556 }
2557 
2558 void
2559 urtwn_rxfilter_init(struct urtwn_softc *sc)
2560 {
2561 	/* Initialize Rx filter. */
2562 	/* TODO: use better filter for monitor mode. */
2563 	urtwn_write_4(sc, R92C_RCR,
2564 	    R92C_RCR_AAP | R92C_RCR_APM | R92C_RCR_AM | R92C_RCR_AB |
2565 	    R92C_RCR_APP_ICV | R92C_RCR_AMF | R92C_RCR_HTC_LOC_CTRL |
2566 	    R92C_RCR_APP_MIC | R92C_RCR_APP_PHYSTS);
2567 	/* Accept all multicast frames. */
2568 	urtwn_write_4(sc, R92C_MAR + 0, 0xffffffff);
2569 	urtwn_write_4(sc, R92C_MAR + 4, 0xffffffff);
2570 	/* Accept all management frames. */
2571 	urtwn_write_2(sc, R92C_RXFLTMAP0, 0xffff);
2572 	/* Reject all control frames. */
2573 	urtwn_write_2(sc, R92C_RXFLTMAP1, 0x0000);
2574 	/* Accept all data frames. */
2575 	urtwn_write_2(sc, R92C_RXFLTMAP2, 0xffff);
2576 }
2577 
2578 void
2579 urtwn_edca_init(struct urtwn_softc *sc)
2580 {
2581 	urtwn_write_2(sc, R92C_SPEC_SIFS, 0x100a);
2582 	urtwn_write_2(sc, R92C_MAC_SPEC_SIFS, 0x100a);
2583 	urtwn_write_2(sc, R92C_SIFS_CCK, 0x100a);
2584 	urtwn_write_2(sc, R92C_SIFS_OFDM, 0x100a);
2585 	urtwn_write_4(sc, R92C_EDCA_BE_PARAM, 0x005ea42b);
2586 	urtwn_write_4(sc, R92C_EDCA_BK_PARAM, 0x0000a44f);
2587 	urtwn_write_4(sc, R92C_EDCA_VI_PARAM, 0x005ea324);
2588 	urtwn_write_4(sc, R92C_EDCA_VO_PARAM, 0x002fa226);
2589 }
2590 
2591 void
2592 urtwn_write_txpower(struct urtwn_softc *sc, int chain,
2593     uint16_t power[URTWN_RIDX_COUNT])
2594 {
2595 	uint32_t reg;
2596 
2597 	/* Write per-CCK rate Tx power. */
2598 	if (chain == 0) {
2599 		reg = urtwn_bb_read(sc, R92C_TXAGC_A_CCK1_MCS32);
2600 		reg = RW(reg, R92C_TXAGC_A_CCK1,  power[0]);
2601 		urtwn_bb_write(sc, R92C_TXAGC_A_CCK1_MCS32, reg);
2602 		reg = urtwn_bb_read(sc, R92C_TXAGC_B_CCK11_A_CCK2_11);
2603 		reg = RW(reg, R92C_TXAGC_A_CCK2,  power[1]);
2604 		reg = RW(reg, R92C_TXAGC_A_CCK55, power[2]);
2605 		reg = RW(reg, R92C_TXAGC_A_CCK11, power[3]);
2606 		urtwn_bb_write(sc, R92C_TXAGC_B_CCK11_A_CCK2_11, reg);
2607 	} else {
2608 		reg = urtwn_bb_read(sc, R92C_TXAGC_B_CCK1_55_MCS32);
2609 		reg = RW(reg, R92C_TXAGC_B_CCK1,  power[0]);
2610 		reg = RW(reg, R92C_TXAGC_B_CCK2,  power[1]);
2611 		reg = RW(reg, R92C_TXAGC_B_CCK55, power[2]);
2612 		urtwn_bb_write(sc, R92C_TXAGC_B_CCK1_55_MCS32, reg);
2613 		reg = urtwn_bb_read(sc, R92C_TXAGC_B_CCK11_A_CCK2_11);
2614 		reg = RW(reg, R92C_TXAGC_B_CCK11, power[3]);
2615 		urtwn_bb_write(sc, R92C_TXAGC_B_CCK11_A_CCK2_11, reg);
2616 	}
2617 	/* Write per-OFDM rate Tx power. */
2618 	urtwn_bb_write(sc, R92C_TXAGC_RATE18_06(chain),
2619 	    SM(R92C_TXAGC_RATE06, power[ 4]) |
2620 	    SM(R92C_TXAGC_RATE09, power[ 5]) |
2621 	    SM(R92C_TXAGC_RATE12, power[ 6]) |
2622 	    SM(R92C_TXAGC_RATE18, power[ 7]));
2623 	urtwn_bb_write(sc, R92C_TXAGC_RATE54_24(chain),
2624 	    SM(R92C_TXAGC_RATE24, power[ 8]) |
2625 	    SM(R92C_TXAGC_RATE36, power[ 9]) |
2626 	    SM(R92C_TXAGC_RATE48, power[10]) |
2627 	    SM(R92C_TXAGC_RATE54, power[11]));
2628 	/* Write per-MCS Tx power. */
2629 	urtwn_bb_write(sc, R92C_TXAGC_MCS03_MCS00(chain),
2630 	    SM(R92C_TXAGC_MCS00,  power[12]) |
2631 	    SM(R92C_TXAGC_MCS01,  power[13]) |
2632 	    SM(R92C_TXAGC_MCS02,  power[14]) |
2633 	    SM(R92C_TXAGC_MCS03,  power[15]));
2634 	urtwn_bb_write(sc, R92C_TXAGC_MCS07_MCS04(chain),
2635 	    SM(R92C_TXAGC_MCS04,  power[16]) |
2636 	    SM(R92C_TXAGC_MCS05,  power[17]) |
2637 	    SM(R92C_TXAGC_MCS06,  power[18]) |
2638 	    SM(R92C_TXAGC_MCS07,  power[19]));
2639 	urtwn_bb_write(sc, R92C_TXAGC_MCS11_MCS08(chain),
2640 	    SM(R92C_TXAGC_MCS08,  power[20]) |
2641 	    SM(R92C_TXAGC_MCS08,  power[21]) |
2642 	    SM(R92C_TXAGC_MCS10,  power[22]) |
2643 	    SM(R92C_TXAGC_MCS11,  power[23]));
2644 	urtwn_bb_write(sc, R92C_TXAGC_MCS15_MCS12(chain),
2645 	    SM(R92C_TXAGC_MCS12,  power[24]) |
2646 	    SM(R92C_TXAGC_MCS13,  power[25]) |
2647 	    SM(R92C_TXAGC_MCS14,  power[26]) |
2648 	    SM(R92C_TXAGC_MCS15,  power[27]));
2649 }
2650 
2651 void
2652 urtwn_get_txpower(struct urtwn_softc *sc, int chain,
2653     struct ieee80211_channel *c, struct ieee80211_channel *extc,
2654     uint16_t power[URTWN_RIDX_COUNT])
2655 {
2656 	struct ieee80211com *ic = &sc->sc_ic;
2657 	struct r92c_rom *rom = &sc->rom;
2658 	uint16_t cckpow, ofdmpow, htpow, diff, max;
2659 	const struct urtwn_txpwr *base;
2660 	int ridx, chan, group;
2661 
2662 	/* Determine channel group. */
2663 	chan = ieee80211_chan2ieee(ic, c);	/* XXX center freq! */
2664 	if (chan <= 3)
2665 		group = 0;
2666 	else if (chan <= 9)
2667 		group = 1;
2668 	else
2669 		group = 2;
2670 
2671 	/* Get original Tx power based on board type and RF chain. */
2672 	if (!(sc->chip & URTWN_CHIP_92C)) {
2673 		if (sc->board_type == R92C_BOARD_TYPE_HIGHPA)
2674 			base = &rtl8188ru_txagc[chain];
2675 		else
2676 			base = &rtl8192cu_txagc[chain];
2677 	} else
2678 		base = &rtl8192cu_txagc[chain];
2679 
2680 	memset(power, 0, URTWN_RIDX_COUNT * sizeof(power[0]));
2681 	if (sc->regulatory == 0) {
2682 		for (ridx = 0; ridx <= 3; ridx++)
2683 			power[ridx] = base->pwr[0][ridx];
2684 	}
2685 	for (ridx = 4; ridx < URTWN_RIDX_COUNT; ridx++) {
2686 		if (sc->regulatory == 3) {
2687 			power[ridx] = base->pwr[0][ridx];
2688 			/* Apply vendor limits. */
2689 			if (extc != NULL)
2690 				max = rom->ht40_max_pwr[group];
2691 			else
2692 				max = rom->ht20_max_pwr[group];
2693 			max = (max >> (chain * 4)) & 0xf;
2694 			if (power[ridx] > max)
2695 				power[ridx] = max;
2696 		} else if (sc->regulatory == 1) {
2697 			if (extc == NULL)
2698 				power[ridx] = base->pwr[group][ridx];
2699 		} else if (sc->regulatory != 2)
2700 			power[ridx] = base->pwr[0][ridx];
2701 	}
2702 
2703 	/* Compute per-CCK rate Tx power. */
2704 	cckpow = rom->cck_tx_pwr[chain][group];
2705 	for (ridx = 0; ridx <= 3; ridx++) {
2706 		power[ridx] += cckpow;
2707 		if (power[ridx] > R92C_MAX_TX_PWR)
2708 			power[ridx] = R92C_MAX_TX_PWR;
2709 	}
2710 
2711 	htpow = rom->ht40_1s_tx_pwr[chain][group];
2712 	if (sc->ntxchains > 1) {
2713 		/* Apply reduction for 2 spatial streams. */
2714 		diff = rom->ht40_2s_tx_pwr_diff[group];
2715 		diff = (diff >> (chain * 4)) & 0xf;
2716 		htpow = (htpow > diff) ? htpow - diff : 0;
2717 	}
2718 
2719 	/* Compute per-OFDM rate Tx power. */
2720 	diff = rom->ofdm_tx_pwr_diff[group];
2721 	diff = (diff >> (chain * 4)) & 0xf;
2722 	ofdmpow = htpow + diff;	/* HT->OFDM correction. */
2723 	for (ridx = 4; ridx <= 11; ridx++) {
2724 		power[ridx] += ofdmpow;
2725 		if (power[ridx] > R92C_MAX_TX_PWR)
2726 			power[ridx] = R92C_MAX_TX_PWR;
2727 	}
2728 
2729 	/* Compute per-MCS Tx power. */
2730 	if (extc == NULL) {
2731 		diff = rom->ht20_tx_pwr_diff[group];
2732 		diff = (diff >> (chain * 4)) & 0xf;
2733 		htpow += diff;	/* HT40->HT20 correction. */
2734 	}
2735 	for (ridx = 12; ridx <= 27; ridx++) {
2736 		power[ridx] += htpow;
2737 		if (power[ridx] > R92C_MAX_TX_PWR)
2738 			power[ridx] = R92C_MAX_TX_PWR;
2739 	}
2740 #ifdef URTWN_DEBUG
2741 	if (urtwn_debug >= 4) {
2742 		/* Dump per-rate Tx power values. */
2743 		printf("Tx power for chain %d:\n", chain);
2744 		for (ridx = 0; ridx < URTWN_RIDX_COUNT; ridx++)
2745 			printf("Rate %d = %u\n", ridx, power[ridx]);
2746 	}
2747 #endif
2748 }
2749 
2750 void
2751 urtwn_set_txpower(struct urtwn_softc *sc, struct ieee80211_channel *c,
2752     struct ieee80211_channel *extc)
2753 {
2754 	uint16_t power[URTWN_RIDX_COUNT];
2755 	int i;
2756 
2757 	for (i = 0; i < sc->ntxchains; i++) {
2758 		/* Compute per-rate Tx power values. */
2759 		urtwn_get_txpower(sc, i, c, extc, power);
2760 		/* Write per-rate Tx power values to hardware. */
2761 		urtwn_write_txpower(sc, i, power);
2762 	}
2763 }
2764 
2765 void
2766 urtwn_set_chan(struct urtwn_softc *sc, struct ieee80211_channel *c,
2767     struct ieee80211_channel *extc)
2768 {
2769 	struct ieee80211com *ic = &sc->sc_ic;
2770 	uint32_t reg;
2771 	u_int chan;
2772 	int i;
2773 
2774 	chan = ieee80211_chan2ieee(ic, c);	/* XXX center freq! */
2775 
2776 	/* Set Tx power for this new channel. */
2777 	urtwn_set_txpower(sc, c, extc);
2778 
2779 	for (i = 0; i < sc->nrxchains; i++) {
2780 		urtwn_rf_write(sc, i, R92C_RF_CHNLBW,
2781 		    RW(sc->rf_chnlbw[i], R92C_RF_CHNLBW_CHNL, chan));
2782 	}
2783 #ifndef IEEE80211_NO_HT
2784 	if (extc != NULL) {
2785 		/* Is secondary channel below or above primary? */
2786 		int prichlo = c->ic_freq < extc->ic_freq;
2787 
2788 		urtwn_write_1(sc, R92C_BWOPMODE,
2789 		    urtwn_read_1(sc, R92C_BWOPMODE) & ~R92C_BWOPMODE_20MHZ);
2790 
2791 		reg = urtwn_read_1(sc, R92C_RRSR + 2);
2792 		reg = (reg & ~0x6f) | (prichlo ? 1 : 2) << 5;
2793 		urtwn_write_1(sc, R92C_RRSR + 2, reg);
2794 
2795 		urtwn_bb_write(sc, R92C_FPGA0_RFMOD,
2796 		    urtwn_bb_read(sc, R92C_FPGA0_RFMOD) | R92C_RFMOD_40MHZ);
2797 		urtwn_bb_write(sc, R92C_FPGA1_RFMOD,
2798 		    urtwn_bb_read(sc, R92C_FPGA1_RFMOD) | R92C_RFMOD_40MHZ);
2799 
2800 		/* Set CCK side band. */
2801 		reg = urtwn_bb_read(sc, R92C_CCK0_SYSTEM);
2802 		reg = (reg & ~0x00000010) | (prichlo ? 0 : 1) << 4;
2803 		urtwn_bb_write(sc, R92C_CCK0_SYSTEM, reg);
2804 
2805 		reg = urtwn_bb_read(sc, R92C_OFDM1_LSTF);
2806 		reg = (reg & ~0x00000c00) | (prichlo ? 1 : 2) << 10;
2807 		urtwn_bb_write(sc, R92C_OFDM1_LSTF, reg);
2808 
2809 		urtwn_bb_write(sc, R92C_FPGA0_ANAPARAM2,
2810 		    urtwn_bb_read(sc, R92C_FPGA0_ANAPARAM2) &
2811 		    ~R92C_FPGA0_ANAPARAM2_CBW20);
2812 
2813 		reg = urtwn_bb_read(sc, 0x818);
2814 		reg = (reg & ~0x0c000000) | (prichlo ? 2 : 1) << 26;
2815 		urtwn_bb_write(sc, 0x818, reg);
2816 
2817 		/* Select 40MHz bandwidth. */
2818 		urtwn_rf_write(sc, 0, R92C_RF_CHNLBW,
2819 		    (sc->rf_chnlbw[0] & ~0xfff) | chan);
2820 	} else
2821 #endif
2822 	{
2823 		urtwn_write_1(sc, R92C_BWOPMODE,
2824 		    urtwn_read_1(sc, R92C_BWOPMODE) | R92C_BWOPMODE_20MHZ);
2825 
2826 		urtwn_bb_write(sc, R92C_FPGA0_RFMOD,
2827 		    urtwn_bb_read(sc, R92C_FPGA0_RFMOD) & ~R92C_RFMOD_40MHZ);
2828 		urtwn_bb_write(sc, R92C_FPGA1_RFMOD,
2829 		    urtwn_bb_read(sc, R92C_FPGA1_RFMOD) & ~R92C_RFMOD_40MHZ);
2830 
2831 		urtwn_bb_write(sc, R92C_FPGA0_ANAPARAM2,
2832 		    urtwn_bb_read(sc, R92C_FPGA0_ANAPARAM2) |
2833 		    R92C_FPGA0_ANAPARAM2_CBW20);
2834 
2835 		/* Select 20MHz bandwidth. */
2836 		urtwn_rf_write(sc, 0, R92C_RF_CHNLBW,
2837 		    (sc->rf_chnlbw[0] & ~0xfff) | R92C_RF_CHNLBW_BW20 | chan);
2838 	}
2839 }
2840 
2841 int
2842 urtwn_iq_calib_chain(struct urtwn_softc *sc, int chain, uint16_t tx[2],
2843     uint16_t rx[2])
2844 {
2845 	uint32_t status;
2846 	int offset = chain * 0x20;
2847 
2848 	if (chain == 0) {	/* IQ calibration for chain 0. */
2849 		/* IQ calibration settings for chain 0. */
2850 		urtwn_bb_write(sc, 0xe30, 0x10008c1f);
2851 		urtwn_bb_write(sc, 0xe34, 0x10008c1f);
2852 		urtwn_bb_write(sc, 0xe38, 0x82140102);
2853 
2854 		if (sc->ntxchains > 1) {
2855 			urtwn_bb_write(sc, 0xe3c, 0x28160202);	/* 2T */
2856 			/* IQ calibration settings for chain 1. */
2857 			urtwn_bb_write(sc, 0xe50, 0x10008c22);
2858 			urtwn_bb_write(sc, 0xe54, 0x10008c22);
2859 			urtwn_bb_write(sc, 0xe58, 0x82140102);
2860 			urtwn_bb_write(sc, 0xe5c, 0x28160202);
2861 		} else
2862 			urtwn_bb_write(sc, 0xe3c, 0x28160502);	/* 1T */
2863 
2864 		/* LO calibration settings. */
2865 		urtwn_bb_write(sc, 0xe4c, 0x001028d1);
2866 		/* We're doing LO and IQ calibration in one shot. */
2867 		urtwn_bb_write(sc, 0xe48, 0xf9000000);
2868 		urtwn_bb_write(sc, 0xe48, 0xf8000000);
2869 
2870 	} else {		/* IQ calibration for chain 1. */
2871 		/* We're doing LO and IQ calibration in one shot. */
2872 		urtwn_bb_write(sc, 0xe60, 0x00000002);
2873 		urtwn_bb_write(sc, 0xe60, 0x00000000);
2874 	}
2875 
2876 	/* Give LO and IQ calibrations the time to complete. */
2877 	usbd_delay_ms(sc->sc_udev, 1);
2878 
2879 	/* Read IQ calibration status. */
2880 	status = urtwn_bb_read(sc, 0xeac);
2881 
2882 	if (status & (1 << (28 + chain * 3)))
2883 		return (0);	/* Tx failed. */
2884 	/* Read Tx IQ calibration results. */
2885 	tx[0] = (urtwn_bb_read(sc, 0xe94 + offset) >> 16) & 0x3ff;
2886 	tx[1] = (urtwn_bb_read(sc, 0xe9c + offset) >> 16) & 0x3ff;
2887 	if (tx[0] == 0x142 || tx[1] == 0x042)
2888 		return (0);	/* Tx failed. */
2889 
2890 	if (status & (1 << (27 + chain * 3)))
2891 		return (1);	/* Rx failed. */
2892 	/* Read Rx IQ calibration results. */
2893 	rx[2] = (urtwn_bb_read(sc, 0xea4 + offset) >> 16) & 0x3ff;
2894 	rx[3] = (urtwn_bb_read(sc, 0xeac + offset) >> 16) & 0x3ff;
2895 	if (rx[2] == 0x132 || rx[3] == 0x036)
2896 		return (1);	/* Rx failed. */
2897 
2898 	return (3);	/* Both Tx and Rx succeeded. */
2899 }
2900 
2901 void
2902 urtwn_iq_calib(struct urtwn_softc *sc)
2903 {
2904 	/* TODO */
2905 }
2906 
2907 void
2908 urtwn_lc_calib(struct urtwn_softc *sc)
2909 {
2910 	uint32_t rf_ac[2];
2911 	uint8_t txmode;
2912 	int i;
2913 
2914 	txmode = urtwn_read_1(sc, R92C_OFDM1_LSTF + 3);
2915 	if ((txmode & 0x70) != 0) {
2916 		/* Disable all continuous Tx. */
2917 		urtwn_write_1(sc, R92C_OFDM1_LSTF + 3, txmode & ~0x70);
2918 
2919 		/* Set RF mode to standby mode. */
2920 		for (i = 0; i < sc->nrxchains; i++) {
2921 			rf_ac[i] = urtwn_rf_read(sc, i, R92C_RF_AC);
2922 			urtwn_rf_write(sc, i, R92C_RF_AC,
2923 			    RW(rf_ac[i], R92C_RF_AC_MODE,
2924 				R92C_RF_AC_MODE_STANDBY));
2925 		}
2926 	} else {
2927 		/* Block all Tx queues. */
2928 		urtwn_write_1(sc, R92C_TXPAUSE, 0xff);
2929 	}
2930 	/* Start calibration. */
2931 	urtwn_rf_write(sc, 0, R92C_RF_CHNLBW,
2932 	    urtwn_rf_read(sc, 0, R92C_RF_CHNLBW) | R92C_RF_CHNLBW_LCSTART);
2933 
2934 	/* Give calibration the time to complete. */
2935 	usbd_delay_ms(sc->sc_udev, 100);
2936 
2937 	/* Restore configuration. */
2938 	if ((txmode & 0x70) != 0) {
2939 		/* Restore Tx mode. */
2940 		urtwn_write_1(sc, R92C_OFDM1_LSTF + 3, txmode);
2941 		/* Restore RF mode. */
2942 		for (i = 0; i < sc->nrxchains; i++)
2943 			urtwn_rf_write(sc, i, R92C_RF_AC, rf_ac[i]);
2944 	} else {
2945 		/* Unblock all Tx queues. */
2946 		urtwn_write_1(sc, R92C_TXPAUSE, 0x00);
2947 	}
2948 }
2949 
2950 void
2951 urtwn_temp_calib(struct urtwn_softc *sc)
2952 {
2953 	int temp;
2954 
2955 	if (sc->thcal_state == 0) {
2956 		/* Start measuring temperature. */
2957 		urtwn_rf_write(sc, 0, R92C_RF_T_METER, 0x60);
2958 		sc->thcal_state = 1;
2959 		return;
2960 	}
2961 	sc->thcal_state = 0;
2962 
2963 	/* Read measured temperature. */
2964 	temp = urtwn_rf_read(sc, 0, R92C_RF_T_METER) & 0x1f;
2965 	if (temp == 0)	/* Read failed, skip. */
2966 		return;
2967 	DPRINTFN(2, ("temperature=%d\n", temp));
2968 
2969 	/*
2970 	 * Redo LC calibration if temperature changed significantly since
2971 	 * last calibration.
2972 	 */
2973 	if (sc->thcal_lctemp == 0) {
2974 		/* First LC calibration is performed in urtwn_init(). */
2975 		sc->thcal_lctemp = temp;
2976 	} else if (abs(temp - sc->thcal_lctemp) > 1) {
2977 		DPRINTF(("LC calib triggered by temp: %d -> %d\n",
2978 		    sc->thcal_lctemp, temp));
2979 		urtwn_lc_calib(sc);
2980 		/* Record temperature of last LC calibration. */
2981 		sc->thcal_lctemp = temp;
2982 	}
2983 }
2984 
2985 int
2986 urtwn_init(struct ifnet *ifp)
2987 {
2988 	struct urtwn_softc *sc = ifp->if_softc;
2989 	struct ieee80211com *ic = &sc->sc_ic;
2990 	struct urtwn_rx_data *data;
2991 	uint32_t reg;
2992 	int i, error;
2993 
2994 	/* Init host async commands ring. */
2995 	sc->cmdq.cur = sc->cmdq.next = sc->cmdq.queued = 0;
2996 	/* Init firmware commands ring. */
2997 	sc->fwcur = 0;
2998 
2999 	/* Allocate Tx/Rx buffers. */
3000 	error = urtwn_alloc_rx_list(sc);
3001 	if (error != 0) {
3002 		printf("%s: could not allocate Rx buffers\n",
3003 		    sc->sc_dev.dv_xname);
3004 		goto fail;
3005 	}
3006 	error = urtwn_alloc_tx_list(sc);
3007 	if (error != 0) {
3008 		printf("%s: could not allocate Tx buffers\n",
3009 		    sc->sc_dev.dv_xname);
3010 		goto fail;
3011 	}
3012 	/* Power on adapter. */
3013 	error = urtwn_power_on(sc);
3014 	if (error != 0)
3015 		goto fail;
3016 
3017 	/* Initialize DMA. */
3018 	error = urtwn_dma_init(sc);
3019 	if (error != 0)
3020 		goto fail;
3021 
3022 	/* Set info size in Rx descriptors (in 64-bit words). */
3023 	urtwn_write_1(sc, R92C_RX_DRVINFO_SZ, 4);
3024 
3025 	/* Init interrupts. */
3026 	urtwn_write_4(sc, R92C_HISR, 0xffffffff);
3027 	urtwn_write_4(sc, R92C_HIMR, 0xffffffff);
3028 
3029 	/* Set MAC address. */
3030 	IEEE80211_ADDR_COPY(ic->ic_myaddr, LLADDR(ifp->if_sadl));
3031 	urtwn_write_region_1(sc, R92C_MACID, ic->ic_myaddr,
3032 	    IEEE80211_ADDR_LEN);
3033 
3034 	/* Set initial network type. */
3035 	reg = urtwn_read_4(sc, R92C_CR);
3036 	reg = RW(reg, R92C_CR_NETTYPE, R92C_CR_NETTYPE_INFRA);
3037 	urtwn_write_4(sc, R92C_CR, reg);
3038 
3039 	urtwn_rxfilter_init(sc);
3040 
3041 	reg = urtwn_read_4(sc, R92C_RRSR);
3042 	reg = RW(reg, R92C_RRSR_RATE_BITMAP, R92C_RRSR_RATE_CCK_ONLY_1M);
3043 	urtwn_write_4(sc, R92C_RRSR, reg);
3044 
3045 	/* Set short/long retry limits. */
3046 	urtwn_write_2(sc, R92C_RL,
3047 	    SM(R92C_RL_SRL, 0x30) | SM(R92C_RL_LRL, 0x30));
3048 
3049 	/* Initialize EDCA parameters. */
3050 	urtwn_edca_init(sc);
3051 
3052 	/* Setup rate fallback. */
3053 	urtwn_write_4(sc, R92C_DARFRC + 0, 0x00000000);
3054 	urtwn_write_4(sc, R92C_DARFRC + 4, 0x10080404);
3055 	urtwn_write_4(sc, R92C_RARFRC + 0, 0x04030201);
3056 	urtwn_write_4(sc, R92C_RARFRC + 4, 0x08070605);
3057 
3058 	urtwn_write_1(sc, R92C_FWHW_TXQ_CTRL,
3059 	    urtwn_read_1(sc, R92C_FWHW_TXQ_CTRL) |
3060 	    R92C_FWHW_TXQ_CTRL_AMPDU_RTY_NEW);
3061 	/* Set ACK timeout. */
3062 	urtwn_write_1(sc, R92C_ACKTO, 0x40);
3063 
3064 	/* Setup USB aggregation. */
3065 	reg = urtwn_read_4(sc, R92C_TDECTRL);
3066 	reg = RW(reg, R92C_TDECTRL_BLK_DESC_NUM, 6);
3067 	urtwn_write_4(sc, R92C_TDECTRL, reg);
3068 	urtwn_write_1(sc, R92C_TRXDMA_CTRL,
3069 	    urtwn_read_1(sc, R92C_TRXDMA_CTRL) |
3070 	    R92C_TRXDMA_CTRL_RXDMA_AGG_EN);
3071 	urtwn_write_1(sc, R92C_USB_SPECIAL_OPTION,
3072 	    urtwn_read_1(sc, R92C_USB_SPECIAL_OPTION) |
3073 	    R92C_USB_SPECIAL_OPTION_AGG_EN);
3074 	urtwn_write_1(sc, R92C_RXDMA_AGG_PG_TH, 48);
3075 	urtwn_write_1(sc, R92C_USB_DMA_AGG_TO, 4);
3076 	urtwn_write_1(sc, R92C_USB_AGG_TH, 8);
3077 	urtwn_write_1(sc, R92C_USB_AGG_TO, 6);
3078 
3079 	/* Initialize beacon parameters. */
3080 	urtwn_write_2(sc, R92C_TBTT_PROHIBIT, 0x6404);
3081 	urtwn_write_1(sc, R92C_DRVERLYINT, 0x05);
3082 	urtwn_write_1(sc, R92C_BCNDMATIM, 0x02);
3083 	urtwn_write_2(sc, R92C_BCNTCFG, 0x660f);
3084 
3085 	/* Setup AMPDU aggregation. */
3086 	urtwn_write_4(sc, R92C_AGGLEN_LMT, 0x99997631);	/* MCS7~0 */
3087 	urtwn_write_1(sc, R92C_AGGR_BREAK_TIME, 0x16);
3088 	urtwn_write_2(sc, 0x4ca, 0x0708);
3089 
3090 	urtwn_write_1(sc, R92C_BCN_MAX_ERR, 0xff);
3091 	urtwn_write_1(sc, R92C_BCN_CTRL, R92C_BCN_CTRL_DIS_TSF_UDT0);
3092 
3093 	/* Load 8051 microcode. */
3094 	error = urtwn_load_firmware(sc);
3095 	if (error != 0)
3096 		goto fail;
3097 
3098 	/* Initialize MAC/BB/RF blocks. */
3099 	urtwn_mac_init(sc);
3100 	urtwn_bb_init(sc);
3101 	urtwn_rf_init(sc);
3102 
3103 	/* Turn CCK and OFDM blocks on. */
3104 	reg = urtwn_bb_read(sc, R92C_FPGA0_RFMOD);
3105 	reg |= R92C_RFMOD_CCK_EN;
3106 	urtwn_bb_write(sc, R92C_FPGA0_RFMOD, reg);
3107 	reg = urtwn_bb_read(sc, R92C_FPGA0_RFMOD);
3108 	reg |= R92C_RFMOD_OFDM_EN;
3109 	urtwn_bb_write(sc, R92C_FPGA0_RFMOD, reg);
3110 
3111 	/* Clear per-station keys table. */
3112 	urtwn_cam_init(sc);
3113 
3114 	/* Enable hardware sequence numbering. */
3115 	urtwn_write_1(sc, R92C_HWSEQ_CTRL, 0xff);
3116 
3117 	/* Perform LO and IQ calibrations. */
3118 	urtwn_iq_calib(sc);
3119 	/* Perform LC calibration. */
3120 	urtwn_lc_calib(sc);
3121 
3122 	/* Fix USB interference issue. */
3123 	urtwn_write_1(sc, 0xfe40, 0xe0);
3124 	urtwn_write_1(sc, 0xfe41, 0x8d);
3125 	urtwn_write_1(sc, 0xfe42, 0x80);
3126 
3127 	urtwn_pa_bias_init(sc);
3128 
3129 	/* Initialize GPIO setting. */
3130 	urtwn_write_1(sc, R92C_GPIO_MUXCFG,
3131 	    urtwn_read_1(sc, R92C_GPIO_MUXCFG) & ~R92C_GPIO_MUXCFG_ENBT);
3132 
3133 	/* Fix for lower temperature. */
3134 	urtwn_write_1(sc, 0x15, 0xe9);
3135 
3136 	/* Set default channel. */
3137 	ic->ic_bss->ni_chan = ic->ic_ibss_chan;
3138 	urtwn_set_chan(sc, ic->ic_ibss_chan, NULL);
3139 
3140 	/* Queue Rx xfers. */
3141 	for (i = 0; i < URTWN_RX_LIST_COUNT; i++) {
3142 		data = &sc->rx_data[i];
3143 
3144 		usbd_setup_xfer(data->xfer, sc->rx_pipe, data, data->buf,
3145 		    URTWN_RXBUFSZ, USBD_SHORT_XFER_OK | USBD_NO_COPY,
3146 		    USBD_NO_TIMEOUT, urtwn_rxeof);
3147 		error = usbd_transfer(data->xfer);
3148 		if (error != 0 && error != USBD_IN_PROGRESS)
3149 			goto fail;
3150 	}
3151 
3152 	/* We're ready to go. */
3153 	ifp->if_flags &= ~IFF_OACTIVE;
3154 	ifp->if_flags |= IFF_RUNNING;
3155 
3156 #ifdef notyet
3157 	if (ic->ic_flags & IEEE80211_F_WEPON) {
3158 		/* Install WEP keys. */
3159 		for (i = 0; i < IEEE80211_WEP_NKID; i++)
3160 			urtwn_set_key(ic, NULL, &ic->ic_nw_keys[i]);
3161 		urtwn_wait_async(sc);
3162 	}
3163 #endif
3164 	if (ic->ic_opmode == IEEE80211_M_MONITOR)
3165 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
3166 	else
3167 		ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
3168 	return (0);
3169  fail:
3170 	urtwn_stop(ifp);
3171 	return (error);
3172 }
3173 
3174 void
3175 urtwn_stop(struct ifnet *ifp)
3176 {
3177 	struct urtwn_softc *sc = ifp->if_softc;
3178 	struct ieee80211com *ic = &sc->sc_ic;
3179 	int i, s;
3180 
3181 	sc->sc_tx_timer = 0;
3182 	ifp->if_timer = 0;
3183 	ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
3184 
3185 	s = splusb();
3186 	ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
3187 	/* Wait for all async commands to complete. */
3188 	urtwn_wait_async(sc);
3189 	splx(s);
3190 
3191 	timeout_del(&sc->scan_to);
3192 	timeout_del(&sc->calib_to);
3193 
3194 	/* Abort Tx. */
3195 	for (i = 0; i < R92C_MAX_EPOUT; i++) {
3196 		if (sc->tx_pipe[i] != NULL)
3197 			usbd_abort_pipe(sc->tx_pipe[i]);
3198 	}
3199 	/* Stop Rx pipe. */
3200 	usbd_abort_pipe(sc->rx_pipe);
3201 	/* Free Tx/Rx buffers. */
3202 	urtwn_free_tx_list(sc);
3203 	urtwn_free_rx_list(sc);
3204 }
3205