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