xref: /freebsd/sys/dev/rtwn/if_rtwn.c (revision 84eacaf728a102612d83861d73c3aaa353ca3dc2)
1 /*	$OpenBSD: if_rtwn.c,v 1.6 2015/08/28 00:03:53 deraadt Exp $	*/
2 
3 /*-
4  * Copyright (c) 2010 Damien Bergamini <damien.bergamini@free.fr>
5  * Copyright (c) 2015 Stefan Sperling <stsp@openbsd.org>
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 #include <sys/cdefs.h>
21 __FBSDID("$FreeBSD$");
22 
23 /*
24  * Driver for Realtek RTL8188CE
25  */
26 
27 #include <sys/param.h>
28 #include <sys/sysctl.h>
29 #include <sys/sockio.h>
30 #include <sys/mbuf.h>
31 #include <sys/kernel.h>
32 #include <sys/socket.h>
33 #include <sys/systm.h>
34 #include <sys/malloc.h>
35 #include <sys/lock.h>
36 #include <sys/mutex.h>
37 #include <sys/module.h>
38 #include <sys/bus.h>
39 #include <sys/endian.h>
40 #include <sys/firmware.h>
41 
42 #include <machine/bus.h>
43 #include <machine/resource.h>
44 #include <sys/rman.h>
45 
46 #include <dev/pci/pcireg.h>
47 #include <dev/pci/pcivar.h>
48 
49 #include <net/bpf.h>
50 #include <net/if.h>
51 #include <net/if_var.h>
52 #include <net/if_arp.h>
53 #include <net/ethernet.h>
54 #include <net/if_dl.h>
55 #include <net/if_media.h>
56 #include <net/if_types.h>
57 
58 #include <net80211/ieee80211_var.h>
59 #include <net80211/ieee80211_radiotap.h>
60 #include <net80211/ieee80211_regdomain.h>
61 #include <net80211/ieee80211_ratectl.h>
62 
63 #include <netinet/in.h>
64 #include <netinet/in_systm.h>
65 #include <netinet/in_var.h>
66 #include <netinet/ip.h>
67 #include <netinet/if_ether.h>
68 
69 #include <dev/rtwn/if_rtwnreg.h>
70 
71 #define	RTWN_DEBUG
72 #ifdef RTWN_DEBUG
73 #define	DPRINTF(x)	do { if (sc->sc_debug > 0) printf x; } while (0)
74 #define	DPRINTFN(n, x)	do { if (sc->sc_debug >= (n)) printf x; } while (0)
75 #else
76 #define	DPRINTF(x)
77 #define	DPRINTFN(n, x)
78 #endif
79 
80 /*
81  * PCI configuration space registers.
82  */
83 #define	RTWN_PCI_IOBA		0x10	/* i/o mapped base */
84 #define	RTWN_PCI_MMBA		0x18	/* memory mapped base */
85 
86 #define RTWN_INT_ENABLE	(R92C_IMR_ROK | R92C_IMR_VODOK | R92C_IMR_VIDOK | \
87 			R92C_IMR_BEDOK | R92C_IMR_BKDOK | R92C_IMR_MGNTDOK | \
88 			R92C_IMR_HIGHDOK | R92C_IMR_BDOK | R92C_IMR_RDU | \
89 			R92C_IMR_RXFOVW)
90 
91 struct rtwn_ident {
92 	uint16_t	vendor;
93 	uint16_t	device;
94 	const char	*name;
95 };
96 
97 
98 static const struct rtwn_ident rtwn_ident_table[] = {
99 	{ 0x10ec, 0x8176, "Realtek RTL8188CE" },
100 	{ 0, 0, NULL }
101 };
102 
103 
104 static void	rtwn_dma_map_addr(void *, bus_dma_segment_t *, int, int);
105 static void	rtwn_setup_rx_desc(struct rtwn_softc *, struct r92c_rx_desc *,
106 		    bus_addr_t, size_t, int);
107 static int	rtwn_alloc_rx_list(struct rtwn_softc *);
108 static void	rtwn_reset_rx_list(struct rtwn_softc *);
109 static void	rtwn_free_rx_list(struct rtwn_softc *);
110 static int	rtwn_alloc_tx_list(struct rtwn_softc *, int);
111 static void	rtwn_reset_tx_list(struct rtwn_softc *, int);
112 static void	rtwn_free_tx_list(struct rtwn_softc *, int);
113 static struct ieee80211vap *rtwn_vap_create(struct ieee80211com *,
114 		    const char [IFNAMSIZ], int, enum ieee80211_opmode, int,
115 		    const uint8_t [IEEE80211_ADDR_LEN],
116 		    const uint8_t [IEEE80211_ADDR_LEN]);
117 static void	rtwn_vap_delete(struct ieee80211vap *);
118 static void	rtwn_write_1(struct rtwn_softc *, uint16_t, uint8_t);
119 static void	rtwn_write_2(struct rtwn_softc *, uint16_t, uint16_t);
120 static void	rtwn_write_4(struct rtwn_softc *, uint16_t, uint32_t);
121 static uint8_t	rtwn_read_1(struct rtwn_softc *, uint16_t);
122 static uint16_t	rtwn_read_2(struct rtwn_softc *, uint16_t);
123 static uint32_t	rtwn_read_4(struct rtwn_softc *, uint16_t);
124 static int	rtwn_fw_cmd(struct rtwn_softc *, uint8_t, const void *, int);
125 static void	rtwn_rf_write(struct rtwn_softc *, int, uint8_t, uint32_t);
126 static uint32_t	rtwn_rf_read(struct rtwn_softc *, int, uint8_t);
127 static int	rtwn_llt_write(struct rtwn_softc *, uint32_t, uint32_t);
128 static uint8_t	rtwn_efuse_read_1(struct rtwn_softc *, uint16_t);
129 static void	rtwn_efuse_read(struct rtwn_softc *);
130 static int	rtwn_read_chipid(struct rtwn_softc *);
131 static void	rtwn_read_rom(struct rtwn_softc *);
132 static int	rtwn_ra_init(struct rtwn_softc *);
133 static void	rtwn_tsf_sync_enable(struct rtwn_softc *);
134 static void	rtwn_set_led(struct rtwn_softc *, int, int);
135 static void	rtwn_calib_to(void *);
136 static int	rtwn_newstate(struct ieee80211vap *, enum ieee80211_state, int);
137 static int	rtwn_updateedca(struct ieee80211com *);
138 static void	rtwn_update_avgrssi(struct rtwn_softc *, int, int8_t);
139 static int8_t	rtwn_get_rssi(struct rtwn_softc *, int, void *);
140 static void	rtwn_rx_frame(struct rtwn_softc *, struct r92c_rx_desc *,
141 		    struct rtwn_rx_data *, int);
142 static int	rtwn_tx(struct rtwn_softc *, struct mbuf *,
143 		    struct ieee80211_node *);
144 static void	rtwn_tx_done(struct rtwn_softc *, int);
145 static int	rtwn_raw_xmit(struct ieee80211_node *, struct mbuf *,
146 		    const struct ieee80211_bpf_params *);
147 static int	rtwn_transmit(struct ieee80211com *, struct mbuf *);
148 static void	rtwn_parent(struct ieee80211com *);
149 static void	rtwn_start(struct rtwn_softc *sc);
150 static void	rtwn_watchdog(void *);
151 static int	rtwn_power_on(struct rtwn_softc *);
152 static int	rtwn_llt_init(struct rtwn_softc *);
153 static void	rtwn_fw_reset(struct rtwn_softc *);
154 static void	rtwn_fw_loadpage(struct rtwn_softc *, int, const uint8_t *,
155 		    int);
156 static int	rtwn_load_firmware(struct rtwn_softc *);
157 static int	rtwn_dma_init(struct rtwn_softc *);
158 static void	rtwn_mac_init(struct rtwn_softc *);
159 static void	rtwn_bb_init(struct rtwn_softc *);
160 static void	rtwn_rf_init(struct rtwn_softc *);
161 static void	rtwn_cam_init(struct rtwn_softc *);
162 static void	rtwn_pa_bias_init(struct rtwn_softc *);
163 static void	rtwn_rxfilter_init(struct rtwn_softc *);
164 static void	rtwn_edca_init(struct rtwn_softc *);
165 static void	rtwn_write_txpower(struct rtwn_softc *, int, uint16_t[]);
166 static void	rtwn_get_txpower(struct rtwn_softc *, int,
167 		    struct ieee80211_channel *, struct ieee80211_channel *,
168 		    uint16_t[]);
169 static void	rtwn_set_txpower(struct rtwn_softc *,
170 		    struct ieee80211_channel *, struct ieee80211_channel *);
171 static void	rtwn_scan_start(struct ieee80211com *);
172 static void	rtwn_scan_end(struct ieee80211com *);
173 static void	rtwn_set_channel(struct ieee80211com *);
174 static void	rtwn_update_mcast(struct ieee80211com *);
175 static void	rtwn_set_chan(struct rtwn_softc *,
176 		    struct ieee80211_channel *, struct ieee80211_channel *);
177 static int	rtwn_iq_calib_chain(struct rtwn_softc *, int, uint16_t[2],
178 		    uint16_t[2]);
179 static void	rtwn_iq_calib_run(struct rtwn_softc *, int, uint16_t[2][2],
180 		    uint16_t[2][2]);
181 static int	rtwn_iq_calib_compare_results(uint16_t[2][2], uint16_t[2][2],
182 		    uint16_t[2][2], uint16_t[2][2], int);
183 static void	rtwn_iq_calib_write_results(struct rtwn_softc *, uint16_t[2],
184 		    uint16_t[2], int);
185 static void	rtwn_iq_calib(struct rtwn_softc *);
186 static void	rtwn_lc_calib(struct rtwn_softc *);
187 static void	rtwn_temp_calib(struct rtwn_softc *);
188 static void	rtwn_init_locked(struct rtwn_softc *);
189 static void	rtwn_init(struct rtwn_softc *);
190 static void	rtwn_stop_locked(struct rtwn_softc *);
191 static void	rtwn_stop(struct rtwn_softc *);
192 static void	rtwn_intr(void *);
193 static void	rtwn_hw_reset(void *, int);
194 
195 /* Aliases. */
196 #define	rtwn_bb_write	rtwn_write_4
197 #define rtwn_bb_read	rtwn_read_4
198 
199 static int	rtwn_probe(device_t);
200 static int	rtwn_attach(device_t);
201 static int	rtwn_detach(device_t);
202 static int	rtwn_shutdown(device_t);
203 static int	rtwn_suspend(device_t);
204 static int	rtwn_resume(device_t);
205 
206 static device_method_t rtwn_methods[] = {
207 	/* Device interface */
208 	DEVMETHOD(device_probe,		rtwn_probe),
209 	DEVMETHOD(device_attach,	rtwn_attach),
210 	DEVMETHOD(device_detach,	rtwn_detach),
211 	DEVMETHOD(device_shutdown,	rtwn_shutdown),
212 	DEVMETHOD(device_suspend,	rtwn_suspend),
213 	DEVMETHOD(device_resume,	rtwn_resume),
214 
215 	DEVMETHOD_END
216 };
217 
218 static driver_t rtwn_driver = {
219 	"rtwn",
220 	rtwn_methods,
221 	sizeof (struct rtwn_softc)
222 };
223 static devclass_t rtwn_devclass;
224 
225 DRIVER_MODULE(rtwn, pci, rtwn_driver, rtwn_devclass, NULL, NULL);
226 
227 MODULE_VERSION(rtwn, 1);
228 
229 MODULE_DEPEND(rtwn, pci,  1, 1, 1);
230 MODULE_DEPEND(rtwn, wlan, 1, 1, 1);
231 MODULE_DEPEND(rtwn, firmware, 1, 1, 1);
232 
233 static int
234 rtwn_probe(device_t dev)
235 {
236 	const struct rtwn_ident *ident;
237 
238 	for (ident = rtwn_ident_table; ident->name != NULL; ident++) {
239 		if (pci_get_vendor(dev) == ident->vendor &&
240 		    pci_get_device(dev) == ident->device) {
241 			device_set_desc(dev, ident->name);
242 			return (BUS_PROBE_DEFAULT);
243 		}
244 	}
245 	return (ENXIO);
246 }
247 
248 static int
249 rtwn_attach(device_t dev)
250 {
251 	struct rtwn_softc *sc = device_get_softc(dev);
252 	struct ieee80211com *ic = &sc->sc_ic;
253 	uint32_t lcsr;
254 	uint8_t bands[howmany(IEEE80211_MODE_MAX, 8)];
255 	int i, count, error, rid;
256 
257 	sc->sc_dev = dev;
258 	sc->sc_debug = 0;
259 
260 	/*
261 	 * Get the offset of the PCI Express Capability Structure in PCI
262 	 * Configuration Space.
263 	 */
264 	error = pci_find_cap(dev, PCIY_EXPRESS, &sc->sc_cap_off);
265 	if (error != 0) {
266 		device_printf(dev, "PCIe capability structure not found!\n");
267 		return (error);
268 	}
269 
270 	/* Enable bus-mastering. */
271 	pci_enable_busmaster(dev);
272 
273 	rid = PCIR_BAR(2);
274 	sc->mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid,
275 	    RF_ACTIVE);
276 	if (sc->mem == NULL) {
277 		device_printf(dev, "can't map mem space\n");
278 		return (ENOMEM);
279 	}
280 	sc->sc_st = rman_get_bustag(sc->mem);
281 	sc->sc_sh = rman_get_bushandle(sc->mem);
282 
283 	/* Install interrupt handler. */
284 	count = 1;
285 	rid = 0;
286 	if (pci_alloc_msi(dev, &count) == 0)
287 		rid = 1;
288 	sc->irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, RF_ACTIVE |
289 	    (rid != 0 ? 0 : RF_SHAREABLE));
290 	if (sc->irq == NULL) {
291 		device_printf(dev, "can't map interrupt\n");
292 		return (ENXIO);
293 	}
294 
295 	RTWN_LOCK_INIT(sc);
296 	callout_init_mtx(&sc->calib_to, &sc->sc_mtx, 0);
297 	callout_init_mtx(&sc->watchdog_to, &sc->sc_mtx, 0);
298 	TASK_INIT(&sc->sc_reinit_task, 0, rtwn_hw_reset, sc);
299 	mbufq_init(&sc->sc_snd, ifqmaxlen);
300 
301 	error = rtwn_read_chipid(sc);
302 	if (error != 0) {
303 		device_printf(dev, "unsupported test chip\n");
304 		goto fail;
305 	}
306 
307 	/* Disable PCIe Active State Power Management (ASPM). */
308 	lcsr = pci_read_config(sc->sc_dev, sc->sc_cap_off + PCIER_LINK_CTL, 4);
309 	lcsr &= ~PCIEM_LINK_CTL_ASPMC;
310 	pci_write_config(sc->sc_dev, sc->sc_cap_off + PCIER_LINK_CTL, lcsr, 4);
311 
312 	/* Allocate Tx/Rx buffers. */
313 	error = rtwn_alloc_rx_list(sc);
314 	if (error != 0) {
315 		device_printf(dev, "could not allocate Rx buffers\n");
316 		goto fail;
317 	}
318 	for (i = 0; i < RTWN_NTXQUEUES; i++) {
319 		error = rtwn_alloc_tx_list(sc, i);
320 		if (error != 0) {
321 			device_printf(dev, "could not allocate Tx buffers\n");
322 			goto fail;
323 		}
324 	}
325 
326 	/* Determine number of Tx/Rx chains. */
327 	if (sc->chip & RTWN_CHIP_92C) {
328 		sc->ntxchains = (sc->chip & RTWN_CHIP_92C_1T2R) ? 1 : 2;
329 		sc->nrxchains = 2;
330 	} else {
331 		sc->ntxchains = 1;
332 		sc->nrxchains = 1;
333 	}
334 	rtwn_read_rom(sc);
335 
336 	device_printf(sc->sc_dev, "MAC/BB RTL%s, RF 6052 %dT%dR\n",
337 	    (sc->chip & RTWN_CHIP_92C) ? "8192CE" : "8188CE",
338 	    sc->ntxchains, sc->nrxchains);
339 
340 	ic->ic_softc = sc;
341 	ic->ic_name = device_get_nameunit(dev);
342 	ic->ic_opmode = IEEE80211_M_STA;
343 	ic->ic_phytype = IEEE80211_T_OFDM; /* not only, but not used */
344 
345 	/* set device capabilities */
346 	ic->ic_caps =
347 		  IEEE80211_C_STA		/* station mode */
348 		| IEEE80211_C_MONITOR		/* monitor mode */
349 		| IEEE80211_C_SHPREAMBLE	/* short preamble supported */
350 		| IEEE80211_C_SHSLOT		/* short slot time supported */
351 		| IEEE80211_C_WPA		/* capable of WPA1+WPA2 */
352 		| IEEE80211_C_BGSCAN		/* capable of bg scanning */
353 		| IEEE80211_C_WME		/* 802.11e */
354 		;
355 
356 	memset(bands, 0, sizeof(bands));
357 	setbit(bands, IEEE80211_MODE_11B);
358 	setbit(bands, IEEE80211_MODE_11G);
359 	ieee80211_init_channels(ic, NULL, bands);
360 
361 	ieee80211_ifattach(ic);
362 
363 	ic->ic_wme.wme_update = rtwn_updateedca;
364 	ic->ic_update_mcast = rtwn_update_mcast;
365 	ic->ic_scan_start =rtwn_scan_start;
366 	ic->ic_scan_end = rtwn_scan_end;
367 	ic->ic_set_channel = rtwn_set_channel;
368 	ic->ic_raw_xmit = rtwn_raw_xmit;
369 	ic->ic_transmit = rtwn_transmit;
370 	ic->ic_parent = rtwn_parent;
371 	ic->ic_vap_create = rtwn_vap_create;
372 	ic->ic_vap_delete = rtwn_vap_delete;
373 
374 	ieee80211_radiotap_attach(ic,
375 	    &sc->sc_txtap.wt_ihdr, sizeof(sc->sc_txtap),
376 		RTWN_TX_RADIOTAP_PRESENT,
377 	    &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap),
378 		RTWN_RX_RADIOTAP_PRESENT);
379 
380 	/*
381 	 * Hook our interrupt after all initialization is complete.
382 	 */
383 	error = bus_setup_intr(dev, sc->irq, INTR_TYPE_NET | INTR_MPSAFE,
384 	    NULL, rtwn_intr, sc, &sc->sc_ih);
385 	if (error != 0) {
386 		device_printf(dev, "can't establish interrupt, error %d\n",
387 		    error);
388 		goto fail;
389 	}
390 
391 	if (bootverbose)
392 		ieee80211_announce(ic);
393 
394 	return (0);
395 
396 fail:
397 	rtwn_detach(dev);
398 	return (error);
399 }
400 
401 
402 static int
403 rtwn_detach(device_t dev)
404 {
405 	struct rtwn_softc *sc = device_get_softc(dev);
406 	int i;
407 
408 	if (sc->sc_ic.ic_softc != NULL) {
409 		ieee80211_draintask(&sc->sc_ic, &sc->sc_reinit_task);
410 		rtwn_stop(sc);
411 
412 		callout_drain(&sc->calib_to);
413 		callout_drain(&sc->watchdog_to);
414 		ieee80211_ifdetach(&sc->sc_ic);
415 		mbufq_drain(&sc->sc_snd);
416 	}
417 
418 	/* Uninstall interrupt handler. */
419 	if (sc->irq != NULL) {
420 		bus_teardown_intr(dev, sc->irq, sc->sc_ih);
421 		bus_release_resource(dev, SYS_RES_IRQ, rman_get_rid(sc->irq),
422 		    sc->irq);
423 		pci_release_msi(dev);
424 	}
425 
426 	/* Free Tx/Rx buffers. */
427 	for (i = 0; i < RTWN_NTXQUEUES; i++)
428 		rtwn_free_tx_list(sc, i);
429 	rtwn_free_rx_list(sc);
430 
431 	if (sc->mem != NULL)
432 		bus_release_resource(dev, SYS_RES_MEMORY,
433 		    rman_get_rid(sc->mem), sc->mem);
434 
435 	RTWN_LOCK_DESTROY(sc);
436 	return (0);
437 }
438 
439 static int
440 rtwn_shutdown(device_t dev)
441 {
442 
443 	return (0);
444 }
445 
446 static int
447 rtwn_suspend(device_t dev)
448 {
449 	return (0);
450 }
451 
452 static int
453 rtwn_resume(device_t dev)
454 {
455 
456 	return (0);
457 }
458 
459 static void
460 rtwn_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
461 {
462 
463 	if (error != 0)
464 		return;
465 	KASSERT(nsegs == 1, ("too many DMA segments, %d should be 1", nsegs));
466 	*(bus_addr_t *)arg = segs[0].ds_addr;
467 }
468 
469 static void
470 rtwn_setup_rx_desc(struct rtwn_softc *sc, struct r92c_rx_desc *desc,
471     bus_addr_t addr, size_t len, int idx)
472 {
473 
474 	memset(desc, 0, sizeof(*desc));
475 	desc->rxdw0 = htole32(SM(R92C_RXDW0_PKTLEN, len) |
476 		((idx == RTWN_RX_LIST_COUNT - 1) ? R92C_RXDW0_EOR : 0));
477 	desc->rxbufaddr = htole32(addr);
478 	bus_space_barrier(sc->sc_st, sc->sc_sh, 0, sc->sc_mapsize,
479 	    BUS_SPACE_BARRIER_WRITE);
480 	desc->rxdw0 |= htole32(R92C_RXDW0_OWN);
481 }
482 
483 static int
484 rtwn_alloc_rx_list(struct rtwn_softc *sc)
485 {
486 	struct rtwn_rx_ring *rx_ring = &sc->rx_ring;
487 	struct rtwn_rx_data *rx_data;
488 	bus_size_t size;
489 	int i, error;
490 
491 	/* Allocate Rx descriptors. */
492 	size = sizeof(struct r92c_rx_desc) * RTWN_RX_LIST_COUNT;
493 	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 1, 0,
494 	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
495 	    size, 1, size, 0, NULL, NULL, &rx_ring->desc_dmat);
496 	if (error != 0) {
497 		device_printf(sc->sc_dev, "could not create rx desc DMA tag\n");
498 		goto fail;
499 	}
500 
501 	error = bus_dmamem_alloc(rx_ring->desc_dmat, (void **)&rx_ring->desc,
502 	    BUS_DMA_NOWAIT | BUS_DMA_ZERO | BUS_DMA_COHERENT,
503 	    &rx_ring->desc_map);
504 	if (error != 0) {
505 		device_printf(sc->sc_dev, "could not allocate rx desc\n");
506 		goto fail;
507 	}
508 	error = bus_dmamap_load(rx_ring->desc_dmat, rx_ring->desc_map,
509 	    rx_ring->desc, size, rtwn_dma_map_addr, &rx_ring->paddr, 0);
510 	if (error != 0) {
511 		device_printf(sc->sc_dev, "could not load rx desc DMA map\n");
512 		goto fail;
513 	}
514 	bus_dmamap_sync(rx_ring->desc_dmat, rx_ring->desc_map,
515 	    BUS_DMASYNC_PREWRITE);
516 
517 	/* Create RX buffer DMA tag. */
518 	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 1, 0,
519 	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES,
520 	    1, MCLBYTES, 0, NULL, NULL, &rx_ring->data_dmat);
521 	if (error != 0) {
522 		device_printf(sc->sc_dev, "could not create rx buf DMA tag\n");
523 		goto fail;
524 	}
525 
526 	/* Allocate Rx buffers. */
527 	for (i = 0; i < RTWN_RX_LIST_COUNT; i++) {
528 		rx_data = &rx_ring->rx_data[i];
529 		error = bus_dmamap_create(rx_ring->data_dmat, 0, &rx_data->map);
530 		if (error != 0) {
531 			device_printf(sc->sc_dev,
532 			    "could not create rx buf DMA map\n");
533 			goto fail;
534 		}
535 
536 		rx_data->m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
537 		if (rx_data->m == NULL) {
538 			device_printf(sc->sc_dev,
539 			    "could not allocate rx mbuf\n");
540 			error = ENOMEM;
541 			goto fail;
542 		}
543 
544 		error = bus_dmamap_load(rx_ring->data_dmat, rx_data->map,
545 		    mtod(rx_data->m, void *), MCLBYTES, rtwn_dma_map_addr,
546 		    &rx_data->paddr, BUS_DMA_NOWAIT);
547 		if (error != 0) {
548 			device_printf(sc->sc_dev,
549 			    "could not load rx buf DMA map");
550 			goto fail;
551 		}
552 
553 		rtwn_setup_rx_desc(sc, &rx_ring->desc[i], rx_data->paddr,
554 		    MCLBYTES, i);
555 	}
556 	return (0);
557 
558 fail:
559 	rtwn_free_rx_list(sc);
560 	return (error);
561 }
562 
563 static void
564 rtwn_reset_rx_list(struct rtwn_softc *sc)
565 {
566 	struct rtwn_rx_ring *rx_ring = &sc->rx_ring;
567 	struct rtwn_rx_data *rx_data;
568 	int i;
569 
570 	for (i = 0; i < RTWN_RX_LIST_COUNT; i++) {
571 		rx_data = &rx_ring->rx_data[i];
572 		rtwn_setup_rx_desc(sc, &rx_ring->desc[i], rx_data->paddr,
573 		    MCLBYTES, i);
574 	}
575 }
576 
577 static void
578 rtwn_free_rx_list(struct rtwn_softc *sc)
579 {
580 	struct rtwn_rx_ring *rx_ring = &sc->rx_ring;
581 	struct rtwn_rx_data *rx_data;
582 	int i;
583 
584 	if (rx_ring->desc_dmat != NULL) {
585 		if (rx_ring->desc != NULL) {
586 			bus_dmamap_unload(rx_ring->desc_dmat,
587 			    rx_ring->desc_map);
588 			bus_dmamem_free(rx_ring->desc_dmat, rx_ring->desc,
589 			    rx_ring->desc_map);
590 			rx_ring->desc = NULL;
591 		}
592 		bus_dma_tag_destroy(rx_ring->desc_dmat);
593 		rx_ring->desc_dmat = NULL;
594 	}
595 
596 	for (i = 0; i < RTWN_RX_LIST_COUNT; i++) {
597 		rx_data = &rx_ring->rx_data[i];
598 
599 		if (rx_data->m != NULL) {
600 			bus_dmamap_unload(rx_ring->data_dmat, rx_data->map);
601 			m_freem(rx_data->m);
602 			rx_data->m = NULL;
603 		}
604 		bus_dmamap_destroy(rx_ring->data_dmat, rx_data->map);
605 		rx_data->map = NULL;
606 	}
607 	if (rx_ring->data_dmat != NULL) {
608 		bus_dma_tag_destroy(rx_ring->data_dmat);
609 		rx_ring->data_dmat = NULL;
610 	}
611 }
612 
613 static int
614 rtwn_alloc_tx_list(struct rtwn_softc *sc, int qid)
615 {
616 	struct rtwn_tx_ring *tx_ring = &sc->tx_ring[qid];
617 	struct rtwn_tx_data *tx_data;
618 	bus_size_t size;
619 	int i, error;
620 
621 	size = sizeof(struct r92c_tx_desc) * RTWN_TX_LIST_COUNT;
622 	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), PAGE_SIZE, 0,
623 	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
624 	    size, 1, size, 0, NULL, NULL, &tx_ring->desc_dmat);
625 	if (error != 0) {
626 		device_printf(sc->sc_dev, "could not create tx ring DMA tag\n");
627 		goto fail;
628 	}
629 
630 	error = bus_dmamem_alloc(tx_ring->desc_dmat, (void **)&tx_ring->desc,
631 	    BUS_DMA_NOWAIT | BUS_DMA_ZERO, &tx_ring->desc_map);
632 	if (error != 0) {
633 		device_printf(sc->sc_dev, "can't map tx ring DMA memory\n");
634 		goto fail;
635 	}
636 	error = bus_dmamap_load(tx_ring->desc_dmat, tx_ring->desc_map,
637 	    tx_ring->desc, size, rtwn_dma_map_addr, &tx_ring->paddr,
638 	    BUS_DMA_NOWAIT);
639 	if (error != 0) {
640 		device_printf(sc->sc_dev, "could not load desc DMA map\n");
641 		goto fail;
642 	}
643 
644 	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 1, 0,
645 	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES,
646 	    1, MCLBYTES, 0, NULL, NULL, &tx_ring->data_dmat);
647 	if (error != 0) {
648 		device_printf(sc->sc_dev, "could not create tx buf DMA tag\n");
649 		goto fail;
650 	}
651 
652 	for (i = 0; i < RTWN_TX_LIST_COUNT; i++) {
653 		struct r92c_tx_desc *desc = &tx_ring->desc[i];
654 
655 		/* setup tx desc */
656 		desc->nextdescaddr = htole32(tx_ring->paddr +
657 		    + sizeof(struct r92c_tx_desc)
658 		    * ((i + 1) % RTWN_TX_LIST_COUNT));
659 		tx_data = &tx_ring->tx_data[i];
660 		error = bus_dmamap_create(tx_ring->data_dmat, 0, &tx_data->map);
661 		if (error != 0) {
662 			device_printf(sc->sc_dev,
663 			    "could not create tx buf DMA map\n");
664 			goto fail;
665 		}
666 		tx_data->m = NULL;
667 		tx_data->ni = NULL;
668 	}
669 	return (0);
670 
671 fail:
672 	rtwn_free_tx_list(sc, qid);
673 	return (error);
674 }
675 
676 static void
677 rtwn_reset_tx_list(struct rtwn_softc *sc, int qid)
678 {
679 	struct rtwn_tx_ring *tx_ring = &sc->tx_ring[qid];
680 	int i;
681 
682 	for (i = 0; i < RTWN_TX_LIST_COUNT; i++) {
683 		struct r92c_tx_desc *desc = &tx_ring->desc[i];
684 		struct rtwn_tx_data *tx_data = &tx_ring->tx_data[i];
685 
686 		memset(desc, 0, sizeof(*desc) -
687 		    (sizeof(desc->reserved) + sizeof(desc->nextdescaddr64) +
688 		    sizeof(desc->nextdescaddr)));
689 
690 		if (tx_data->m != NULL) {
691 			bus_dmamap_unload(tx_ring->data_dmat, tx_data->map);
692 			m_freem(tx_data->m);
693 			tx_data->m = NULL;
694 		}
695 		if (tx_data->ni != NULL) {
696 			ieee80211_free_node(tx_data->ni);
697 			tx_data->ni = NULL;
698 		}
699 	}
700 
701 	bus_dmamap_sync(tx_ring->desc_dmat, tx_ring->desc_map,
702 	    BUS_DMASYNC_POSTWRITE);
703 
704 	sc->qfullmsk &= ~(1 << qid);
705 	tx_ring->queued = 0;
706 	tx_ring->cur = 0;
707 }
708 
709 static void
710 rtwn_free_tx_list(struct rtwn_softc *sc, int qid)
711 {
712 	struct rtwn_tx_ring *tx_ring = &sc->tx_ring[qid];
713 	struct rtwn_tx_data *tx_data;
714 	int i;
715 
716 	if (tx_ring->desc_dmat != NULL) {
717 		if (tx_ring->desc != NULL) {
718 			bus_dmamap_unload(tx_ring->desc_dmat,
719 			    tx_ring->desc_map);
720 			bus_dmamem_free(tx_ring->desc_dmat, tx_ring->desc,
721 			    tx_ring->desc_map);
722 		}
723 		bus_dma_tag_destroy(tx_ring->desc_dmat);
724 	}
725 
726 	for (i = 0; i < RTWN_TX_LIST_COUNT; i++) {
727 		tx_data = &tx_ring->tx_data[i];
728 
729 		if (tx_data->m != NULL) {
730 			bus_dmamap_unload(tx_ring->data_dmat, tx_data->map);
731 			m_freem(tx_data->m);
732 			tx_data->m = NULL;
733 		}
734 	}
735 	if (tx_ring->data_dmat != NULL) {
736 		bus_dma_tag_destroy(tx_ring->data_dmat);
737 		tx_ring->data_dmat = NULL;
738 	}
739 
740 	sc->qfullmsk &= ~(1 << qid);
741 	tx_ring->queued = 0;
742 	tx_ring->cur = 0;
743 }
744 
745 
746 static struct ieee80211vap *
747 rtwn_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
748     enum ieee80211_opmode opmode, int flags,
749     const uint8_t bssid[IEEE80211_ADDR_LEN],
750     const uint8_t mac[IEEE80211_ADDR_LEN])
751 {
752 	struct rtwn_vap *rvp;
753 	struct ieee80211vap *vap;
754 
755 	if (!TAILQ_EMPTY(&ic->ic_vaps))
756 		return (NULL);
757 
758 	rvp = malloc(sizeof(struct rtwn_vap), M_80211_VAP, M_WAITOK | M_ZERO);
759 	vap = &rvp->vap;
760 	if (ieee80211_vap_setup(ic, vap, name, unit, opmode,
761 	    flags | IEEE80211_CLONE_NOBEACONS, bssid) != 0) {
762 		/* out of memory */
763 		 free(rvp, M_80211_VAP);
764 		 return (NULL);
765 	}
766 
767 	/* Override state transition machine. */
768 	rvp->newstate = vap->iv_newstate;
769 	vap->iv_newstate = rtwn_newstate;
770 
771 	/* Complete setup. */
772 	ieee80211_vap_attach(vap, ieee80211_media_change,
773 	    ieee80211_media_status, mac);
774 	ic->ic_opmode = opmode;
775 	return (vap);
776 }
777 
778 static void
779 rtwn_vap_delete(struct ieee80211vap *vap)
780 {
781 	struct rtwn_vap *rvp = RTWN_VAP(vap);
782 
783 	ieee80211_vap_detach(vap);
784 	free(rvp, M_80211_VAP);
785 }
786 
787 static void
788 rtwn_write_1(struct rtwn_softc *sc, uint16_t addr, uint8_t val)
789 {
790 
791 	bus_space_write_1(sc->sc_st, sc->sc_sh, addr, val);
792 }
793 
794 static void
795 rtwn_write_2(struct rtwn_softc *sc, uint16_t addr, uint16_t val)
796 {
797 
798 	val = htole16(val);
799 	bus_space_write_2(sc->sc_st, sc->sc_sh, addr, val);
800 }
801 
802 static void
803 rtwn_write_4(struct rtwn_softc *sc, uint16_t addr, uint32_t val)
804 {
805 
806 	val = htole32(val);
807 	bus_space_write_4(sc->sc_st, sc->sc_sh, addr, val);
808 }
809 
810 static uint8_t
811 rtwn_read_1(struct rtwn_softc *sc, uint16_t addr)
812 {
813 
814 	return (bus_space_read_1(sc->sc_st, sc->sc_sh, addr));
815 }
816 
817 static uint16_t
818 rtwn_read_2(struct rtwn_softc *sc, uint16_t addr)
819 {
820 
821 	return (bus_space_read_2(sc->sc_st, sc->sc_sh, addr));
822 }
823 
824 static uint32_t
825 rtwn_read_4(struct rtwn_softc *sc, uint16_t addr)
826 {
827 
828 	return (bus_space_read_4(sc->sc_st, sc->sc_sh, addr));
829 }
830 
831 static int
832 rtwn_fw_cmd(struct rtwn_softc *sc, uint8_t id, const void *buf, int len)
833 {
834 	struct r92c_fw_cmd cmd;
835 	int ntries;
836 
837 	/* Wait for current FW box to be empty. */
838 	for (ntries = 0; ntries < 100; ntries++) {
839 		if (!(rtwn_read_1(sc, R92C_HMETFR) & (1 << sc->fwcur)))
840 			break;
841 		DELAY(1);
842 	}
843 	if (ntries == 100) {
844 		device_printf(sc->sc_dev,
845 		    "could not send firmware command %d\n", id);
846 		return (ETIMEDOUT);
847 	}
848 	memset(&cmd, 0, sizeof(cmd));
849 	cmd.id = id;
850 	if (len > 3)
851 		cmd.id |= R92C_CMD_FLAG_EXT;
852 	KASSERT(len <= sizeof(cmd.msg), ("rtwn_fw_cmd\n"));
853 	memcpy(cmd.msg, buf, len);
854 
855 	/* Write the first word last since that will trigger the FW. */
856 	rtwn_write_2(sc, R92C_HMEBOX_EXT(sc->fwcur), *((uint8_t *)&cmd + 4));
857 	rtwn_write_4(sc, R92C_HMEBOX(sc->fwcur), *((uint8_t *)&cmd + 0));
858 
859 	sc->fwcur = (sc->fwcur + 1) % R92C_H2C_NBOX;
860 
861 	/* Give firmware some time for processing. */
862 	DELAY(2000);
863 
864 	return (0);
865 }
866 
867 static void
868 rtwn_rf_write(struct rtwn_softc *sc, int chain, uint8_t addr, uint32_t val)
869 {
870 	rtwn_bb_write(sc, R92C_LSSI_PARAM(chain),
871 	    SM(R92C_LSSI_PARAM_ADDR, addr) |
872 	    SM(R92C_LSSI_PARAM_DATA, val));
873 }
874 
875 static uint32_t
876 rtwn_rf_read(struct rtwn_softc *sc, int chain, uint8_t addr)
877 {
878 	uint32_t reg[R92C_MAX_CHAINS], val;
879 
880 	reg[0] = rtwn_bb_read(sc, R92C_HSSI_PARAM2(0));
881 	if (chain != 0)
882 		reg[chain] = rtwn_bb_read(sc, R92C_HSSI_PARAM2(chain));
883 
884 	rtwn_bb_write(sc, R92C_HSSI_PARAM2(0),
885 	    reg[0] & ~R92C_HSSI_PARAM2_READ_EDGE);
886 	DELAY(1000);
887 
888 	rtwn_bb_write(sc, R92C_HSSI_PARAM2(chain),
889 	    RW(reg[chain], R92C_HSSI_PARAM2_READ_ADDR, addr) |
890 	    R92C_HSSI_PARAM2_READ_EDGE);
891 	DELAY(1000);
892 
893 	rtwn_bb_write(sc, R92C_HSSI_PARAM2(0),
894 	    reg[0] | R92C_HSSI_PARAM2_READ_EDGE);
895 	DELAY(1000);
896 
897 	if (rtwn_bb_read(sc, R92C_HSSI_PARAM1(chain)) & R92C_HSSI_PARAM1_PI)
898 		val = rtwn_bb_read(sc, R92C_HSPI_READBACK(chain));
899 	else
900 		val = rtwn_bb_read(sc, R92C_LSSI_READBACK(chain));
901 	return (MS(val, R92C_LSSI_READBACK_DATA));
902 }
903 
904 static int
905 rtwn_llt_write(struct rtwn_softc *sc, uint32_t addr, uint32_t data)
906 {
907 	int ntries;
908 
909 	rtwn_write_4(sc, R92C_LLT_INIT,
910 	    SM(R92C_LLT_INIT_OP, R92C_LLT_INIT_OP_WRITE) |
911 	    SM(R92C_LLT_INIT_ADDR, addr) |
912 	    SM(R92C_LLT_INIT_DATA, data));
913 	/* Wait for write operation to complete. */
914 	for (ntries = 0; ntries < 20; ntries++) {
915 		if (MS(rtwn_read_4(sc, R92C_LLT_INIT), R92C_LLT_INIT_OP) ==
916 		    R92C_LLT_INIT_OP_NO_ACTIVE)
917 			return (0);
918 		DELAY(5);
919 	}
920 	return (ETIMEDOUT);
921 }
922 
923 static uint8_t
924 rtwn_efuse_read_1(struct rtwn_softc *sc, uint16_t addr)
925 {
926 	uint32_t reg;
927 	int ntries;
928 
929 	reg = rtwn_read_4(sc, R92C_EFUSE_CTRL);
930 	reg = RW(reg, R92C_EFUSE_CTRL_ADDR, addr);
931 	reg &= ~R92C_EFUSE_CTRL_VALID;
932 	rtwn_write_4(sc, R92C_EFUSE_CTRL, reg);
933 	/* Wait for read operation to complete. */
934 	for (ntries = 0; ntries < 100; ntries++) {
935 		reg = rtwn_read_4(sc, R92C_EFUSE_CTRL);
936 		if (reg & R92C_EFUSE_CTRL_VALID)
937 			return (MS(reg, R92C_EFUSE_CTRL_DATA));
938 		DELAY(5);
939 	}
940 	device_printf(sc->sc_dev,
941 	    "could not read efuse byte at address 0x%x\n", addr);
942 	return (0xff);
943 }
944 
945 static void
946 rtwn_efuse_read(struct rtwn_softc *sc)
947 {
948 	uint8_t *rom = (uint8_t *)&sc->rom;
949 	uint16_t addr = 0;
950 	uint32_t reg;
951 	uint8_t off, msk;
952 	int i;
953 
954 	reg = rtwn_read_2(sc, R92C_SYS_ISO_CTRL);
955 	if (!(reg & R92C_SYS_ISO_CTRL_PWC_EV12V)) {
956 		rtwn_write_2(sc, R92C_SYS_ISO_CTRL,
957 		    reg | R92C_SYS_ISO_CTRL_PWC_EV12V);
958 	}
959 	reg = rtwn_read_2(sc, R92C_SYS_FUNC_EN);
960 	if (!(reg & R92C_SYS_FUNC_EN_ELDR)) {
961 		rtwn_write_2(sc, R92C_SYS_FUNC_EN,
962 		    reg | R92C_SYS_FUNC_EN_ELDR);
963 	}
964 	reg = rtwn_read_2(sc, R92C_SYS_CLKR);
965 	if ((reg & (R92C_SYS_CLKR_LOADER_EN | R92C_SYS_CLKR_ANA8M)) !=
966 	    (R92C_SYS_CLKR_LOADER_EN | R92C_SYS_CLKR_ANA8M)) {
967 		rtwn_write_2(sc, R92C_SYS_CLKR,
968 		    reg | R92C_SYS_CLKR_LOADER_EN | R92C_SYS_CLKR_ANA8M);
969 	}
970 	memset(&sc->rom, 0xff, sizeof(sc->rom));
971 	while (addr < 512) {
972 		reg = rtwn_efuse_read_1(sc, addr);
973 		if (reg == 0xff)
974 			break;
975 		addr++;
976 		off = reg >> 4;
977 		msk = reg & 0xf;
978 		for (i = 0; i < 4; i++) {
979 			if (msk & (1 << i))
980 				continue;
981 			rom[off * 8 + i * 2 + 0] =
982 			    rtwn_efuse_read_1(sc, addr);
983 			addr++;
984 			rom[off * 8 + i * 2 + 1] =
985 			    rtwn_efuse_read_1(sc, addr);
986 			addr++;
987 		}
988 	}
989 #ifdef RTWN_DEBUG
990 	if (sc->sc_debug >= 2) {
991 		/* Dump ROM content. */
992 		printf("\n");
993 		for (i = 0; i < sizeof(sc->rom); i++)
994 			printf("%02x:", rom[i]);
995 		printf("\n");
996 	}
997 #endif
998 }
999 
1000 static int
1001 rtwn_read_chipid(struct rtwn_softc *sc)
1002 {
1003 	uint32_t reg;
1004 
1005 	reg = rtwn_read_4(sc, R92C_SYS_CFG);
1006 	if (reg & R92C_SYS_CFG_TRP_VAUX_EN)
1007 		/* Unsupported test chip. */
1008 		return (EIO);
1009 
1010 	if (reg & R92C_SYS_CFG_TYPE_92C) {
1011 		sc->chip |= RTWN_CHIP_92C;
1012 		/* Check if it is a castrated 8192C. */
1013 		if (MS(rtwn_read_4(sc, R92C_HPON_FSM),
1014 		    R92C_HPON_FSM_CHIP_BONDING_ID) ==
1015 		    R92C_HPON_FSM_CHIP_BONDING_ID_92C_1T2R)
1016 			sc->chip |= RTWN_CHIP_92C_1T2R;
1017 	}
1018 	if (reg & R92C_SYS_CFG_VENDOR_UMC) {
1019 		sc->chip |= RTWN_CHIP_UMC;
1020 		if (MS(reg, R92C_SYS_CFG_CHIP_VER_RTL) == 0)
1021 			sc->chip |= RTWN_CHIP_UMC_A_CUT;
1022 	}
1023 	return (0);
1024 }
1025 
1026 static void
1027 rtwn_read_rom(struct rtwn_softc *sc)
1028 {
1029 	struct r92c_rom *rom = &sc->rom;
1030 
1031 	/* Read full ROM image. */
1032 	rtwn_efuse_read(sc);
1033 
1034 	if (rom->id != 0x8129)
1035 		device_printf(sc->sc_dev, "invalid EEPROM ID 0x%x\n", rom->id);
1036 
1037 	/* XXX Weird but this is what the vendor driver does. */
1038 	sc->pa_setting = rtwn_efuse_read_1(sc, 0x1fa);
1039 	DPRINTF(("PA setting=0x%x\n", sc->pa_setting));
1040 
1041 	sc->board_type = MS(rom->rf_opt1, R92C_ROM_RF1_BOARD_TYPE);
1042 
1043 	sc->regulatory = MS(rom->rf_opt1, R92C_ROM_RF1_REGULATORY);
1044 	DPRINTF(("regulatory type=%d\n", sc->regulatory));
1045 
1046 	IEEE80211_ADDR_COPY(sc->sc_ic.ic_macaddr, rom->macaddr);
1047 }
1048 
1049 /*
1050  * Initialize rate adaptation in firmware.
1051  */
1052 static int
1053 rtwn_ra_init(struct rtwn_softc *sc)
1054 {
1055 	static const uint8_t map[] =
1056 	    { 2, 4, 11, 22, 12, 18, 24, 36, 48, 72, 96, 108 };
1057 	struct ieee80211com *ic = &sc->sc_ic;
1058 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1059 	struct ieee80211_node *ni = ieee80211_ref_node(vap->iv_bss);
1060 	struct ieee80211_rateset *rs = &ni->ni_rates;
1061 	struct r92c_fw_cmd_macid_cfg cmd;
1062 	uint32_t rates, basicrates;
1063 	uint8_t mode;
1064 	int maxrate, maxbasicrate, error, i, j;
1065 
1066 	/* Get normal and basic rates mask. */
1067 	rates = basicrates = 0;
1068 	maxrate = maxbasicrate = 0;
1069 	for (i = 0; i < rs->rs_nrates; i++) {
1070 		/* Convert 802.11 rate to HW rate index. */
1071 		for (j = 0; j < nitems(map); j++)
1072 			if ((rs->rs_rates[i] & IEEE80211_RATE_VAL) == map[j])
1073 				break;
1074 		if (j == nitems(map))	/* Unknown rate, skip. */
1075 			continue;
1076 		rates |= 1 << j;
1077 		if (j > maxrate)
1078 			maxrate = j;
1079 		if (rs->rs_rates[i] & IEEE80211_RATE_BASIC) {
1080 			basicrates |= 1 << j;
1081 			if (j > maxbasicrate)
1082 				maxbasicrate = j;
1083 		}
1084 	}
1085 	if (ic->ic_curmode == IEEE80211_MODE_11B)
1086 		mode = R92C_RAID_11B;
1087 	else
1088 		mode = R92C_RAID_11BG;
1089 	DPRINTF(("mode=0x%x rates=0x%08x, basicrates=0x%08x\n",
1090 	    mode, rates, basicrates));
1091 
1092 	/* Set rates mask for group addressed frames. */
1093 	cmd.macid = RTWN_MACID_BC | RTWN_MACID_VALID;
1094 	cmd.mask = htole32(mode << 28 | basicrates);
1095 	error = rtwn_fw_cmd(sc, R92C_CMD_MACID_CONFIG, &cmd, sizeof(cmd));
1096 	if (error != 0) {
1097 		device_printf(sc->sc_dev,
1098 		    "could not add broadcast station\n");
1099 		return (error);
1100 	}
1101 	/* Set initial MRR rate. */
1102 	DPRINTF(("maxbasicrate=%d\n", maxbasicrate));
1103 	rtwn_write_1(sc, R92C_INIDATA_RATE_SEL(RTWN_MACID_BC),
1104 	    maxbasicrate);
1105 
1106 	/* Set rates mask for unicast frames. */
1107 	cmd.macid = RTWN_MACID_BSS | RTWN_MACID_VALID;
1108 	cmd.mask = htole32(mode << 28 | rates);
1109 	error = rtwn_fw_cmd(sc, R92C_CMD_MACID_CONFIG, &cmd, sizeof(cmd));
1110 	if (error != 0) {
1111 		device_printf(sc->sc_dev, "could not add BSS station\n");
1112 		return (error);
1113 	}
1114 	/* Set initial MRR rate. */
1115 	DPRINTF(("maxrate=%d\n", maxrate));
1116 	rtwn_write_1(sc, R92C_INIDATA_RATE_SEL(RTWN_MACID_BSS),
1117 	    maxrate);
1118 
1119 	/* Configure Automatic Rate Fallback Register. */
1120 	if (ic->ic_curmode == IEEE80211_MODE_11B) {
1121 		if (rates & 0x0c)
1122 			rtwn_write_4(sc, R92C_ARFR(0), htole32(rates & 0x0d));
1123 		else
1124 			rtwn_write_4(sc, R92C_ARFR(0), htole32(rates & 0x0f));
1125 	} else
1126 		rtwn_write_4(sc, R92C_ARFR(0), htole32(rates & 0x0ff5));
1127 
1128 	/* Indicate highest supported rate. */
1129 	ni->ni_txrate = rs->rs_rates[rs->rs_nrates - 1];
1130 	return (0);
1131 }
1132 
1133 static void
1134 rtwn_tsf_sync_enable(struct rtwn_softc *sc)
1135 {
1136 	struct ieee80211com *ic = &sc->sc_ic;
1137 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1138 	struct ieee80211_node *ni = vap->iv_bss;
1139 	uint64_t tsf;
1140 
1141 	/* Enable TSF synchronization. */
1142 	rtwn_write_1(sc, R92C_BCN_CTRL,
1143 	    rtwn_read_1(sc, R92C_BCN_CTRL) & ~R92C_BCN_CTRL_DIS_TSF_UDT0);
1144 
1145 	rtwn_write_1(sc, R92C_BCN_CTRL,
1146 	    rtwn_read_1(sc, R92C_BCN_CTRL) & ~R92C_BCN_CTRL_EN_BCN);
1147 
1148 	/* Set initial TSF. */
1149 	memcpy(&tsf, ni->ni_tstamp.data, 8);
1150 	tsf = le64toh(tsf);
1151 	tsf = tsf - (tsf % (vap->iv_bss->ni_intval * IEEE80211_DUR_TU));
1152 	tsf -= IEEE80211_DUR_TU;
1153 	rtwn_write_4(sc, R92C_TSFTR + 0, tsf);
1154 	rtwn_write_4(sc, R92C_TSFTR + 4, tsf >> 32);
1155 
1156 	rtwn_write_1(sc, R92C_BCN_CTRL,
1157 	    rtwn_read_1(sc, R92C_BCN_CTRL) | R92C_BCN_CTRL_EN_BCN);
1158 }
1159 
1160 static void
1161 rtwn_set_led(struct rtwn_softc *sc, int led, int on)
1162 {
1163 	uint8_t reg;
1164 
1165 	if (led == RTWN_LED_LINK) {
1166 		reg = rtwn_read_1(sc, R92C_LEDCFG2) & 0xf0;
1167 		if (!on)
1168 			reg |= R92C_LEDCFG2_DIS;
1169 		else
1170 			reg |= R92C_LEDCFG2_EN;
1171 		rtwn_write_1(sc, R92C_LEDCFG2, reg);
1172 		sc->ledlink = on;	/* Save LED state. */
1173 	}
1174 }
1175 
1176 static void
1177 rtwn_calib_to(void *arg)
1178 {
1179 	struct rtwn_softc *sc = arg;
1180 	struct r92c_fw_cmd_rssi cmd;
1181 
1182 	if (sc->avg_pwdb != -1) {
1183 		/* Indicate Rx signal strength to FW for rate adaptation. */
1184 		memset(&cmd, 0, sizeof(cmd));
1185 		cmd.macid = 0;	/* BSS. */
1186 		cmd.pwdb = sc->avg_pwdb;
1187 		DPRINTFN(3, ("sending RSSI command avg=%d\n", sc->avg_pwdb));
1188 		rtwn_fw_cmd(sc, R92C_CMD_RSSI_SETTING, &cmd, sizeof(cmd));
1189 	}
1190 
1191 	/* Do temperature compensation. */
1192 	rtwn_temp_calib(sc);
1193 
1194 	callout_reset(&sc->calib_to, hz * 2, rtwn_calib_to, sc);
1195 }
1196 
1197 static int
1198 rtwn_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
1199 {
1200 	struct rtwn_vap *rvp = RTWN_VAP(vap);
1201 	struct ieee80211com *ic = vap->iv_ic;
1202 	struct ieee80211_node *ni = vap->iv_bss;
1203 	struct rtwn_softc *sc = ic->ic_softc;
1204 	uint32_t reg;
1205 
1206 	IEEE80211_UNLOCK(ic);
1207 	RTWN_LOCK(sc);
1208 
1209 	if (vap->iv_state == IEEE80211_S_RUN) {
1210 		/* Stop calibration. */
1211 		callout_stop(&sc->calib_to);
1212 
1213 		/* Turn link LED off. */
1214 		rtwn_set_led(sc, RTWN_LED_LINK, 0);
1215 
1216 		/* Set media status to 'No Link'. */
1217 		reg = rtwn_read_4(sc, R92C_CR);
1218 		reg = RW(reg, R92C_CR_NETTYPE, R92C_CR_NETTYPE_NOLINK);
1219 		rtwn_write_4(sc, R92C_CR, reg);
1220 
1221 		/* Stop Rx of data frames. */
1222 		rtwn_write_2(sc, R92C_RXFLTMAP2, 0);
1223 
1224 		/* Rest TSF. */
1225 		rtwn_write_1(sc, R92C_DUAL_TSF_RST, 0x03);
1226 
1227 		/* Disable TSF synchronization. */
1228 		rtwn_write_1(sc, R92C_BCN_CTRL,
1229 		    rtwn_read_1(sc, R92C_BCN_CTRL) |
1230 		    R92C_BCN_CTRL_DIS_TSF_UDT0);
1231 
1232 		/* Reset EDCA parameters. */
1233 		rtwn_write_4(sc, R92C_EDCA_VO_PARAM, 0x002f3217);
1234 		rtwn_write_4(sc, R92C_EDCA_VI_PARAM, 0x005e4317);
1235 		rtwn_write_4(sc, R92C_EDCA_BE_PARAM, 0x00105320);
1236 		rtwn_write_4(sc, R92C_EDCA_BK_PARAM, 0x0000a444);
1237 	}
1238 	switch (nstate) {
1239 	case IEEE80211_S_INIT:
1240 		/* Turn link LED off. */
1241 		rtwn_set_led(sc, RTWN_LED_LINK, 0);
1242 		break;
1243 	case IEEE80211_S_SCAN:
1244 		if (vap->iv_state != IEEE80211_S_SCAN) {
1245 			/* Allow Rx from any BSSID. */
1246 			rtwn_write_4(sc, R92C_RCR,
1247 			    rtwn_read_4(sc, R92C_RCR) &
1248 			    ~(R92C_RCR_CBSSID_DATA | R92C_RCR_CBSSID_BCN));
1249 
1250 			/* Set gain for scanning. */
1251 			reg = rtwn_bb_read(sc, R92C_OFDM0_AGCCORE1(0));
1252 			reg = RW(reg, R92C_OFDM0_AGCCORE1_GAIN, 0x20);
1253 			rtwn_bb_write(sc, R92C_OFDM0_AGCCORE1(0), reg);
1254 
1255 			reg = rtwn_bb_read(sc, R92C_OFDM0_AGCCORE1(1));
1256 			reg = RW(reg, R92C_OFDM0_AGCCORE1_GAIN, 0x20);
1257 			rtwn_bb_write(sc, R92C_OFDM0_AGCCORE1(1), reg);
1258 		}
1259 
1260 		/* Make link LED blink during scan. */
1261 		rtwn_set_led(sc, RTWN_LED_LINK, !sc->ledlink);
1262 
1263 		/* Pause AC Tx queues. */
1264 		rtwn_write_1(sc, R92C_TXPAUSE,
1265 		    rtwn_read_1(sc, R92C_TXPAUSE) | 0x0f);
1266 		break;
1267 	case IEEE80211_S_AUTH:
1268 		/* Set initial gain under link. */
1269 		reg = rtwn_bb_read(sc, R92C_OFDM0_AGCCORE1(0));
1270 		reg = RW(reg, R92C_OFDM0_AGCCORE1_GAIN, 0x32);
1271 		rtwn_bb_write(sc, R92C_OFDM0_AGCCORE1(0), reg);
1272 
1273 		reg = rtwn_bb_read(sc, R92C_OFDM0_AGCCORE1(1));
1274 		reg = RW(reg, R92C_OFDM0_AGCCORE1_GAIN, 0x32);
1275 		rtwn_bb_write(sc, R92C_OFDM0_AGCCORE1(1), reg);
1276 		rtwn_set_chan(sc, ic->ic_curchan, NULL);
1277 		break;
1278 	case IEEE80211_S_RUN:
1279 		if (ic->ic_opmode == IEEE80211_M_MONITOR) {
1280 			/* Enable Rx of data frames. */
1281 			rtwn_write_2(sc, R92C_RXFLTMAP2, 0xffff);
1282 
1283 			/* Turn link LED on. */
1284 			rtwn_set_led(sc, RTWN_LED_LINK, 1);
1285 			break;
1286 		}
1287 
1288 		/* Set media status to 'Associated'. */
1289 		reg = rtwn_read_4(sc, R92C_CR);
1290 		reg = RW(reg, R92C_CR_NETTYPE, R92C_CR_NETTYPE_INFRA);
1291 		rtwn_write_4(sc, R92C_CR, reg);
1292 
1293 		/* Set BSSID. */
1294 		rtwn_write_4(sc, R92C_BSSID + 0, LE_READ_4(&ni->ni_bssid[0]));
1295 		rtwn_write_4(sc, R92C_BSSID + 4, LE_READ_2(&ni->ni_bssid[4]));
1296 
1297 		if (ic->ic_curmode == IEEE80211_MODE_11B)
1298 			rtwn_write_1(sc, R92C_INIRTS_RATE_SEL, 0);
1299 		else	/* 802.11b/g */
1300 			rtwn_write_1(sc, R92C_INIRTS_RATE_SEL, 3);
1301 
1302 		/* Enable Rx of data frames. */
1303 		rtwn_write_2(sc, R92C_RXFLTMAP2, 0xffff);
1304 
1305 		/* Flush all AC queues. */
1306 		rtwn_write_1(sc, R92C_TXPAUSE, 0);
1307 
1308 		/* Set beacon interval. */
1309 		rtwn_write_2(sc, R92C_BCN_INTERVAL, ni->ni_intval);
1310 
1311 		/* Allow Rx from our BSSID only. */
1312 		rtwn_write_4(sc, R92C_RCR,
1313 		    rtwn_read_4(sc, R92C_RCR) |
1314 		    R92C_RCR_CBSSID_DATA | R92C_RCR_CBSSID_BCN);
1315 
1316 		/* Enable TSF synchronization. */
1317 		rtwn_tsf_sync_enable(sc);
1318 
1319 		rtwn_write_1(sc, R92C_SIFS_CCK + 1, 10);
1320 		rtwn_write_1(sc, R92C_SIFS_OFDM + 1, 10);
1321 		rtwn_write_1(sc, R92C_SPEC_SIFS + 1, 10);
1322 		rtwn_write_1(sc, R92C_MAC_SPEC_SIFS + 1, 10);
1323 		rtwn_write_1(sc, R92C_R2T_SIFS + 1, 10);
1324 		rtwn_write_1(sc, R92C_T2T_SIFS + 1, 10);
1325 
1326 		/* Intialize rate adaptation. */
1327 		rtwn_ra_init(sc);
1328 		/* Turn link LED on. */
1329 		rtwn_set_led(sc, RTWN_LED_LINK, 1);
1330 
1331 		sc->avg_pwdb = -1;	/* Reset average RSSI. */
1332 		/* Reset temperature calibration state machine. */
1333 		sc->thcal_state = 0;
1334 		sc->thcal_lctemp = 0;
1335 		/* Start periodic calibration. */
1336 		callout_reset(&sc->calib_to, hz * 2, rtwn_calib_to, sc);
1337 		break;
1338 	default:
1339 		break;
1340 	}
1341 	RTWN_UNLOCK(sc);
1342 	IEEE80211_LOCK(ic);
1343 	return (rvp->newstate(vap, nstate, arg));
1344 }
1345 
1346 static int
1347 rtwn_updateedca(struct ieee80211com *ic)
1348 {
1349 	struct rtwn_softc *sc = ic->ic_softc;
1350 	const uint16_t aci2reg[WME_NUM_AC] = {
1351 		R92C_EDCA_BE_PARAM,
1352 		R92C_EDCA_BK_PARAM,
1353 		R92C_EDCA_VI_PARAM,
1354 		R92C_EDCA_VO_PARAM
1355 	};
1356 	int aci, aifs, slottime;
1357 
1358 	IEEE80211_LOCK(ic);
1359 	slottime = (ic->ic_flags & IEEE80211_F_SHSLOT) ? 9 : 20;
1360 	for (aci = 0; aci < WME_NUM_AC; aci++) {
1361 		const struct wmeParams *ac =
1362 		    &ic->ic_wme.wme_chanParams.cap_wmeParams[aci];
1363 		/* AIFS[AC] = AIFSN[AC] * aSlotTime + aSIFSTime. */
1364 		aifs = ac->wmep_aifsn * slottime + 10;
1365 		rtwn_write_4(sc, aci2reg[aci],
1366 		    SM(R92C_EDCA_PARAM_TXOP, ac->wmep_txopLimit) |
1367 		    SM(R92C_EDCA_PARAM_ECWMIN, ac->wmep_logcwmin) |
1368 		    SM(R92C_EDCA_PARAM_ECWMAX, ac->wmep_logcwmax) |
1369 		    SM(R92C_EDCA_PARAM_AIFS, aifs));
1370 	}
1371 	IEEE80211_UNLOCK(ic);
1372 	return (0);
1373 }
1374 
1375 static void
1376 rtwn_update_avgrssi(struct rtwn_softc *sc, int rate, int8_t rssi)
1377 {
1378 	int pwdb;
1379 
1380 	/* Convert antenna signal to percentage. */
1381 	if (rssi <= -100 || rssi >= 20)
1382 		pwdb = 0;
1383 	else if (rssi >= 0)
1384 		pwdb = 100;
1385 	else
1386 		pwdb = 100 + rssi;
1387 	if (rate <= 3) {
1388 		/* CCK gain is smaller than OFDM/MCS gain. */
1389 		pwdb += 6;
1390 		if (pwdb > 100)
1391 			pwdb = 100;
1392 		if (pwdb <= 14)
1393 			pwdb -= 4;
1394 		else if (pwdb <= 26)
1395 			pwdb -= 8;
1396 		else if (pwdb <= 34)
1397 			pwdb -= 6;
1398 		else if (pwdb <= 42)
1399 			pwdb -= 2;
1400 	}
1401 	if (sc->avg_pwdb == -1)	/* Init. */
1402 		sc->avg_pwdb = pwdb;
1403 	else if (sc->avg_pwdb < pwdb)
1404 		sc->avg_pwdb = ((sc->avg_pwdb * 19 + pwdb) / 20) + 1;
1405 	else
1406 		sc->avg_pwdb = ((sc->avg_pwdb * 19 + pwdb) / 20);
1407 	DPRINTFN(4, ("PWDB=%d EMA=%d\n", pwdb, sc->avg_pwdb));
1408 }
1409 
1410 static int8_t
1411 rtwn_get_rssi(struct rtwn_softc *sc, int rate, void *physt)
1412 {
1413 	static const int8_t cckoff[] = { 16, -12, -26, -46 };
1414 	struct r92c_rx_phystat *phy;
1415 	struct r92c_rx_cck *cck;
1416 	uint8_t rpt;
1417 	int8_t rssi;
1418 
1419 	if (rate <= 3) {
1420 		cck = (struct r92c_rx_cck *)physt;
1421 		if (sc->sc_flags & RTWN_FLAG_CCK_HIPWR) {
1422 			rpt = (cck->agc_rpt >> 5) & 0x3;
1423 			rssi = (cck->agc_rpt & 0x1f) << 1;
1424 		} else {
1425 			rpt = (cck->agc_rpt >> 6) & 0x3;
1426 			rssi = cck->agc_rpt & 0x3e;
1427 		}
1428 		rssi = cckoff[rpt] - rssi;
1429 	} else {	/* OFDM/HT. */
1430 		phy = (struct r92c_rx_phystat *)physt;
1431 		rssi = ((le32toh(phy->phydw1) >> 1) & 0x7f) - 110;
1432 	}
1433 	return (rssi);
1434 }
1435 
1436 static void
1437 rtwn_rx_frame(struct rtwn_softc *sc, struct r92c_rx_desc *rx_desc,
1438     struct rtwn_rx_data *rx_data, int desc_idx)
1439 {
1440 	struct ieee80211com *ic = &sc->sc_ic;
1441 	struct ieee80211_frame *wh;
1442 	struct ieee80211_node *ni;
1443 	struct r92c_rx_phystat *phy = NULL;
1444 	uint32_t rxdw0, rxdw3;
1445 	struct mbuf *m, *m1;
1446 	bus_dma_segment_t segs[1];
1447 	bus_addr_t physaddr;
1448 	uint8_t rate;
1449 	int8_t rssi = 0, nf;
1450 	int infosz, nsegs, pktlen, shift, error;
1451 
1452 	rxdw0 = le32toh(rx_desc->rxdw0);
1453 	rxdw3 = le32toh(rx_desc->rxdw3);
1454 
1455 	if (__predict_false(rxdw0 & (R92C_RXDW0_CRCERR | R92C_RXDW0_ICVERR))) {
1456 		/*
1457 		 * This should not happen since we setup our Rx filter
1458 		 * to not receive these frames.
1459 		 */
1460 		counter_u64_add(ic->ic_ierrors, 1);
1461 		return;
1462 	}
1463 
1464 	pktlen = MS(rxdw0, R92C_RXDW0_PKTLEN);
1465 	if (__predict_false(pktlen < sizeof(*wh) || pktlen > MCLBYTES)) {
1466 		counter_u64_add(ic->ic_ierrors, 1);
1467 		return;
1468 	}
1469 
1470 	rate = MS(rxdw3, R92C_RXDW3_RATE);
1471 	infosz = MS(rxdw0, R92C_RXDW0_INFOSZ) * 8;
1472 	if (infosz > sizeof(struct r92c_rx_phystat))
1473 		infosz = sizeof(struct r92c_rx_phystat);
1474 	shift = MS(rxdw0, R92C_RXDW0_SHIFT);
1475 
1476 	/* Get RSSI from PHY status descriptor if present. */
1477 	if (infosz != 0 && (rxdw0 & R92C_RXDW0_PHYST)) {
1478 		phy = mtod(rx_data->m, struct r92c_rx_phystat *);
1479 		rssi = rtwn_get_rssi(sc, rate, phy);
1480 		/* Update our average RSSI. */
1481 		rtwn_update_avgrssi(sc, rate, rssi);
1482 	}
1483 
1484 	DPRINTFN(5, ("Rx frame len=%d rate=%d infosz=%d shift=%d rssi=%d\n",
1485 	    pktlen, rate, infosz, shift, rssi));
1486 
1487 	m1 = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
1488 	if (m1 == NULL) {
1489 		counter_u64_add(ic->ic_ierrors, 1);
1490 		return;
1491 	}
1492 	bus_dmamap_unload(sc->rx_ring.data_dmat, rx_data->map);
1493 
1494 	error = bus_dmamap_load(sc->rx_ring.data_dmat, rx_data->map,
1495 	     mtod(m1, void *), MCLBYTES, rtwn_dma_map_addr,
1496 	     &physaddr, 0);
1497 	if (error != 0) {
1498 		m_freem(m1);
1499 
1500 		if (bus_dmamap_load_mbuf_sg(sc->rx_ring.data_dmat,
1501 		    rx_data->map, rx_data->m, segs, &nsegs, 0))
1502 			panic("%s: could not load old RX mbuf",
1503 			    device_get_name(sc->sc_dev));
1504 
1505 		/* Physical address may have changed. */
1506 		rtwn_setup_rx_desc(sc, rx_desc, physaddr, MCLBYTES, desc_idx);
1507 		counter_u64_add(ic->ic_ierrors, 1);
1508 		return;
1509 	}
1510 
1511 	/* Finalize mbuf. */
1512 	m = rx_data->m;
1513 	rx_data->m = m1;
1514 	m->m_pkthdr.len = m->m_len = pktlen + infosz + shift;
1515 
1516 	/* Update RX descriptor. */
1517 	rtwn_setup_rx_desc(sc, rx_desc, physaddr, MCLBYTES, desc_idx);
1518 
1519 	/* Get ieee80211 frame header. */
1520 	if (rxdw0 & R92C_RXDW0_PHYST)
1521 		m_adj(m, infosz + shift);
1522 	else
1523 		m_adj(m, shift);
1524 
1525 	nf = -95;
1526 	if (ieee80211_radiotap_active(ic)) {
1527 		struct rtwn_rx_radiotap_header *tap = &sc->sc_rxtap;
1528 
1529 		tap->wr_flags = 0;
1530 		if (!(rxdw3 & R92C_RXDW3_HT)) {
1531 			switch (rate) {
1532 			/* CCK. */
1533 			case  0: tap->wr_rate =   2; break;
1534 			case  1: tap->wr_rate =   4; break;
1535 			case  2: tap->wr_rate =  11; break;
1536 			case  3: tap->wr_rate =  22; break;
1537 			/* OFDM. */
1538 			case  4: tap->wr_rate =  12; break;
1539 			case  5: tap->wr_rate =  18; break;
1540 			case  6: tap->wr_rate =  24; break;
1541 			case  7: tap->wr_rate =  36; break;
1542 			case  8: tap->wr_rate =  48; break;
1543 			case  9: tap->wr_rate =  72; break;
1544 			case 10: tap->wr_rate =  96; break;
1545 			case 11: tap->wr_rate = 108; break;
1546 			}
1547 		} else if (rate >= 12) {	/* MCS0~15. */
1548 			/* Bit 7 set means HT MCS instead of rate. */
1549 			tap->wr_rate = 0x80 | (rate - 12);
1550 		}
1551 		tap->wr_dbm_antsignal = rssi;
1552 		tap->wr_chan_freq = htole16(ic->ic_curchan->ic_freq);
1553 		tap->wr_chan_flags = htole16(ic->ic_curchan->ic_flags);
1554 	}
1555 
1556 	RTWN_UNLOCK(sc);
1557 	wh = mtod(m, struct ieee80211_frame *);
1558 
1559 	/* Send the frame to the 802.11 layer. */
1560 	ni = ieee80211_find_rxnode(ic, (struct ieee80211_frame_min *)wh);
1561 	if (ni != NULL) {
1562 		(void)ieee80211_input(ni, m, rssi - nf, nf);
1563 		/* Node is no longer needed. */
1564 		ieee80211_free_node(ni);
1565 	} else
1566 		(void)ieee80211_input_all(ic, m, rssi - nf, nf);
1567 
1568 	RTWN_LOCK(sc);
1569 }
1570 
1571 static int
1572 rtwn_tx(struct rtwn_softc *sc, struct mbuf *m, struct ieee80211_node *ni)
1573 {
1574 	struct ieee80211com *ic = &sc->sc_ic;
1575 	struct ieee80211vap *vap = ni->ni_vap;
1576 	struct ieee80211_frame *wh;
1577 	struct ieee80211_key *k = NULL;
1578 	struct rtwn_tx_ring *tx_ring;
1579 	struct rtwn_tx_data *data;
1580 	struct r92c_tx_desc *txd;
1581 	bus_dma_segment_t segs[1];
1582 	uint16_t qos;
1583 	uint8_t raid, type, tid, qid;
1584 	int nsegs, error;
1585 
1586 	wh = mtod(m, struct ieee80211_frame *);
1587 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
1588 
1589 	/* Encrypt the frame if need be. */
1590 	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
1591 		k = ieee80211_crypto_encap(ni, m);
1592 		if (k == NULL) {
1593 			m_freem(m);
1594 			return (ENOBUFS);
1595 		}
1596 		/* 802.11 header may have moved. */
1597 		wh = mtod(m, struct ieee80211_frame *);
1598 	}
1599 
1600 	if (IEEE80211_QOS_HAS_SEQ(wh)) {
1601 		qos = ((const struct ieee80211_qosframe *)wh)->i_qos[0];
1602 		tid = qos & IEEE80211_QOS_TID;
1603 	} else {
1604 		qos = 0;
1605 		tid = 0;
1606 	}
1607 
1608 	switch (type) {
1609 	case IEEE80211_FC0_TYPE_CTL:
1610 	case IEEE80211_FC0_TYPE_MGT:
1611 		qid = RTWN_VO_QUEUE;
1612 		break;
1613 	default:
1614 		qid = M_WME_GETAC(m);
1615 		break;
1616 	}
1617 
1618 	/* Grab a Tx buffer from the ring. */
1619 	tx_ring = &sc->tx_ring[qid];
1620 	data = &tx_ring->tx_data[tx_ring->cur];
1621 	if (data->m != NULL) {
1622 		m_freem(m);
1623 		return (ENOBUFS);
1624 	}
1625 
1626 	/* Fill Tx descriptor. */
1627 	txd = &tx_ring->desc[tx_ring->cur];
1628 	if (htole32(txd->txdw0) & R92C_RXDW0_OWN) {
1629 		m_freem(m);
1630 		return (ENOBUFS);
1631 	}
1632 	txd->txdw0 = htole32(
1633 	    SM(R92C_TXDW0_PKTLEN, m->m_pkthdr.len) |
1634 	    SM(R92C_TXDW0_OFFSET, sizeof(*txd)) |
1635 	    R92C_TXDW0_FSG | R92C_TXDW0_LSG);
1636 	if (IEEE80211_IS_MULTICAST(wh->i_addr1))
1637 		txd->txdw0 |= htole32(R92C_TXDW0_BMCAST);
1638 
1639 	txd->txdw1 = 0;
1640 	txd->txdw4 = 0;
1641 	txd->txdw5 = 0;
1642 
1643 	/* XXX TODO: rate control; implement low-rate for EAPOL */
1644 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1) &&
1645 	    type == IEEE80211_FC0_TYPE_DATA) {
1646 		if (ic->ic_curmode == IEEE80211_MODE_11B)
1647 			raid = R92C_RAID_11B;
1648 		else
1649 			raid = R92C_RAID_11BG;
1650 		txd->txdw1 |= htole32(
1651 		    SM(R92C_TXDW1_MACID, RTWN_MACID_BSS) |
1652 		    SM(R92C_TXDW1_QSEL, R92C_TXDW1_QSEL_BE) |
1653 		    SM(R92C_TXDW1_RAID, raid) |
1654 		    R92C_TXDW1_AGGBK);
1655 
1656 		if (ic->ic_flags & IEEE80211_F_USEPROT) {
1657 			if (ic->ic_protmode == IEEE80211_PROT_CTSONLY) {
1658 				txd->txdw4 |= htole32(R92C_TXDW4_CTS2SELF |
1659 				    R92C_TXDW4_HWRTSEN);
1660 			} else if (ic->ic_protmode == IEEE80211_PROT_RTSCTS) {
1661 				txd->txdw4 |= htole32(R92C_TXDW4_RTSEN |
1662 				    R92C_TXDW4_HWRTSEN);
1663 			}
1664 		}
1665 
1666 		/* XXX TODO: implement rate control */
1667 
1668 		/* Send RTS at OFDM24. */
1669 		txd->txdw4 |= htole32(SM(R92C_TXDW4_RTSRATE, 8));
1670 		txd->txdw5 |= htole32(SM(R92C_TXDW5_RTSRATE_FBLIMIT, 0xf));
1671 		/* Send data at OFDM54. */
1672 		txd->txdw5 |= htole32(SM(R92C_TXDW5_DATARATE, 11));
1673 		txd->txdw5 |= htole32(SM(R92C_TXDW5_DATARATE_FBLIMIT, 0x1f));
1674 
1675 	} else {
1676 		txd->txdw1 |= htole32(
1677 		    SM(R92C_TXDW1_MACID, 0) |
1678 		    SM(R92C_TXDW1_QSEL, R92C_TXDW1_QSEL_MGNT) |
1679 		    SM(R92C_TXDW1_RAID, R92C_RAID_11B));
1680 
1681 		/* Force CCK1. */
1682 		txd->txdw4 |= htole32(R92C_TXDW4_DRVRATE);
1683 		txd->txdw5 |= htole32(SM(R92C_TXDW5_DATARATE, 0));
1684 	}
1685 	/* Set sequence number (already little endian). */
1686 	txd->txdseq = htole16(M_SEQNO_GET(m) % IEEE80211_SEQ_RANGE);
1687 
1688 	if (!qos) {
1689 		/* Use HW sequence numbering for non-QoS frames. */
1690 		txd->txdw4  |= htole32(R92C_TXDW4_HWSEQ);
1691 		txd->txdseq |= htole16(0x8000);
1692 	} else
1693 		txd->txdw4 |= htole32(R92C_TXDW4_QOS);
1694 
1695 	error = bus_dmamap_load_mbuf_sg(tx_ring->data_dmat, data->map, m, segs,
1696 	    &nsegs, BUS_DMA_NOWAIT);
1697 	if (error != 0 && error != EFBIG) {
1698 		device_printf(sc->sc_dev, "can't map mbuf (error %d)\n", error);
1699 		m_freem(m);
1700 		return (error);
1701 	}
1702 	if (error != 0) {
1703 		struct mbuf *mnew;
1704 
1705 		mnew = m_defrag(m, M_NOWAIT);
1706 		if (mnew == NULL) {
1707 			device_printf(sc->sc_dev,
1708 			    "can't defragment mbuf\n");
1709 			m_freem(m);
1710 			return (ENOBUFS);
1711 		}
1712 		m = mnew;
1713 
1714 		error = bus_dmamap_load_mbuf_sg(tx_ring->data_dmat, data->map,
1715 		    m, segs, &nsegs, BUS_DMA_NOWAIT);
1716 		if (error != 0) {
1717 			device_printf(sc->sc_dev,
1718 			    "can't map mbuf (error %d)\n", error);
1719 			m_freem(m);
1720 			return (error);
1721 		}
1722 	}
1723 
1724 	txd->txbufaddr = htole32(segs[0].ds_addr);
1725 	txd->txbufsize = htole16(m->m_pkthdr.len);
1726 	bus_space_barrier(sc->sc_st, sc->sc_sh, 0, sc->sc_mapsize,
1727 	    BUS_SPACE_BARRIER_WRITE);
1728 	txd->txdw0 |= htole32(R92C_TXDW0_OWN);
1729 
1730 	bus_dmamap_sync(tx_ring->desc_dmat, tx_ring->desc_map,
1731 	    BUS_DMASYNC_POSTWRITE);
1732 	bus_dmamap_sync(tx_ring->data_dmat, data->map, BUS_DMASYNC_POSTWRITE);
1733 
1734 	data->m = m;
1735 	data->ni = ni;
1736 
1737 	if (ieee80211_radiotap_active_vap(vap)) {
1738 		struct rtwn_tx_radiotap_header *tap = &sc->sc_txtap;
1739 
1740 		tap->wt_flags = 0;
1741 		tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
1742 		tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
1743 
1744 		ieee80211_radiotap_tx(vap, m);
1745 	}
1746 
1747 	tx_ring->cur = (tx_ring->cur + 1) % RTWN_TX_LIST_COUNT;
1748 	tx_ring->queued++;
1749 
1750 	if (tx_ring->queued >= (RTWN_TX_LIST_COUNT - 1))
1751 		sc->qfullmsk |= (1 << qid);
1752 
1753 	/* Kick TX. */
1754 	rtwn_write_2(sc, R92C_PCIE_CTRL_REG, (1 << qid));
1755 	return (0);
1756 }
1757 
1758 static void
1759 rtwn_tx_done(struct rtwn_softc *sc, int qid)
1760 {
1761 	struct rtwn_tx_ring *tx_ring = &sc->tx_ring[qid];
1762 	struct rtwn_tx_data *tx_data;
1763 	struct r92c_tx_desc *tx_desc;
1764 	int i;
1765 
1766 	bus_dmamap_sync(tx_ring->desc_dmat, tx_ring->desc_map,
1767 	    BUS_DMASYNC_POSTREAD);
1768 
1769 	for (i = 0; i < RTWN_TX_LIST_COUNT; i++) {
1770 		tx_data = &tx_ring->tx_data[i];
1771 		if (tx_data->m == NULL)
1772 			continue;
1773 
1774 		tx_desc = &tx_ring->desc[i];
1775 		if (le32toh(tx_desc->txdw0) & R92C_TXDW0_OWN)
1776 			continue;
1777 
1778 		bus_dmamap_unload(tx_ring->desc_dmat, tx_ring->desc_map);
1779 
1780 		/*
1781 		 * XXX TODO: figure out whether the transmit succeeded or not.
1782 		 * .. and then notify rate control.
1783 		 */
1784 		ieee80211_tx_complete(tx_data->ni, tx_data->m, 0);
1785 		tx_data->ni = NULL;
1786 		tx_data->m = NULL;
1787 
1788 		sc->sc_tx_timer = 0;
1789 		tx_ring->queued--;
1790 	}
1791 
1792 	if (tx_ring->queued < (RTWN_TX_LIST_COUNT - 1))
1793 		sc->qfullmsk &= ~(1 << qid);
1794 	rtwn_start(sc);
1795 }
1796 
1797 static int
1798 rtwn_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
1799     const struct ieee80211_bpf_params *params)
1800 {
1801 	struct ieee80211com *ic = ni->ni_ic;
1802 	struct rtwn_softc *sc = ic->ic_softc;
1803 
1804 	RTWN_LOCK(sc);
1805 
1806 	/* Prevent management frames from being sent if we're not ready. */
1807 	if (!(sc->sc_flags & RTWN_RUNNING)) {
1808 		RTWN_UNLOCK(sc);
1809 		m_freem(m);
1810 		return (ENETDOWN);
1811 	}
1812 
1813 	if (rtwn_tx(sc, m, ni) != 0) {
1814 		m_freem(m);
1815 		RTWN_UNLOCK(sc);
1816 		return (EIO);
1817 	}
1818 	sc->sc_tx_timer = 5;
1819 	RTWN_UNLOCK(sc);
1820 	return (0);
1821 }
1822 
1823 static int
1824 rtwn_transmit(struct ieee80211com *ic, struct mbuf *m)
1825 {
1826 	struct rtwn_softc *sc = ic->ic_softc;
1827 	int error;
1828 
1829 	RTWN_LOCK(sc);
1830 	if ((sc->sc_flags & RTWN_RUNNING) == 0) {
1831 		RTWN_UNLOCK(sc);
1832 		return (ENXIO);
1833 	}
1834 	error = mbufq_enqueue(&sc->sc_snd, m);
1835 	if (error) {
1836 		RTWN_UNLOCK(sc);
1837 		return (error);
1838 	}
1839 	rtwn_start(sc);
1840 	RTWN_UNLOCK(sc);
1841 	return (0);
1842 }
1843 
1844 static void
1845 rtwn_parent(struct ieee80211com *ic)
1846 {
1847 	struct rtwn_softc *sc = ic->ic_softc;
1848 	int startall = 0;
1849 
1850 	RTWN_LOCK(sc);
1851 	if (ic->ic_nrunning> 0) {
1852 		if (!(sc->sc_flags & RTWN_RUNNING)) {
1853 			rtwn_init_locked(sc);
1854 			startall = 1;
1855 		}
1856 	} else if (sc->sc_flags & RTWN_RUNNING)
1857 		 rtwn_stop_locked(sc);
1858 	RTWN_UNLOCK(sc);
1859 	if (startall)
1860 		ieee80211_start_all(ic);
1861 }
1862 
1863 static void
1864 rtwn_start(struct rtwn_softc *sc)
1865 {
1866 	struct ieee80211_node *ni;
1867 	struct mbuf *m;
1868 
1869 	RTWN_LOCK_ASSERT(sc);
1870 
1871 	if ((sc->sc_flags & RTWN_RUNNING) == 0)
1872 		return;
1873 
1874 	while (sc->qfullmsk == 0 && (m = mbufq_dequeue(&sc->sc_snd)) != NULL) {
1875 		ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
1876 		if (rtwn_tx(sc, m, ni) != 0) {
1877 			if_inc_counter(ni->ni_vap->iv_ifp,
1878 			    IFCOUNTER_OERRORS, 1);
1879 			ieee80211_free_node(ni);
1880 			continue;
1881 		}
1882 		sc->sc_tx_timer = 5;
1883 	}
1884 }
1885 
1886 static void
1887 rtwn_watchdog(void *arg)
1888 {
1889 	struct rtwn_softc *sc = arg;
1890 	struct ieee80211com *ic = &sc->sc_ic;
1891 
1892 	RTWN_LOCK_ASSERT(sc);
1893 
1894 	KASSERT(sc->sc_flags & RTWN_RUNNING, ("not running"));
1895 
1896 	if (sc->sc_tx_timer != 0 && --sc->sc_tx_timer == 0) {
1897 		ic_printf(ic, "device timeout\n");
1898 		ieee80211_runtask(ic, &sc->sc_reinit_task);
1899 		return;
1900 	}
1901 	callout_reset(&sc->watchdog_to, hz, rtwn_watchdog, sc);
1902 }
1903 
1904 static int
1905 rtwn_power_on(struct rtwn_softc *sc)
1906 {
1907 	uint32_t reg;
1908 	int ntries;
1909 
1910 	/* Wait for autoload done bit. */
1911 	for (ntries = 0; ntries < 1000; ntries++) {
1912 		if (rtwn_read_1(sc, R92C_APS_FSMCO) & R92C_APS_FSMCO_PFM_ALDN)
1913 			break;
1914 		DELAY(5);
1915 	}
1916 	if (ntries == 1000) {
1917 		device_printf(sc->sc_dev,
1918 		    "timeout waiting for chip autoload\n");
1919 		return (ETIMEDOUT);
1920 	}
1921 
1922 	/* Unlock ISO/CLK/Power control register. */
1923 	rtwn_write_1(sc, R92C_RSV_CTRL, 0);
1924 
1925 	/* TODO: check if we need this for 8188CE */
1926 	if (sc->board_type != R92C_BOARD_TYPE_DONGLE) {
1927 		/* bt coex */
1928 		reg = rtwn_read_4(sc, R92C_APS_FSMCO);
1929 		reg |= (R92C_APS_FSMCO_SOP_ABG |
1930 			R92C_APS_FSMCO_SOP_AMB |
1931 			R92C_APS_FSMCO_XOP_BTCK);
1932 		rtwn_write_4(sc, R92C_APS_FSMCO, reg);
1933 	}
1934 
1935 	/* Move SPS into PWM mode. */
1936 	rtwn_write_1(sc, R92C_SPS0_CTRL, 0x2b);
1937 
1938 	/* Set low byte to 0x0f, leave others unchanged. */
1939 	rtwn_write_4(sc, R92C_AFE_XTAL_CTRL,
1940 	    (rtwn_read_4(sc, R92C_AFE_XTAL_CTRL) & 0xffffff00) | 0x0f);
1941 
1942 	/* TODO: check if we need this for 8188CE */
1943 	if (sc->board_type != R92C_BOARD_TYPE_DONGLE) {
1944 		/* bt coex */
1945 		reg = rtwn_read_4(sc, R92C_AFE_XTAL_CTRL);
1946 		reg &= (~0x00024800); /* XXX magic from linux */
1947 		rtwn_write_4(sc, R92C_AFE_XTAL_CTRL, reg);
1948 	}
1949 
1950 	rtwn_write_2(sc, R92C_SYS_ISO_CTRL,
1951 	  (rtwn_read_2(sc, R92C_SYS_ISO_CTRL) & 0xff) |
1952 	  R92C_SYS_ISO_CTRL_PWC_EV12V | R92C_SYS_ISO_CTRL_DIOR);
1953 	DELAY(200);
1954 
1955 	/* TODO: linux does additional btcoex stuff here */
1956 
1957 	/* Auto enable WLAN. */
1958 	rtwn_write_2(sc, R92C_APS_FSMCO,
1959 	    rtwn_read_2(sc, R92C_APS_FSMCO) | R92C_APS_FSMCO_APFM_ONMAC);
1960 	for (ntries = 0; ntries < 1000; ntries++) {
1961 		if (!(rtwn_read_2(sc, R92C_APS_FSMCO) &
1962 		    R92C_APS_FSMCO_APFM_ONMAC))
1963 			break;
1964 		DELAY(5);
1965 	}
1966 	if (ntries == 1000) {
1967 		device_printf(sc->sc_dev, "timeout waiting for MAC auto ON\n");
1968 		return (ETIMEDOUT);
1969 	}
1970 
1971 	/* Enable radio, GPIO and LED functions. */
1972 	rtwn_write_2(sc, R92C_APS_FSMCO,
1973 	    R92C_APS_FSMCO_AFSM_PCIE |
1974 	    R92C_APS_FSMCO_PDN_EN |
1975 	    R92C_APS_FSMCO_PFM_ALDN);
1976 	/* Release RF digital isolation. */
1977 	rtwn_write_2(sc, R92C_SYS_ISO_CTRL,
1978 	    rtwn_read_2(sc, R92C_SYS_ISO_CTRL) & ~R92C_SYS_ISO_CTRL_DIOR);
1979 
1980 	if (sc->chip & RTWN_CHIP_92C)
1981 		rtwn_write_1(sc, R92C_PCIE_CTRL_REG + 3, 0x77);
1982 	else
1983 		rtwn_write_1(sc, R92C_PCIE_CTRL_REG + 3, 0x22);
1984 
1985 	rtwn_write_4(sc, R92C_INT_MIG, 0);
1986 
1987 	if (sc->board_type != R92C_BOARD_TYPE_DONGLE) {
1988 		/* bt coex */
1989 		reg = rtwn_read_4(sc, R92C_AFE_XTAL_CTRL + 2);
1990 		reg &= 0xfd; /* XXX magic from linux */
1991 		rtwn_write_4(sc, R92C_AFE_XTAL_CTRL + 2, reg);
1992 	}
1993 
1994 	rtwn_write_1(sc, R92C_GPIO_MUXCFG,
1995 	    rtwn_read_1(sc, R92C_GPIO_MUXCFG) & ~R92C_GPIO_MUXCFG_RFKILL);
1996 
1997 	reg = rtwn_read_1(sc, R92C_GPIO_IO_SEL);
1998 	if (!(reg & R92C_GPIO_IO_SEL_RFKILL)) {
1999 		device_printf(sc->sc_dev,
2000 		    "radio is disabled by hardware switch\n");
2001 		return (EPERM);
2002 	}
2003 
2004 	/* Initialize MAC. */
2005 	reg = rtwn_read_1(sc, R92C_APSD_CTRL);
2006 	rtwn_write_1(sc, R92C_APSD_CTRL,
2007 	    rtwn_read_1(sc, R92C_APSD_CTRL) & ~R92C_APSD_CTRL_OFF);
2008 	for (ntries = 0; ntries < 200; ntries++) {
2009 		if (!(rtwn_read_1(sc, R92C_APSD_CTRL) &
2010 		    R92C_APSD_CTRL_OFF_STATUS))
2011 			break;
2012 		DELAY(500);
2013 	}
2014 	if (ntries == 200) {
2015 		device_printf(sc->sc_dev,
2016 		    "timeout waiting for MAC initialization\n");
2017 		return (ETIMEDOUT);
2018 	}
2019 
2020 	/* Enable MAC DMA/WMAC/SCHEDULE/SEC blocks. */
2021 	reg = rtwn_read_2(sc, R92C_CR);
2022 	reg |= R92C_CR_HCI_TXDMA_EN | R92C_CR_HCI_RXDMA_EN |
2023 	    R92C_CR_TXDMA_EN | R92C_CR_RXDMA_EN | R92C_CR_PROTOCOL_EN |
2024 	    R92C_CR_SCHEDULE_EN | R92C_CR_MACTXEN | R92C_CR_MACRXEN |
2025 	    R92C_CR_ENSEC;
2026 	rtwn_write_2(sc, R92C_CR, reg);
2027 
2028 	rtwn_write_1(sc, 0xfe10, 0x19);
2029 
2030 	return (0);
2031 }
2032 
2033 static int
2034 rtwn_llt_init(struct rtwn_softc *sc)
2035 {
2036 	int i, error;
2037 
2038 	/* Reserve pages [0; R92C_TX_PAGE_COUNT]. */
2039 	for (i = 0; i < R92C_TX_PAGE_COUNT; i++) {
2040 		if ((error = rtwn_llt_write(sc, i, i + 1)) != 0)
2041 			return (error);
2042 	}
2043 	/* NB: 0xff indicates end-of-list. */
2044 	if ((error = rtwn_llt_write(sc, i, 0xff)) != 0)
2045 		return (error);
2046 	/*
2047 	 * Use pages [R92C_TX_PAGE_COUNT + 1; R92C_TXPKTBUF_COUNT - 1]
2048 	 * as ring buffer.
2049 	 */
2050 	for (++i; i < R92C_TXPKTBUF_COUNT - 1; i++) {
2051 		if ((error = rtwn_llt_write(sc, i, i + 1)) != 0)
2052 			return (error);
2053 	}
2054 	/* Make the last page point to the beginning of the ring buffer. */
2055 	error = rtwn_llt_write(sc, i, R92C_TX_PAGE_COUNT + 1);
2056 	return (error);
2057 }
2058 
2059 static void
2060 rtwn_fw_reset(struct rtwn_softc *sc)
2061 {
2062 	uint16_t reg;
2063 	int ntries;
2064 
2065 	/* Tell 8051 to reset itself. */
2066 	rtwn_write_1(sc, R92C_HMETFR + 3, 0x20);
2067 
2068 	/* Wait until 8051 resets by itself. */
2069 	for (ntries = 0; ntries < 100; ntries++) {
2070 		reg = rtwn_read_2(sc, R92C_SYS_FUNC_EN);
2071 		if (!(reg & R92C_SYS_FUNC_EN_CPUEN))
2072 			goto sleep;
2073 		DELAY(50);
2074 	}
2075 	/* Force 8051 reset. */
2076 	rtwn_write_2(sc, R92C_SYS_FUNC_EN, reg & ~R92C_SYS_FUNC_EN_CPUEN);
2077 sleep:
2078 	/*
2079 	 * We must sleep for one second to let the firmware settle.
2080 	 * Accessing registers too early will hang the whole system.
2081 	 */
2082 	if (msleep(&reg, &sc->sc_mtx, 0, "rtwnrst", hz)) {
2083 		device_printf(sc->sc_dev, "timeout waiting for firmware "
2084 		    "initialization to complete\n");
2085 	}
2086 }
2087 
2088 static void
2089 rtwn_fw_loadpage(struct rtwn_softc *sc, int page, const uint8_t *buf, int len)
2090 {
2091 	uint32_t reg;
2092 	int off, mlen, i;
2093 
2094 	reg = rtwn_read_4(sc, R92C_MCUFWDL);
2095 	reg = RW(reg, R92C_MCUFWDL_PAGE, page);
2096 	rtwn_write_4(sc, R92C_MCUFWDL, reg);
2097 
2098 	DELAY(5);
2099 
2100 	off = R92C_FW_START_ADDR;
2101 	while (len > 0) {
2102 		if (len > 196)
2103 			mlen = 196;
2104 		else if (len > 4)
2105 			mlen = 4;
2106 		else
2107 			mlen = 1;
2108 		for (i = 0; i < mlen; i++)
2109 			rtwn_write_1(sc, off++, buf[i]);
2110 		buf += mlen;
2111 		len -= mlen;
2112 	}
2113 }
2114 
2115 static int
2116 rtwn_load_firmware(struct rtwn_softc *sc)
2117 {
2118 	const struct firmware *fw;
2119 	const struct r92c_fw_hdr *hdr;
2120 	const char *name;
2121 	const u_char *ptr;
2122 	size_t len;
2123 	uint32_t reg;
2124 	int mlen, ntries, page, error = 0;
2125 
2126 	/* Read firmware image from the filesystem. */
2127 	if ((sc->chip & (RTWN_CHIP_UMC_A_CUT | RTWN_CHIP_92C)) ==
2128 	    RTWN_CHIP_UMC_A_CUT)
2129 		name = "rtwn-rtl8192cfwU";
2130 	else
2131 		name = "rtwn-rtl8192cfwU_B";
2132 	RTWN_UNLOCK(sc);
2133 	fw = firmware_get(name);
2134 	RTWN_LOCK(sc);
2135 	if (fw == NULL) {
2136 		device_printf(sc->sc_dev,
2137 		    "could not read firmware %s\n", name);
2138 		return (ENOENT);
2139 	}
2140 	len = fw->datasize;
2141 	if (len < sizeof(*hdr)) {
2142 		device_printf(sc->sc_dev, "firmware too short\n");
2143 		error = EINVAL;
2144 		goto fail;
2145 	}
2146 	ptr = fw->data;
2147 	hdr = (const struct r92c_fw_hdr *)ptr;
2148 	/* Check if there is a valid FW header and skip it. */
2149 	if ((le16toh(hdr->signature) >> 4) == 0x88c ||
2150 	    (le16toh(hdr->signature) >> 4) == 0x92c) {
2151 		DPRINTF(("FW V%d.%d %02d-%02d %02d:%02d\n",
2152 		    le16toh(hdr->version), le16toh(hdr->subversion),
2153 		    hdr->month, hdr->date, hdr->hour, hdr->minute));
2154 		ptr += sizeof(*hdr);
2155 		len -= sizeof(*hdr);
2156 	}
2157 
2158 	if (rtwn_read_1(sc, R92C_MCUFWDL) & R92C_MCUFWDL_RAM_DL_SEL)
2159 		rtwn_fw_reset(sc);
2160 
2161 	/* Enable FW download. */
2162 	rtwn_write_2(sc, R92C_SYS_FUNC_EN,
2163 	    rtwn_read_2(sc, R92C_SYS_FUNC_EN) |
2164 	    R92C_SYS_FUNC_EN_CPUEN);
2165 	rtwn_write_1(sc, R92C_MCUFWDL,
2166 	    rtwn_read_1(sc, R92C_MCUFWDL) | R92C_MCUFWDL_EN);
2167 	rtwn_write_1(sc, R92C_MCUFWDL + 2,
2168 	    rtwn_read_1(sc, R92C_MCUFWDL + 2) & ~0x08);
2169 
2170 	/* Reset the FWDL checksum. */
2171 	rtwn_write_1(sc, R92C_MCUFWDL,
2172 	    rtwn_read_1(sc, R92C_MCUFWDL) | R92C_MCUFWDL_CHKSUM_RPT);
2173 
2174 	for (page = 0; len > 0; page++) {
2175 		mlen = MIN(len, R92C_FW_PAGE_SIZE);
2176 		rtwn_fw_loadpage(sc, page, ptr, mlen);
2177 		ptr += mlen;
2178 		len -= mlen;
2179 	}
2180 
2181 	/* Disable FW download. */
2182 	rtwn_write_1(sc, R92C_MCUFWDL,
2183 	    rtwn_read_1(sc, R92C_MCUFWDL) & ~R92C_MCUFWDL_EN);
2184 	rtwn_write_1(sc, R92C_MCUFWDL + 1, 0);
2185 
2186 	/* Wait for checksum report. */
2187 	for (ntries = 0; ntries < 1000; ntries++) {
2188 		if (rtwn_read_4(sc, R92C_MCUFWDL) & R92C_MCUFWDL_CHKSUM_RPT)
2189 			break;
2190 		DELAY(5);
2191 	}
2192 	if (ntries == 1000) {
2193 		device_printf(sc->sc_dev,
2194 		    "timeout waiting for checksum report\n");
2195 		error = ETIMEDOUT;
2196 		goto fail;
2197 	}
2198 
2199 	reg = rtwn_read_4(sc, R92C_MCUFWDL);
2200 	reg = (reg & ~R92C_MCUFWDL_WINTINI_RDY) | R92C_MCUFWDL_RDY;
2201 	rtwn_write_4(sc, R92C_MCUFWDL, reg);
2202 	/* Wait for firmware readiness. */
2203 	for (ntries = 0; ntries < 2000; ntries++) {
2204 		if (rtwn_read_4(sc, R92C_MCUFWDL) & R92C_MCUFWDL_WINTINI_RDY)
2205 			break;
2206 		DELAY(50);
2207 	}
2208 	if (ntries == 1000) {
2209 		device_printf(sc->sc_dev,
2210 		    "timeout waiting for firmware readiness\n");
2211 		error = ETIMEDOUT;
2212 		goto fail;
2213 	}
2214 fail:
2215 	firmware_put(fw, FIRMWARE_UNLOAD);
2216 	return (error);
2217 }
2218 
2219 static int
2220 rtwn_dma_init(struct rtwn_softc *sc)
2221 {
2222 	uint32_t reg;
2223 	int error;
2224 
2225 	/* Initialize LLT table. */
2226 	error = rtwn_llt_init(sc);
2227 	if (error != 0)
2228 		return error;
2229 
2230 	/* Set number of pages for normal priority queue. */
2231 	rtwn_write_2(sc, R92C_RQPN_NPQ, 0);
2232 	rtwn_write_4(sc, R92C_RQPN,
2233 	    /* Set number of pages for public queue. */
2234 	    SM(R92C_RQPN_PUBQ, R92C_PUBQ_NPAGES) |
2235 	    /* Set number of pages for high priority queue. */
2236 	    SM(R92C_RQPN_HPQ, R92C_HPQ_NPAGES) |
2237 	    /* Set number of pages for low priority queue. */
2238 	    SM(R92C_RQPN_LPQ, R92C_LPQ_NPAGES) |
2239 	    /* Load values. */
2240 	    R92C_RQPN_LD);
2241 
2242 	rtwn_write_1(sc, R92C_TXPKTBUF_BCNQ_BDNY, R92C_TX_PAGE_BOUNDARY);
2243 	rtwn_write_1(sc, R92C_TXPKTBUF_MGQ_BDNY, R92C_TX_PAGE_BOUNDARY);
2244 	rtwn_write_1(sc, R92C_TXPKTBUF_WMAC_LBK_BF_HD, R92C_TX_PAGE_BOUNDARY);
2245 	rtwn_write_1(sc, R92C_TRXFF_BNDY, R92C_TX_PAGE_BOUNDARY);
2246 	rtwn_write_1(sc, R92C_TDECTRL + 1, R92C_TX_PAGE_BOUNDARY);
2247 
2248 	reg = rtwn_read_2(sc, R92C_TRXDMA_CTRL);
2249 	reg &= ~R92C_TRXDMA_CTRL_QMAP_M;
2250 	reg |= 0xF771;
2251 	rtwn_write_2(sc, R92C_TRXDMA_CTRL, reg);
2252 
2253 	rtwn_write_4(sc, R92C_TCR, R92C_TCR_CFENDFORM | (1 << 12) | (1 << 13));
2254 
2255 	/* Configure Tx DMA. */
2256 	rtwn_write_4(sc, R92C_BKQ_DESA, sc->tx_ring[RTWN_BK_QUEUE].paddr);
2257 	rtwn_write_4(sc, R92C_BEQ_DESA, sc->tx_ring[RTWN_BE_QUEUE].paddr);
2258 	rtwn_write_4(sc, R92C_VIQ_DESA, sc->tx_ring[RTWN_VI_QUEUE].paddr);
2259 	rtwn_write_4(sc, R92C_VOQ_DESA, sc->tx_ring[RTWN_VO_QUEUE].paddr);
2260 	rtwn_write_4(sc, R92C_BCNQ_DESA, sc->tx_ring[RTWN_BEACON_QUEUE].paddr);
2261 	rtwn_write_4(sc, R92C_MGQ_DESA, sc->tx_ring[RTWN_MGNT_QUEUE].paddr);
2262 	rtwn_write_4(sc, R92C_HQ_DESA, sc->tx_ring[RTWN_HIGH_QUEUE].paddr);
2263 
2264 	/* Configure Rx DMA. */
2265 	rtwn_write_4(sc, R92C_RX_DESA, sc->rx_ring.paddr);
2266 
2267 	/* Set Tx/Rx transfer page boundary. */
2268 	rtwn_write_2(sc, R92C_TRXFF_BNDY + 2, 0x27ff);
2269 
2270 	/* Set Tx/Rx transfer page size. */
2271 	rtwn_write_1(sc, R92C_PBP,
2272 	    SM(R92C_PBP_PSRX, R92C_PBP_128) |
2273 	    SM(R92C_PBP_PSTX, R92C_PBP_128));
2274 	return (0);
2275 }
2276 
2277 static void
2278 rtwn_mac_init(struct rtwn_softc *sc)
2279 {
2280 	int i;
2281 
2282 	/* Write MAC initialization values. */
2283 	for (i = 0; i < nitems(rtl8192ce_mac); i++)
2284 		rtwn_write_1(sc, rtl8192ce_mac[i].reg, rtl8192ce_mac[i].val);
2285 }
2286 
2287 static void
2288 rtwn_bb_init(struct rtwn_softc *sc)
2289 {
2290 	const struct rtwn_bb_prog *prog;
2291 	uint32_t reg;
2292 	int i;
2293 
2294 	/* Enable BB and RF. */
2295 	rtwn_write_2(sc, R92C_SYS_FUNC_EN,
2296 	    rtwn_read_2(sc, R92C_SYS_FUNC_EN) |
2297 	    R92C_SYS_FUNC_EN_BBRSTB | R92C_SYS_FUNC_EN_BB_GLB_RST |
2298 	    R92C_SYS_FUNC_EN_DIO_RF);
2299 
2300 	rtwn_write_2(sc, R92C_AFE_PLL_CTRL, 0xdb83);
2301 
2302 	rtwn_write_1(sc, R92C_RF_CTRL,
2303 	    R92C_RF_CTRL_EN | R92C_RF_CTRL_RSTB | R92C_RF_CTRL_SDMRSTB);
2304 
2305 	rtwn_write_1(sc, R92C_SYS_FUNC_EN,
2306 	    R92C_SYS_FUNC_EN_DIO_PCIE | R92C_SYS_FUNC_EN_PCIEA |
2307 	    R92C_SYS_FUNC_EN_PPLL | R92C_SYS_FUNC_EN_BB_GLB_RST |
2308 	    R92C_SYS_FUNC_EN_BBRSTB);
2309 
2310 	rtwn_write_1(sc, R92C_AFE_XTAL_CTRL + 1, 0x80);
2311 
2312 	rtwn_write_4(sc, R92C_LEDCFG0,
2313 	    rtwn_read_4(sc, R92C_LEDCFG0) | 0x00800000);
2314 
2315 	/* Select BB programming. */
2316 	prog = (sc->chip & RTWN_CHIP_92C) ?
2317 	    &rtl8192ce_bb_prog_2t : &rtl8192ce_bb_prog_1t;
2318 
2319 	/* Write BB initialization values. */
2320 	for (i = 0; i < prog->count; i++) {
2321 		rtwn_bb_write(sc, prog->regs[i], prog->vals[i]);
2322 		DELAY(1);
2323 	}
2324 
2325 	if (sc->chip & RTWN_CHIP_92C_1T2R) {
2326 		/* 8192C 1T only configuration. */
2327 		reg = rtwn_bb_read(sc, R92C_FPGA0_TXINFO);
2328 		reg = (reg & ~0x00000003) | 0x2;
2329 		rtwn_bb_write(sc, R92C_FPGA0_TXINFO, reg);
2330 
2331 		reg = rtwn_bb_read(sc, R92C_FPGA1_TXINFO);
2332 		reg = (reg & ~0x00300033) | 0x00200022;
2333 		rtwn_bb_write(sc, R92C_FPGA1_TXINFO, reg);
2334 
2335 		reg = rtwn_bb_read(sc, R92C_CCK0_AFESETTING);
2336 		reg = (reg & ~0xff000000) | 0x45 << 24;
2337 		rtwn_bb_write(sc, R92C_CCK0_AFESETTING, reg);
2338 
2339 		reg = rtwn_bb_read(sc, R92C_OFDM0_TRXPATHENA);
2340 		reg = (reg & ~0x000000ff) | 0x23;
2341 		rtwn_bb_write(sc, R92C_OFDM0_TRXPATHENA, reg);
2342 
2343 		reg = rtwn_bb_read(sc, R92C_OFDM0_AGCPARAM1);
2344 		reg = (reg & ~0x00000030) | 1 << 4;
2345 		rtwn_bb_write(sc, R92C_OFDM0_AGCPARAM1, reg);
2346 
2347 		reg = rtwn_bb_read(sc, 0xe74);
2348 		reg = (reg & ~0x0c000000) | 2 << 26;
2349 		rtwn_bb_write(sc, 0xe74, reg);
2350 		reg = rtwn_bb_read(sc, 0xe78);
2351 		reg = (reg & ~0x0c000000) | 2 << 26;
2352 		rtwn_bb_write(sc, 0xe78, reg);
2353 		reg = rtwn_bb_read(sc, 0xe7c);
2354 		reg = (reg & ~0x0c000000) | 2 << 26;
2355 		rtwn_bb_write(sc, 0xe7c, reg);
2356 		reg = rtwn_bb_read(sc, 0xe80);
2357 		reg = (reg & ~0x0c000000) | 2 << 26;
2358 		rtwn_bb_write(sc, 0xe80, reg);
2359 		reg = rtwn_bb_read(sc, 0xe88);
2360 		reg = (reg & ~0x0c000000) | 2 << 26;
2361 		rtwn_bb_write(sc, 0xe88, reg);
2362 	}
2363 
2364 	/* Write AGC values. */
2365 	for (i = 0; i < prog->agccount; i++) {
2366 		rtwn_bb_write(sc, R92C_OFDM0_AGCRSSITABLE,
2367 		    prog->agcvals[i]);
2368 		DELAY(1);
2369 	}
2370 
2371 	if (rtwn_bb_read(sc, R92C_HSSI_PARAM2(0)) &
2372 	    R92C_HSSI_PARAM2_CCK_HIPWR)
2373 		sc->sc_flags |= RTWN_FLAG_CCK_HIPWR;
2374 }
2375 
2376 static void
2377 rtwn_rf_init(struct rtwn_softc *sc)
2378 {
2379 	const struct rtwn_rf_prog *prog;
2380 	uint32_t reg, type;
2381 	int i, j, idx, off;
2382 
2383 	/* Select RF programming based on board type. */
2384 	if (!(sc->chip & RTWN_CHIP_92C)) {
2385 		if (sc->board_type == R92C_BOARD_TYPE_MINICARD)
2386 			prog = rtl8188ce_rf_prog;
2387 		else if (sc->board_type == R92C_BOARD_TYPE_HIGHPA)
2388 			prog = rtl8188ru_rf_prog;
2389 		else
2390 			prog = rtl8188cu_rf_prog;
2391 	} else
2392 		prog = rtl8192ce_rf_prog;
2393 
2394 	for (i = 0; i < sc->nrxchains; i++) {
2395 		/* Save RF_ENV control type. */
2396 		idx = i / 2;
2397 		off = (i % 2) * 16;
2398 		reg = rtwn_bb_read(sc, R92C_FPGA0_RFIFACESW(idx));
2399 		type = (reg >> off) & 0x10;
2400 
2401 		/* Set RF_ENV enable. */
2402 		reg = rtwn_bb_read(sc, R92C_FPGA0_RFIFACEOE(i));
2403 		reg |= 0x100000;
2404 		rtwn_bb_write(sc, R92C_FPGA0_RFIFACEOE(i), reg);
2405 		DELAY(1);
2406 		/* Set RF_ENV output high. */
2407 		reg = rtwn_bb_read(sc, R92C_FPGA0_RFIFACEOE(i));
2408 		reg |= 0x10;
2409 		rtwn_bb_write(sc, R92C_FPGA0_RFIFACEOE(i), reg);
2410 		DELAY(1);
2411 		/* Set address and data lengths of RF registers. */
2412 		reg = rtwn_bb_read(sc, R92C_HSSI_PARAM2(i));
2413 		reg &= ~R92C_HSSI_PARAM2_ADDR_LENGTH;
2414 		rtwn_bb_write(sc, R92C_HSSI_PARAM2(i), reg);
2415 		DELAY(1);
2416 		reg = rtwn_bb_read(sc, R92C_HSSI_PARAM2(i));
2417 		reg &= ~R92C_HSSI_PARAM2_DATA_LENGTH;
2418 		rtwn_bb_write(sc, R92C_HSSI_PARAM2(i), reg);
2419 		DELAY(1);
2420 
2421 		/* Write RF initialization values for this chain. */
2422 		for (j = 0; j < prog[i].count; j++) {
2423 			if (prog[i].regs[j] >= 0xf9 &&
2424 			    prog[i].regs[j] <= 0xfe) {
2425 				/*
2426 				 * These are fake RF registers offsets that
2427 				 * indicate a delay is required.
2428 				 */
2429 				DELAY(50);
2430 				continue;
2431 			}
2432 			rtwn_rf_write(sc, i, prog[i].regs[j],
2433 			    prog[i].vals[j]);
2434 			DELAY(1);
2435 		}
2436 
2437 		/* Restore RF_ENV control type. */
2438 		reg = rtwn_bb_read(sc, R92C_FPGA0_RFIFACESW(idx));
2439 		reg &= ~(0x10 << off) | (type << off);
2440 		rtwn_bb_write(sc, R92C_FPGA0_RFIFACESW(idx), reg);
2441 
2442 		/* Cache RF register CHNLBW. */
2443 		sc->rf_chnlbw[i] = rtwn_rf_read(sc, i, R92C_RF_CHNLBW);
2444 	}
2445 
2446 	if ((sc->chip & (RTWN_CHIP_UMC_A_CUT | RTWN_CHIP_92C)) ==
2447 	    RTWN_CHIP_UMC_A_CUT) {
2448 		rtwn_rf_write(sc, 0, R92C_RF_RX_G1, 0x30255);
2449 		rtwn_rf_write(sc, 0, R92C_RF_RX_G2, 0x50a00);
2450 	}
2451 }
2452 
2453 static void
2454 rtwn_cam_init(struct rtwn_softc *sc)
2455 {
2456 	/* Invalidate all CAM entries. */
2457 	rtwn_write_4(sc, R92C_CAMCMD,
2458 	    R92C_CAMCMD_POLLING | R92C_CAMCMD_CLR);
2459 }
2460 
2461 static void
2462 rtwn_pa_bias_init(struct rtwn_softc *sc)
2463 {
2464 	uint8_t reg;
2465 	int i;
2466 
2467 	for (i = 0; i < sc->nrxchains; i++) {
2468 		if (sc->pa_setting & (1 << i))
2469 			continue;
2470 		rtwn_rf_write(sc, i, R92C_RF_IPA, 0x0f406);
2471 		rtwn_rf_write(sc, i, R92C_RF_IPA, 0x4f406);
2472 		rtwn_rf_write(sc, i, R92C_RF_IPA, 0x8f406);
2473 		rtwn_rf_write(sc, i, R92C_RF_IPA, 0xcf406);
2474 	}
2475 	if (!(sc->pa_setting & 0x10)) {
2476 		reg = rtwn_read_1(sc, 0x16);
2477 		reg = (reg & ~0xf0) | 0x90;
2478 		rtwn_write_1(sc, 0x16, reg);
2479 	}
2480 }
2481 
2482 static void
2483 rtwn_rxfilter_init(struct rtwn_softc *sc)
2484 {
2485 	/* Initialize Rx filter. */
2486 	/* TODO: use better filter for monitor mode. */
2487 	rtwn_write_4(sc, R92C_RCR,
2488 	    R92C_RCR_AAP | R92C_RCR_APM | R92C_RCR_AM | R92C_RCR_AB |
2489 	    R92C_RCR_APP_ICV | R92C_RCR_AMF | R92C_RCR_HTC_LOC_CTRL |
2490 	    R92C_RCR_APP_MIC | R92C_RCR_APP_PHYSTS);
2491 	/* Accept all multicast frames. */
2492 	rtwn_write_4(sc, R92C_MAR + 0, 0xffffffff);
2493 	rtwn_write_4(sc, R92C_MAR + 4, 0xffffffff);
2494 	/* Accept all management frames. */
2495 	rtwn_write_2(sc, R92C_RXFLTMAP0, 0xffff);
2496 	/* Reject all control frames. */
2497 	rtwn_write_2(sc, R92C_RXFLTMAP1, 0x0000);
2498 	/* Accept all data frames. */
2499 	rtwn_write_2(sc, R92C_RXFLTMAP2, 0xffff);
2500 }
2501 
2502 static void
2503 rtwn_edca_init(struct rtwn_softc *sc)
2504 {
2505 
2506 	rtwn_write_2(sc, R92C_SPEC_SIFS, 0x1010);
2507 	rtwn_write_2(sc, R92C_MAC_SPEC_SIFS, 0x1010);
2508 	rtwn_write_2(sc, R92C_SIFS_CCK, 0x1010);
2509 	rtwn_write_2(sc, R92C_SIFS_OFDM, 0x0e0e);
2510 	rtwn_write_4(sc, R92C_EDCA_BE_PARAM, 0x005ea42b);
2511 	rtwn_write_4(sc, R92C_EDCA_BK_PARAM, 0x0000a44f);
2512 	rtwn_write_4(sc, R92C_EDCA_VI_PARAM, 0x005e4322);
2513 	rtwn_write_4(sc, R92C_EDCA_VO_PARAM, 0x002f3222);
2514 }
2515 
2516 static void
2517 rtwn_write_txpower(struct rtwn_softc *sc, int chain,
2518     uint16_t power[RTWN_RIDX_COUNT])
2519 {
2520 	uint32_t reg;
2521 
2522 	/* Write per-CCK rate Tx power. */
2523 	if (chain == 0) {
2524 		reg = rtwn_bb_read(sc, R92C_TXAGC_A_CCK1_MCS32);
2525 		reg = RW(reg, R92C_TXAGC_A_CCK1,  power[0]);
2526 		rtwn_bb_write(sc, R92C_TXAGC_A_CCK1_MCS32, reg);
2527 		reg = rtwn_bb_read(sc, R92C_TXAGC_B_CCK11_A_CCK2_11);
2528 		reg = RW(reg, R92C_TXAGC_A_CCK2,  power[1]);
2529 		reg = RW(reg, R92C_TXAGC_A_CCK55, power[2]);
2530 		reg = RW(reg, R92C_TXAGC_A_CCK11, power[3]);
2531 		rtwn_bb_write(sc, R92C_TXAGC_B_CCK11_A_CCK2_11, reg);
2532 	} else {
2533 		reg = rtwn_bb_read(sc, R92C_TXAGC_B_CCK1_55_MCS32);
2534 		reg = RW(reg, R92C_TXAGC_B_CCK1,  power[0]);
2535 		reg = RW(reg, R92C_TXAGC_B_CCK2,  power[1]);
2536 		reg = RW(reg, R92C_TXAGC_B_CCK55, power[2]);
2537 		rtwn_bb_write(sc, R92C_TXAGC_B_CCK1_55_MCS32, reg);
2538 		reg = rtwn_bb_read(sc, R92C_TXAGC_B_CCK11_A_CCK2_11);
2539 		reg = RW(reg, R92C_TXAGC_B_CCK11, power[3]);
2540 		rtwn_bb_write(sc, R92C_TXAGC_B_CCK11_A_CCK2_11, reg);
2541 	}
2542 	/* Write per-OFDM rate Tx power. */
2543 	rtwn_bb_write(sc, R92C_TXAGC_RATE18_06(chain),
2544 	    SM(R92C_TXAGC_RATE06, power[ 4]) |
2545 	    SM(R92C_TXAGC_RATE09, power[ 5]) |
2546 	    SM(R92C_TXAGC_RATE12, power[ 6]) |
2547 	    SM(R92C_TXAGC_RATE18, power[ 7]));
2548 	rtwn_bb_write(sc, R92C_TXAGC_RATE54_24(chain),
2549 	    SM(R92C_TXAGC_RATE24, power[ 8]) |
2550 	    SM(R92C_TXAGC_RATE36, power[ 9]) |
2551 	    SM(R92C_TXAGC_RATE48, power[10]) |
2552 	    SM(R92C_TXAGC_RATE54, power[11]));
2553 	/* Write per-MCS Tx power. */
2554 	rtwn_bb_write(sc, R92C_TXAGC_MCS03_MCS00(chain),
2555 	    SM(R92C_TXAGC_MCS00,  power[12]) |
2556 	    SM(R92C_TXAGC_MCS01,  power[13]) |
2557 	    SM(R92C_TXAGC_MCS02,  power[14]) |
2558 	    SM(R92C_TXAGC_MCS03,  power[15]));
2559 	rtwn_bb_write(sc, R92C_TXAGC_MCS07_MCS04(chain),
2560 	    SM(R92C_TXAGC_MCS04,  power[16]) |
2561 	    SM(R92C_TXAGC_MCS05,  power[17]) |
2562 	    SM(R92C_TXAGC_MCS06,  power[18]) |
2563 	    SM(R92C_TXAGC_MCS07,  power[19]));
2564 	rtwn_bb_write(sc, R92C_TXAGC_MCS11_MCS08(chain),
2565 	    SM(R92C_TXAGC_MCS08,  power[20]) |
2566 	    SM(R92C_TXAGC_MCS09,  power[21]) |
2567 	    SM(R92C_TXAGC_MCS10,  power[22]) |
2568 	    SM(R92C_TXAGC_MCS11,  power[23]));
2569 	rtwn_bb_write(sc, R92C_TXAGC_MCS15_MCS12(chain),
2570 	    SM(R92C_TXAGC_MCS12,  power[24]) |
2571 	    SM(R92C_TXAGC_MCS13,  power[25]) |
2572 	    SM(R92C_TXAGC_MCS14,  power[26]) |
2573 	    SM(R92C_TXAGC_MCS15,  power[27]));
2574 }
2575 
2576 static void
2577 rtwn_get_txpower(struct rtwn_softc *sc, int chain,
2578     struct ieee80211_channel *c, struct ieee80211_channel *extc,
2579     uint16_t power[RTWN_RIDX_COUNT])
2580 {
2581 	struct ieee80211com *ic = &sc->sc_ic;
2582 	struct r92c_rom *rom = &sc->rom;
2583 	uint16_t cckpow, ofdmpow, htpow, diff, max;
2584 	const struct rtwn_txpwr *base;
2585 	int ridx, chan, group;
2586 
2587 	/* Determine channel group. */
2588 	chan = ieee80211_chan2ieee(ic, c);	/* XXX center freq! */
2589 	if (chan <= 3)
2590 		group = 0;
2591 	else if (chan <= 9)
2592 		group = 1;
2593 	else
2594 		group = 2;
2595 
2596 	/* Get original Tx power based on board type and RF chain. */
2597 	if (!(sc->chip & RTWN_CHIP_92C)) {
2598 		if (sc->board_type == R92C_BOARD_TYPE_HIGHPA)
2599 			base = &rtl8188ru_txagc[chain];
2600 		else
2601 			base = &rtl8192cu_txagc[chain];
2602 	} else
2603 		base = &rtl8192cu_txagc[chain];
2604 
2605 	memset(power, 0, RTWN_RIDX_COUNT * sizeof(power[0]));
2606 	if (sc->regulatory == 0) {
2607 		for (ridx = 0; ridx <= 3; ridx++)
2608 			power[ridx] = base->pwr[0][ridx];
2609 	}
2610 	for (ridx = 4; ridx < RTWN_RIDX_COUNT; ridx++) {
2611 		if (sc->regulatory == 3) {
2612 			power[ridx] = base->pwr[0][ridx];
2613 			/* Apply vendor limits. */
2614 			if (extc != NULL)
2615 				max = rom->ht40_max_pwr[group];
2616 			else
2617 				max = rom->ht20_max_pwr[group];
2618 			max = (max >> (chain * 4)) & 0xf;
2619 			if (power[ridx] > max)
2620 				power[ridx] = max;
2621 		} else if (sc->regulatory == 1) {
2622 			if (extc == NULL)
2623 				power[ridx] = base->pwr[group][ridx];
2624 		} else if (sc->regulatory != 2)
2625 			power[ridx] = base->pwr[0][ridx];
2626 	}
2627 
2628 	/* Compute per-CCK rate Tx power. */
2629 	cckpow = rom->cck_tx_pwr[chain][group];
2630 	for (ridx = 0; ridx <= 3; ridx++) {
2631 		power[ridx] += cckpow;
2632 		if (power[ridx] > R92C_MAX_TX_PWR)
2633 			power[ridx] = R92C_MAX_TX_PWR;
2634 	}
2635 
2636 	htpow = rom->ht40_1s_tx_pwr[chain][group];
2637 	if (sc->ntxchains > 1) {
2638 		/* Apply reduction for 2 spatial streams. */
2639 		diff = rom->ht40_2s_tx_pwr_diff[group];
2640 		diff = (diff >> (chain * 4)) & 0xf;
2641 		htpow = (htpow > diff) ? htpow - diff : 0;
2642 	}
2643 
2644 	/* Compute per-OFDM rate Tx power. */
2645 	diff = rom->ofdm_tx_pwr_diff[group];
2646 	diff = (diff >> (chain * 4)) & 0xf;
2647 	ofdmpow = htpow + diff;	/* HT->OFDM correction. */
2648 	for (ridx = 4; ridx <= 11; ridx++) {
2649 		power[ridx] += ofdmpow;
2650 		if (power[ridx] > R92C_MAX_TX_PWR)
2651 			power[ridx] = R92C_MAX_TX_PWR;
2652 	}
2653 
2654 	/* Compute per-MCS Tx power. */
2655 	if (extc == NULL) {
2656 		diff = rom->ht20_tx_pwr_diff[group];
2657 		diff = (diff >> (chain * 4)) & 0xf;
2658 		htpow += diff;	/* HT40->HT20 correction. */
2659 	}
2660 	for (ridx = 12; ridx <= 27; ridx++) {
2661 		power[ridx] += htpow;
2662 		if (power[ridx] > R92C_MAX_TX_PWR)
2663 			power[ridx] = R92C_MAX_TX_PWR;
2664 	}
2665 #ifdef RTWN_DEBUG
2666 	if (sc->sc_debug >= 4) {
2667 		/* Dump per-rate Tx power values. */
2668 		printf("Tx power for chain %d:\n", chain);
2669 		for (ridx = 0; ridx < RTWN_RIDX_COUNT; ridx++)
2670 			printf("Rate %d = %u\n", ridx, power[ridx]);
2671 	}
2672 #endif
2673 }
2674 
2675 static void
2676 rtwn_set_txpower(struct rtwn_softc *sc, struct ieee80211_channel *c,
2677     struct ieee80211_channel *extc)
2678 {
2679 	uint16_t power[RTWN_RIDX_COUNT];
2680 	int i;
2681 
2682 	for (i = 0; i < sc->ntxchains; i++) {
2683 		/* Compute per-rate Tx power values. */
2684 		rtwn_get_txpower(sc, i, c, extc, power);
2685 		/* Write per-rate Tx power values to hardware. */
2686 		rtwn_write_txpower(sc, i, power);
2687 	}
2688 }
2689 
2690 static void
2691 rtwn_scan_start(struct ieee80211com *ic)
2692 {
2693 
2694 	/* XXX do nothing?  */
2695 }
2696 
2697 static void
2698 rtwn_scan_end(struct ieee80211com *ic)
2699 {
2700 
2701 	/* XXX do nothing?  */
2702 }
2703 
2704 static void
2705 rtwn_set_channel(struct ieee80211com *ic)
2706 {
2707 	struct rtwn_softc *sc = ic->ic_softc;
2708 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2709 
2710 	RTWN_LOCK(sc);
2711 	if (vap->iv_state == IEEE80211_S_SCAN) {
2712 		/* Make link LED blink during scan. */
2713 		rtwn_set_led(sc, RTWN_LED_LINK, !sc->ledlink);
2714 	}
2715 	rtwn_set_chan(sc, ic->ic_curchan, NULL);
2716 	RTWN_UNLOCK(sc);
2717 }
2718 
2719 static void
2720 rtwn_update_mcast(struct ieee80211com *ic)
2721 {
2722 
2723 	/* XXX do nothing?  */
2724 }
2725 
2726 static void
2727 rtwn_set_chan(struct rtwn_softc *sc, struct ieee80211_channel *c,
2728     struct ieee80211_channel *extc)
2729 {
2730 	struct ieee80211com *ic = &sc->sc_ic;
2731 	u_int chan;
2732 	int i;
2733 
2734 	chan = ieee80211_chan2ieee(ic, c);	/* XXX center freq! */
2735 	if (chan == 0 || chan == IEEE80211_CHAN_ANY) {
2736 		device_printf(sc->sc_dev,
2737 		    "%s: invalid channel %x\n", __func__, chan);
2738 		return;
2739 	}
2740 
2741 	/* Set Tx power for this new channel. */
2742 	rtwn_set_txpower(sc, c, extc);
2743 
2744 	for (i = 0; i < sc->nrxchains; i++) {
2745 		rtwn_rf_write(sc, i, R92C_RF_CHNLBW,
2746 		    RW(sc->rf_chnlbw[i], R92C_RF_CHNLBW_CHNL, chan));
2747 	}
2748 #ifndef IEEE80211_NO_HT
2749 	if (extc != NULL) {
2750 		uint32_t reg;
2751 
2752 		/* Is secondary channel below or above primary? */
2753 		int prichlo = c->ic_freq < extc->ic_freq;
2754 
2755 		rtwn_write_1(sc, R92C_BWOPMODE,
2756 		    rtwn_read_1(sc, R92C_BWOPMODE) & ~R92C_BWOPMODE_20MHZ);
2757 
2758 		reg = rtwn_read_1(sc, R92C_RRSR + 2);
2759 		reg = (reg & ~0x6f) | (prichlo ? 1 : 2) << 5;
2760 		rtwn_write_1(sc, R92C_RRSR + 2, reg);
2761 
2762 		rtwn_bb_write(sc, R92C_FPGA0_RFMOD,
2763 		    rtwn_bb_read(sc, R92C_FPGA0_RFMOD) | R92C_RFMOD_40MHZ);
2764 		rtwn_bb_write(sc, R92C_FPGA1_RFMOD,
2765 		    rtwn_bb_read(sc, R92C_FPGA1_RFMOD) | R92C_RFMOD_40MHZ);
2766 
2767 		/* Set CCK side band. */
2768 		reg = rtwn_bb_read(sc, R92C_CCK0_SYSTEM);
2769 		reg = (reg & ~0x00000010) | (prichlo ? 0 : 1) << 4;
2770 		rtwn_bb_write(sc, R92C_CCK0_SYSTEM, reg);
2771 
2772 		reg = rtwn_bb_read(sc, R92C_OFDM1_LSTF);
2773 		reg = (reg & ~0x00000c00) | (prichlo ? 1 : 2) << 10;
2774 		rtwn_bb_write(sc, R92C_OFDM1_LSTF, reg);
2775 
2776 		rtwn_bb_write(sc, R92C_FPGA0_ANAPARAM2,
2777 		    rtwn_bb_read(sc, R92C_FPGA0_ANAPARAM2) &
2778 		    ~R92C_FPGA0_ANAPARAM2_CBW20);
2779 
2780 		reg = rtwn_bb_read(sc, 0x818);
2781 		reg = (reg & ~0x0c000000) | (prichlo ? 2 : 1) << 26;
2782 		rtwn_bb_write(sc, 0x818, reg);
2783 
2784 		/* Select 40MHz bandwidth. */
2785 		rtwn_rf_write(sc, 0, R92C_RF_CHNLBW,
2786 		    (sc->rf_chnlbw[0] & ~0xfff) | chan);
2787 	} else
2788 #endif
2789 	{
2790 		rtwn_write_1(sc, R92C_BWOPMODE,
2791 		    rtwn_read_1(sc, R92C_BWOPMODE) | R92C_BWOPMODE_20MHZ);
2792 
2793 		rtwn_bb_write(sc, R92C_FPGA0_RFMOD,
2794 		    rtwn_bb_read(sc, R92C_FPGA0_RFMOD) & ~R92C_RFMOD_40MHZ);
2795 		rtwn_bb_write(sc, R92C_FPGA1_RFMOD,
2796 		    rtwn_bb_read(sc, R92C_FPGA1_RFMOD) & ~R92C_RFMOD_40MHZ);
2797 
2798 		rtwn_bb_write(sc, R92C_FPGA0_ANAPARAM2,
2799 		    rtwn_bb_read(sc, R92C_FPGA0_ANAPARAM2) |
2800 		    R92C_FPGA0_ANAPARAM2_CBW20);
2801 
2802 		/* Select 20MHz bandwidth. */
2803 		rtwn_rf_write(sc, 0, R92C_RF_CHNLBW,
2804 		    (sc->rf_chnlbw[0] & ~0xfff) | R92C_RF_CHNLBW_BW20 | chan);
2805 	}
2806 }
2807 
2808 static int
2809 rtwn_iq_calib_chain(struct rtwn_softc *sc, int chain, uint16_t tx[2],
2810     uint16_t rx[2])
2811 {
2812 	uint32_t status;
2813 	int offset = chain * 0x20;
2814 
2815 	if (chain == 0) {	/* IQ calibration for chain 0. */
2816 		/* IQ calibration settings for chain 0. */
2817 		rtwn_bb_write(sc, 0xe30, 0x10008c1f);
2818 		rtwn_bb_write(sc, 0xe34, 0x10008c1f);
2819 		rtwn_bb_write(sc, 0xe38, 0x82140102);
2820 
2821 		if (sc->ntxchains > 1) {
2822 			rtwn_bb_write(sc, 0xe3c, 0x28160202);	/* 2T */
2823 			/* IQ calibration settings for chain 1. */
2824 			rtwn_bb_write(sc, 0xe50, 0x10008c22);
2825 			rtwn_bb_write(sc, 0xe54, 0x10008c22);
2826 			rtwn_bb_write(sc, 0xe58, 0x82140102);
2827 			rtwn_bb_write(sc, 0xe5c, 0x28160202);
2828 		} else
2829 			rtwn_bb_write(sc, 0xe3c, 0x28160502);	/* 1T */
2830 
2831 		/* LO calibration settings. */
2832 		rtwn_bb_write(sc, 0xe4c, 0x001028d1);
2833 		/* We're doing LO and IQ calibration in one shot. */
2834 		rtwn_bb_write(sc, 0xe48, 0xf9000000);
2835 		rtwn_bb_write(sc, 0xe48, 0xf8000000);
2836 
2837 	} else {		/* IQ calibration for chain 1. */
2838 		/* We're doing LO and IQ calibration in one shot. */
2839 		rtwn_bb_write(sc, 0xe60, 0x00000002);
2840 		rtwn_bb_write(sc, 0xe60, 0x00000000);
2841 	}
2842 
2843 	/* Give LO and IQ calibrations the time to complete. */
2844 	DELAY(1000);
2845 
2846 	/* Read IQ calibration status. */
2847 	status = rtwn_bb_read(sc, 0xeac);
2848 
2849 	if (status & (1 << (28 + chain * 3)))
2850 		return (0);	/* Tx failed. */
2851 	/* Read Tx IQ calibration results. */
2852 	tx[0] = (rtwn_bb_read(sc, 0xe94 + offset) >> 16) & 0x3ff;
2853 	tx[1] = (rtwn_bb_read(sc, 0xe9c + offset) >> 16) & 0x3ff;
2854 	if (tx[0] == 0x142 || tx[1] == 0x042)
2855 		return (0);	/* Tx failed. */
2856 
2857 	if (status & (1 << (27 + chain * 3)))
2858 		return (1);	/* Rx failed. */
2859 	/* Read Rx IQ calibration results. */
2860 	rx[0] = (rtwn_bb_read(sc, 0xea4 + offset) >> 16) & 0x3ff;
2861 	rx[1] = (rtwn_bb_read(sc, 0xeac + offset) >> 16) & 0x3ff;
2862 	if (rx[0] == 0x132 || rx[1] == 0x036)
2863 		return (1);	/* Rx failed. */
2864 
2865 	return (3);	/* Both Tx and Rx succeeded. */
2866 }
2867 
2868 static void
2869 rtwn_iq_calib_run(struct rtwn_softc *sc, int n, uint16_t tx[2][2],
2870     uint16_t rx[2][2])
2871 {
2872 	/* Registers to save and restore during IQ calibration. */
2873 	struct iq_cal_regs {
2874 		uint32_t	adda[16];
2875 		uint8_t		txpause;
2876 		uint8_t		bcn_ctrl;
2877 		uint8_t		ustime_tsf;
2878 		uint32_t	gpio_muxcfg;
2879 		uint32_t	ofdm0_trxpathena;
2880 		uint32_t	ofdm0_trmuxpar;
2881 		uint32_t	fpga0_rfifacesw1;
2882 	} iq_cal_regs;
2883 	static const uint16_t reg_adda[16] = {
2884 		0x85c, 0xe6c, 0xe70, 0xe74,
2885 		0xe78, 0xe7c, 0xe80, 0xe84,
2886 		0xe88, 0xe8c, 0xed0, 0xed4,
2887 		0xed8, 0xedc, 0xee0, 0xeec
2888 	};
2889 	int i, chain;
2890 	uint32_t hssi_param1;
2891 
2892 	if (n == 0) {
2893 		for (i = 0; i < nitems(reg_adda); i++)
2894 			iq_cal_regs.adda[i] = rtwn_bb_read(sc, reg_adda[i]);
2895 
2896 		iq_cal_regs.txpause = rtwn_read_1(sc, R92C_TXPAUSE);
2897 		iq_cal_regs.bcn_ctrl = rtwn_read_1(sc, R92C_BCN_CTRL);
2898 		iq_cal_regs.ustime_tsf = rtwn_read_1(sc, R92C_USTIME_TSF);
2899 		iq_cal_regs.gpio_muxcfg = rtwn_read_4(sc, R92C_GPIO_MUXCFG);
2900 	}
2901 
2902 	if (sc->ntxchains == 1) {
2903 		rtwn_bb_write(sc, reg_adda[0], 0x0b1b25a0);
2904 		for (i = 1; i < nitems(reg_adda); i++)
2905 			rtwn_bb_write(sc, reg_adda[i], 0x0bdb25a0);
2906 	} else {
2907 		for (i = 0; i < nitems(reg_adda); i++)
2908 			rtwn_bb_write(sc, reg_adda[i], 0x04db25a4);
2909 	}
2910 
2911 	hssi_param1 = rtwn_bb_read(sc, R92C_HSSI_PARAM1(0));
2912 	if (!(hssi_param1 & R92C_HSSI_PARAM1_PI)) {
2913 		rtwn_bb_write(sc, R92C_HSSI_PARAM1(0),
2914 		    hssi_param1 | R92C_HSSI_PARAM1_PI);
2915 		rtwn_bb_write(sc, R92C_HSSI_PARAM1(1),
2916 		    hssi_param1 | R92C_HSSI_PARAM1_PI);
2917 	}
2918 
2919 	if (n == 0) {
2920 		iq_cal_regs.ofdm0_trxpathena =
2921 		    rtwn_bb_read(sc, R92C_OFDM0_TRXPATHENA);
2922 		iq_cal_regs.ofdm0_trmuxpar =
2923 		    rtwn_bb_read(sc, R92C_OFDM0_TRMUXPAR);
2924 		iq_cal_regs.fpga0_rfifacesw1 =
2925 		    rtwn_bb_read(sc, R92C_FPGA0_RFIFACESW(1));
2926 	}
2927 
2928 	rtwn_bb_write(sc, R92C_OFDM0_TRXPATHENA, 0x03a05600);
2929 	rtwn_bb_write(sc, R92C_OFDM0_TRMUXPAR, 0x000800e4);
2930 	rtwn_bb_write(sc, R92C_FPGA0_RFIFACESW(1), 0x22204000);
2931 	if (sc->ntxchains > 1) {
2932 		rtwn_bb_write(sc, R92C_LSSI_PARAM(0), 0x00010000);
2933 		rtwn_bb_write(sc, R92C_LSSI_PARAM(1), 0x00010000);
2934 	}
2935 
2936 	rtwn_write_1(sc, R92C_TXPAUSE, 0x3f);
2937 	rtwn_write_1(sc, R92C_BCN_CTRL, iq_cal_regs.bcn_ctrl & ~(0x08));
2938 	rtwn_write_1(sc, R92C_USTIME_TSF, iq_cal_regs.ustime_tsf & ~(0x08));
2939 	rtwn_write_1(sc, R92C_GPIO_MUXCFG,
2940 	    iq_cal_regs.gpio_muxcfg & ~(0x20));
2941 
2942 	rtwn_bb_write(sc, 0x0b68, 0x00080000);
2943 	if (sc->ntxchains > 1)
2944 		rtwn_bb_write(sc, 0x0b6c, 0x00080000);
2945 
2946 	rtwn_bb_write(sc, 0x0e28, 0x80800000);
2947 	rtwn_bb_write(sc, 0x0e40, 0x01007c00);
2948 	rtwn_bb_write(sc, 0x0e44, 0x01004800);
2949 
2950 	rtwn_bb_write(sc, 0x0b68, 0x00080000);
2951 
2952 	for (chain = 0; chain < sc->ntxchains; chain++) {
2953 		if (chain > 0) {
2954 			/* Put chain 0 on standby. */
2955 			rtwn_bb_write(sc, 0x0e28, 0x00);
2956 			rtwn_bb_write(sc, R92C_LSSI_PARAM(0), 0x00010000);
2957 			rtwn_bb_write(sc, 0x0e28, 0x80800000);
2958 
2959 			/* Enable chain 1. */
2960 			for (i = 0; i < nitems(reg_adda); i++)
2961 				rtwn_bb_write(sc, reg_adda[i], 0x0b1b25a4);
2962 		}
2963 
2964 		/* Run IQ calibration twice. */
2965 		for (i = 0; i < 2; i++) {
2966 			int ret;
2967 
2968 			ret = rtwn_iq_calib_chain(sc, chain,
2969 			    tx[chain], rx[chain]);
2970 			if (ret == 0) {
2971 				DPRINTF(("%s: chain %d: Tx failed.\n",
2972 				    __func__, chain));
2973 				tx[chain][0] = 0xff;
2974 				tx[chain][1] = 0xff;
2975 				rx[chain][0] = 0xff;
2976 				rx[chain][1] = 0xff;
2977 			} else if (ret == 1) {
2978 				DPRINTF(("%s: chain %d: Rx failed.\n",
2979 				    __func__, chain));
2980 				rx[chain][0] = 0xff;
2981 				rx[chain][1] = 0xff;
2982 			} else if (ret == 3) {
2983 				DPRINTF(("%s: chain %d: Both Tx and Rx "
2984 				    "succeeded.\n", __func__, chain));
2985 			}
2986 		}
2987 
2988 		DPRINTF(("%s: results for run %d chain %d: tx[0]=0x%x, "
2989 		    "tx[1]=0x%x rx[0]=0x%x rx[1]=0x%x\n", __func__, n, chain,
2990 		    tx[chain][0], tx[chain][1], rx[chain][0], rx[chain][1]));
2991 	}
2992 
2993 	rtwn_bb_write(sc, R92C_OFDM0_TRXPATHENA,
2994 	    iq_cal_regs.ofdm0_trxpathena);
2995 	rtwn_bb_write(sc, R92C_FPGA0_RFIFACESW(1),
2996 	    iq_cal_regs.fpga0_rfifacesw1);
2997 	rtwn_bb_write(sc, R92C_OFDM0_TRMUXPAR, iq_cal_regs.ofdm0_trmuxpar);
2998 
2999 	rtwn_bb_write(sc, 0x0e28, 0x00);
3000 	rtwn_bb_write(sc, R92C_LSSI_PARAM(0), 0x00032ed3);
3001 	if (sc->ntxchains > 1)
3002 		rtwn_bb_write(sc, R92C_LSSI_PARAM(1), 0x00032ed3);
3003 
3004 	if (n != 0) {
3005 		if (!(hssi_param1 & R92C_HSSI_PARAM1_PI)) {
3006 			rtwn_bb_write(sc, R92C_HSSI_PARAM1(0), hssi_param1);
3007 			rtwn_bb_write(sc, R92C_HSSI_PARAM1(1), hssi_param1);
3008 		}
3009 
3010 		for (i = 0; i < nitems(reg_adda); i++)
3011 			rtwn_bb_write(sc, reg_adda[i], iq_cal_regs.adda[i]);
3012 
3013 		rtwn_write_1(sc, R92C_TXPAUSE, iq_cal_regs.txpause);
3014 		rtwn_write_1(sc, R92C_BCN_CTRL, iq_cal_regs.bcn_ctrl);
3015 		rtwn_write_1(sc, R92C_USTIME_TSF, iq_cal_regs.ustime_tsf);
3016 		rtwn_write_4(sc, R92C_GPIO_MUXCFG, iq_cal_regs.gpio_muxcfg);
3017 	}
3018 }
3019 
3020 #define RTWN_IQ_CAL_MAX_TOLERANCE 5
3021 static int
3022 rtwn_iq_calib_compare_results(uint16_t tx1[2][2], uint16_t rx1[2][2],
3023     uint16_t tx2[2][2], uint16_t rx2[2][2], int ntxchains)
3024 {
3025 	int chain, i, tx_ok[2], rx_ok[2];
3026 
3027 	tx_ok[0] = tx_ok[1] = rx_ok[0] = rx_ok[1] = 0;
3028 	for (chain = 0; chain < ntxchains; chain++) {
3029 		for (i = 0; i < 2; i++)	{
3030 			if (tx1[chain][i] == 0xff || tx2[chain][i] == 0xff ||
3031 			    rx1[chain][i] == 0xff || rx2[chain][i] == 0xff)
3032 				continue;
3033 
3034 			tx_ok[chain] = (abs(tx1[chain][i] - tx2[chain][i]) <=
3035 			    RTWN_IQ_CAL_MAX_TOLERANCE);
3036 
3037 			rx_ok[chain] = (abs(rx1[chain][i] - rx2[chain][i]) <=
3038 			    RTWN_IQ_CAL_MAX_TOLERANCE);
3039 		}
3040 	}
3041 
3042 	if (ntxchains > 1)
3043 		return (tx_ok[0] && tx_ok[1] && rx_ok[0] && rx_ok[1]);
3044 	else
3045 		return (tx_ok[0] && rx_ok[0]);
3046 }
3047 #undef RTWN_IQ_CAL_MAX_TOLERANCE
3048 
3049 static void
3050 rtwn_iq_calib_write_results(struct rtwn_softc *sc, uint16_t tx[2],
3051     uint16_t rx[2], int chain)
3052 {
3053 	uint32_t reg, val, x;
3054 	long y, tx_c;
3055 
3056 	if (tx[0] == 0xff || tx[1] == 0xff)
3057 		return;
3058 
3059 	reg = rtwn_bb_read(sc, R92C_OFDM0_TXIQIMBALANCE(chain));
3060 	val = ((reg >> 22) & 0x3ff);
3061 	x = tx[0];
3062 	if (x & 0x0200)
3063 		x |= 0xfc00;
3064 	reg = (((x * val) >> 8) & 0x3ff);
3065 	rtwn_bb_write(sc, R92C_OFDM0_TXIQIMBALANCE(chain), reg);
3066 
3067 	reg = rtwn_bb_read(sc, R92C_OFDM0_ECCATHRESHOLD);
3068 	if (((x * val) >> 7) & 0x01)
3069 		reg |= 0x80000000;
3070 	else
3071 		reg &= ~0x80000000;
3072 	rtwn_bb_write(sc, R92C_OFDM0_ECCATHRESHOLD, reg);
3073 
3074 	y = tx[1];
3075 	if (y & 0x00000200)
3076 		y |= 0xfffffc00;
3077 	tx_c = (y * val) >> 8;
3078 	reg = rtwn_bb_read(sc, R92C_OFDM0_TXAFE(chain));
3079 	reg |= ((((tx_c & 0x3c0) >> 6) << 24) & 0xf0000000);
3080 	rtwn_bb_write(sc, R92C_OFDM0_TXAFE(chain), reg);
3081 
3082 	reg = rtwn_bb_read(sc, R92C_OFDM0_TXIQIMBALANCE(chain));
3083 	reg |= (((tx_c & 0x3f) << 16) & 0x003F0000);
3084 	rtwn_bb_write(sc, R92C_OFDM0_TXIQIMBALANCE(chain), reg);
3085 
3086 	reg = rtwn_bb_read(sc, R92C_OFDM0_ECCATHRESHOLD);
3087 	if (((y * val) >> 7) & 0x01)
3088 		reg |= 0x20000000;
3089 	else
3090 		reg &= ~0x20000000;
3091 	rtwn_bb_write(sc, R92C_OFDM0_ECCATHRESHOLD, reg);
3092 
3093 	if (rx[0] == 0xff || rx[1] == 0xff)
3094 		return;
3095 
3096 	reg = rtwn_bb_read(sc, R92C_OFDM0_RXIQIMBALANCE(chain));
3097 	reg |= (rx[0] & 0x3ff);
3098 	rtwn_bb_write(sc, R92C_OFDM0_RXIQIMBALANCE(chain), reg);
3099 	reg |= (((rx[1] & 0x03f) << 8) & 0xFC00);
3100 	rtwn_bb_write(sc, R92C_OFDM0_RXIQIMBALANCE(chain), reg);
3101 
3102 	if (chain == 0) {
3103 		reg = rtwn_bb_read(sc, R92C_OFDM0_RXIQEXTANTA);
3104 		reg |= (((rx[1] & 0xf) >> 6) & 0x000f);
3105 		rtwn_bb_write(sc, R92C_OFDM0_RXIQEXTANTA, reg);
3106 	} else {
3107 		reg = rtwn_bb_read(sc, R92C_OFDM0_AGCRSSITABLE);
3108 		reg |= ((((rx[1] & 0xf) >> 6) << 12) & 0xf000);
3109 		rtwn_bb_write(sc, R92C_OFDM0_AGCRSSITABLE, reg);
3110 	}
3111 }
3112 
3113 #define RTWN_IQ_CAL_NRUN	3
3114 static void
3115 rtwn_iq_calib(struct rtwn_softc *sc)
3116 {
3117 	uint16_t tx[RTWN_IQ_CAL_NRUN][2][2], rx[RTWN_IQ_CAL_NRUN][2][2];
3118 	int n, valid;
3119 
3120 	valid = 0;
3121 	for (n = 0; n < RTWN_IQ_CAL_NRUN; n++) {
3122 		rtwn_iq_calib_run(sc, n, tx[n], rx[n]);
3123 
3124 		if (n == 0)
3125 			continue;
3126 
3127 		/* Valid results remain stable after consecutive runs. */
3128 		valid = rtwn_iq_calib_compare_results(tx[n - 1], rx[n - 1],
3129 		    tx[n], rx[n], sc->ntxchains);
3130 		if (valid)
3131 			break;
3132 	}
3133 
3134 	if (valid) {
3135 		rtwn_iq_calib_write_results(sc, tx[n][0], rx[n][0], 0);
3136 		if (sc->ntxchains > 1)
3137 			rtwn_iq_calib_write_results(sc, tx[n][1], rx[n][1], 1);
3138 	}
3139 }
3140 #undef RTWN_IQ_CAL_NRUN
3141 
3142 static void
3143 rtwn_lc_calib(struct rtwn_softc *sc)
3144 {
3145 	uint32_t rf_ac[2];
3146 	uint8_t txmode;
3147 	int i;
3148 
3149 	txmode = rtwn_read_1(sc, R92C_OFDM1_LSTF + 3);
3150 	if ((txmode & 0x70) != 0) {
3151 		/* Disable all continuous Tx. */
3152 		rtwn_write_1(sc, R92C_OFDM1_LSTF + 3, txmode & ~0x70);
3153 
3154 		/* Set RF mode to standby mode. */
3155 		for (i = 0; i < sc->nrxchains; i++) {
3156 			rf_ac[i] = rtwn_rf_read(sc, i, R92C_RF_AC);
3157 			rtwn_rf_write(sc, i, R92C_RF_AC,
3158 			    RW(rf_ac[i], R92C_RF_AC_MODE,
3159 				R92C_RF_AC_MODE_STANDBY));
3160 		}
3161 	} else {
3162 		/* Block all Tx queues. */
3163 		rtwn_write_1(sc, R92C_TXPAUSE, 0xff);
3164 	}
3165 	/* Start calibration. */
3166 	rtwn_rf_write(sc, 0, R92C_RF_CHNLBW,
3167 	    rtwn_rf_read(sc, 0, R92C_RF_CHNLBW) | R92C_RF_CHNLBW_LCSTART);
3168 
3169 	/* Give calibration the time to complete. */
3170 	DELAY(100);
3171 
3172 	/* Restore configuration. */
3173 	if ((txmode & 0x70) != 0) {
3174 		/* Restore Tx mode. */
3175 		rtwn_write_1(sc, R92C_OFDM1_LSTF + 3, txmode);
3176 		/* Restore RF mode. */
3177 		for (i = 0; i < sc->nrxchains; i++)
3178 			rtwn_rf_write(sc, i, R92C_RF_AC, rf_ac[i]);
3179 	} else {
3180 		/* Unblock all Tx queues. */
3181 		rtwn_write_1(sc, R92C_TXPAUSE, 0x00);
3182 	}
3183 }
3184 
3185 static void
3186 rtwn_temp_calib(struct rtwn_softc *sc)
3187 {
3188 	int temp;
3189 
3190 	if (sc->thcal_state == 0) {
3191 		/* Start measuring temperature. */
3192 		rtwn_rf_write(sc, 0, R92C_RF_T_METER, 0x60);
3193 		sc->thcal_state = 1;
3194 		return;
3195 	}
3196 	sc->thcal_state = 0;
3197 
3198 	/* Read measured temperature. */
3199 	temp = rtwn_rf_read(sc, 0, R92C_RF_T_METER) & 0x1f;
3200 	if (temp == 0)	/* Read failed, skip. */
3201 		return;
3202 	DPRINTFN(2, ("temperature=%d\n", temp));
3203 
3204 	/*
3205 	 * Redo IQ and LC calibration if temperature changed significantly
3206 	 * since last calibration.
3207 	 */
3208 	if (sc->thcal_lctemp == 0) {
3209 		/* First calibration is performed in rtwn_init(). */
3210 		sc->thcal_lctemp = temp;
3211 	} else if (abs(temp - sc->thcal_lctemp) > 1) {
3212 		DPRINTF(("IQ/LC calib triggered by temp: %d -> %d\n",
3213 		    sc->thcal_lctemp, temp));
3214 		rtwn_iq_calib(sc);
3215 		rtwn_lc_calib(sc);
3216 		/* Record temperature of last calibration. */
3217 		sc->thcal_lctemp = temp;
3218 	}
3219 }
3220 
3221 static void
3222 rtwn_init_locked(struct rtwn_softc *sc)
3223 {
3224 	struct ieee80211com *ic = &sc->sc_ic;
3225 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3226 	uint32_t reg;
3227 	uint8_t macaddr[IEEE80211_ADDR_LEN];
3228 	int i, error;
3229 
3230 	RTWN_LOCK_ASSERT(sc);
3231 
3232 	/* Init firmware commands ring. */
3233 	sc->fwcur = 0;
3234 
3235 	/* Power on adapter. */
3236 	error = rtwn_power_on(sc);
3237 	if (error != 0) {
3238 		device_printf(sc->sc_dev, "could not power on adapter\n");
3239 		goto fail;
3240 	}
3241 
3242 	/* Initialize DMA. */
3243 	error = rtwn_dma_init(sc);
3244 	if (error != 0) {
3245 		device_printf(sc->sc_dev, "could not initialize DMA\n");
3246 		goto fail;
3247 	}
3248 
3249 	/* Set info size in Rx descriptors (in 64-bit words). */
3250 	rtwn_write_1(sc, R92C_RX_DRVINFO_SZ, 4);
3251 
3252 	/* Disable interrupts. */
3253 	rtwn_write_4(sc, R92C_HISR, 0x00000000);
3254 	rtwn_write_4(sc, R92C_HIMR, 0x00000000);
3255 
3256 	/* Set MAC address. */
3257 	IEEE80211_ADDR_COPY(macaddr, vap ? vap->iv_myaddr : ic->ic_macaddr);
3258 	for (i = 0; i < IEEE80211_ADDR_LEN; i++)
3259 		rtwn_write_1(sc, R92C_MACID + i, macaddr[i]);
3260 
3261 	/* Set initial network type. */
3262 	reg = rtwn_read_4(sc, R92C_CR);
3263 	reg = RW(reg, R92C_CR_NETTYPE, R92C_CR_NETTYPE_INFRA);
3264 	rtwn_write_4(sc, R92C_CR, reg);
3265 
3266 	rtwn_rxfilter_init(sc);
3267 
3268 	reg = rtwn_read_4(sc, R92C_RRSR);
3269 	reg = RW(reg, R92C_RRSR_RATE_BITMAP, R92C_RRSR_RATE_ALL);
3270 	rtwn_write_4(sc, R92C_RRSR, reg);
3271 
3272 	/* Set short/long retry limits. */
3273 	rtwn_write_2(sc, R92C_RL,
3274 	    SM(R92C_RL_SRL, 0x07) | SM(R92C_RL_LRL, 0x07));
3275 
3276 	/* Initialize EDCA parameters. */
3277 	rtwn_edca_init(sc);
3278 
3279 	/* Set data and response automatic rate fallback retry counts. */
3280 	rtwn_write_4(sc, R92C_DARFRC + 0, 0x01000000);
3281 	rtwn_write_4(sc, R92C_DARFRC + 4, 0x07060504);
3282 	rtwn_write_4(sc, R92C_RARFRC + 0, 0x01000000);
3283 	rtwn_write_4(sc, R92C_RARFRC + 4, 0x07060504);
3284 
3285 	rtwn_write_2(sc, R92C_FWHW_TXQ_CTRL, 0x1f80);
3286 
3287 	/* Set ACK timeout. */
3288 	rtwn_write_1(sc, R92C_ACKTO, 0x40);
3289 
3290 	/* Initialize beacon parameters. */
3291 	rtwn_write_2(sc, R92C_TBTT_PROHIBIT, 0x6404);
3292 	rtwn_write_1(sc, R92C_DRVERLYINT, 0x05);
3293 	rtwn_write_1(sc, R92C_BCNDMATIM, 0x02);
3294 	rtwn_write_2(sc, R92C_BCNTCFG, 0x660f);
3295 
3296 	/* Setup AMPDU aggregation. */
3297 	rtwn_write_4(sc, R92C_AGGLEN_LMT, 0x99997631);	/* MCS7~0 */
3298 	rtwn_write_1(sc, R92C_AGGR_BREAK_TIME, 0x16);
3299 
3300 	rtwn_write_1(sc, R92C_BCN_MAX_ERR, 0xff);
3301 	rtwn_write_1(sc, R92C_BCN_CTRL, R92C_BCN_CTRL_DIS_TSF_UDT0);
3302 
3303 	rtwn_write_4(sc, R92C_PIFS, 0x1c);
3304 	rtwn_write_4(sc, R92C_MCUTST_1, 0x0);
3305 
3306 	/* Load 8051 microcode. */
3307 	error = rtwn_load_firmware(sc);
3308 	if (error != 0)
3309 		goto fail;
3310 
3311 	/* Initialize MAC/BB/RF blocks. */
3312 	rtwn_mac_init(sc);
3313 	rtwn_bb_init(sc);
3314 	rtwn_rf_init(sc);
3315 
3316 	/* Turn CCK and OFDM blocks on. */
3317 	reg = rtwn_bb_read(sc, R92C_FPGA0_RFMOD);
3318 	reg |= R92C_RFMOD_CCK_EN;
3319 	rtwn_bb_write(sc, R92C_FPGA0_RFMOD, reg);
3320 	reg = rtwn_bb_read(sc, R92C_FPGA0_RFMOD);
3321 	reg |= R92C_RFMOD_OFDM_EN;
3322 	rtwn_bb_write(sc, R92C_FPGA0_RFMOD, reg);
3323 
3324 	/* Clear per-station keys table. */
3325 	rtwn_cam_init(sc);
3326 
3327 	/* Enable hardware sequence numbering. */
3328 	rtwn_write_1(sc, R92C_HWSEQ_CTRL, 0xff);
3329 
3330 	/* Perform LO and IQ calibrations. */
3331 	rtwn_iq_calib(sc);
3332 	/* Perform LC calibration. */
3333 	rtwn_lc_calib(sc);
3334 
3335 	rtwn_pa_bias_init(sc);
3336 
3337 	/* Initialize GPIO setting. */
3338 	rtwn_write_1(sc, R92C_GPIO_MUXCFG,
3339 	    rtwn_read_1(sc, R92C_GPIO_MUXCFG) & ~R92C_GPIO_MUXCFG_ENBT);
3340 
3341 	/* Fix for lower temperature. */
3342 	rtwn_write_1(sc, 0x15, 0xe9);
3343 
3344 	/* CLear pending interrupts. */
3345 	rtwn_write_4(sc, R92C_HISR, 0xffffffff);
3346 
3347 	/* Enable interrupts. */
3348 	rtwn_write_4(sc, R92C_HIMR, RTWN_INT_ENABLE);
3349 
3350 	sc->sc_flags |= RTWN_RUNNING;
3351 
3352 	callout_reset(&sc->watchdog_to, hz, rtwn_watchdog, sc);
3353 	return;
3354 
3355 fail:
3356 	rtwn_stop_locked(sc);
3357 }
3358 
3359 static void
3360 rtwn_init(struct rtwn_softc *sc)
3361 {
3362 
3363 	RTWN_LOCK(sc);
3364 	rtwn_init_locked(sc);
3365 	RTWN_UNLOCK(sc);
3366 
3367 	if (sc->sc_flags & RTWN_RUNNING)
3368 		ieee80211_start_all(&sc->sc_ic);
3369 }
3370 
3371 static void
3372 rtwn_stop_locked(struct rtwn_softc *sc)
3373 {
3374 	uint16_t reg;
3375 	int i;
3376 
3377 	RTWN_LOCK_ASSERT(sc);
3378 
3379 	sc->sc_tx_timer = 0;
3380 	callout_stop(&sc->watchdog_to);
3381 	callout_stop(&sc->calib_to);
3382 	sc->sc_flags &= ~RTWN_RUNNING;
3383 
3384 	/* Disable interrupts. */
3385 	rtwn_write_4(sc, R92C_HISR, 0x00000000);
3386 	rtwn_write_4(sc, R92C_HIMR, 0x00000000);
3387 
3388 	/* Stop hardware. */
3389 	rtwn_write_1(sc, R92C_TXPAUSE, 0xff);
3390 	rtwn_write_1(sc, R92C_RF_CTRL, 0x00);
3391 	reg = rtwn_read_1(sc, R92C_SYS_FUNC_EN);
3392 	reg |= R92C_SYS_FUNC_EN_BB_GLB_RST;
3393 	rtwn_write_1(sc, R92C_SYS_FUNC_EN, reg);
3394 	reg &= ~R92C_SYS_FUNC_EN_BB_GLB_RST;
3395 	rtwn_write_1(sc, R92C_SYS_FUNC_EN, reg);
3396 	reg = rtwn_read_2(sc, R92C_CR);
3397 	reg &= ~(R92C_CR_HCI_TXDMA_EN | R92C_CR_HCI_RXDMA_EN |
3398 	    R92C_CR_TXDMA_EN | R92C_CR_RXDMA_EN | R92C_CR_PROTOCOL_EN |
3399 	    R92C_CR_SCHEDULE_EN | R92C_CR_MACTXEN | R92C_CR_MACRXEN |
3400 	    R92C_CR_ENSEC);
3401 	rtwn_write_2(sc, R92C_CR, reg);
3402 	if (rtwn_read_1(sc, R92C_MCUFWDL) & R92C_MCUFWDL_RAM_DL_SEL)
3403 		rtwn_fw_reset(sc);
3404 	/* TODO: linux does additional btcoex stuff here */
3405 	rtwn_write_2(sc, R92C_AFE_PLL_CTRL, 0x80); /* linux magic number */
3406 	rtwn_write_1(sc, R92C_SPS0_CTRL, 0x23); /* ditto */
3407 	rtwn_write_1(sc, R92C_AFE_XTAL_CTRL, 0x0e); /* different with btcoex */
3408 	rtwn_write_1(sc, R92C_RSV_CTRL, 0x0e);
3409 	rtwn_write_1(sc, R92C_APS_FSMCO, R92C_APS_FSMCO_PDN_EN);
3410 
3411 	for (i = 0; i < RTWN_NTXQUEUES; i++)
3412 		rtwn_reset_tx_list(sc, i);
3413 	rtwn_reset_rx_list(sc);
3414 }
3415 
3416 static void
3417 rtwn_stop(struct rtwn_softc *sc)
3418 {
3419 	RTWN_LOCK(sc);
3420 	rtwn_stop_locked(sc);
3421 	RTWN_UNLOCK(sc);
3422 }
3423 
3424 static void
3425 rtwn_intr(void *arg)
3426 {
3427 	struct rtwn_softc *sc = arg;
3428 	uint32_t status;
3429 	int i;
3430 
3431 	RTWN_LOCK(sc);
3432 	status = rtwn_read_4(sc, R92C_HISR);
3433 	if (status == 0 || status == 0xffffffff) {
3434 		RTWN_UNLOCK(sc);
3435 		return;
3436 	}
3437 
3438 	/* Disable interrupts. */
3439 	rtwn_write_4(sc, R92C_HIMR, 0x00000000);
3440 
3441 	/* Ack interrupts. */
3442 	rtwn_write_4(sc, R92C_HISR, status);
3443 
3444 	/* Vendor driver treats RX errors like ROK... */
3445 	if (status & (R92C_IMR_ROK | R92C_IMR_RXFOVW | R92C_IMR_RDU)) {
3446 		bus_dmamap_sync(sc->rx_ring.desc_dmat, sc->rx_ring.desc_map,
3447 		    BUS_DMASYNC_POSTREAD);
3448 
3449 		for (i = 0; i < RTWN_RX_LIST_COUNT; i++) {
3450 			struct r92c_rx_desc *rx_desc = &sc->rx_ring.desc[i];
3451 			struct rtwn_rx_data *rx_data = &sc->rx_ring.rx_data[i];
3452 
3453 			if (le32toh(rx_desc->rxdw0) & R92C_RXDW0_OWN)
3454 				continue;
3455 
3456 			rtwn_rx_frame(sc, rx_desc, rx_data, i);
3457 		}
3458 	}
3459 
3460 	if (status & R92C_IMR_BDOK)
3461 		rtwn_tx_done(sc, RTWN_BEACON_QUEUE);
3462 	if (status & R92C_IMR_HIGHDOK)
3463 		rtwn_tx_done(sc, RTWN_HIGH_QUEUE);
3464 	if (status & R92C_IMR_MGNTDOK)
3465 		rtwn_tx_done(sc, RTWN_MGNT_QUEUE);
3466 	if (status & R92C_IMR_BKDOK)
3467 		rtwn_tx_done(sc, RTWN_BK_QUEUE);
3468 	if (status & R92C_IMR_BEDOK)
3469 		rtwn_tx_done(sc, RTWN_BE_QUEUE);
3470 	if (status & R92C_IMR_VIDOK)
3471 		rtwn_tx_done(sc, RTWN_VI_QUEUE);
3472 	if (status & R92C_IMR_VODOK)
3473 		rtwn_tx_done(sc, RTWN_VO_QUEUE);
3474 
3475 	/* Enable interrupts. */
3476 	rtwn_write_4(sc, R92C_HIMR, RTWN_INT_ENABLE);
3477 
3478 	RTWN_UNLOCK(sc);
3479 }
3480 
3481 static void
3482 rtwn_hw_reset(void *arg0, int pending)
3483 {
3484 	struct rtwn_softc *sc = arg0;
3485 	struct ieee80211com *ic = &sc->sc_ic;
3486 
3487 	rtwn_stop(sc);
3488 	rtwn_init(sc);
3489 	ieee80211_notify_radio(ic, 1);
3490 }
3491