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