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