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