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