xref: /freebsd/sys/dev/rtwn/if_rtwn.c (revision 780fb4a2)
1 /*	$OpenBSD: if_urtwn.c,v 1.16 2011/02/10 17:26:40 jakemsr Exp $	*/
2 
3 /*-
4  * Copyright (c) 2010 Damien Bergamini <damien.bergamini@free.fr>
5  * Copyright (c) 2014 Kevin Lo <kevlo@FreeBSD.org>
6  * Copyright (c) 2015-2016 Andriy Voskoboinyk <avos@FreeBSD.org>
7  *
8  * Permission to use, copy, modify, and distribute this software for any
9  * purpose with or without fee is hereby granted, provided that the above
10  * copyright notice and this permission notice appear in all copies.
11  *
12  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19  */
20 
21 #include <sys/cdefs.h>
22 __FBSDID("$FreeBSD$");
23 
24 /*
25  * Driver for Realtek RTL8188CE-VAU/RTL8188CUS/RTL8188EU/RTL8188RU/RTL8192CU/RTL8812AU/RTL8821AU.
26  */
27 #include "opt_wlan.h"
28 
29 #include <sys/param.h>
30 #include <sys/sockio.h>
31 #include <sys/sysctl.h>
32 #include <sys/lock.h>
33 #include <sys/mutex.h>
34 #include <sys/mbuf.h>
35 #include <sys/kernel.h>
36 #include <sys/socket.h>
37 #include <sys/systm.h>
38 #include <sys/malloc.h>
39 #include <sys/module.h>
40 #include <sys/bus.h>
41 #include <sys/endian.h>
42 #include <sys/linker.h>
43 #include <sys/firmware.h>
44 #include <sys/kdb.h>
45 
46 #include <net/bpf.h>
47 #include <net/if.h>
48 #include <net/if_var.h>
49 #include <net/if_arp.h>
50 #include <net/ethernet.h>
51 #include <net/if_dl.h>
52 #include <net/if_media.h>
53 #include <net/if_types.h>
54 
55 #include <netinet/in.h>
56 #include <netinet/in_systm.h>
57 #include <netinet/in_var.h>
58 #include <netinet/if_ether.h>
59 #include <netinet/ip.h>
60 
61 #include <net80211/ieee80211_var.h>
62 #include <net80211/ieee80211_regdomain.h>
63 #include <net80211/ieee80211_radiotap.h>
64 #include <net80211/ieee80211_ratectl.h>
65 
66 #include <dev/rtwn/if_rtwnreg.h>
67 #include <dev/rtwn/if_rtwnvar.h>
68 
69 #include <dev/rtwn/if_rtwn_beacon.h>
70 #include <dev/rtwn/if_rtwn_calib.h>
71 #include <dev/rtwn/if_rtwn_cam.h>
72 #include <dev/rtwn/if_rtwn_debug.h>
73 #include <dev/rtwn/if_rtwn_efuse.h>
74 #include <dev/rtwn/if_rtwn_fw.h>
75 #include <dev/rtwn/if_rtwn_ridx.h>
76 #include <dev/rtwn/if_rtwn_rx.h>
77 #include <dev/rtwn/if_rtwn_task.h>
78 #include <dev/rtwn/if_rtwn_tx.h>
79 
80 #include <dev/rtwn/rtl8192c/r92c_reg.h>
81 
82 
83 static void		rtwn_radiotap_attach(struct rtwn_softc *);
84 static void		rtwn_vap_decrement_counters(struct rtwn_softc *,
85 			    enum ieee80211_opmode, int);
86 static void		rtwn_set_ic_opmode(struct rtwn_softc *);
87 static struct ieee80211vap *rtwn_vap_create(struct ieee80211com *,
88 			    const char [IFNAMSIZ], int, enum ieee80211_opmode,
89 			    int, const uint8_t [IEEE80211_ADDR_LEN],
90 			    const uint8_t [IEEE80211_ADDR_LEN]);
91 static void		rtwn_vap_delete(struct ieee80211vap *);
92 static int		rtwn_read_chipid(struct rtwn_softc *);
93 static int		rtwn_ioctl_reset(struct ieee80211vap *, u_long);
94 static void		rtwn_set_media_status(struct rtwn_softc *,
95 			    union sec_param *);
96 #ifndef RTWN_WITHOUT_UCODE
97 static int		rtwn_tx_fwpkt_check(struct rtwn_softc *,
98 			    struct ieee80211vap *);
99 static int		rtwn_construct_nulldata(struct rtwn_softc *,
100 			    struct ieee80211vap *, uint8_t *, int);
101 static int		rtwn_push_nulldata(struct rtwn_softc *,
102 			    struct ieee80211vap *);
103 static void		rtwn_pwrmode_init(void *);
104 static void		rtwn_set_pwrmode_cb(struct rtwn_softc *,
105 			    union sec_param *);
106 #endif
107 static void		rtwn_tsf_sync_adhoc(void *);
108 static void		rtwn_tsf_sync_adhoc_task(void *, int);
109 static void		rtwn_tsf_sync_enable(struct rtwn_softc *,
110 			    struct ieee80211vap *);
111 static void		rtwn_set_ack_preamble(struct rtwn_softc *);
112 static void		rtwn_set_mode(struct rtwn_softc *, uint8_t, int);
113 static int		rtwn_monitor_newstate(struct ieee80211vap *,
114 			    enum ieee80211_state, int);
115 static int		rtwn_newstate(struct ieee80211vap *,
116 			    enum ieee80211_state, int);
117 static void		rtwn_calc_basicrates(struct rtwn_softc *);
118 static int		rtwn_run(struct rtwn_softc *,
119 			    struct ieee80211vap *);
120 #ifndef D4054
121 static void		rtwn_watchdog(void *);
122 #endif
123 static void		rtwn_parent(struct ieee80211com *);
124 static int		rtwn_dma_init(struct rtwn_softc *);
125 static int		rtwn_mac_init(struct rtwn_softc *);
126 static void		rtwn_mrr_init(struct rtwn_softc *);
127 static void		rtwn_scan_start(struct ieee80211com *);
128 static void		rtwn_scan_curchan(struct ieee80211_scan_state *,
129 			    unsigned long);
130 static void		rtwn_scan_end(struct ieee80211com *);
131 static void		rtwn_getradiocaps(struct ieee80211com *, int, int *,
132 			    struct ieee80211_channel[]);
133 static void		rtwn_update_chw(struct ieee80211com *);
134 static void		rtwn_set_channel(struct ieee80211com *);
135 static int		rtwn_wme_update(struct ieee80211com *);
136 static void		rtwn_update_slot(struct ieee80211com *);
137 static void		rtwn_update_slot_cb(struct rtwn_softc *,
138 			    union sec_param *);
139 static void		rtwn_update_aifs(struct rtwn_softc *, uint8_t);
140 static void		rtwn_update_promisc(struct ieee80211com *);
141 static void		rtwn_update_mcast(struct ieee80211com *);
142 static int		rtwn_set_bssid(struct rtwn_softc *,
143 			    const uint8_t *, int);
144 static int		rtwn_set_macaddr(struct rtwn_softc *,
145 			    const uint8_t *, int);
146 static struct ieee80211_node *rtwn_node_alloc(struct ieee80211vap *,
147 			    const uint8_t mac[IEEE80211_ADDR_LEN]);
148 static void		rtwn_newassoc(struct ieee80211_node *, int);
149 static void		rtwn_node_free(struct ieee80211_node *);
150 static void		rtwn_init_beacon_reg(struct rtwn_softc *);
151 static int		rtwn_init(struct rtwn_softc *);
152 static void		rtwn_stop(struct rtwn_softc *);
153 
154 MALLOC_DEFINE(M_RTWN_PRIV, "rtwn_priv", "rtwn driver private state");
155 
156 static const uint8_t rtwn_chan_2ghz[] =
157 	{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 };
158 
159 static const uint16_t wme2reg[] =
160 	{ R92C_EDCA_BE_PARAM, R92C_EDCA_BK_PARAM,
161 	  R92C_EDCA_VI_PARAM, R92C_EDCA_VO_PARAM };
162 
163 int
164 rtwn_attach(struct rtwn_softc *sc)
165 {
166 	struct ieee80211com *ic = &sc->sc_ic;
167 	int error;
168 
169 	sc->cur_bcnq_id = RTWN_VAP_ID_INVALID;
170 
171 	RTWN_NT_LOCK_INIT(sc);
172 	rtwn_cmdq_init(sc);
173 #ifndef D4054
174 	callout_init_mtx(&sc->sc_watchdog_to, &sc->sc_mtx, 0);
175 #endif
176 	callout_init(&sc->sc_calib_to, 0);
177 	callout_init(&sc->sc_pwrmode_init, 0);
178 	mbufq_init(&sc->sc_snd, ifqmaxlen);
179 
180 	RTWN_LOCK(sc);
181 	error = rtwn_read_chipid(sc);
182 	RTWN_UNLOCK(sc);
183 	if (error != 0) {
184 		device_printf(sc->sc_dev, "unsupported test chip\n");
185 		goto detach;
186 	}
187 
188 	error = rtwn_read_rom(sc);
189 	if (error != 0) {
190 		device_printf(sc->sc_dev, "%s: cannot read rom, error %d\n",
191 		    __func__, error);
192 		goto detach;
193 	}
194 
195 	if (sc->macid_limit > RTWN_MACID_LIMIT) {
196 		device_printf(sc->sc_dev,
197 		    "macid limit will be reduced from %d to %d\n",
198 		    sc->macid_limit, RTWN_MACID_LIMIT);
199 		sc->macid_limit = RTWN_MACID_LIMIT;
200 	}
201 	if (sc->cam_entry_limit > RTWN_CAM_ENTRY_LIMIT) {
202 		device_printf(sc->sc_dev,
203 		    "cam entry limit will be reduced from %d to %d\n",
204 		    sc->cam_entry_limit, RTWN_CAM_ENTRY_LIMIT);
205 		sc->cam_entry_limit = RTWN_CAM_ENTRY_LIMIT;
206 	}
207 	if (sc->txdesc_len > RTWN_TX_DESC_SIZE) {
208 		device_printf(sc->sc_dev,
209 		    "adjust size for Tx descriptor (current %d, needed %d)\n",
210 		    RTWN_TX_DESC_SIZE, sc->txdesc_len);
211 		goto detach;
212 	}
213 
214 	device_printf(sc->sc_dev, "MAC/BB %s, RF 6052 %dT%dR\n",
215 	    sc->name, sc->ntxchains, sc->nrxchains);
216 
217 	ic->ic_softc = sc;
218 	ic->ic_phytype = IEEE80211_T_OFDM;	/* not only, but not used */
219 	ic->ic_opmode = IEEE80211_M_STA;	/* default to BSS mode */
220 
221 	/* set device capabilities */
222 	ic->ic_caps =
223 		  IEEE80211_C_STA		/* station mode */
224 		| IEEE80211_C_MONITOR		/* monitor mode */
225 		| IEEE80211_C_IBSS		/* adhoc mode */
226 		| IEEE80211_C_HOSTAP		/* hostap mode */
227 #if 0	/* TODO: HRPWM register setup */
228 #ifndef RTWN_WITHOUT_UCODE
229 		| IEEE80211_C_PMGT		/* Station-side power mgmt */
230 #endif
231 #endif
232 		| IEEE80211_C_SHPREAMBLE	/* short preamble supported */
233 		| IEEE80211_C_SHSLOT		/* short slot time supported */
234 #if 0
235 		| IEEE80211_C_BGSCAN		/* capable of bg scanning */
236 #endif
237 		| IEEE80211_C_WPA		/* 802.11i */
238 		| IEEE80211_C_WME		/* 802.11e */
239 		| IEEE80211_C_SWAMSDUTX		/* Do software A-MSDU TX */
240 		| IEEE80211_C_FF		/* Atheros fast-frames */
241 		;
242 
243 	if (sc->sc_hwcrypto != RTWN_CRYPTO_SW) {
244 		ic->ic_cryptocaps =
245 		    IEEE80211_CRYPTO_WEP |
246 		    IEEE80211_CRYPTO_TKIP |
247 		    IEEE80211_CRYPTO_AES_CCM;
248 	}
249 
250 	ic->ic_htcaps =
251 	      IEEE80211_HTCAP_SHORTGI20		/* short GI in 20MHz */
252 	    | IEEE80211_HTCAP_MAXAMSDU_3839	/* max A-MSDU length */
253 	    | IEEE80211_HTCAP_SMPS_OFF		/* SM PS mode disabled */
254 	    /* s/w capabilities */
255 	    | IEEE80211_HTC_HT			/* HT operation */
256 	    | IEEE80211_HTC_AMPDU		/* A-MPDU tx */
257 	    | IEEE80211_HTC_AMSDU		/* A-MSDU tx */
258 	    ;
259 
260 	if (sc->sc_ht40) {
261 		ic->ic_htcaps |=
262 		      IEEE80211_HTCAP_CHWIDTH40	/* 40 MHz channel width */
263 		    | IEEE80211_HTCAP_SHORTGI40	/* short GI in 40MHz */
264 		    ;
265 	}
266 
267 	ic->ic_txstream = sc->ntxchains;
268 	ic->ic_rxstream = sc->nrxchains;
269 
270 	/* Enable TX watchdog */
271 #ifdef D4054
272 	ic->ic_flags_ext |= IEEE80211_FEXT_WATCHDOG;
273 #endif
274 
275 	/* Adjust capabilities. */
276 	rtwn_adj_devcaps(sc);
277 
278 	rtwn_getradiocaps(ic, IEEE80211_CHAN_MAX, &ic->ic_nchans,
279 	    ic->ic_channels);
280 
281 	/* XXX TODO: setup regdomain if R92C_CHANNEL_PLAN_BY_HW bit is set. */
282 
283 	ieee80211_ifattach(ic);
284 	ic->ic_raw_xmit = rtwn_raw_xmit;
285 	ic->ic_scan_start = rtwn_scan_start;
286 	sc->sc_scan_curchan = ic->ic_scan_curchan;
287 	ic->ic_scan_curchan = rtwn_scan_curchan;
288 	ic->ic_scan_end = rtwn_scan_end;
289 	ic->ic_getradiocaps = rtwn_getradiocaps;
290 	ic->ic_update_chw = rtwn_update_chw;
291 	ic->ic_set_channel = rtwn_set_channel;
292 	ic->ic_transmit = rtwn_transmit;
293 	ic->ic_parent = rtwn_parent;
294 	ic->ic_vap_create = rtwn_vap_create;
295 	ic->ic_vap_delete = rtwn_vap_delete;
296 	ic->ic_wme.wme_update = rtwn_wme_update;
297 	ic->ic_updateslot = rtwn_update_slot;
298 	ic->ic_update_promisc = rtwn_update_promisc;
299 	ic->ic_update_mcast = rtwn_update_mcast;
300 	ic->ic_node_alloc = rtwn_node_alloc;
301 	ic->ic_newassoc = rtwn_newassoc;
302 	sc->sc_node_free = ic->ic_node_free;
303 	ic->ic_node_free = rtwn_node_free;
304 
305 	rtwn_postattach(sc);
306 	rtwn_radiotap_attach(sc);
307 
308 	if (bootverbose)
309 		ieee80211_announce(ic);
310 
311 	return (0);
312 
313 detach:
314 	return (ENXIO);			/* failure */
315 }
316 
317 static void
318 rtwn_radiotap_attach(struct rtwn_softc *sc)
319 {
320 	struct rtwn_rx_radiotap_header *rxtap = &sc->sc_rxtap;
321 	struct rtwn_tx_radiotap_header *txtap = &sc->sc_txtap;
322 
323 	ieee80211_radiotap_attach(&sc->sc_ic,
324 	    &txtap->wt_ihdr, sizeof(*txtap), RTWN_TX_RADIOTAP_PRESENT,
325 	    &rxtap->wr_ihdr, sizeof(*rxtap), RTWN_RX_RADIOTAP_PRESENT);
326 }
327 
328 void
329 rtwn_sysctlattach(struct rtwn_softc *sc)
330 {
331 	struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->sc_dev);
332 	struct sysctl_oid *tree = device_get_sysctl_tree(sc->sc_dev);
333 
334 #if 1
335 	sc->sc_ht40 = 0;
336 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
337 	    "ht40", CTLFLAG_RDTUN, &sc->sc_ht40,
338 	    sc->sc_ht40, "Enable 40 MHz mode support");
339 #endif
340 
341 #ifdef RTWN_DEBUG
342 	SYSCTL_ADD_U32(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
343 	    "debug", CTLFLAG_RWTUN, &sc->sc_debug, sc->sc_debug,
344 	    "Control debugging printfs");
345 #endif
346 
347 	sc->sc_hwcrypto = RTWN_CRYPTO_PAIR;
348 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
349 	    "hwcrypto", CTLFLAG_RDTUN, &sc->sc_hwcrypto,
350 	    sc->sc_hwcrypto, "Enable h/w crypto: "
351 	    "0 - disable, 1 - pairwise keys, 2 - all keys");
352 	if (sc->sc_hwcrypto >= RTWN_CRYPTO_MAX)
353 		sc->sc_hwcrypto = RTWN_CRYPTO_FULL;
354 
355 	sc->sc_ratectl_sysctl = RTWN_RATECTL_NET80211;
356 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
357 	    "ratectl", CTLFLAG_RDTUN, &sc->sc_ratectl_sysctl,
358 	    sc->sc_ratectl_sysctl, "Select rate control mechanism: "
359 	    "0 - disabled, 1 - via net80211, 2 - via firmware");
360 	if (sc->sc_ratectl_sysctl >= RTWN_RATECTL_MAX)
361 		sc->sc_ratectl_sysctl = RTWN_RATECTL_FW;
362 
363 	sc->sc_ratectl = sc->sc_ratectl_sysctl;
364 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
365 	    "ratectl_selected", CTLFLAG_RD, &sc->sc_ratectl,
366 	    sc->sc_ratectl,
367 	    "Currently selected rate control mechanism (by the driver)");
368 }
369 
370 void
371 rtwn_detach(struct rtwn_softc *sc)
372 {
373 	struct ieee80211com *ic = &sc->sc_ic;
374 
375 	if (ic->ic_softc == sc) {
376 		/* Stop command queue. */
377 		RTWN_CMDQ_LOCK(sc);
378 		sc->sc_detached = 1;
379 		RTWN_CMDQ_UNLOCK(sc);
380 
381 		ieee80211_draintask(ic, &sc->cmdq_task);
382 		ieee80211_ifdetach(ic);
383 	}
384 
385 	rtwn_cmdq_destroy(sc);
386 	if (RTWN_NT_LOCK_INITIALIZED(sc))
387 		RTWN_NT_LOCK_DESTROY(sc);
388 }
389 
390 void
391 rtwn_suspend(struct rtwn_softc *sc)
392 {
393 	struct ieee80211com *ic = &sc->sc_ic;
394 
395 	ieee80211_suspend_all(ic);
396 }
397 
398 void
399 rtwn_resume(struct rtwn_softc *sc)
400 {
401 	struct ieee80211com *ic = &sc->sc_ic;
402 
403 	ieee80211_resume_all(ic);
404 }
405 
406 static void
407 rtwn_vap_decrement_counters(struct rtwn_softc *sc,
408     enum ieee80211_opmode opmode, int id)
409 {
410 
411 	RTWN_ASSERT_LOCKED(sc);
412 
413 	if (id != RTWN_VAP_ID_INVALID) {
414 		KASSERT(id == 0 || id == 1, ("wrong vap id %d!\n", id));
415 		KASSERT(sc->vaps[id] != NULL, ("vap pointer is NULL\n"));
416 		sc->vaps[id] = NULL;
417 	}
418 
419 	switch (opmode) {
420 	case IEEE80211_M_HOSTAP:
421 		sc->ap_vaps--;
422 		/* FALLTHROUGH */
423 	case IEEE80211_M_IBSS:
424 		sc->bcn_vaps--;
425 		/* FALLTHROUGH */
426 	case IEEE80211_M_STA:
427 		sc->nvaps--;
428 		break;
429 	case IEEE80211_M_MONITOR:
430 		sc->mon_vaps--;
431 		break;
432 	default:
433 		KASSERT(0, ("wrong opmode %d\n", opmode));
434 		break;
435 	}
436 
437 	KASSERT(sc->vaps_running >= 0 && sc->monvaps_running >= 0,
438 	    ("number of running vaps is negative (vaps %d, monvaps %d)\n",
439 	    sc->vaps_running, sc->monvaps_running));
440 	KASSERT(sc->vaps_running - sc->monvaps_running <= RTWN_PORT_COUNT,
441 	    ("number of running vaps is too big (vaps %d, monvaps %d)\n",
442 	    sc->vaps_running, sc->monvaps_running));
443 
444 	KASSERT(sc->nvaps >= 0 && sc->nvaps <= RTWN_PORT_COUNT,
445 	    ("wrong value %d for nvaps\n", sc->nvaps));
446 	KASSERT(sc->mon_vaps >= 0, ("mon_vaps is negative (%d)\n",
447 	    sc->mon_vaps));
448 	KASSERT(sc->bcn_vaps >= 0 && ((RTWN_CHIP_HAS_BCNQ1(sc) &&
449 	    sc->bcn_vaps <= RTWN_PORT_COUNT) || sc->bcn_vaps <= 1),
450 	    ("bcn_vaps value %d is wrong\n", sc->bcn_vaps));
451 	KASSERT(sc->ap_vaps >= 0 && ((RTWN_CHIP_HAS_BCNQ1(sc) &&
452 	    sc->ap_vaps <= RTWN_PORT_COUNT) || sc->ap_vaps <= 1),
453 	    ("ap_vaps value %d is wrong\n", sc->ap_vaps));
454 }
455 
456 static void
457 rtwn_set_ic_opmode(struct rtwn_softc *sc)
458 {
459 	struct ieee80211com *ic = &sc->sc_ic;
460 
461 	RTWN_ASSERT_LOCKED(sc);
462 
463 	/* for ieee80211_reset_erp() */
464 	if (sc->bcn_vaps - sc->ap_vaps > 0)
465 		ic->ic_opmode = IEEE80211_M_IBSS;
466 	else if (sc->ap_vaps > 0)
467 		ic->ic_opmode = IEEE80211_M_HOSTAP;
468 	else if (sc->nvaps > 0)
469 		ic->ic_opmode = IEEE80211_M_STA;
470 	else
471 		ic->ic_opmode = IEEE80211_M_MONITOR;
472 }
473 
474 static struct ieee80211vap *
475 rtwn_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
476     enum ieee80211_opmode opmode, int flags,
477     const uint8_t bssid[IEEE80211_ADDR_LEN],
478     const uint8_t mac[IEEE80211_ADDR_LEN])
479 {
480 	struct rtwn_softc *sc = ic->ic_softc;
481 	struct rtwn_vap *uvp;
482 	struct ieee80211vap *vap;
483 	int id = RTWN_VAP_ID_INVALID;
484 
485 	RTWN_LOCK(sc);
486 	KASSERT(sc->nvaps <= RTWN_PORT_COUNT,
487 	    ("nvaps overflow (%d > %d)\n", sc->nvaps, RTWN_PORT_COUNT));
488 	KASSERT(sc->ap_vaps <= RTWN_PORT_COUNT,
489 	    ("ap_vaps overflow (%d > %d)\n", sc->ap_vaps, RTWN_PORT_COUNT));
490 	KASSERT(sc->bcn_vaps <= RTWN_PORT_COUNT,
491 	    ("bcn_vaps overflow (%d > %d)\n", sc->bcn_vaps, RTWN_PORT_COUNT));
492 
493 	if (opmode != IEEE80211_M_MONITOR) {
494 		switch (sc->nvaps) {
495 		case 0:
496 			id = 0;
497 			break;
498 		case 1:
499 			if (sc->vaps[1] == NULL)
500 				id = 1;
501 			else if (sc->vaps[0] == NULL)
502 				id = 0;
503 			KASSERT(id != RTWN_VAP_ID_INVALID,
504 			    ("no free ports left\n"));
505 			break;
506 		case 2:
507 		default:
508 			goto fail;
509 		}
510 
511 		if (opmode == IEEE80211_M_IBSS ||
512 		    opmode == IEEE80211_M_HOSTAP) {
513 			if ((sc->bcn_vaps == 1 && !RTWN_CHIP_HAS_BCNQ1(sc)) ||
514 			    sc->bcn_vaps == RTWN_PORT_COUNT)
515 				goto fail;
516 		}
517 	}
518 
519 	switch (opmode) {
520 	case IEEE80211_M_HOSTAP:
521 		sc->ap_vaps++;
522 		/* FALLTHROUGH */
523 	case IEEE80211_M_IBSS:
524 		sc->bcn_vaps++;
525 		/* FALLTHROUGH */
526 	case IEEE80211_M_STA:
527 		sc->nvaps++;
528 		break;
529 	case IEEE80211_M_MONITOR:
530 		sc->mon_vaps++;
531 		break;
532 	default:
533 		KASSERT(0, ("unknown opmode %d\n", opmode));
534 		goto fail;
535 	}
536 	RTWN_UNLOCK(sc);
537 
538 	uvp = malloc(sizeof(struct rtwn_vap), M_80211_VAP, M_WAITOK | M_ZERO);
539 	uvp->id = id;
540 	if (id != RTWN_VAP_ID_INVALID) {
541 		RTWN_LOCK(sc);
542 		sc->vaps[id] = uvp;
543 		RTWN_UNLOCK(sc);
544 	}
545 	vap = &uvp->vap;
546 	/* enable s/w bmiss handling for sta mode */
547 
548 	if (ieee80211_vap_setup(ic, vap, name, unit, opmode,
549 	    flags | IEEE80211_CLONE_NOBEACONS, bssid) != 0) {
550 		/* out of memory */
551 		free(uvp, M_80211_VAP);
552 
553 		RTWN_LOCK(sc);
554 		rtwn_vap_decrement_counters(sc, opmode, id);
555 		RTWN_UNLOCK(sc);
556 
557 		return (NULL);
558 	}
559 
560 	rtwn_beacon_init(sc, &uvp->bcn_desc.txd[0], uvp->id);
561 	rtwn_vap_preattach(sc, vap);
562 
563 	/* override state transition machine */
564 	uvp->newstate = vap->iv_newstate;
565 	if (opmode == IEEE80211_M_MONITOR)
566 		vap->iv_newstate = rtwn_monitor_newstate;
567 	else
568 		vap->iv_newstate = rtwn_newstate;
569 	vap->iv_update_beacon = rtwn_update_beacon;
570 	vap->iv_reset = rtwn_ioctl_reset;
571 	vap->iv_key_alloc = rtwn_key_alloc;
572 	vap->iv_key_set = rtwn_key_set;
573 	vap->iv_key_delete = rtwn_key_delete;
574 	vap->iv_max_aid = sc->macid_limit;
575 
576 	/* 802.11n parameters */
577 	vap->iv_ampdu_density = IEEE80211_HTCAP_MPDUDENSITY_16;
578 	vap->iv_ampdu_rxmax = IEEE80211_HTCAP_MAXRXAMPDU_64K;
579 
580 	TIMEOUT_TASK_INIT(taskqueue_thread, &uvp->tx_beacon_csa, 0,
581 	    rtwn_tx_beacon_csa, vap);
582 	if (opmode == IEEE80211_M_IBSS) {
583 		uvp->recv_mgmt = vap->iv_recv_mgmt;
584 		vap->iv_recv_mgmt = rtwn_adhoc_recv_mgmt;
585 		TASK_INIT(&uvp->tsf_sync_adhoc_task, 0,
586 		    rtwn_tsf_sync_adhoc_task, vap);
587 		callout_init(&uvp->tsf_sync_adhoc, 0);
588 	}
589 
590 	/*
591 	 * NB: driver can select net80211 RA even when user requests
592 	 * another mechanism.
593 	 */
594 	ieee80211_ratectl_init(vap);
595 
596 	/* complete setup */
597 	ieee80211_vap_attach(vap, ieee80211_media_change,
598 	    ieee80211_media_status, mac);
599 
600 	RTWN_LOCK(sc);
601 	rtwn_set_ic_opmode(sc);
602 	if (sc->sc_flags & RTWN_RUNNING) {
603 		if (uvp->id != RTWN_VAP_ID_INVALID)
604 			rtwn_set_macaddr(sc, vap->iv_myaddr, uvp->id);
605 
606 		rtwn_rxfilter_update(sc);
607 	}
608 	RTWN_UNLOCK(sc);
609 
610 	return (vap);
611 
612 fail:
613 	RTWN_UNLOCK(sc);
614 	return (NULL);
615 }
616 
617 static void
618 rtwn_vap_delete(struct ieee80211vap *vap)
619 {
620 	struct ieee80211com *ic = vap->iv_ic;
621 	struct rtwn_softc *sc = ic->ic_softc;
622 	struct rtwn_vap *uvp = RTWN_VAP(vap);
623 
624 	/* Put vap into INIT state + stop device if needed. */
625 	ieee80211_stop(vap);
626 	ieee80211_draintask(ic, &vap->iv_nstate_task);
627 	ieee80211_draintask(ic, &ic->ic_parent_task);
628 
629 	RTWN_LOCK(sc);
630 	/* Cancel any unfinished Tx. */
631 	rtwn_reset_lists(sc, vap);
632 	if (uvp->bcn_mbuf != NULL)
633 		m_freem(uvp->bcn_mbuf);
634 	rtwn_vap_decrement_counters(sc, vap->iv_opmode, uvp->id);
635 	rtwn_set_ic_opmode(sc);
636 	if (sc->sc_flags & RTWN_RUNNING)
637 		rtwn_rxfilter_update(sc);
638 	RTWN_UNLOCK(sc);
639 
640 	if (vap->iv_opmode == IEEE80211_M_IBSS) {
641 		ieee80211_draintask(ic, &uvp->tsf_sync_adhoc_task);
642 		callout_drain(&uvp->tsf_sync_adhoc);
643 	}
644 
645 	ieee80211_ratectl_deinit(vap);
646 	ieee80211_vap_detach(vap);
647 	free(uvp, M_80211_VAP);
648 }
649 
650 static int
651 rtwn_read_chipid(struct rtwn_softc *sc)
652 {
653 	uint32_t reg;
654 
655 	reg = rtwn_read_4(sc, R92C_SYS_CFG);
656 	if (reg & R92C_SYS_CFG_TRP_VAUX_EN)	/* test chip */
657 		return (EOPNOTSUPP);
658 
659 	rtwn_read_chipid_vendor(sc, reg);
660 
661 	return (0);
662 }
663 
664 static int
665 rtwn_ioctl_reset(struct ieee80211vap *vap, u_long cmd)
666 {
667 	int error;
668 
669 	switch (cmd) {
670 #ifndef RTWN_WITHOUT_UCODE
671 	case IEEE80211_IOC_POWERSAVE:
672 	case IEEE80211_IOC_POWERSAVESLEEP:
673 	{
674 		struct rtwn_softc *sc = vap->iv_ic->ic_softc;
675 		struct rtwn_vap *uvp = RTWN_VAP(vap);
676 
677 		if (vap->iv_opmode == IEEE80211_M_STA && uvp->id == 0) {
678 			RTWN_LOCK(sc);
679 			if (sc->sc_flags & RTWN_RUNNING)
680 				error = rtwn_set_pwrmode(sc, vap, 1);
681 			else
682 				error = 0;
683 			RTWN_UNLOCK(sc);
684 			if (error != 0)
685 				error = ENETRESET;
686 		} else
687 			error = EOPNOTSUPP;
688 		break;
689 	}
690 #endif
691 	case IEEE80211_IOC_SHORTGI:
692 	case IEEE80211_IOC_RTSTHRESHOLD:
693 	case IEEE80211_IOC_PROTMODE:
694 	case IEEE80211_IOC_HTPROTMODE:
695 	case IEEE80211_IOC_LDPC:
696 		error = 0;
697 		break;
698 	default:
699 		error = ENETRESET;
700 		break;
701 	}
702 
703 	return (error);
704 }
705 
706 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 i;
1532 
1533 	memset(bands, 0, sizeof(bands));
1534 	setbit(bands, IEEE80211_MODE_11B);
1535 	setbit(bands, IEEE80211_MODE_11G);
1536 	setbit(bands, IEEE80211_MODE_11NG);
1537 	ieee80211_add_channel_list_2ghz(chans, maxchans, nchans,
1538 	    rtwn_chan_2ghz, nitems(rtwn_chan_2ghz), bands,
1539 	    !!(ic->ic_htcaps & IEEE80211_HTCAP_CHWIDTH40));
1540 
1541 	/* XXX workaround add_channel_list() limitations */
1542 	setbit(bands, IEEE80211_MODE_11A);
1543 	setbit(bands, IEEE80211_MODE_11NA);
1544 	for (i = 0; i < nitems(sc->chan_num_5ghz); i++) {
1545 		if (sc->chan_num_5ghz[i] == 0)
1546 			continue;
1547 
1548 		ieee80211_add_channel_list_5ghz(chans, maxchans, nchans,
1549 		    sc->chan_list_5ghz[i], sc->chan_num_5ghz[i], bands,
1550 		    !!(ic->ic_htcaps & IEEE80211_HTCAP_CHWIDTH40));
1551 	}
1552 }
1553 
1554 static void
1555 rtwn_update_chw(struct ieee80211com *ic)
1556 {
1557 }
1558 
1559 static void
1560 rtwn_set_channel(struct ieee80211com *ic)
1561 {
1562 	struct rtwn_softc *sc = ic->ic_softc;
1563 	struct ieee80211_channel *c = ic->ic_curchan;
1564 
1565 	RTWN_LOCK(sc);
1566 	rtwn_set_chan(sc, c);
1567 	sc->sc_rxtap.wr_chan_freq = htole16(c->ic_freq);
1568 	sc->sc_rxtap.wr_chan_flags = htole16(c->ic_flags);
1569 	sc->sc_txtap.wt_chan_freq = htole16(c->ic_freq);
1570 	sc->sc_txtap.wt_chan_flags = htole16(c->ic_flags);
1571 	RTWN_UNLOCK(sc);
1572 }
1573 
1574 static int
1575 rtwn_wme_update(struct ieee80211com *ic)
1576 {
1577 	struct chanAccParams chp;
1578 	struct ieee80211_channel *c = ic->ic_curchan;
1579 	struct rtwn_softc *sc = ic->ic_softc;
1580 	struct wmeParams *wmep = sc->cap_wmeParams;
1581 	uint8_t aifs, acm, slottime;
1582 	int ac;
1583 
1584 	ieee80211_wme_ic_getparams(ic, &chp);
1585 
1586 	/* Prevent possible races. */
1587 	IEEE80211_LOCK(ic);	/* XXX */
1588 	RTWN_LOCK(sc);
1589 	memcpy(wmep, chp.cap_wmeParams, sizeof(sc->cap_wmeParams));
1590 	RTWN_UNLOCK(sc);
1591 	IEEE80211_UNLOCK(ic);
1592 
1593 	acm = 0;
1594 	slottime = IEEE80211_GET_SLOTTIME(ic);
1595 
1596 	RTWN_LOCK(sc);
1597 	for (ac = WME_AC_BE; ac < WME_NUM_AC; ac++) {
1598 		/* AIFS[AC] = AIFSN[AC] * aSlotTime + aSIFSTime. */
1599 		aifs = wmep[ac].wmep_aifsn * slottime +
1600 		    (IEEE80211_IS_CHAN_5GHZ(c) ?
1601 			IEEE80211_DUR_OFDM_SIFS : IEEE80211_DUR_SIFS);
1602 		rtwn_write_4(sc, wme2reg[ac],
1603 		    SM(R92C_EDCA_PARAM_TXOP, wmep[ac].wmep_txopLimit) |
1604 		    SM(R92C_EDCA_PARAM_ECWMIN, wmep[ac].wmep_logcwmin) |
1605 		    SM(R92C_EDCA_PARAM_ECWMAX, wmep[ac].wmep_logcwmax) |
1606 		    SM(R92C_EDCA_PARAM_AIFS, aifs));
1607 		if (ac != WME_AC_BE)
1608 			acm |= wmep[ac].wmep_acm << ac;
1609 	}
1610 
1611 	if (acm != 0)
1612 		acm |= R92C_ACMHWCTRL_EN;
1613 	rtwn_setbits_1(sc, R92C_ACMHWCTRL, R92C_ACMHWCTRL_ACM_MASK, acm);
1614 	RTWN_UNLOCK(sc);
1615 
1616 	return 0;
1617 }
1618 
1619 static void
1620 rtwn_update_slot(struct ieee80211com *ic)
1621 {
1622 	rtwn_cmd_sleepable(ic->ic_softc, NULL, 0, rtwn_update_slot_cb);
1623 }
1624 
1625 static void
1626 rtwn_update_slot_cb(struct rtwn_softc *sc, union sec_param *data)
1627 {
1628 	struct ieee80211com *ic = &sc->sc_ic;
1629 	uint8_t slottime;
1630 
1631 	slottime = IEEE80211_GET_SLOTTIME(ic);
1632 
1633 	RTWN_DPRINTF(sc, RTWN_DEBUG_STATE, "%s: setting slot time to %uus\n",
1634 	    __func__, slottime);
1635 
1636 	rtwn_write_1(sc, R92C_SLOT, slottime);
1637 	rtwn_update_aifs(sc, slottime);
1638 }
1639 
1640 static void
1641 rtwn_update_aifs(struct rtwn_softc *sc, uint8_t slottime)
1642 {
1643 	struct ieee80211_channel *c = sc->sc_ic.ic_curchan;
1644 	const struct wmeParams *wmep = sc->cap_wmeParams;
1645 	uint8_t aifs, ac;
1646 
1647 	for (ac = WME_AC_BE; ac < WME_NUM_AC; ac++) {
1648 		/* AIFS[AC] = AIFSN[AC] * aSlotTime + aSIFSTime. */
1649 		aifs = wmep[ac].wmep_aifsn * slottime +
1650 		    (IEEE80211_IS_CHAN_5GHZ(c) ?
1651 			IEEE80211_DUR_OFDM_SIFS : IEEE80211_DUR_SIFS);
1652 		rtwn_write_1(sc, wme2reg[ac], aifs);
1653 	}
1654 }
1655 
1656 static void
1657 rtwn_update_promisc(struct ieee80211com *ic)
1658 {
1659 	struct rtwn_softc *sc = ic->ic_softc;
1660 
1661 	RTWN_LOCK(sc);
1662 	if (sc->sc_flags & RTWN_RUNNING)
1663 		rtwn_set_promisc(sc);
1664 	RTWN_UNLOCK(sc);
1665 }
1666 
1667 static void
1668 rtwn_update_mcast(struct ieee80211com *ic)
1669 {
1670 	struct rtwn_softc *sc = ic->ic_softc;
1671 
1672 	RTWN_LOCK(sc);
1673 	if (sc->sc_flags & RTWN_RUNNING)
1674 		rtwn_set_multi(sc);
1675 	RTWN_UNLOCK(sc);
1676 }
1677 
1678 static int
1679 rtwn_set_bssid(struct rtwn_softc *sc, const uint8_t *bssid, int id)
1680 {
1681 	int error;
1682 
1683 	error = rtwn_write_4(sc, R92C_BSSID(id), le32dec(&bssid[0]));
1684 	if (error != 0)
1685 		return (error);
1686 	error = rtwn_write_2(sc, R92C_BSSID(id) + 4, le16dec(&bssid[4]));
1687 
1688 	return (error);
1689 }
1690 
1691 static int
1692 rtwn_set_macaddr(struct rtwn_softc *sc, const uint8_t *addr, int id)
1693 {
1694 	int error;
1695 
1696 	error = rtwn_write_4(sc, R92C_MACID(id), le32dec(&addr[0]));
1697 	if (error != 0)
1698 		return (error);
1699 	error = rtwn_write_2(sc, R92C_MACID(id) + 4, le16dec(&addr[4]));
1700 
1701 	return (error);
1702 }
1703 
1704 static struct ieee80211_node *
1705 rtwn_node_alloc(struct ieee80211vap *vap,
1706     const uint8_t mac[IEEE80211_ADDR_LEN])
1707 {
1708 	struct rtwn_node *un;
1709 
1710 	un = malloc(sizeof (struct rtwn_node), M_80211_NODE,
1711 	    M_NOWAIT | M_ZERO);
1712 
1713 	if (un == NULL)
1714 		return NULL;
1715 
1716 	un->id = RTWN_MACID_UNDEFINED;
1717 	un->avg_pwdb = -1;
1718 
1719 	return &un->ni;
1720 }
1721 
1722 static void
1723 rtwn_newassoc(struct ieee80211_node *ni, int isnew __unused)
1724 {
1725 	struct rtwn_softc *sc = ni->ni_ic->ic_softc;
1726 	struct rtwn_node *un = RTWN_NODE(ni);
1727 	int id;
1728 
1729 	if (un->id != RTWN_MACID_UNDEFINED)
1730 		return;
1731 
1732 	RTWN_NT_LOCK(sc);
1733 	for (id = 0; id <= sc->macid_limit; id++) {
1734 		if (id != RTWN_MACID_BC && sc->node_list[id] == NULL) {
1735 			un->id = id;
1736 			sc->node_list[id] = ni;
1737 			break;
1738 		}
1739 	}
1740 	RTWN_NT_UNLOCK(sc);
1741 
1742 	if (id > sc->macid_limit) {
1743 		device_printf(sc->sc_dev, "%s: node table is full\n",
1744 		    __func__);
1745 		return;
1746 	}
1747 
1748 	/* Notify firmware. */
1749 	id |= RTWN_MACID_VALID;
1750 	rtwn_cmd_sleepable(sc, &id, sizeof(id), rtwn_set_media_status);
1751 }
1752 
1753 static void
1754 rtwn_node_free(struct ieee80211_node *ni)
1755 {
1756 	struct rtwn_softc *sc = ni->ni_ic->ic_softc;
1757 	struct rtwn_node *un = RTWN_NODE(ni);
1758 
1759 	RTWN_NT_LOCK(sc);
1760 	if (un->id != RTWN_MACID_UNDEFINED) {
1761 		sc->node_list[un->id] = NULL;
1762 		rtwn_cmd_sleepable(sc, &un->id, sizeof(un->id),
1763 		    rtwn_set_media_status);
1764 	}
1765 	RTWN_NT_UNLOCK(sc);
1766 
1767 	sc->sc_node_free(ni);
1768 }
1769 
1770 static void
1771 rtwn_init_beacon_reg(struct rtwn_softc *sc)
1772 {
1773 	rtwn_write_1(sc, R92C_BCN_CTRL(0), R92C_BCN_CTRL_DIS_TSF_UDT0);
1774 	rtwn_write_1(sc, R92C_BCN_CTRL(1), R92C_BCN_CTRL_DIS_TSF_UDT0);
1775 	rtwn_write_2(sc, R92C_TBTT_PROHIBIT, 0x6404);
1776 	rtwn_write_1(sc, R92C_DRVERLYINT, 0x05);
1777 	rtwn_write_1(sc, R92C_BCNDMATIM, 0x02);
1778 	rtwn_write_2(sc, R92C_BCNTCFG, 0x660f);
1779 }
1780 
1781 static int
1782 rtwn_init(struct rtwn_softc *sc)
1783 {
1784 	struct ieee80211com *ic = &sc->sc_ic;
1785 	int i, error;
1786 
1787 	RTWN_LOCK(sc);
1788 	if (sc->sc_flags & RTWN_RUNNING) {
1789 		RTWN_UNLOCK(sc);
1790 		return (0);
1791 	}
1792 	sc->sc_flags |= RTWN_STARTED;
1793 
1794 	/* Power on adapter. */
1795 	error = rtwn_power_on(sc);
1796 	if (error != 0)
1797 		goto fail;
1798 
1799 #ifndef RTWN_WITHOUT_UCODE
1800 	/* Load 8051 microcode. */
1801 	error = rtwn_load_firmware(sc);
1802 	if (error == 0)
1803 		sc->sc_flags |= RTWN_FW_LOADED;
1804 
1805 	/* Init firmware commands ring. */
1806 	sc->fwcur = 0;
1807 #endif
1808 
1809 	/* Initialize MAC block. */
1810 	error = rtwn_mac_init(sc);
1811 	if (error != 0) {
1812 		device_printf(sc->sc_dev,
1813 		    "%s: error while initializing MAC block\n", __func__);
1814 		goto fail;
1815 	}
1816 
1817 	/* Initialize DMA. */
1818 	error = rtwn_dma_init(sc);
1819 	if (error != 0)
1820 		goto fail;
1821 
1822 	/* Drop incorrect TX (USB). */
1823 	rtwn_drop_incorrect_tx(sc);
1824 
1825 	/* Set info size in Rx descriptors (in 64-bit words). */
1826 	rtwn_write_1(sc, R92C_RX_DRVINFO_SZ, R92C_RX_DRVINFO_SZ_DEF);
1827 
1828 	/* Init interrupts. */
1829 	rtwn_init_intr(sc);
1830 
1831 	for (i = 0; i < nitems(sc->vaps); i++) {
1832 		struct rtwn_vap *uvp = sc->vaps[i];
1833 
1834 		/* Set initial network type. */
1835 		rtwn_set_mode(sc, R92C_MSR_NOLINK, i);
1836 
1837 		if (uvp == NULL)
1838 			continue;
1839 
1840 		/* Set MAC address. */
1841 		error = rtwn_set_macaddr(sc, uvp->vap.iv_myaddr, uvp->id);
1842 		if (error != 0)
1843 			goto fail;
1844 	}
1845 
1846 	/* Initialize Rx filter. */
1847 	rtwn_rxfilter_init(sc);
1848 
1849 	/* Set short/long retry limits. */
1850 	rtwn_write_2(sc, R92C_RL,
1851 	    SM(R92C_RL_SRL, 0x30) | SM(R92C_RL_LRL, 0x30));
1852 
1853 	/* Initialize EDCA parameters. */
1854 	rtwn_init_edca(sc);
1855 
1856 	rtwn_setbits_1(sc, R92C_FWHW_TXQ_CTRL, 0,
1857 	    R92C_FWHW_TXQ_CTRL_AMPDU_RTY_NEW);
1858 	/* Set ACK timeout. */
1859 	rtwn_write_1(sc, R92C_ACKTO, sc->ackto);
1860 
1861 	/* Setup aggregation. */
1862 	/* Tx aggregation. */
1863 	rtwn_init_tx_agg(sc);
1864 	rtwn_init_rx_agg(sc);
1865 
1866 	/* Initialize beacon parameters. */
1867 	rtwn_init_beacon_reg(sc);
1868 
1869 	/* Init A-MPDU parameters. */
1870 	rtwn_init_ampdu(sc);
1871 
1872 	/* Init MACTXEN / MACRXEN after setting RxFF boundary. */
1873 	rtwn_setbits_1(sc, R92C_CR, 0, R92C_CR_MACTXEN | R92C_CR_MACRXEN);
1874 
1875 	/* Initialize BB/RF blocks. */
1876 	rtwn_init_bb(sc);
1877 	rtwn_init_rf(sc);
1878 
1879 	/* Initialize wireless band. */
1880 	rtwn_set_chan(sc, ic->ic_curchan);
1881 
1882 	/* Clear per-station keys table. */
1883 	rtwn_init_cam(sc);
1884 
1885 	/* Enable decryption / encryption. */
1886 	rtwn_init_seccfg(sc);
1887 
1888 	/* Install static keys (if any). */
1889 	for (i = 0; i < nitems(sc->vaps); i++) {
1890 		if (sc->vaps[i] != NULL) {
1891 			error = rtwn_init_static_keys(sc, sc->vaps[i]);
1892 			if (error != 0)
1893 				goto fail;
1894 		}
1895 	}
1896 
1897 	/* Initialize antenna selection. */
1898 	rtwn_init_antsel(sc);
1899 
1900 	/* Enable hardware sequence numbering. */
1901 	rtwn_write_1(sc, R92C_HWSEQ_CTRL, R92C_TX_QUEUE_ALL);
1902 
1903 	/* Disable BAR. */
1904 	rtwn_write_4(sc, R92C_BAR_MODE_CTRL, 0x0201ffff);
1905 
1906 	/* NAV limit. */
1907 	rtwn_write_1(sc, R92C_NAV_UPPER, 0);
1908 
1909 	/* Initialize GPIO setting. */
1910 	rtwn_setbits_1(sc, R92C_GPIO_MUXCFG, R92C_GPIO_MUXCFG_ENBT, 0);
1911 
1912 	/* Initialize MRR. */
1913 	rtwn_mrr_init(sc);
1914 
1915 	/* Device-specific post initialization. */
1916 	rtwn_post_init(sc);
1917 
1918 	rtwn_start_xfers(sc);
1919 
1920 #ifndef D4054
1921 	callout_reset(&sc->sc_watchdog_to, hz, rtwn_watchdog, sc);
1922 #endif
1923 
1924 	sc->sc_flags |= RTWN_RUNNING;
1925 fail:
1926 	RTWN_UNLOCK(sc);
1927 
1928 	return (error);
1929 }
1930 
1931 static void
1932 rtwn_stop(struct rtwn_softc *sc)
1933 {
1934 
1935 	RTWN_LOCK(sc);
1936 	if (!(sc->sc_flags & RTWN_STARTED)) {
1937 		RTWN_UNLOCK(sc);
1938 		return;
1939 	}
1940 
1941 #ifndef D4054
1942 	callout_stop(&sc->sc_watchdog_to);
1943 	sc->sc_tx_timer = 0;
1944 #endif
1945 	sc->sc_flags &= ~(RTWN_STARTED | RTWN_RUNNING | RTWN_FW_LOADED);
1946 	sc->sc_flags &= ~RTWN_TEMP_MEASURED;
1947 	sc->fwver = 0;
1948 	sc->thcal_temp = 0;
1949 	sc->cur_bcnq_id = RTWN_VAP_ID_INVALID;
1950 	bzero(&sc->last_physt, sizeof(sc->last_physt));
1951 
1952 #ifdef D4054
1953 	ieee80211_tx_watchdog_stop(&sc->sc_ic);
1954 #endif
1955 
1956 	rtwn_abort_xfers(sc);
1957 	rtwn_drain_mbufq(sc);
1958 	rtwn_power_off(sc);
1959 	rtwn_reset_lists(sc, NULL);
1960 	RTWN_UNLOCK(sc);
1961 }
1962 
1963 MODULE_VERSION(rtwn, 2);
1964 MODULE_DEPEND(rtwn, wlan, 1, 1, 1);
1965 #ifndef RTWN_WITHOUT_UCODE
1966 MODULE_DEPEND(rtwn, firmware, 1, 1, 1);
1967 #endif
1968