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