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