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