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