xref: /freebsd/sys/dev/rtwn/if_rtwn.c (revision cbd30a72ca196976c1c700400ecd424baa1b9c16)
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  * Copyright (c) 2014 Kevin Lo <kevlo@FreeBSD.org>
6  * Copyright (c) 2015-2016 Andriy Voskoboinyk <avos@FreeBSD.org>
7  *
8  * Permission to use, copy, modify, and distribute this software for any
9  * purpose with or without fee is hereby granted, provided that the above
10  * copyright notice and this permission notice appear in all copies.
11  *
12  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19  */
20 
21 #include <sys/cdefs.h>
22 __FBSDID("$FreeBSD$");
23 
24 /*
25  * Driver for Realtek RTL8188CE-VAU/RTL8188CUS/RTL8188EU/RTL8188RU/RTL8192CU/RTL8812AU/RTL8821AU.
26  */
27 #include "opt_wlan.h"
28 
29 #include <sys/param.h>
30 #include <sys/sockio.h>
31 #include <sys/sysctl.h>
32 #include <sys/lock.h>
33 #include <sys/mutex.h>
34 #include <sys/mbuf.h>
35 #include <sys/kernel.h>
36 #include <sys/socket.h>
37 #include <sys/systm.h>
38 #include <sys/malloc.h>
39 #include <sys/module.h>
40 #include <sys/bus.h>
41 #include <sys/endian.h>
42 #include <sys/linker.h>
43 #include <sys/firmware.h>
44 #include <sys/kdb.h>
45 
46 #include <net/bpf.h>
47 #include <net/if.h>
48 #include <net/if_var.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/rtwn/if_rtwnreg.h>
67 #include <dev/rtwn/if_rtwnvar.h>
68 
69 #include <dev/rtwn/if_rtwn_beacon.h>
70 #include <dev/rtwn/if_rtwn_calib.h>
71 #include <dev/rtwn/if_rtwn_cam.h>
72 #include <dev/rtwn/if_rtwn_debug.h>
73 #include <dev/rtwn/if_rtwn_efuse.h>
74 #include <dev/rtwn/if_rtwn_fw.h>
75 #include <dev/rtwn/if_rtwn_ridx.h>
76 #include <dev/rtwn/if_rtwn_rx.h>
77 #include <dev/rtwn/if_rtwn_task.h>
78 #include <dev/rtwn/if_rtwn_tx.h>
79 
80 #include <dev/rtwn/rtl8192c/r92c_reg.h>
81 
82 
83 static void		rtwn_radiotap_attach(struct rtwn_softc *);
84 static void		rtwn_vap_decrement_counters(struct rtwn_softc *,
85 			    enum ieee80211_opmode, int);
86 static void		rtwn_set_ic_opmode(struct rtwn_softc *);
87 static struct ieee80211vap *rtwn_vap_create(struct ieee80211com *,
88 			    const char [IFNAMSIZ], int, enum ieee80211_opmode,
89 			    int, const uint8_t [IEEE80211_ADDR_LEN],
90 			    const uint8_t [IEEE80211_ADDR_LEN]);
91 static void		rtwn_vap_delete(struct ieee80211vap *);
92 static int		rtwn_read_chipid(struct rtwn_softc *);
93 static int		rtwn_ioctl_reset(struct ieee80211vap *, u_long);
94 #ifndef RTWN_WITHOUT_UCODE
95 static void		rtwn_set_media_status(struct rtwn_softc *,
96 			    union sec_param *);
97 static int		rtwn_tx_fwpkt_check(struct rtwn_softc *,
98 			    struct ieee80211vap *);
99 static int		rtwn_construct_nulldata(struct rtwn_softc *,
100 			    struct ieee80211vap *, uint8_t *, int);
101 static int		rtwn_push_nulldata(struct rtwn_softc *,
102 			    struct ieee80211vap *);
103 static void		rtwn_pwrmode_init(void *);
104 static void		rtwn_set_pwrmode_cb(struct rtwn_softc *,
105 			    union sec_param *);
106 #endif
107 static void		rtwn_tsf_sync_adhoc(void *);
108 static void		rtwn_tsf_sync_adhoc_task(void *, int);
109 static void		rtwn_tsf_sync_enable(struct rtwn_softc *,
110 			    struct ieee80211vap *);
111 static void		rtwn_set_ack_preamble(struct rtwn_softc *);
112 static void		rtwn_set_mode(struct rtwn_softc *, uint8_t, int);
113 static int		rtwn_monitor_newstate(struct ieee80211vap *,
114 			    enum ieee80211_state, int);
115 static int		rtwn_newstate(struct ieee80211vap *,
116 			    enum ieee80211_state, int);
117 static void		rtwn_calc_basicrates(struct rtwn_softc *);
118 static int		rtwn_run(struct rtwn_softc *,
119 			    struct ieee80211vap *);
120 #ifndef D4054
121 static void		rtwn_watchdog(void *);
122 #endif
123 static void		rtwn_parent(struct ieee80211com *);
124 static int		rtwn_dma_init(struct rtwn_softc *);
125 static int		rtwn_mac_init(struct rtwn_softc *);
126 static void		rtwn_mrr_init(struct rtwn_softc *);
127 static void		rtwn_scan_start(struct ieee80211com *);
128 static void		rtwn_scan_curchan(struct ieee80211_scan_state *,
129 			    unsigned long);
130 static void		rtwn_scan_end(struct ieee80211com *);
131 static void		rtwn_getradiocaps(struct ieee80211com *, int, int *,
132 			    struct ieee80211_channel[]);
133 static void		rtwn_update_chw(struct ieee80211com *);
134 static void		rtwn_set_channel(struct ieee80211com *);
135 static int		rtwn_wme_update(struct ieee80211com *);
136 static void		rtwn_update_slot(struct ieee80211com *);
137 static void		rtwn_update_slot_cb(struct rtwn_softc *,
138 			    union sec_param *);
139 static void		rtwn_update_aifs(struct rtwn_softc *, uint8_t);
140 static void		rtwn_update_promisc(struct ieee80211com *);
141 static void		rtwn_update_mcast(struct ieee80211com *);
142 static int		rtwn_set_bssid(struct rtwn_softc *,
143 			    const uint8_t *, int);
144 static int		rtwn_set_macaddr(struct rtwn_softc *,
145 			    const uint8_t *, int);
146 static struct ieee80211_node *rtwn_node_alloc(struct ieee80211vap *,
147 			    const uint8_t mac[IEEE80211_ADDR_LEN]);
148 static void		rtwn_newassoc(struct ieee80211_node *, int);
149 static void		rtwn_node_free(struct ieee80211_node *);
150 static void		rtwn_init_beacon_reg(struct rtwn_softc *);
151 static int		rtwn_init(struct rtwn_softc *);
152 static void		rtwn_stop(struct rtwn_softc *);
153 
154 MALLOC_DEFINE(M_RTWN_PRIV, "rtwn_priv", "rtwn driver private state");
155 
156 static const uint8_t rtwn_chan_2ghz[] =
157 	{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 };
158 
159 static const uint16_t wme2reg[] =
160 	{ R92C_EDCA_BE_PARAM, R92C_EDCA_BK_PARAM,
161 	  R92C_EDCA_VI_PARAM, R92C_EDCA_VO_PARAM };
162 
163 int
164 rtwn_attach(struct rtwn_softc *sc)
165 {
166 	struct ieee80211com *ic = &sc->sc_ic;
167 	int error;
168 
169 	sc->cur_bcnq_id = RTWN_VAP_ID_INVALID;
170 
171 	RTWN_NT_LOCK_INIT(sc);
172 	rtwn_cmdq_init(sc);
173 #ifndef D4054
174 	callout_init_mtx(&sc->sc_watchdog_to, &sc->sc_mtx, 0);
175 #endif
176 	callout_init(&sc->sc_calib_to, 0);
177 	callout_init(&sc->sc_pwrmode_init, 0);
178 	mbufq_init(&sc->sc_snd, ifqmaxlen);
179 
180 	RTWN_LOCK(sc);
181 	error = rtwn_read_chipid(sc);
182 	RTWN_UNLOCK(sc);
183 	if (error != 0) {
184 		device_printf(sc->sc_dev, "unsupported test chip\n");
185 		goto detach;
186 	}
187 
188 	error = rtwn_read_rom(sc);
189 	if (error != 0) {
190 		device_printf(sc->sc_dev, "%s: cannot read rom, error %d\n",
191 		    __func__, error);
192 		goto detach;
193 	}
194 
195 	if (sc->macid_limit > RTWN_MACID_LIMIT) {
196 		device_printf(sc->sc_dev,
197 		    "macid limit will be reduced from %d to %d\n",
198 		    sc->macid_limit, RTWN_MACID_LIMIT);
199 		sc->macid_limit = RTWN_MACID_LIMIT;
200 	}
201 	if (sc->cam_entry_limit > RTWN_CAM_ENTRY_LIMIT) {
202 		device_printf(sc->sc_dev,
203 		    "cam entry limit will be reduced from %d to %d\n",
204 		    sc->cam_entry_limit, RTWN_CAM_ENTRY_LIMIT);
205 		sc->cam_entry_limit = RTWN_CAM_ENTRY_LIMIT;
206 	}
207 	if (sc->txdesc_len > RTWN_TX_DESC_SIZE) {
208 		device_printf(sc->sc_dev,
209 		    "adjust size for Tx descriptor (current %d, needed %d)\n",
210 		    RTWN_TX_DESC_SIZE, sc->txdesc_len);
211 		goto detach;
212 	}
213 
214 	device_printf(sc->sc_dev, "MAC/BB %s, RF 6052 %dT%dR\n",
215 	    sc->name, sc->ntxchains, sc->nrxchains);
216 
217 	ic->ic_softc = sc;
218 	ic->ic_phytype = IEEE80211_T_OFDM;	/* not only, but not used */
219 	ic->ic_opmode = IEEE80211_M_STA;	/* default to BSS mode */
220 
221 	/* set device capabilities */
222 	ic->ic_caps =
223 		  IEEE80211_C_STA		/* station mode */
224 		| IEEE80211_C_MONITOR		/* monitor mode */
225 		| IEEE80211_C_IBSS		/* adhoc mode */
226 		| IEEE80211_C_HOSTAP		/* hostap mode */
227 #if 0	/* TODO: HRPWM register setup */
228 #ifndef RTWN_WITHOUT_UCODE
229 		| IEEE80211_C_PMGT		/* Station-side power mgmt */
230 #endif
231 #endif
232 		| IEEE80211_C_SHPREAMBLE	/* short preamble supported */
233 		| IEEE80211_C_SHSLOT		/* short slot time supported */
234 #if 0
235 		| IEEE80211_C_BGSCAN		/* capable of bg scanning */
236 #endif
237 		| IEEE80211_C_WPA		/* 802.11i */
238 		| IEEE80211_C_WME		/* 802.11e */
239 		| IEEE80211_C_SWAMSDUTX		/* Do software A-MSDU TX */
240 		| IEEE80211_C_FF		/* Atheros fast-frames */
241 		;
242 
243 	if (sc->sc_hwcrypto != RTWN_CRYPTO_SW) {
244 		ic->ic_cryptocaps =
245 		    IEEE80211_CRYPTO_WEP |
246 		    IEEE80211_CRYPTO_TKIP |
247 		    IEEE80211_CRYPTO_AES_CCM;
248 	}
249 
250 	ic->ic_htcaps =
251 	      IEEE80211_HTCAP_SHORTGI20		/* short GI in 20MHz */
252 	    | IEEE80211_HTCAP_MAXAMSDU_3839	/* max A-MSDU length */
253 	    | IEEE80211_HTCAP_SMPS_OFF		/* SM PS mode disabled */
254 	    /* s/w capabilities */
255 	    | IEEE80211_HTC_HT			/* HT operation */
256 	    | IEEE80211_HTC_AMPDU		/* A-MPDU tx */
257 	    | IEEE80211_HTC_AMSDU		/* A-MSDU tx */
258 	    ;
259 
260 	if (sc->sc_ht40) {
261 		ic->ic_htcaps |=
262 		      IEEE80211_HTCAP_CHWIDTH40	/* 40 MHz channel width */
263 		    | IEEE80211_HTCAP_SHORTGI40	/* short GI in 40MHz */
264 		    ;
265 	}
266 
267 	ic->ic_txstream = sc->ntxchains;
268 	ic->ic_rxstream = sc->nrxchains;
269 
270 	/* Enable TX watchdog */
271 #ifdef D4054
272 	ic->ic_flags_ext |= IEEE80211_FEXT_WATCHDOG;
273 #endif
274 
275 	/* Adjust capabilities. */
276 	rtwn_adj_devcaps(sc);
277 
278 	rtwn_getradiocaps(ic, IEEE80211_CHAN_MAX, &ic->ic_nchans,
279 	    ic->ic_channels);
280 
281 	/* XXX TODO: setup regdomain if R92C_CHANNEL_PLAN_BY_HW bit is set. */
282 
283 	ieee80211_ifattach(ic);
284 	ic->ic_raw_xmit = rtwn_raw_xmit;
285 	ic->ic_scan_start = rtwn_scan_start;
286 	sc->sc_scan_curchan = ic->ic_scan_curchan;
287 	ic->ic_scan_curchan = rtwn_scan_curchan;
288 	ic->ic_scan_end = rtwn_scan_end;
289 	ic->ic_getradiocaps = rtwn_getradiocaps;
290 	ic->ic_update_chw = rtwn_update_chw;
291 	ic->ic_set_channel = rtwn_set_channel;
292 	ic->ic_transmit = rtwn_transmit;
293 	ic->ic_parent = rtwn_parent;
294 	ic->ic_vap_create = rtwn_vap_create;
295 	ic->ic_vap_delete = rtwn_vap_delete;
296 	ic->ic_wme.wme_update = rtwn_wme_update;
297 	ic->ic_updateslot = rtwn_update_slot;
298 	ic->ic_update_promisc = rtwn_update_promisc;
299 	ic->ic_update_mcast = rtwn_update_mcast;
300 	ic->ic_node_alloc = rtwn_node_alloc;
301 	ic->ic_newassoc = rtwn_newassoc;
302 	sc->sc_node_free = ic->ic_node_free;
303 	ic->ic_node_free = rtwn_node_free;
304 
305 	rtwn_postattach(sc);
306 	rtwn_radiotap_attach(sc);
307 
308 	if (bootverbose)
309 		ieee80211_announce(ic);
310 
311 	return (0);
312 
313 detach:
314 	return (ENXIO);			/* failure */
315 }
316 
317 static void
318 rtwn_radiotap_attach(struct rtwn_softc *sc)
319 {
320 	struct rtwn_rx_radiotap_header *rxtap = &sc->sc_rxtap;
321 	struct rtwn_tx_radiotap_header *txtap = &sc->sc_txtap;
322 
323 	ieee80211_radiotap_attach(&sc->sc_ic,
324 	    &txtap->wt_ihdr, sizeof(*txtap), RTWN_TX_RADIOTAP_PRESENT,
325 	    &rxtap->wr_ihdr, sizeof(*rxtap), RTWN_RX_RADIOTAP_PRESENT);
326 }
327 
328 void
329 rtwn_sysctlattach(struct rtwn_softc *sc)
330 {
331 	struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->sc_dev);
332 	struct sysctl_oid *tree = device_get_sysctl_tree(sc->sc_dev);
333 
334 #if 1
335 	sc->sc_ht40 = 0;
336 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
337 	    "ht40", CTLFLAG_RDTUN, &sc->sc_ht40,
338 	    sc->sc_ht40, "Enable 40 MHz mode support");
339 #endif
340 
341 #ifdef RTWN_DEBUG
342 	SYSCTL_ADD_U32(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
343 	    "debug", CTLFLAG_RWTUN, &sc->sc_debug, sc->sc_debug,
344 	    "Control debugging printfs");
345 #endif
346 
347 	sc->sc_hwcrypto = RTWN_CRYPTO_PAIR;
348 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
349 	    "hwcrypto", CTLFLAG_RDTUN, &sc->sc_hwcrypto,
350 	    sc->sc_hwcrypto, "Enable h/w crypto: "
351 	    "0 - disable, 1 - pairwise keys, 2 - all keys");
352 	if (sc->sc_hwcrypto >= RTWN_CRYPTO_MAX)
353 		sc->sc_hwcrypto = RTWN_CRYPTO_FULL;
354 
355 	sc->sc_ratectl_sysctl = RTWN_RATECTL_NET80211;
356 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
357 	    "ratectl", CTLFLAG_RDTUN, &sc->sc_ratectl_sysctl,
358 	    sc->sc_ratectl_sysctl, "Select rate control mechanism: "
359 	    "0 - disabled, 1 - via net80211, 2 - via firmware");
360 	if (sc->sc_ratectl_sysctl >= RTWN_RATECTL_MAX)
361 		sc->sc_ratectl_sysctl = RTWN_RATECTL_FW;
362 
363 	sc->sc_ratectl = sc->sc_ratectl_sysctl;
364 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
365 	    "ratectl_selected", CTLFLAG_RD, &sc->sc_ratectl,
366 	    sc->sc_ratectl,
367 	    "Currently selected rate control mechanism (by the driver)");
368 }
369 
370 void
371 rtwn_detach(struct rtwn_softc *sc)
372 {
373 	struct ieee80211com *ic = &sc->sc_ic;
374 
375 	if (ic->ic_softc == sc) {
376 		/* Stop command queue. */
377 		RTWN_CMDQ_LOCK(sc);
378 		sc->sc_detached = 1;
379 		RTWN_CMDQ_UNLOCK(sc);
380 
381 		ieee80211_draintask(ic, &sc->cmdq_task);
382 		ieee80211_ifdetach(ic);
383 	}
384 
385 	rtwn_cmdq_destroy(sc);
386 	if (RTWN_NT_LOCK_INITIALIZED(sc))
387 		RTWN_NT_LOCK_DESTROY(sc);
388 }
389 
390 void
391 rtwn_suspend(struct rtwn_softc *sc)
392 {
393 	struct ieee80211com *ic = &sc->sc_ic;
394 
395 	ieee80211_suspend_all(ic);
396 }
397 
398 void
399 rtwn_resume(struct rtwn_softc *sc)
400 {
401 	struct ieee80211com *ic = &sc->sc_ic;
402 
403 	ieee80211_resume_all(ic);
404 }
405 
406 static void
407 rtwn_vap_decrement_counters(struct rtwn_softc *sc,
408     enum ieee80211_opmode opmode, int id)
409 {
410 
411 	RTWN_ASSERT_LOCKED(sc);
412 
413 	if (id != RTWN_VAP_ID_INVALID) {
414 		KASSERT(id == 0 || id == 1, ("wrong vap id %d!\n", id));
415 		KASSERT(sc->vaps[id] != NULL, ("vap pointer is NULL\n"));
416 		sc->vaps[id] = NULL;
417 	}
418 
419 	switch (opmode) {
420 	case IEEE80211_M_HOSTAP:
421 		sc->ap_vaps--;
422 		/* FALLTHROUGH */
423 	case IEEE80211_M_IBSS:
424 		sc->bcn_vaps--;
425 		/* FALLTHROUGH */
426 	case IEEE80211_M_STA:
427 		sc->nvaps--;
428 		break;
429 	case IEEE80211_M_MONITOR:
430 		sc->mon_vaps--;
431 		break;
432 	default:
433 		KASSERT(0, ("wrong opmode %d\n", opmode));
434 		break;
435 	}
436 
437 	KASSERT(sc->vaps_running >= 0 && sc->monvaps_running >= 0,
438 	    ("number of running vaps is negative (vaps %d, monvaps %d)\n",
439 	    sc->vaps_running, sc->monvaps_running));
440 	KASSERT(sc->vaps_running - sc->monvaps_running <= RTWN_PORT_COUNT,
441 	    ("number of running vaps is too big (vaps %d, monvaps %d)\n",
442 	    sc->vaps_running, sc->monvaps_running));
443 
444 	KASSERT(sc->nvaps >= 0 && sc->nvaps <= RTWN_PORT_COUNT,
445 	    ("wrong value %d for nvaps\n", sc->nvaps));
446 	KASSERT(sc->mon_vaps >= 0, ("mon_vaps is negative (%d)\n",
447 	    sc->mon_vaps));
448 	KASSERT(sc->bcn_vaps >= 0 && ((RTWN_CHIP_HAS_BCNQ1(sc) &&
449 	    sc->bcn_vaps <= RTWN_PORT_COUNT) || sc->bcn_vaps <= 1),
450 	    ("bcn_vaps value %d is wrong\n", sc->bcn_vaps));
451 	KASSERT(sc->ap_vaps >= 0 && ((RTWN_CHIP_HAS_BCNQ1(sc) &&
452 	    sc->ap_vaps <= RTWN_PORT_COUNT) || sc->ap_vaps <= 1),
453 	    ("ap_vaps value %d is wrong\n", sc->ap_vaps));
454 }
455 
456 static void
457 rtwn_set_ic_opmode(struct rtwn_softc *sc)
458 {
459 	struct ieee80211com *ic = &sc->sc_ic;
460 
461 	RTWN_ASSERT_LOCKED(sc);
462 
463 	/* for ieee80211_reset_erp() */
464 	if (sc->bcn_vaps - sc->ap_vaps > 0)
465 		ic->ic_opmode = IEEE80211_M_IBSS;
466 	else if (sc->ap_vaps > 0)
467 		ic->ic_opmode = IEEE80211_M_HOSTAP;
468 	else if (sc->nvaps > 0)
469 		ic->ic_opmode = IEEE80211_M_STA;
470 	else
471 		ic->ic_opmode = IEEE80211_M_MONITOR;
472 }
473 
474 static struct ieee80211vap *
475 rtwn_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
476     enum ieee80211_opmode opmode, int flags,
477     const uint8_t bssid[IEEE80211_ADDR_LEN],
478     const uint8_t mac[IEEE80211_ADDR_LEN])
479 {
480 	struct rtwn_softc *sc = ic->ic_softc;
481 	struct rtwn_vap *uvp;
482 	struct ieee80211vap *vap;
483 	int id = RTWN_VAP_ID_INVALID;
484 
485 	RTWN_LOCK(sc);
486 	KASSERT(sc->nvaps <= RTWN_PORT_COUNT,
487 	    ("nvaps overflow (%d > %d)\n", sc->nvaps, RTWN_PORT_COUNT));
488 	KASSERT(sc->ap_vaps <= RTWN_PORT_COUNT,
489 	    ("ap_vaps overflow (%d > %d)\n", sc->ap_vaps, RTWN_PORT_COUNT));
490 	KASSERT(sc->bcn_vaps <= RTWN_PORT_COUNT,
491 	    ("bcn_vaps overflow (%d > %d)\n", sc->bcn_vaps, RTWN_PORT_COUNT));
492 
493 	if (opmode != IEEE80211_M_MONITOR) {
494 		switch (sc->nvaps) {
495 		case 0:
496 			id = 0;
497 			break;
498 		case 1:
499 			if (sc->vaps[1] == NULL)
500 				id = 1;
501 			else if (sc->vaps[0] == NULL)
502 				id = 0;
503 			KASSERT(id != RTWN_VAP_ID_INVALID,
504 			    ("no free ports left\n"));
505 			break;
506 		case 2:
507 		default:
508 			goto fail;
509 		}
510 
511 		if (opmode == IEEE80211_M_IBSS ||
512 		    opmode == IEEE80211_M_HOSTAP) {
513 			if ((sc->bcn_vaps == 1 && !RTWN_CHIP_HAS_BCNQ1(sc)) ||
514 			    sc->bcn_vaps == RTWN_PORT_COUNT)
515 				goto fail;
516 		}
517 	}
518 
519 	switch (opmode) {
520 	case IEEE80211_M_HOSTAP:
521 		sc->ap_vaps++;
522 		/* FALLTHROUGH */
523 	case IEEE80211_M_IBSS:
524 		sc->bcn_vaps++;
525 		/* FALLTHROUGH */
526 	case IEEE80211_M_STA:
527 		sc->nvaps++;
528 		break;
529 	case IEEE80211_M_MONITOR:
530 		sc->mon_vaps++;
531 		break;
532 	default:
533 		KASSERT(0, ("unknown opmode %d\n", opmode));
534 		goto fail;
535 	}
536 	RTWN_UNLOCK(sc);
537 
538 	uvp = malloc(sizeof(struct rtwn_vap), M_80211_VAP, M_WAITOK | M_ZERO);
539 	uvp->id = id;
540 	if (id != RTWN_VAP_ID_INVALID) {
541 		RTWN_LOCK(sc);
542 		sc->vaps[id] = uvp;
543 		RTWN_UNLOCK(sc);
544 	}
545 	vap = &uvp->vap;
546 	/* enable s/w bmiss handling for sta mode */
547 
548 	if (ieee80211_vap_setup(ic, vap, name, unit, opmode,
549 	    flags | IEEE80211_CLONE_NOBEACONS, bssid) != 0) {
550 		/* out of memory */
551 		free(uvp, M_80211_VAP);
552 
553 		RTWN_LOCK(sc);
554 		rtwn_vap_decrement_counters(sc, opmode, id);
555 		RTWN_UNLOCK(sc);
556 
557 		return (NULL);
558 	}
559 
560 	rtwn_beacon_init(sc, &uvp->bcn_desc.txd[0], uvp->id);
561 	rtwn_vap_preattach(sc, vap);
562 
563 	/* override state transition machine */
564 	uvp->newstate = vap->iv_newstate;
565 	if (opmode == IEEE80211_M_MONITOR)
566 		vap->iv_newstate = rtwn_monitor_newstate;
567 	else
568 		vap->iv_newstate = rtwn_newstate;
569 	vap->iv_update_beacon = rtwn_update_beacon;
570 	vap->iv_reset = rtwn_ioctl_reset;
571 	vap->iv_key_alloc = rtwn_key_alloc;
572 	vap->iv_key_set = rtwn_key_set;
573 	vap->iv_key_delete = rtwn_key_delete;
574 	vap->iv_max_aid = sc->macid_limit;
575 
576 	/* 802.11n parameters */
577 	vap->iv_ampdu_density = IEEE80211_HTCAP_MPDUDENSITY_16;
578 	vap->iv_ampdu_rxmax = IEEE80211_HTCAP_MAXRXAMPDU_64K;
579 
580 	TIMEOUT_TASK_INIT(taskqueue_thread, &uvp->tx_beacon_csa, 0,
581 	    rtwn_tx_beacon_csa, vap);
582 	if (opmode == IEEE80211_M_IBSS) {
583 		uvp->recv_mgmt = vap->iv_recv_mgmt;
584 		vap->iv_recv_mgmt = rtwn_adhoc_recv_mgmt;
585 		TASK_INIT(&uvp->tsf_sync_adhoc_task, 0,
586 		    rtwn_tsf_sync_adhoc_task, vap);
587 		callout_init(&uvp->tsf_sync_adhoc, 0);
588 	}
589 
590 	/*
591 	 * NB: driver can select net80211 RA even when user requests
592 	 * another mechanism.
593 	 */
594 	ieee80211_ratectl_init(vap);
595 
596 	/* complete setup */
597 	ieee80211_vap_attach(vap, ieee80211_media_change,
598 	    ieee80211_media_status, mac);
599 
600 	RTWN_LOCK(sc);
601 	rtwn_set_ic_opmode(sc);
602 	if (sc->sc_flags & RTWN_RUNNING) {
603 		if (uvp->id != RTWN_VAP_ID_INVALID)
604 			rtwn_set_macaddr(sc, vap->iv_myaddr, uvp->id);
605 
606 		rtwn_rxfilter_update(sc);
607 	}
608 	RTWN_UNLOCK(sc);
609 
610 	return (vap);
611 
612 fail:
613 	RTWN_UNLOCK(sc);
614 	return (NULL);
615 }
616 
617 static void
618 rtwn_vap_delete(struct ieee80211vap *vap)
619 {
620 	struct ieee80211com *ic = vap->iv_ic;
621 	struct rtwn_softc *sc = ic->ic_softc;
622 	struct rtwn_vap *uvp = RTWN_VAP(vap);
623 
624 	/* Put vap into INIT state + stop device if needed. */
625 	ieee80211_stop(vap);
626 	ieee80211_draintask(ic, &vap->iv_nstate_task);
627 	ieee80211_draintask(ic, &ic->ic_parent_task);
628 
629 	RTWN_LOCK(sc);
630 	/* Cancel any unfinished Tx. */
631 	rtwn_reset_lists(sc, vap);
632 	if (uvp->bcn_mbuf != NULL)
633 		m_freem(uvp->bcn_mbuf);
634 	rtwn_vap_decrement_counters(sc, vap->iv_opmode, uvp->id);
635 	rtwn_set_ic_opmode(sc);
636 	if (sc->sc_flags & RTWN_RUNNING)
637 		rtwn_rxfilter_update(sc);
638 	RTWN_UNLOCK(sc);
639 
640 	if (vap->iv_opmode == IEEE80211_M_IBSS) {
641 		ieee80211_draintask(ic, &uvp->tsf_sync_adhoc_task);
642 		callout_drain(&uvp->tsf_sync_adhoc);
643 	}
644 
645 	ieee80211_ratectl_deinit(vap);
646 	ieee80211_vap_detach(vap);
647 	free(uvp, M_80211_VAP);
648 }
649 
650 static int
651 rtwn_read_chipid(struct rtwn_softc *sc)
652 {
653 	uint32_t reg;
654 
655 	reg = rtwn_read_4(sc, R92C_SYS_CFG);
656 	if (reg & R92C_SYS_CFG_TRP_VAUX_EN)	/* test chip */
657 		return (EOPNOTSUPP);
658 
659 	rtwn_read_chipid_vendor(sc, reg);
660 
661 	return (0);
662 }
663 
664 static int
665 rtwn_ioctl_reset(struct ieee80211vap *vap, u_long cmd)
666 {
667 	int error;
668 
669 	switch (cmd) {
670 #ifndef RTWN_WITHOUT_UCODE
671 	case IEEE80211_IOC_POWERSAVE:
672 	case IEEE80211_IOC_POWERSAVESLEEP:
673 	{
674 		struct rtwn_softc *sc = vap->iv_ic->ic_softc;
675 		struct rtwn_vap *uvp = RTWN_VAP(vap);
676 
677 		if (vap->iv_opmode == IEEE80211_M_STA && uvp->id == 0) {
678 			RTWN_LOCK(sc);
679 			if (sc->sc_flags & RTWN_RUNNING)
680 				error = rtwn_set_pwrmode(sc, vap, 1);
681 			else
682 				error = 0;
683 			RTWN_UNLOCK(sc);
684 			if (error != 0)
685 				error = ENETRESET;
686 		} else
687 			error = EOPNOTSUPP;
688 		break;
689 	}
690 #endif
691 	case IEEE80211_IOC_SHORTGI:
692 	case IEEE80211_IOC_RTSTHRESHOLD:
693 	case IEEE80211_IOC_PROTMODE:
694 	case IEEE80211_IOC_HTPROTMODE:
695 	case IEEE80211_IOC_LDPC:
696 		error = 0;
697 		break;
698 	default:
699 		error = ENETRESET;
700 		break;
701 	}
702 
703 	return (error);
704 }
705 
706 #ifndef RTWN_WITHOUT_UCODE
707 static void
708 rtwn_set_media_status(struct rtwn_softc *sc, union sec_param *data)
709 {
710 	sc->sc_set_media_status(sc, data->macid);
711 }
712 
713 static int
714 rtwn_tx_fwpkt_check(struct rtwn_softc *sc, struct ieee80211vap *vap)
715 {
716 	int ntries, error;
717 
718 	for (ntries = 0; ntries < 5; ntries++) {
719 		error = rtwn_push_nulldata(sc, vap);
720 		if (error == 0)
721 			break;
722 	}
723 	if (ntries == 5) {
724 		device_printf(sc->sc_dev,
725 		    "%s: cannot push f/w frames into chip, error %d!\n",
726 		    __func__, error);
727 		return (error);
728 	}
729 
730 	return (0);
731 }
732 
733 static int
734 rtwn_construct_nulldata(struct rtwn_softc *sc, struct ieee80211vap *vap,
735     uint8_t *ptr, int qos)
736 {
737 	struct rtwn_vap *uvp = RTWN_VAP(vap);
738 	struct ieee80211com *ic = &sc->sc_ic;
739 	struct rtwn_tx_desc_common *txd;
740 	struct ieee80211_frame *wh;
741 	int pktlen;
742 
743 	/* XXX obtain from net80211 */
744 	wh = (struct ieee80211_frame *)(ptr + sc->txdesc_len);
745 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_DATA;
746 	wh->i_fc[1] = IEEE80211_FC1_DIR_TODS;
747 	IEEE80211_ADDR_COPY(wh->i_addr1, vap->iv_bss->ni_bssid);
748 	IEEE80211_ADDR_COPY(wh->i_addr2, vap->iv_myaddr);
749 	IEEE80211_ADDR_COPY(wh->i_addr3, vap->iv_bss->ni_macaddr);
750 
751 	txd = (struct rtwn_tx_desc_common *)ptr;
752 	txd->offset = sc->txdesc_len;
753 	pktlen = sc->txdesc_len;
754 	if (qos) {
755 		struct ieee80211_qosframe *qwh;
756 		const int tid = WME_AC_TO_TID(WME_AC_BE);
757 
758 		qwh = (struct ieee80211_qosframe *)wh;
759 		qwh->i_fc[0] |= IEEE80211_FC0_SUBTYPE_QOS_NULL;
760 		qwh->i_qos[0] = tid & IEEE80211_QOS_TID;
761 
762 		txd->pktlen = htole16(sizeof(struct ieee80211_qosframe));
763 		pktlen += sizeof(struct ieee80211_qosframe);
764 	} else {
765 		wh->i_fc[0] |= IEEE80211_FC0_SUBTYPE_NODATA;
766 
767 		txd->pktlen = htole16(sizeof(struct ieee80211_frame));
768 		pktlen += sizeof(struct ieee80211_frame);
769 	}
770 
771 	rtwn_fill_tx_desc_null(sc, ptr,
772 	    ic->ic_curmode == IEEE80211_MODE_11B, qos, uvp->id);
773 
774 	return (pktlen);
775 }
776 
777 static int
778 rtwn_push_nulldata(struct rtwn_softc *sc, struct ieee80211vap *vap)
779 {
780 	struct rtwn_vap *uvp = RTWN_VAP(vap);
781 	struct ieee80211com *ic = vap->iv_ic;
782 	struct ieee80211_channel *c = ic->ic_curchan;
783 	struct mbuf *m;
784 	uint8_t *ptr;
785 	int required_size, bcn_size, null_size, null_data, error;
786 
787 	if (!(sc->sc_flags & RTWN_FW_LOADED))
788 		return (0);	/* requires firmware */
789 
790 	KASSERT(sc->page_size > 0, ("page size was not set!\n"));
791 
792 	/* Leave some space for beacon (multi-vap) */
793 	bcn_size = roundup(RTWN_BCN_MAX_SIZE, sc->page_size);
794 	/* 1 page for Null Data + 1 page for Qos Null Data frames. */
795 	required_size = bcn_size + sc->page_size * 2;
796 
797 	m = m_get2(required_size, M_NOWAIT, MT_DATA, M_PKTHDR);
798 	if (m == NULL)
799 		return (ENOMEM);
800 
801 	/* Setup beacon descriptor. */
802 	rtwn_beacon_set_rate(sc, &uvp->bcn_desc.txd[0],
803 	    IEEE80211_IS_CHAN_5GHZ(c));
804 
805 	ptr = mtod(m, uint8_t *);
806 	memset(ptr, 0, required_size - sc->txdesc_len);
807 
808 	/* Construct Null Data frame. */
809 	ptr += bcn_size - sc->txdesc_len;
810 	null_size = rtwn_construct_nulldata(sc, vap, ptr, 0);
811 	KASSERT(null_size < sc->page_size,
812 	    ("recalculate size for Null Data frame\n"));
813 
814 	/* Construct Qos Null Data frame. */
815 	ptr += roundup(null_size, sc->page_size);
816 	null_size = rtwn_construct_nulldata(sc, vap, ptr, 1);
817 	KASSERT(null_size < sc->page_size,
818 	    ("recalculate size for Qos Null Data frame\n"));
819 
820 	/* Do not try to detect a beacon here. */
821 	rtwn_setbits_1_shift(sc, R92C_CR, 0, R92C_CR_ENSWBCN, 1);
822 	rtwn_setbits_1_shift(sc, R92C_FWHW_TXQ_CTRL,
823 	    R92C_FWHW_TXQ_CTRL_REAL_BEACON, 0, 2);
824 
825 	if (uvp->bcn_mbuf != NULL) {
826 		rtwn_beacon_unload(sc, uvp->id);
827 		m_freem(uvp->bcn_mbuf);
828 	}
829 
830 	m->m_pkthdr.len = m->m_len = required_size - sc->txdesc_len;
831 	uvp->bcn_mbuf = m;
832 
833 	error = rtwn_tx_beacon_check(sc, uvp);
834 	if (error != 0) {
835 		RTWN_DPRINTF(sc, RTWN_DEBUG_BEACON,
836 		    "%s: frame was not recognized!\n", __func__);
837 		goto fail;
838 	}
839 
840 	/* Setup addresses in firmware. */
841 	null_data = howmany(bcn_size, sc->page_size);
842 	error = rtwn_set_rsvd_page(sc, 0, null_data, null_data + 1);
843 	if (error != 0) {
844 		device_printf(sc->sc_dev,
845 		    "%s: CMD_RSVD_PAGE was not sent, error %d\n",
846 		    __func__, error);
847 		goto fail;
848 	}
849 
850 fail:
851 	/* Re-enable beacon detection. */
852 	rtwn_setbits_1_shift(sc, R92C_FWHW_TXQ_CTRL,
853 	    0, R92C_FWHW_TXQ_CTRL_REAL_BEACON, 2);
854 	rtwn_setbits_1_shift(sc, R92C_CR, R92C_CR_ENSWBCN, 0, 1);
855 
856 	/* Restore beacon (if present). */
857 	if (sc->bcn_vaps > 0 && sc->vaps[!uvp->id] != NULL) {
858 		struct rtwn_vap *uvp2 = sc->vaps[!uvp->id];
859 
860 		if (uvp2->curr_mode != R92C_MSR_NOLINK)
861 			error = rtwn_tx_beacon_check(sc, uvp2);
862 	}
863 
864 	return (error);
865 }
866 
867 static void
868 rtwn_pwrmode_init(void *arg)
869 {
870 	struct rtwn_softc *sc = arg;
871 
872 	rtwn_cmd_sleepable(sc, NULL, 0, rtwn_set_pwrmode_cb);
873 }
874 
875 static void
876 rtwn_set_pwrmode_cb(struct rtwn_softc *sc, union sec_param *data)
877 {
878 	struct ieee80211vap *vap = &sc->vaps[0]->vap;
879 
880 	if (vap != NULL)
881 		rtwn_set_pwrmode(sc, vap, 1);
882 }
883 #endif
884 
885 static void
886 rtwn_tsf_sync_adhoc(void *arg)
887 {
888 	struct ieee80211vap *vap = arg;
889 	struct ieee80211com *ic = vap->iv_ic;
890 	struct rtwn_vap *uvp = RTWN_VAP(vap);
891 
892 	if (uvp->curr_mode != R92C_MSR_NOLINK) {
893 		/* Do it in process context. */
894 		ieee80211_runtask(ic, &uvp->tsf_sync_adhoc_task);
895 	}
896 }
897 
898 /*
899  * Workaround for TSF synchronization:
900  * when BSSID filter in IBSS mode is not set
901  * (and TSF synchronization is enabled), then any beacon may update it.
902  * This routine synchronizes it when BSSID matching is enabled (IBSS merge
903  * is not possible during this period).
904  *
905  * NOTE: there is no race with rtwn_newstate(), since it uses the same
906  * taskqueue.
907  */
908 static void
909 rtwn_tsf_sync_adhoc_task(void *arg, int pending)
910 {
911 	struct ieee80211vap *vap = arg;
912 	struct rtwn_vap *uvp = RTWN_VAP(vap);
913 	struct rtwn_softc *sc = vap->iv_ic->ic_softc;
914 	struct ieee80211_node *ni;
915 
916 	RTWN_LOCK(sc);
917 	ni = ieee80211_ref_node(vap->iv_bss);
918 
919 	/* Accept beacons with the same BSSID. */
920 	rtwn_set_rx_bssid_all(sc, 0);
921 
922 	/* Deny RCR updates. */
923 	sc->sc_flags |= RTWN_RCR_LOCKED;
924 
925 	/* Enable synchronization. */
926 	rtwn_setbits_1(sc, R92C_BCN_CTRL(uvp->id),
927 	    R92C_BCN_CTRL_DIS_TSF_UDT0, 0);
928 
929 	/* Synchronize. */
930 	rtwn_delay(sc, ni->ni_intval * 5 * 1000);
931 
932 	/* Disable synchronization. */
933 	rtwn_setbits_1(sc, R92C_BCN_CTRL(uvp->id),
934 	    0, R92C_BCN_CTRL_DIS_TSF_UDT0);
935 
936 	/* Accept all beacons. */
937 	sc->sc_flags &= ~RTWN_RCR_LOCKED;
938 	rtwn_set_rx_bssid_all(sc, 1);
939 
940 	/* Schedule next TSF synchronization. */
941 	callout_reset(&uvp->tsf_sync_adhoc, 60*hz, rtwn_tsf_sync_adhoc, vap);
942 
943 	ieee80211_free_node(ni);
944 	RTWN_UNLOCK(sc);
945 }
946 
947 static void
948 rtwn_tsf_sync_enable(struct rtwn_softc *sc, struct ieee80211vap *vap)
949 {
950 	struct ieee80211com *ic = &sc->sc_ic;
951 	struct rtwn_vap *uvp = RTWN_VAP(vap);
952 
953 	/* Reset TSF. */
954 	rtwn_write_1(sc, R92C_DUAL_TSF_RST, R92C_DUAL_TSF_RESET(uvp->id));
955 
956 	switch (vap->iv_opmode) {
957 	case IEEE80211_M_STA:
958 		/* Enable TSF synchronization. */
959 		rtwn_setbits_1(sc, R92C_BCN_CTRL(uvp->id),
960 		    R92C_BCN_CTRL_DIS_TSF_UDT0, 0);
961 		break;
962 	case IEEE80211_M_IBSS:
963 		ieee80211_runtask(ic, &uvp->tsf_sync_adhoc_task);
964 		/* FALLTHROUGH */
965 	case IEEE80211_M_HOSTAP:
966 		/* Enable beaconing. */
967 		rtwn_beacon_enable(sc, uvp->id, 1);
968 		break;
969 	default:
970 		device_printf(sc->sc_dev, "undefined opmode %d\n",
971 		    vap->iv_opmode);
972 		return;
973 	}
974 }
975 
976 static void
977 rtwn_set_ack_preamble(struct rtwn_softc *sc)
978 {
979 	struct ieee80211com *ic = &sc->sc_ic;
980 	uint32_t reg;
981 
982 	reg = rtwn_read_4(sc, R92C_WMAC_TRXPTCL_CTL);
983 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
984 		reg |= R92C_WMAC_TRXPTCL_SHPRE;
985 	else
986 		reg &= ~R92C_WMAC_TRXPTCL_SHPRE;
987 	rtwn_write_4(sc, R92C_WMAC_TRXPTCL_CTL, reg);
988 }
989 
990 static void
991 rtwn_set_mode(struct rtwn_softc *sc, uint8_t mode, int id)
992 {
993 
994 	rtwn_setbits_1(sc, R92C_MSR, R92C_MSR_MASK << id * 2, mode << id * 2);
995 	if (sc->vaps[id] != NULL)
996 		sc->vaps[id]->curr_mode = mode;
997 }
998 
999 static int
1000 rtwn_monitor_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate,
1001     int arg)
1002 {
1003 	struct ieee80211com *ic = vap->iv_ic;
1004 	struct rtwn_softc *sc = ic->ic_softc;
1005 	struct rtwn_vap *uvp = RTWN_VAP(vap);
1006 
1007 	RTWN_DPRINTF(sc, RTWN_DEBUG_STATE, "%s -> %s\n",
1008 	    ieee80211_state_name[vap->iv_state],
1009 	    ieee80211_state_name[nstate]);
1010 
1011 	if (vap->iv_state != nstate) {
1012 		IEEE80211_UNLOCK(ic);
1013 		RTWN_LOCK(sc);
1014 
1015 		switch (nstate) {
1016 		case IEEE80211_S_INIT:
1017 			sc->vaps_running--;
1018 			sc->monvaps_running--;
1019 
1020 			if (sc->vaps_running == 0) {
1021 				/* Turn link LED off. */
1022 				rtwn_set_led(sc, RTWN_LED_LINK, 0);
1023 			}
1024 			break;
1025 		case IEEE80211_S_RUN:
1026 			sc->vaps_running++;
1027 			sc->monvaps_running++;
1028 
1029 			if (sc->vaps_running == 1) {
1030 				/* Turn link LED on. */
1031 				rtwn_set_led(sc, RTWN_LED_LINK, 1);
1032 			}
1033 			break;
1034 		default:
1035 			/* NOTREACHED */
1036 			break;
1037 		}
1038 
1039 		RTWN_UNLOCK(sc);
1040 		IEEE80211_LOCK(ic);
1041 	}
1042 
1043 	return (uvp->newstate(vap, nstate, arg));
1044 }
1045 
1046 static int
1047 rtwn_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
1048 {
1049 	struct rtwn_vap *uvp = RTWN_VAP(vap);
1050 	struct ieee80211com *ic = vap->iv_ic;
1051 	struct rtwn_softc *sc = ic->ic_softc;
1052 	enum ieee80211_state ostate;
1053 	int error, early_newstate;
1054 
1055 	ostate = vap->iv_state;
1056 	RTWN_DPRINTF(sc, RTWN_DEBUG_STATE, "%s -> %s\n",
1057 	    ieee80211_state_name[ostate], ieee80211_state_name[nstate]);
1058 
1059 	if (vap->iv_bss->ni_chan == IEEE80211_CHAN_ANYC &&
1060 	    ostate == IEEE80211_S_INIT && nstate == IEEE80211_S_RUN) {
1061 		/* need to call iv_newstate() firstly */
1062 		error = uvp->newstate(vap, nstate, arg);
1063 		if (error != 0)
1064 			return (error);
1065 
1066 		early_newstate = 1;
1067 	} else
1068 		early_newstate = 0;
1069 
1070 	if (ostate == IEEE80211_S_CSA) {
1071 		taskqueue_cancel_timeout(taskqueue_thread,
1072 		    &uvp->tx_beacon_csa, NULL);
1073 
1074 		/*
1075 		 * In multi-vap case second counter may not be cleared
1076 		 * properly.
1077 		 */
1078 		vap->iv_csa_count = 0;
1079 	}
1080 	IEEE80211_UNLOCK(ic);
1081 	RTWN_LOCK(sc);
1082 
1083 	if (ostate == IEEE80211_S_CSA) {
1084 		/* Unblock all queues (multi-vap case). */
1085 		rtwn_write_1(sc, R92C_TXPAUSE, 0);
1086 	}
1087 
1088 	if ((ostate == IEEE80211_S_RUN && nstate != IEEE80211_S_CSA) ||
1089 	    ostate == IEEE80211_S_CSA) {
1090 		sc->vaps_running--;
1091 
1092 		/* Set media status to 'No Link'. */
1093 		rtwn_set_mode(sc, R92C_MSR_NOLINK, uvp->id);
1094 
1095 		if (vap->iv_opmode == IEEE80211_M_IBSS) {
1096 			/* Stop periodical TSF synchronization. */
1097 			callout_stop(&uvp->tsf_sync_adhoc);
1098 		}
1099 
1100 		/* Disable TSF synchronization / beaconing. */
1101 		rtwn_beacon_enable(sc, uvp->id, 0);
1102 		rtwn_setbits_1(sc, R92C_BCN_CTRL(uvp->id),
1103 		    0, R92C_BCN_CTRL_DIS_TSF_UDT0);
1104 
1105 		/* NB: monitor mode vaps are using port 0. */
1106 		if (uvp->id != 0 || sc->monvaps_running == 0) {
1107 			/* Reset TSF. */
1108 			rtwn_write_1(sc, R92C_DUAL_TSF_RST,
1109 			    R92C_DUAL_TSF_RESET(uvp->id));
1110 		}
1111 
1112 #ifndef RTWN_WITHOUT_UCODE
1113 		if ((ic->ic_caps & IEEE80211_C_PMGT) != 0 && uvp->id == 0) {
1114 			/* Disable power management. */
1115 			callout_stop(&sc->sc_pwrmode_init);
1116 			rtwn_set_pwrmode(sc, vap, 0);
1117 		}
1118 #endif
1119 		if (sc->vaps_running - sc->monvaps_running > 0) {
1120 			/* Recalculate basic rates bitmap. */
1121 			rtwn_calc_basicrates(sc);
1122 		}
1123 
1124 		if (sc->vaps_running == sc->monvaps_running) {
1125 			/* Stop calibration. */
1126 			callout_stop(&sc->sc_calib_to);
1127 
1128 			/* Stop Rx of data frames. */
1129 			rtwn_write_2(sc, R92C_RXFLTMAP2, 0);
1130 
1131 			/* Reset EDCA parameters. */
1132 			rtwn_write_4(sc, R92C_EDCA_VO_PARAM, 0x002f3217);
1133 			rtwn_write_4(sc, R92C_EDCA_VI_PARAM, 0x005e4317);
1134 			rtwn_write_4(sc, R92C_EDCA_BE_PARAM, 0x00105320);
1135 			rtwn_write_4(sc, R92C_EDCA_BK_PARAM, 0x0000a444);
1136 
1137 			if (sc->vaps_running == 0) {
1138 				/* Turn link LED off. */
1139 				rtwn_set_led(sc, RTWN_LED_LINK, 0);
1140 			}
1141 		}
1142 	}
1143 
1144 	error = 0;
1145 	switch (nstate) {
1146 	case IEEE80211_S_SCAN:
1147 		/* Pause AC Tx queues. */
1148 		if (sc->vaps_running == 0)
1149 			rtwn_setbits_1(sc, R92C_TXPAUSE, 0, R92C_TX_QUEUE_AC);
1150 		break;
1151 	case IEEE80211_S_RUN:
1152 		error = rtwn_run(sc, vap);
1153 		if (error != 0) {
1154 			device_printf(sc->sc_dev,
1155 			    "%s: could not move to RUN state\n", __func__);
1156 			break;
1157 		}
1158 
1159 		sc->vaps_running++;
1160 		break;
1161 	case IEEE80211_S_CSA:
1162 		/* Block all Tx queues (except beacon queue). */
1163 		rtwn_setbits_1(sc, R92C_TXPAUSE, 0,
1164 		    R92C_TX_QUEUE_AC | R92C_TX_QUEUE_MGT | R92C_TX_QUEUE_HIGH);
1165 		break;
1166 	default:
1167 		break;
1168 	}
1169 
1170 	RTWN_UNLOCK(sc);
1171 	IEEE80211_LOCK(ic);
1172 	if (error != 0)
1173 		return (error);
1174 
1175 	return (early_newstate ? 0 : uvp->newstate(vap, nstate, arg));
1176 }
1177 
1178 static void
1179 rtwn_calc_basicrates(struct rtwn_softc *sc)
1180 {
1181 	struct ieee80211com *ic = &sc->sc_ic;
1182 	uint32_t basicrates;
1183 	int i;
1184 
1185 	RTWN_ASSERT_LOCKED(sc);
1186 
1187 	if (ic->ic_flags & IEEE80211_F_SCAN)
1188 		return;		/* will be done by rtwn_scan_end(). */
1189 
1190 	basicrates = 0;
1191 	for (i = 0; i < nitems(sc->vaps); i++) {
1192 		struct rtwn_vap *rvp;
1193 		struct ieee80211vap *vap;
1194 		struct ieee80211_node *ni;
1195 		uint32_t rates;
1196 
1197 		rvp = sc->vaps[i];
1198 		if (rvp == NULL || rvp->curr_mode == R92C_MSR_NOLINK)
1199 			continue;
1200 
1201 		vap = &rvp->vap;
1202 		if (vap->iv_bss == NULL)
1203 			continue;
1204 
1205 		ni = ieee80211_ref_node(vap->iv_bss);
1206 		rtwn_get_rates(sc, &ni->ni_rates, NULL, &rates, NULL, 1);
1207 		basicrates |= rates;
1208 		ieee80211_free_node(ni);
1209 	}
1210 
1211 	if (basicrates == 0)
1212 		return;
1213 
1214 	/* XXX initial RTS rate? */
1215 	rtwn_set_basicrates(sc, basicrates);
1216 }
1217 
1218 static int
1219 rtwn_run(struct rtwn_softc *sc, struct ieee80211vap *vap)
1220 {
1221 	struct ieee80211com *ic = vap->iv_ic;
1222 	struct rtwn_vap *uvp = RTWN_VAP(vap);
1223 	struct ieee80211_node *ni;
1224 	uint8_t mode;
1225 	int error;
1226 
1227 	RTWN_ASSERT_LOCKED(sc);
1228 
1229 	error = 0;
1230 	ni = ieee80211_ref_node(vap->iv_bss);
1231 
1232 	if (ic->ic_bsschan == IEEE80211_CHAN_ANYC ||
1233 	    ni->ni_chan == IEEE80211_CHAN_ANYC) {
1234 		error = EINVAL;
1235 		goto fail;
1236 	}
1237 
1238 	switch (vap->iv_opmode) {
1239 	case IEEE80211_M_STA:
1240 		mode = R92C_MSR_INFRA;
1241 		break;
1242 	case IEEE80211_M_IBSS:
1243 		mode = R92C_MSR_ADHOC;
1244 		break;
1245 	case IEEE80211_M_HOSTAP:
1246 		mode = R92C_MSR_AP;
1247 		break;
1248 	default:
1249 		KASSERT(0, ("undefined opmode %d\n", vap->iv_opmode));
1250 		error = EINVAL;
1251 		goto fail;
1252 	}
1253 
1254 	/* Set media status to 'Associated'. */
1255 	rtwn_set_mode(sc, mode, uvp->id);
1256 
1257 	/* Set AssocID. */
1258 	/* XXX multi-vap? */
1259 	rtwn_write_2(sc, R92C_BCN_PSR_RPT,
1260 	    0xc000 | IEEE80211_NODE_AID(ni));
1261 
1262 	/* Set BSSID. */
1263 	rtwn_set_bssid(sc, ni->ni_bssid, uvp->id);
1264 
1265 	/* Set beacon interval. */
1266 	rtwn_write_2(sc, R92C_BCN_INTERVAL(uvp->id), ni->ni_intval);
1267 
1268 	if (sc->vaps_running == sc->monvaps_running) {
1269 		/* Enable Rx of data frames. */
1270 		rtwn_write_2(sc, R92C_RXFLTMAP2, 0xffff);
1271 
1272 		/* Flush all AC queues. */
1273 		rtwn_write_1(sc, R92C_TXPAUSE, 0);
1274 	}
1275 
1276 #ifndef RTWN_WITHOUT_UCODE
1277 	/* Upload (QoS) Null Data frame to firmware. */
1278 	/* Note: do this for port 0 only. */
1279 	if ((ic->ic_caps & IEEE80211_C_PMGT) != 0 &&
1280 	    vap->iv_opmode == IEEE80211_M_STA && uvp->id == 0) {
1281 		error = rtwn_tx_fwpkt_check(sc, vap);
1282 		if (error != 0)
1283 			goto fail;
1284 
1285 		/* Setup power management. */
1286 		/*
1287 		 * NB: it will be enabled immediately - delay it,
1288 		 * so 4-Way handshake will not be interrupted.
1289 		 */
1290 		callout_reset(&sc->sc_pwrmode_init, 5*hz,
1291 		    rtwn_pwrmode_init, sc);
1292 	}
1293 #endif
1294 
1295 	/* Enable TSF synchronization. */
1296 	rtwn_tsf_sync_enable(sc, vap);
1297 
1298 	if (vap->iv_opmode == IEEE80211_M_HOSTAP ||
1299 	    vap->iv_opmode == IEEE80211_M_IBSS) {
1300 		error = rtwn_setup_beacon(sc, ni);
1301 		if (error != 0) {
1302 			device_printf(sc->sc_dev,
1303 			    "unable to push beacon into the chip, "
1304 			    "error %d\n", error);
1305 			goto fail;
1306 		}
1307 	}
1308 
1309 	/* Set ACK preamble type. */
1310 	rtwn_set_ack_preamble(sc);
1311 
1312 	/* Set basic rates mask. */
1313 	rtwn_calc_basicrates(sc);
1314 
1315 #ifdef RTWN_TODO
1316 	rtwn_write_1(sc, R92C_SIFS_CCK + 1, 10);
1317 	rtwn_write_1(sc, R92C_SIFS_OFDM + 1, 10);
1318 	rtwn_write_1(sc, R92C_SPEC_SIFS + 1, 10);
1319 	rtwn_write_1(sc, R92C_MAC_SPEC_SIFS + 1, 10);
1320 	rtwn_write_1(sc, R92C_R2T_SIFS + 1, 10);
1321 	rtwn_write_1(sc, R92C_T2T_SIFS + 1, 10);
1322 #endif
1323 
1324 	if (sc->vaps_running == sc->monvaps_running) {
1325 		/* Reset temperature calibration state machine. */
1326 		sc->sc_flags &= ~RTWN_TEMP_MEASURED;
1327 		sc->thcal_temp = sc->thermal_meter;
1328 
1329 		/* Start periodic calibration. */
1330 		callout_reset(&sc->sc_calib_to, 2*hz, rtwn_calib_to,
1331 		    sc);
1332 
1333 		if (sc->vaps_running == 0) {
1334 			/* Turn link LED on. */
1335 			rtwn_set_led(sc, RTWN_LED_LINK, 1);
1336 		}
1337 	}
1338 
1339 fail:
1340 	ieee80211_free_node(ni);
1341 
1342 	return (error);
1343 }
1344 
1345 #ifndef D4054
1346 static void
1347 rtwn_watchdog(void *arg)
1348 {
1349 	struct rtwn_softc *sc = arg;
1350 	struct ieee80211com *ic = &sc->sc_ic;
1351 
1352 	RTWN_ASSERT_LOCKED(sc);
1353 
1354 	KASSERT(sc->sc_flags & RTWN_RUNNING, ("not running"));
1355 
1356 	if (sc->sc_tx_timer != 0 && --sc->sc_tx_timer == 0) {
1357 		ic_printf(ic, "device timeout\n");
1358 		ieee80211_restart_all(ic);
1359 		return;
1360 	}
1361 	callout_reset(&sc->sc_watchdog_to, hz, rtwn_watchdog, sc);
1362 }
1363 #endif
1364 
1365 static void
1366 rtwn_parent(struct ieee80211com *ic)
1367 {
1368 	struct rtwn_softc *sc = ic->ic_softc;
1369 	struct ieee80211vap *vap;
1370 
1371 	if (ic->ic_nrunning > 0) {
1372 		if (rtwn_init(sc) != 0) {
1373 			IEEE80211_LOCK(ic);
1374 			TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next)
1375 				ieee80211_stop_locked(vap);
1376 			IEEE80211_UNLOCK(ic);
1377 		} else
1378 			ieee80211_start_all(ic);
1379 	} else
1380 		rtwn_stop(sc);
1381 }
1382 
1383 static int
1384 rtwn_dma_init(struct rtwn_softc *sc)
1385 {
1386 #define RTWN_CHK(res) do {	\
1387 	if (res != 0)		\
1388 		return (EIO);	\
1389 } while(0)
1390 	uint16_t reg;
1391 	uint8_t tx_boundary;
1392 	int error;
1393 
1394 	/* Initialize LLT table. */
1395 	error = rtwn_llt_init(sc);
1396 	if (error != 0)
1397 		return (error);
1398 
1399 	/* Set the number of pages for each queue. */
1400 	RTWN_DPRINTF(sc, RTWN_DEBUG_RESET,
1401 	    "%s: pages per queue: high %d, normal %d, low %d, public %d\n",
1402 	    __func__, sc->nhqpages, sc->nnqpages, sc->nlqpages,
1403 	    sc->npubqpages);
1404 
1405 	RTWN_CHK(rtwn_write_1(sc, R92C_RQPN_NPQ, sc->nnqpages));
1406 	RTWN_CHK(rtwn_write_4(sc, R92C_RQPN,
1407 	    /* Set number of pages for public queue. */
1408 	    SM(R92C_RQPN_PUBQ, sc->npubqpages) |
1409 	    /* Set number of pages for high priority queue. */
1410 	    SM(R92C_RQPN_HPQ, sc->nhqpages) |
1411 	    /* Set number of pages for low priority queue. */
1412 	    SM(R92C_RQPN_LPQ, sc->nlqpages) |
1413 	    /* Load values. */
1414 	    R92C_RQPN_LD));
1415 
1416 	/* Initialize TX buffer boundary. */
1417 	KASSERT(sc->page_count < 255 && sc->page_count > 0,
1418 	    ("page_count is %d\n", sc->page_count));
1419 	tx_boundary = sc->page_count + 1;
1420 	RTWN_CHK(rtwn_write_1(sc, R92C_TXPKTBUF_BCNQ_BDNY, tx_boundary));
1421 	RTWN_CHK(rtwn_write_1(sc, R92C_TXPKTBUF_MGQ_BDNY, tx_boundary));
1422 	RTWN_CHK(rtwn_write_1(sc, R92C_TXPKTBUF_WMAC_LBK_BF_HD, tx_boundary));
1423 	RTWN_CHK(rtwn_write_1(sc, R92C_TRXFF_BNDY, tx_boundary));
1424 	RTWN_CHK(rtwn_write_1(sc, R92C_TDECTRL + 1, tx_boundary));
1425 
1426 	error = rtwn_init_bcnq1_boundary(sc);
1427 	if (error != 0)
1428 		return (error);
1429 
1430 	/* Set queue to USB pipe mapping. */
1431 	/* Note: PCIe devices are using some magic number here. */
1432 	reg = rtwn_get_qmap(sc);
1433 	RTWN_CHK(rtwn_setbits_2(sc, R92C_TRXDMA_CTRL,
1434 	    R92C_TRXDMA_CTRL_QMAP_M, reg));
1435 
1436 	/* Configure Tx/Rx DMA (PCIe). */
1437 	rtwn_set_desc_addr(sc);
1438 
1439 	/* Set Tx/Rx transfer page boundary. */
1440 	RTWN_CHK(rtwn_write_2(sc, R92C_TRXFF_BNDY + 2,
1441 	    sc->rx_dma_size - 1));
1442 
1443 	/* Set Tx/Rx transfer page size. */
1444 	rtwn_set_page_size(sc);
1445 
1446 	return (0);
1447 }
1448 
1449 static int
1450 rtwn_mac_init(struct rtwn_softc *sc)
1451 {
1452 	int i, error;
1453 
1454 	/* Write MAC initialization values. */
1455 	for (i = 0; i < sc->mac_size; i++) {
1456 		error = rtwn_write_1(sc, sc->mac_prog[i].reg,
1457 		    sc->mac_prog[i].val);
1458 		if (error != 0)
1459 			return (error);
1460 	}
1461 
1462 	return (0);
1463 }
1464 
1465 static void
1466 rtwn_mrr_init(struct rtwn_softc *sc)
1467 {
1468 	int i;
1469 
1470 	/* Drop rate index by 1 per retry. */
1471 	for (i = 0; i < R92C_DARFRC_SIZE; i++) {
1472 		rtwn_write_1(sc, R92C_DARFRC + i, i + 1);
1473 		rtwn_write_1(sc, R92C_RARFRC + i, i + 1);
1474 	}
1475 }
1476 
1477 static void
1478 rtwn_scan_start(struct ieee80211com *ic)
1479 {
1480 	struct rtwn_softc *sc = ic->ic_softc;
1481 
1482 	RTWN_LOCK(sc);
1483 	/* Pause beaconing. */
1484 	rtwn_setbits_1(sc, R92C_TXPAUSE, 0, R92C_TX_QUEUE_BCN);
1485 	/* Receive beacons / probe responses from any BSSID. */
1486 	if (sc->bcn_vaps == 0)
1487 		rtwn_set_rx_bssid_all(sc, 1);
1488 	RTWN_UNLOCK(sc);
1489 }
1490 
1491 static void
1492 rtwn_scan_curchan(struct ieee80211_scan_state *ss, unsigned long maxdwell)
1493 {
1494 	struct rtwn_softc *sc = ss->ss_ic->ic_softc;
1495 
1496 	/* Make link LED blink during scan. */
1497 	RTWN_LOCK(sc);
1498 	rtwn_set_led(sc, RTWN_LED_LINK, !sc->ledlink);
1499 	RTWN_UNLOCK(sc);
1500 
1501 	sc->sc_scan_curchan(ss, maxdwell);
1502 }
1503 
1504 static void
1505 rtwn_scan_end(struct ieee80211com *ic)
1506 {
1507 	struct rtwn_softc *sc = ic->ic_softc;
1508 
1509 	RTWN_LOCK(sc);
1510 	/* Restore limitations. */
1511 	if (ic->ic_promisc == 0 && sc->bcn_vaps == 0)
1512 		rtwn_set_rx_bssid_all(sc, 0);
1513 
1514 	/* Restore LED state. */
1515 	rtwn_set_led(sc, RTWN_LED_LINK, (sc->vaps_running != 0));
1516 
1517 	/* Restore basic rates mask. */
1518 	rtwn_calc_basicrates(sc);
1519 
1520 	/* Resume beaconing. */
1521 	rtwn_setbits_1(sc, R92C_TXPAUSE, R92C_TX_QUEUE_BCN, 0);
1522 	RTWN_UNLOCK(sc);
1523 }
1524 
1525 static void
1526 rtwn_getradiocaps(struct ieee80211com *ic,
1527     int maxchans, int *nchans, struct ieee80211_channel chans[])
1528 {
1529 	struct rtwn_softc *sc = ic->ic_softc;
1530 	uint8_t bands[IEEE80211_MODE_BYTES];
1531 	int i;
1532 
1533 	memset(bands, 0, sizeof(bands));
1534 	setbit(bands, IEEE80211_MODE_11B);
1535 	setbit(bands, IEEE80211_MODE_11G);
1536 	setbit(bands, IEEE80211_MODE_11NG);
1537 	ieee80211_add_channel_list_2ghz(chans, maxchans, nchans,
1538 	    rtwn_chan_2ghz, nitems(rtwn_chan_2ghz), bands,
1539 	    !!(ic->ic_htcaps & IEEE80211_HTCAP_CHWIDTH40));
1540 
1541 	/* XXX workaround add_channel_list() limitations */
1542 	setbit(bands, IEEE80211_MODE_11A);
1543 	setbit(bands, IEEE80211_MODE_11NA);
1544 	for (i = 0; i < nitems(sc->chan_num_5ghz); i++) {
1545 		if (sc->chan_num_5ghz[i] == 0)
1546 			continue;
1547 
1548 		ieee80211_add_channel_list_5ghz(chans, maxchans, nchans,
1549 		    sc->chan_list_5ghz[i], sc->chan_num_5ghz[i], bands,
1550 		    !!(ic->ic_htcaps & IEEE80211_HTCAP_CHWIDTH40));
1551 	}
1552 }
1553 
1554 static void
1555 rtwn_update_chw(struct ieee80211com *ic)
1556 {
1557 }
1558 
1559 static void
1560 rtwn_set_channel(struct ieee80211com *ic)
1561 {
1562 	struct rtwn_softc *sc = ic->ic_softc;
1563 	struct ieee80211_channel *c = ic->ic_curchan;
1564 
1565 	RTWN_LOCK(sc);
1566 	rtwn_set_chan(sc, c);
1567 	sc->sc_rxtap.wr_chan_freq = htole16(c->ic_freq);
1568 	sc->sc_rxtap.wr_chan_flags = htole16(c->ic_flags);
1569 	sc->sc_txtap.wt_chan_freq = htole16(c->ic_freq);
1570 	sc->sc_txtap.wt_chan_flags = htole16(c->ic_flags);
1571 	RTWN_UNLOCK(sc);
1572 }
1573 
1574 static int
1575 rtwn_wme_update(struct ieee80211com *ic)
1576 {
1577 	struct ieee80211_channel *c = ic->ic_curchan;
1578 	struct rtwn_softc *sc = ic->ic_softc;
1579 	struct wmeParams *wmep = sc->cap_wmeParams;
1580 	uint8_t aifs, acm, slottime;
1581 	int ac;
1582 
1583 	/* Prevent possible races. */
1584 	IEEE80211_LOCK(ic);	/* XXX */
1585 	RTWN_LOCK(sc);
1586 	memcpy(wmep, ic->ic_wme.wme_chanParams.cap_wmeParams,
1587 	    sizeof(sc->cap_wmeParams));
1588 	RTWN_UNLOCK(sc);
1589 	IEEE80211_UNLOCK(ic);
1590 
1591 	acm = 0;
1592 	slottime = IEEE80211_GET_SLOTTIME(ic);
1593 
1594 	RTWN_LOCK(sc);
1595 	for (ac = WME_AC_BE; ac < WME_NUM_AC; ac++) {
1596 		/* AIFS[AC] = AIFSN[AC] * aSlotTime + aSIFSTime. */
1597 		aifs = wmep[ac].wmep_aifsn * slottime +
1598 		    (IEEE80211_IS_CHAN_5GHZ(c) ?
1599 			IEEE80211_DUR_OFDM_SIFS : IEEE80211_DUR_SIFS);
1600 		rtwn_write_4(sc, wme2reg[ac],
1601 		    SM(R92C_EDCA_PARAM_TXOP, wmep[ac].wmep_txopLimit) |
1602 		    SM(R92C_EDCA_PARAM_ECWMIN, wmep[ac].wmep_logcwmin) |
1603 		    SM(R92C_EDCA_PARAM_ECWMAX, wmep[ac].wmep_logcwmax) |
1604 		    SM(R92C_EDCA_PARAM_AIFS, aifs));
1605 		if (ac != WME_AC_BE)
1606 			acm |= wmep[ac].wmep_acm << ac;
1607 	}
1608 
1609 	if (acm != 0)
1610 		acm |= R92C_ACMHWCTRL_EN;
1611 	rtwn_setbits_1(sc, R92C_ACMHWCTRL, R92C_ACMHWCTRL_ACM_MASK, acm);
1612 	RTWN_UNLOCK(sc);
1613 
1614 	return 0;
1615 }
1616 
1617 static void
1618 rtwn_update_slot(struct ieee80211com *ic)
1619 {
1620 	rtwn_cmd_sleepable(ic->ic_softc, NULL, 0, rtwn_update_slot_cb);
1621 }
1622 
1623 static void
1624 rtwn_update_slot_cb(struct rtwn_softc *sc, union sec_param *data)
1625 {
1626 	struct ieee80211com *ic = &sc->sc_ic;
1627 	uint8_t slottime;
1628 
1629 	slottime = IEEE80211_GET_SLOTTIME(ic);
1630 
1631 	RTWN_DPRINTF(sc, RTWN_DEBUG_STATE, "%s: setting slot time to %uus\n",
1632 	    __func__, slottime);
1633 
1634 	rtwn_write_1(sc, R92C_SLOT, slottime);
1635 	rtwn_update_aifs(sc, slottime);
1636 }
1637 
1638 static void
1639 rtwn_update_aifs(struct rtwn_softc *sc, uint8_t slottime)
1640 {
1641 	struct ieee80211_channel *c = sc->sc_ic.ic_curchan;
1642 	const struct wmeParams *wmep = sc->cap_wmeParams;
1643 	uint8_t aifs, ac;
1644 
1645 	for (ac = WME_AC_BE; ac < WME_NUM_AC; ac++) {
1646 		/* AIFS[AC] = AIFSN[AC] * aSlotTime + aSIFSTime. */
1647 		aifs = wmep[ac].wmep_aifsn * slottime +
1648 		    (IEEE80211_IS_CHAN_5GHZ(c) ?
1649 			IEEE80211_DUR_OFDM_SIFS : IEEE80211_DUR_SIFS);
1650 		rtwn_write_1(sc, wme2reg[ac], aifs);
1651 	}
1652 }
1653 
1654 static void
1655 rtwn_update_promisc(struct ieee80211com *ic)
1656 {
1657 	struct rtwn_softc *sc = ic->ic_softc;
1658 
1659 	RTWN_LOCK(sc);
1660 	if (sc->sc_flags & RTWN_RUNNING)
1661 		rtwn_set_promisc(sc);
1662 	RTWN_UNLOCK(sc);
1663 }
1664 
1665 static void
1666 rtwn_update_mcast(struct ieee80211com *ic)
1667 {
1668 	struct rtwn_softc *sc = ic->ic_softc;
1669 
1670 	RTWN_LOCK(sc);
1671 	if (sc->sc_flags & RTWN_RUNNING)
1672 		rtwn_set_multi(sc);
1673 	RTWN_UNLOCK(sc);
1674 }
1675 
1676 static int
1677 rtwn_set_bssid(struct rtwn_softc *sc, const uint8_t *bssid, int id)
1678 {
1679 	int error;
1680 
1681 	error = rtwn_write_4(sc, R92C_BSSID(id), le32dec(&bssid[0]));
1682 	if (error != 0)
1683 		return (error);
1684 	error = rtwn_write_2(sc, R92C_BSSID(id) + 4, le16dec(&bssid[4]));
1685 
1686 	return (error);
1687 }
1688 
1689 static int
1690 rtwn_set_macaddr(struct rtwn_softc *sc, const uint8_t *addr, int id)
1691 {
1692 	int error;
1693 
1694 	error = rtwn_write_4(sc, R92C_MACID(id), le32dec(&addr[0]));
1695 	if (error != 0)
1696 		return (error);
1697 	error = rtwn_write_2(sc, R92C_MACID(id) + 4, le16dec(&addr[4]));
1698 
1699 	return (error);
1700 }
1701 
1702 static struct ieee80211_node *
1703 rtwn_node_alloc(struct ieee80211vap *vap,
1704     const uint8_t mac[IEEE80211_ADDR_LEN])
1705 {
1706 	struct rtwn_node *un;
1707 
1708 	un = malloc(sizeof (struct rtwn_node), M_80211_NODE,
1709 	    M_NOWAIT | M_ZERO);
1710 
1711 	if (un == NULL)
1712 		return NULL;
1713 
1714 	un->id = RTWN_MACID_UNDEFINED;
1715 	un->avg_pwdb = -1;
1716 
1717 	return &un->ni;
1718 }
1719 
1720 static void
1721 rtwn_newassoc(struct ieee80211_node *ni, int isnew)
1722 {
1723 	struct rtwn_softc *sc = ni->ni_ic->ic_softc;
1724 	struct rtwn_node *un = RTWN_NODE(ni);
1725 	int id;
1726 
1727 	if (!isnew)
1728 		return;
1729 
1730 	RTWN_NT_LOCK(sc);
1731 	for (id = 0; id <= sc->macid_limit; id++) {
1732 		if (id != RTWN_MACID_BC && sc->node_list[id] == NULL) {
1733 			un->id = id;
1734 			sc->node_list[id] = ni;
1735 			break;
1736 		}
1737 	}
1738 	RTWN_NT_UNLOCK(sc);
1739 
1740 	if (id > sc->macid_limit) {
1741 		device_printf(sc->sc_dev, "%s: node table is full\n",
1742 		    __func__);
1743 		return;
1744 	}
1745 
1746 #ifndef RTWN_WITHOUT_UCODE
1747 	/* Notify firmware. */
1748 	id |= RTWN_MACID_VALID;
1749 	rtwn_cmd_sleepable(sc, &id, sizeof(id), rtwn_set_media_status);
1750 #endif
1751 }
1752 
1753 static void
1754 rtwn_node_free(struct ieee80211_node *ni)
1755 {
1756 	struct rtwn_softc *sc = ni->ni_ic->ic_softc;
1757 	struct rtwn_node *un = RTWN_NODE(ni);
1758 
1759 	RTWN_NT_LOCK(sc);
1760 	if (un->id != RTWN_MACID_UNDEFINED) {
1761 		sc->node_list[un->id] = NULL;
1762 #ifndef RTWN_WITHOUT_UCODE
1763 		rtwn_cmd_sleepable(sc, &un->id, sizeof(un->id),
1764 		    rtwn_set_media_status);
1765 #endif
1766 	}
1767 	RTWN_NT_UNLOCK(sc);
1768 
1769 	sc->sc_node_free(ni);
1770 }
1771 
1772 static void
1773 rtwn_init_beacon_reg(struct rtwn_softc *sc)
1774 {
1775 	rtwn_write_1(sc, R92C_BCN_CTRL(0), R92C_BCN_CTRL_DIS_TSF_UDT0);
1776 	rtwn_write_1(sc, R92C_BCN_CTRL(1), R92C_BCN_CTRL_DIS_TSF_UDT0);
1777 	rtwn_write_2(sc, R92C_TBTT_PROHIBIT, 0x6404);
1778 	rtwn_write_1(sc, R92C_DRVERLYINT, 0x05);
1779 	rtwn_write_1(sc, R92C_BCNDMATIM, 0x02);
1780 	rtwn_write_2(sc, R92C_BCNTCFG, 0x660f);
1781 }
1782 
1783 static int
1784 rtwn_init(struct rtwn_softc *sc)
1785 {
1786 	struct ieee80211com *ic = &sc->sc_ic;
1787 	int i, error;
1788 
1789 	RTWN_LOCK(sc);
1790 	if (sc->sc_flags & RTWN_RUNNING) {
1791 		RTWN_UNLOCK(sc);
1792 		return (0);
1793 	}
1794 	sc->sc_flags |= RTWN_STARTED;
1795 
1796 	/* Power on adapter. */
1797 	error = rtwn_power_on(sc);
1798 	if (error != 0)
1799 		goto fail;
1800 
1801 #ifndef RTWN_WITHOUT_UCODE
1802 	/* Load 8051 microcode. */
1803 	error = rtwn_load_firmware(sc);
1804 	if (error == 0)
1805 		sc->sc_flags |= RTWN_FW_LOADED;
1806 
1807 	/* Init firmware commands ring. */
1808 	sc->fwcur = 0;
1809 #endif
1810 
1811 	/* Initialize MAC block. */
1812 	error = rtwn_mac_init(sc);
1813 	if (error != 0) {
1814 		device_printf(sc->sc_dev,
1815 		    "%s: error while initializing MAC block\n", __func__);
1816 		goto fail;
1817 	}
1818 
1819 	/* Initialize DMA. */
1820 	error = rtwn_dma_init(sc);
1821 	if (error != 0)
1822 		goto fail;
1823 
1824 	/* Drop incorrect TX (USB). */
1825 	rtwn_drop_incorrect_tx(sc);
1826 
1827 	/* Set info size in Rx descriptors (in 64-bit words). */
1828 	rtwn_write_1(sc, R92C_RX_DRVINFO_SZ, R92C_RX_DRVINFO_SZ_DEF);
1829 
1830 	/* Init interrupts. */
1831 	rtwn_init_intr(sc);
1832 
1833 	for (i = 0; i < nitems(sc->vaps); i++) {
1834 		struct rtwn_vap *uvp = sc->vaps[i];
1835 
1836 		/* Set initial network type. */
1837 		rtwn_set_mode(sc, R92C_MSR_NOLINK, i);
1838 
1839 		if (uvp == NULL)
1840 			continue;
1841 
1842 		/* Set MAC address. */
1843 		error = rtwn_set_macaddr(sc, uvp->vap.iv_myaddr, uvp->id);
1844 		if (error != 0)
1845 			goto fail;
1846 	}
1847 
1848 	/* Initialize Rx filter. */
1849 	rtwn_rxfilter_init(sc);
1850 
1851 	/* Set short/long retry limits. */
1852 	rtwn_write_2(sc, R92C_RL,
1853 	    SM(R92C_RL_SRL, 0x30) | SM(R92C_RL_LRL, 0x30));
1854 
1855 	/* Initialize EDCA parameters. */
1856 	rtwn_init_edca(sc);
1857 
1858 	rtwn_setbits_1(sc, R92C_FWHW_TXQ_CTRL, 0,
1859 	    R92C_FWHW_TXQ_CTRL_AMPDU_RTY_NEW);
1860 	/* Set ACK timeout. */
1861 	rtwn_write_1(sc, R92C_ACKTO, sc->ackto);
1862 
1863 	/* Setup aggregation. */
1864 	/* Tx aggregation. */
1865 	rtwn_init_tx_agg(sc);
1866 	rtwn_init_rx_agg(sc);
1867 
1868 	/* Initialize beacon parameters. */
1869 	rtwn_init_beacon_reg(sc);
1870 
1871 	/* Init A-MPDU parameters. */
1872 	rtwn_init_ampdu(sc);
1873 
1874 	/* Init MACTXEN / MACRXEN after setting RxFF boundary. */
1875 	rtwn_setbits_1(sc, R92C_CR, 0, R92C_CR_MACTXEN | R92C_CR_MACRXEN);
1876 
1877 	/* Initialize BB/RF blocks. */
1878 	rtwn_init_bb(sc);
1879 	rtwn_init_rf(sc);
1880 
1881 	/* Initialize wireless band. */
1882 	rtwn_set_chan(sc, ic->ic_curchan);
1883 
1884 	/* Clear per-station keys table. */
1885 	rtwn_init_cam(sc);
1886 
1887 	/* Enable decryption / encryption. */
1888 	rtwn_init_seccfg(sc);
1889 
1890 	/* Install static keys (if any). */
1891 	for (i = 0; i < nitems(sc->vaps); i++) {
1892 		if (sc->vaps[i] != NULL) {
1893 			error = rtwn_init_static_keys(sc, sc->vaps[i]);
1894 			if (error != 0)
1895 				goto fail;
1896 		}
1897 	}
1898 
1899 	/* Initialize antenna selection. */
1900 	rtwn_init_antsel(sc);
1901 
1902 	/* Enable hardware sequence numbering. */
1903 	rtwn_write_1(sc, R92C_HWSEQ_CTRL, R92C_TX_QUEUE_ALL);
1904 
1905 	/* Disable BAR. */
1906 	rtwn_write_4(sc, R92C_BAR_MODE_CTRL, 0x0201ffff);
1907 
1908 	/* NAV limit. */
1909 	rtwn_write_1(sc, R92C_NAV_UPPER, 0);
1910 
1911 	/* Initialize GPIO setting. */
1912 	rtwn_setbits_1(sc, R92C_GPIO_MUXCFG, R92C_GPIO_MUXCFG_ENBT, 0);
1913 
1914 	/* Initialize MRR. */
1915 	rtwn_mrr_init(sc);
1916 
1917 	/* Device-specific post initialization. */
1918 	rtwn_post_init(sc);
1919 
1920 	rtwn_start_xfers(sc);
1921 
1922 #ifndef D4054
1923 	callout_reset(&sc->sc_watchdog_to, hz, rtwn_watchdog, sc);
1924 #endif
1925 
1926 	sc->sc_flags |= RTWN_RUNNING;
1927 fail:
1928 	RTWN_UNLOCK(sc);
1929 
1930 	return (error);
1931 }
1932 
1933 static void
1934 rtwn_stop(struct rtwn_softc *sc)
1935 {
1936 
1937 	RTWN_LOCK(sc);
1938 	if (!(sc->sc_flags & RTWN_STARTED)) {
1939 		RTWN_UNLOCK(sc);
1940 		return;
1941 	}
1942 
1943 #ifndef D4054
1944 	callout_stop(&sc->sc_watchdog_to);
1945 	sc->sc_tx_timer = 0;
1946 #endif
1947 	sc->sc_flags &= ~(RTWN_STARTED | RTWN_RUNNING | RTWN_FW_LOADED);
1948 	sc->sc_flags &= ~RTWN_TEMP_MEASURED;
1949 	sc->fwver = 0;
1950 	sc->thcal_temp = 0;
1951 	sc->cur_bcnq_id = RTWN_VAP_ID_INVALID;
1952 	bzero(&sc->last_physt, sizeof(sc->last_physt));
1953 
1954 #ifdef D4054
1955 	ieee80211_tx_watchdog_stop(&sc->sc_ic);
1956 #endif
1957 
1958 	rtwn_abort_xfers(sc);
1959 	rtwn_drain_mbufq(sc);
1960 	rtwn_power_off(sc);
1961 	rtwn_reset_lists(sc, NULL);
1962 	RTWN_UNLOCK(sc);
1963 }
1964 
1965 MODULE_VERSION(rtwn, 2);
1966 MODULE_DEPEND(rtwn, wlan, 1, 1, 1);
1967 #ifndef RTWN_WITHOUT_UCODE
1968 MODULE_DEPEND(rtwn, firmware, 1, 1, 1);
1969 #endif
1970