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