xref: /freebsd/sys/dev/wpi/if_wpi.c (revision bdd1243df58e60e85101c09001d9812a789b6bc4)
1 /*-
2  * Copyright (c) 2006,2007
3  *	Damien Bergamini <damien.bergamini@free.fr>
4  *	Benjamin Close <Benjamin.Close@clearchain.com>
5  * Copyright (c) 2015 Andriy Voskoboinyk <avos@FreeBSD.org>
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 #include <sys/cdefs.h>
21 __FBSDID("$FreeBSD$");
22 
23 /*
24  * Driver for Intel PRO/Wireless 3945ABG 802.11 network adapters.
25  *
26  * The 3945ABG network adapter doesn't use traditional hardware as
27  * many other adaptors do. Instead at run time the eeprom is set into a known
28  * state and told to load boot firmware. The boot firmware loads an init and a
29  * main  binary firmware image into SRAM on the card via DMA.
30  * Once the firmware is loaded, the driver/hw then
31  * communicate by way of circular dma rings via the SRAM to the firmware.
32  *
33  * There is 6 memory rings. 1 command ring, 1 rx data ring & 4 tx data rings.
34  * The 4 tx data rings allow for prioritization QoS.
35  *
36  * The rx data ring consists of 32 dma buffers. Two registers are used to
37  * indicate where in the ring the driver and the firmware are up to. The
38  * driver sets the initial read index (reg1) and the initial write index (reg2),
39  * the firmware updates the read index (reg1) on rx of a packet and fires an
40  * interrupt. The driver then processes the buffers starting at reg1 indicating
41  * to the firmware which buffers have been accessed by updating reg2. At the
42  * same time allocating new memory for the processed buffer.
43  *
44  * A similar thing happens with the tx rings. The difference is the firmware
45  * stop processing buffers once the queue is full and until confirmation
46  * of a successful transmition (tx_done) has occurred.
47  *
48  * The command ring operates in the same manner as the tx queues.
49  *
50  * All communication direct to the card (ie eeprom) is classed as Stage1
51  * communication
52  *
53  * All communication via the firmware to the card is classed as State2.
54  * The firmware consists of 2 parts. A bootstrap firmware and a runtime
55  * firmware. The bootstrap firmware and runtime firmware are loaded
56  * from host memory via dma to the card then told to execute. From this point
57  * on the majority of communications between the driver and the card goes
58  * via the firmware.
59  */
60 
61 #include "opt_wlan.h"
62 #include "opt_wpi.h"
63 
64 #include <sys/param.h>
65 #include <sys/sysctl.h>
66 #include <sys/sockio.h>
67 #include <sys/mbuf.h>
68 #include <sys/kernel.h>
69 #include <sys/socket.h>
70 #include <sys/systm.h>
71 #include <sys/malloc.h>
72 #include <sys/queue.h>
73 #include <sys/taskqueue.h>
74 #include <sys/module.h>
75 #include <sys/bus.h>
76 #include <sys/endian.h>
77 #include <sys/linker.h>
78 #include <sys/firmware.h>
79 
80 #include <machine/bus.h>
81 #include <machine/resource.h>
82 #include <sys/rman.h>
83 
84 #include <dev/pci/pcireg.h>
85 #include <dev/pci/pcivar.h>
86 
87 #include <net/bpf.h>
88 #include <net/if.h>
89 #include <net/if_var.h>
90 #include <net/if_arp.h>
91 #include <net/ethernet.h>
92 #include <net/if_dl.h>
93 #include <net/if_media.h>
94 #include <net/if_types.h>
95 
96 #include <netinet/in.h>
97 #include <netinet/in_systm.h>
98 #include <netinet/in_var.h>
99 #include <netinet/if_ether.h>
100 #include <netinet/ip.h>
101 
102 #include <net80211/ieee80211_var.h>
103 #include <net80211/ieee80211_radiotap.h>
104 #include <net80211/ieee80211_regdomain.h>
105 #include <net80211/ieee80211_ratectl.h>
106 
107 #include <dev/wpi/if_wpireg.h>
108 #include <dev/wpi/if_wpivar.h>
109 #include <dev/wpi/if_wpi_debug.h>
110 
111 struct wpi_ident {
112 	uint16_t	vendor;
113 	uint16_t	device;
114 	uint16_t	subdevice;
115 	const char	*name;
116 };
117 
118 static const struct wpi_ident wpi_ident_table[] = {
119 	/* The below entries support ABG regardless of the subid */
120 	{ 0x8086, 0x4222,    0x0, "Intel(R) PRO/Wireless 3945ABG" },
121 	{ 0x8086, 0x4227,    0x0, "Intel(R) PRO/Wireless 3945ABG" },
122 	/* The below entries only support BG */
123 	{ 0x8086, 0x4222, 0x1005, "Intel(R) PRO/Wireless 3945BG"  },
124 	{ 0x8086, 0x4222, 0x1034, "Intel(R) PRO/Wireless 3945BG"  },
125 	{ 0x8086, 0x4227, 0x1014, "Intel(R) PRO/Wireless 3945BG"  },
126 	{ 0x8086, 0x4222, 0x1044, "Intel(R) PRO/Wireless 3945BG"  },
127 	{ 0, 0, 0, NULL }
128 };
129 
130 static int	wpi_probe(device_t);
131 static int	wpi_attach(device_t);
132 static void	wpi_radiotap_attach(struct wpi_softc *);
133 static void	wpi_sysctlattach(struct wpi_softc *);
134 static void	wpi_init_beacon(struct wpi_vap *);
135 static struct ieee80211vap *wpi_vap_create(struct ieee80211com *,
136 		    const char [IFNAMSIZ], int, enum ieee80211_opmode, int,
137 		    const uint8_t [IEEE80211_ADDR_LEN],
138 		    const uint8_t [IEEE80211_ADDR_LEN]);
139 static void	wpi_vap_delete(struct ieee80211vap *);
140 static int	wpi_detach(device_t);
141 static int	wpi_shutdown(device_t);
142 static int	wpi_suspend(device_t);
143 static int	wpi_resume(device_t);
144 static int	wpi_nic_lock(struct wpi_softc *);
145 static int	wpi_read_prom_data(struct wpi_softc *, uint32_t, void *, int);
146 static void	wpi_dma_map_addr(void *, bus_dma_segment_t *, int, int);
147 static int	wpi_dma_contig_alloc(struct wpi_softc *, struct wpi_dma_info *,
148 		    void **, bus_size_t, bus_size_t);
149 static void	wpi_dma_contig_free(struct wpi_dma_info *);
150 static int	wpi_alloc_shared(struct wpi_softc *);
151 static void	wpi_free_shared(struct wpi_softc *);
152 static int	wpi_alloc_fwmem(struct wpi_softc *);
153 static void	wpi_free_fwmem(struct wpi_softc *);
154 static int	wpi_alloc_rx_ring(struct wpi_softc *);
155 static void	wpi_update_rx_ring(struct wpi_softc *);
156 static void	wpi_update_rx_ring_ps(struct wpi_softc *);
157 static void	wpi_reset_rx_ring(struct wpi_softc *);
158 static void	wpi_free_rx_ring(struct wpi_softc *);
159 static int	wpi_alloc_tx_ring(struct wpi_softc *, struct wpi_tx_ring *,
160 		    uint8_t);
161 static void	wpi_update_tx_ring(struct wpi_softc *, struct wpi_tx_ring *);
162 static void	wpi_update_tx_ring_ps(struct wpi_softc *,
163 		    struct wpi_tx_ring *);
164 static void	wpi_reset_tx_ring(struct wpi_softc *, struct wpi_tx_ring *);
165 static void	wpi_free_tx_ring(struct wpi_softc *, struct wpi_tx_ring *);
166 static int	wpi_read_eeprom(struct wpi_softc *,
167 		    uint8_t macaddr[IEEE80211_ADDR_LEN]);
168 static uint32_t	wpi_eeprom_channel_flags(struct wpi_eeprom_chan *);
169 static void	wpi_read_eeprom_band(struct wpi_softc *, uint8_t, int, int *,
170 		    struct ieee80211_channel[]);
171 static int	wpi_read_eeprom_channels(struct wpi_softc *, uint8_t);
172 static struct wpi_eeprom_chan *wpi_find_eeprom_channel(struct wpi_softc *,
173 		    struct ieee80211_channel *);
174 static void	wpi_getradiocaps(struct ieee80211com *, int, int *,
175 		    struct ieee80211_channel[]);
176 static int	wpi_setregdomain(struct ieee80211com *,
177 		    struct ieee80211_regdomain *, int,
178 		    struct ieee80211_channel[]);
179 static int	wpi_read_eeprom_group(struct wpi_softc *, uint8_t);
180 static struct ieee80211_node *wpi_node_alloc(struct ieee80211vap *,
181 		    const uint8_t mac[IEEE80211_ADDR_LEN]);
182 static void	wpi_node_free(struct ieee80211_node *);
183 static void	wpi_ibss_recv_mgmt(struct ieee80211_node *, struct mbuf *, int,
184 		    const struct ieee80211_rx_stats *,
185 		    int, int);
186 static void	wpi_restore_node(void *, struct ieee80211_node *);
187 static void	wpi_restore_node_table(struct wpi_softc *, struct wpi_vap *);
188 static int	wpi_newstate(struct ieee80211vap *, enum ieee80211_state, int);
189 static void	wpi_calib_timeout(void *);
190 static void	wpi_rx_done(struct wpi_softc *, struct wpi_rx_desc *,
191 		    struct wpi_rx_data *);
192 static void	wpi_rx_statistics(struct wpi_softc *, struct wpi_rx_desc *,
193 		    struct wpi_rx_data *);
194 static void	wpi_tx_done(struct wpi_softc *, struct wpi_rx_desc *);
195 static void	wpi_cmd_done(struct wpi_softc *, struct wpi_rx_desc *);
196 static void	wpi_notif_intr(struct wpi_softc *);
197 static void	wpi_wakeup_intr(struct wpi_softc *);
198 #ifdef WPI_DEBUG
199 static void	wpi_debug_registers(struct wpi_softc *);
200 #endif
201 static void	wpi_fatal_intr(struct wpi_softc *);
202 static void	wpi_intr(void *);
203 static void	wpi_free_txfrags(struct wpi_softc *, uint16_t);
204 static int	wpi_cmd2(struct wpi_softc *, struct wpi_buf *);
205 static int	wpi_tx_data(struct wpi_softc *, struct mbuf *,
206 		    struct ieee80211_node *);
207 static int	wpi_tx_data_raw(struct wpi_softc *, struct mbuf *,
208 		    struct ieee80211_node *,
209 		    const struct ieee80211_bpf_params *);
210 static int	wpi_raw_xmit(struct ieee80211_node *, struct mbuf *,
211 		    const struct ieee80211_bpf_params *);
212 static int	wpi_transmit(struct ieee80211com *, struct mbuf *);
213 static void	wpi_watchdog_rfkill(void *);
214 static void	wpi_scan_timeout(void *);
215 static void	wpi_tx_timeout(void *);
216 static void	wpi_parent(struct ieee80211com *);
217 static int	wpi_cmd(struct wpi_softc *, uint8_t, const void *, uint16_t,
218 		    int);
219 static int	wpi_mrr_setup(struct wpi_softc *);
220 static int	wpi_add_node(struct wpi_softc *, struct ieee80211_node *);
221 static int	wpi_add_broadcast_node(struct wpi_softc *, int);
222 static int	wpi_add_ibss_node(struct wpi_softc *, struct ieee80211_node *);
223 static void	wpi_del_node(struct wpi_softc *, struct ieee80211_node *);
224 static int	wpi_updateedca(struct ieee80211com *);
225 static void	wpi_set_promisc(struct wpi_softc *);
226 static void	wpi_update_promisc(struct ieee80211com *);
227 static void	wpi_update_mcast(struct ieee80211com *);
228 static void	wpi_set_led(struct wpi_softc *, uint8_t, uint8_t, uint8_t);
229 static int	wpi_set_timing(struct wpi_softc *, struct ieee80211_node *);
230 static void	wpi_power_calibration(struct wpi_softc *);
231 static int	wpi_set_txpower(struct wpi_softc *, int);
232 static int	wpi_get_power_index(struct wpi_softc *,
233 		    struct wpi_power_group *, uint8_t, int, int);
234 static int	wpi_set_pslevel(struct wpi_softc *, uint8_t, int, int);
235 static int	wpi_send_btcoex(struct wpi_softc *);
236 static int	wpi_send_rxon(struct wpi_softc *, int, int);
237 static int	wpi_config(struct wpi_softc *);
238 static uint16_t	wpi_get_active_dwell_time(struct wpi_softc *,
239 		    struct ieee80211_channel *, uint8_t);
240 static uint16_t	wpi_limit_dwell(struct wpi_softc *, uint16_t);
241 static uint16_t	wpi_get_passive_dwell_time(struct wpi_softc *,
242 		    struct ieee80211_channel *);
243 static uint32_t	wpi_get_scan_pause_time(uint32_t, uint16_t);
244 static int	wpi_scan(struct wpi_softc *, struct ieee80211_channel *);
245 static int	wpi_auth(struct wpi_softc *, struct ieee80211vap *);
246 static int	wpi_config_beacon(struct wpi_vap *);
247 static int	wpi_setup_beacon(struct wpi_softc *, struct ieee80211_node *);
248 static void	wpi_update_beacon(struct ieee80211vap *, int);
249 static void	wpi_newassoc(struct ieee80211_node *, int);
250 static int	wpi_run(struct wpi_softc *, struct ieee80211vap *);
251 static int	wpi_load_key(struct ieee80211_node *,
252 		    const struct ieee80211_key *);
253 static void	wpi_load_key_cb(void *, struct ieee80211_node *);
254 static int	wpi_set_global_keys(struct ieee80211_node *);
255 static int	wpi_del_key(struct ieee80211_node *,
256 		    const struct ieee80211_key *);
257 static void	wpi_del_key_cb(void *, struct ieee80211_node *);
258 static int	wpi_process_key(struct ieee80211vap *,
259 		    const struct ieee80211_key *, int);
260 static int	wpi_key_set(struct ieee80211vap *,
261 		    const struct ieee80211_key *);
262 static int	wpi_key_delete(struct ieee80211vap *,
263 		    const struct ieee80211_key *);
264 static int	wpi_post_alive(struct wpi_softc *);
265 static int	wpi_load_bootcode(struct wpi_softc *, const uint8_t *,
266 		    uint32_t);
267 static int	wpi_load_firmware(struct wpi_softc *);
268 static int	wpi_read_firmware(struct wpi_softc *);
269 static void	wpi_unload_firmware(struct wpi_softc *);
270 static int	wpi_clock_wait(struct wpi_softc *);
271 static int	wpi_apm_init(struct wpi_softc *);
272 static void	wpi_apm_stop_master(struct wpi_softc *);
273 static void	wpi_apm_stop(struct wpi_softc *);
274 static void	wpi_nic_config(struct wpi_softc *);
275 static int	wpi_hw_init(struct wpi_softc *);
276 static void	wpi_hw_stop(struct wpi_softc *);
277 static void	wpi_radio_on(void *, int);
278 static void	wpi_radio_off(void *, int);
279 static int	wpi_init(struct wpi_softc *);
280 static void	wpi_stop_locked(struct wpi_softc *);
281 static void	wpi_stop(struct wpi_softc *);
282 static void	wpi_scan_start(struct ieee80211com *);
283 static void	wpi_scan_end(struct ieee80211com *);
284 static void	wpi_set_channel(struct ieee80211com *);
285 static void	wpi_scan_curchan(struct ieee80211_scan_state *, unsigned long);
286 static void	wpi_scan_mindwell(struct ieee80211_scan_state *);
287 
288 static device_method_t wpi_methods[] = {
289 	/* Device interface */
290 	DEVMETHOD(device_probe,		wpi_probe),
291 	DEVMETHOD(device_attach,	wpi_attach),
292 	DEVMETHOD(device_detach,	wpi_detach),
293 	DEVMETHOD(device_shutdown,	wpi_shutdown),
294 	DEVMETHOD(device_suspend,	wpi_suspend),
295 	DEVMETHOD(device_resume,	wpi_resume),
296 
297 	DEVMETHOD_END
298 };
299 
300 static driver_t wpi_driver = {
301 	"wpi",
302 	wpi_methods,
303 	sizeof (struct wpi_softc)
304 };
305 
306 DRIVER_MODULE(wpi, pci, wpi_driver, NULL, NULL);
307 
308 MODULE_VERSION(wpi, 1);
309 
310 MODULE_DEPEND(wpi, pci,  1, 1, 1);
311 MODULE_DEPEND(wpi, wlan, 1, 1, 1);
312 MODULE_DEPEND(wpi, firmware, 1, 1, 1);
313 
314 static int
315 wpi_probe(device_t dev)
316 {
317 	const struct wpi_ident *ident;
318 
319 	for (ident = wpi_ident_table; ident->name != NULL; ident++) {
320 		if (pci_get_vendor(dev) == ident->vendor &&
321 		    pci_get_device(dev) == ident->device) {
322 			device_set_desc(dev, ident->name);
323 			return (BUS_PROBE_DEFAULT);
324 		}
325 	}
326 	return ENXIO;
327 }
328 
329 static int
330 wpi_attach(device_t dev)
331 {
332 	struct wpi_softc *sc = (struct wpi_softc *)device_get_softc(dev);
333 	struct ieee80211com *ic;
334 	uint8_t i;
335 	int error, rid;
336 #ifdef WPI_DEBUG
337 	int supportsa = 1;
338 	const struct wpi_ident *ident;
339 #endif
340 
341 	sc->sc_dev = dev;
342 
343 #ifdef WPI_DEBUG
344 	error = resource_int_value(device_get_name(sc->sc_dev),
345 	    device_get_unit(sc->sc_dev), "debug", &(sc->sc_debug));
346 	if (error != 0)
347 		sc->sc_debug = 0;
348 #else
349 	sc->sc_debug = 0;
350 #endif
351 
352 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
353 
354 	/*
355 	 * Get the offset of the PCI Express Capability Structure in PCI
356 	 * Configuration Space.
357 	 */
358 	error = pci_find_cap(dev, PCIY_EXPRESS, &sc->sc_cap_off);
359 	if (error != 0) {
360 		device_printf(dev, "PCIe capability structure not found!\n");
361 		return error;
362 	}
363 
364 	/*
365 	 * Some card's only support 802.11b/g not a, check to see if
366 	 * this is one such card. A 0x0 in the subdevice table indicates
367 	 * the entire subdevice range is to be ignored.
368 	 */
369 #ifdef WPI_DEBUG
370 	for (ident = wpi_ident_table; ident->name != NULL; ident++) {
371 		if (ident->subdevice &&
372 		    pci_get_subdevice(dev) == ident->subdevice) {
373 		    supportsa = 0;
374 		    break;
375 		}
376 	}
377 #endif
378 
379 	/* Clear device-specific "PCI retry timeout" register (41h). */
380 	pci_write_config(dev, 0x41, 0, 1);
381 
382 	/* Enable bus-mastering. */
383 	pci_enable_busmaster(dev);
384 
385 	rid = PCIR_BAR(0);
386 	sc->mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid,
387 	    RF_ACTIVE);
388 	if (sc->mem == NULL) {
389 		device_printf(dev, "can't map mem space\n");
390 		return ENOMEM;
391 	}
392 	sc->sc_st = rman_get_bustag(sc->mem);
393 	sc->sc_sh = rman_get_bushandle(sc->mem);
394 
395 	rid = 1;
396 	if (pci_alloc_msi(dev, &rid) == 0)
397 		rid = 1;
398 	else
399 		rid = 0;
400 	/* Install interrupt handler. */
401 	sc->irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid, RF_ACTIVE |
402 	    (rid != 0 ? 0 : RF_SHAREABLE));
403 	if (sc->irq == NULL) {
404 		device_printf(dev, "can't map interrupt\n");
405 		error = ENOMEM;
406 		goto fail;
407 	}
408 
409 	WPI_LOCK_INIT(sc);
410 	WPI_TX_LOCK_INIT(sc);
411 	WPI_RXON_LOCK_INIT(sc);
412 	WPI_NT_LOCK_INIT(sc);
413 	WPI_TXQ_LOCK_INIT(sc);
414 	WPI_TXQ_STATE_LOCK_INIT(sc);
415 
416 	/* Allocate DMA memory for firmware transfers. */
417 	if ((error = wpi_alloc_fwmem(sc)) != 0) {
418 		device_printf(dev,
419 		    "could not allocate memory for firmware, error %d\n",
420 		    error);
421 		goto fail;
422 	}
423 
424 	/* Allocate shared page. */
425 	if ((error = wpi_alloc_shared(sc)) != 0) {
426 		device_printf(dev, "could not allocate shared page\n");
427 		goto fail;
428 	}
429 
430 	/* Allocate TX rings - 4 for QoS purposes, 1 for commands. */
431 	for (i = 0; i < WPI_DRV_NTXQUEUES; i++) {
432 		if ((error = wpi_alloc_tx_ring(sc, &sc->txq[i], i)) != 0) {
433 			device_printf(dev,
434 			    "could not allocate TX ring %d, error %d\n", i,
435 			    error);
436 			goto fail;
437 		}
438 	}
439 
440 	/* Allocate RX ring. */
441 	if ((error = wpi_alloc_rx_ring(sc)) != 0) {
442 		device_printf(dev, "could not allocate RX ring, error %d\n",
443 		    error);
444 		goto fail;
445 	}
446 
447 	/* Clear pending interrupts. */
448 	WPI_WRITE(sc, WPI_INT, 0xffffffff);
449 
450 	ic = &sc->sc_ic;
451 	ic->ic_softc = sc;
452 	ic->ic_name = device_get_nameunit(dev);
453 	ic->ic_phytype = IEEE80211_T_OFDM;	/* not only, but not used */
454 	ic->ic_opmode = IEEE80211_M_STA;	/* default to BSS mode */
455 
456 	/* Set device capabilities. */
457 	ic->ic_caps =
458 		  IEEE80211_C_STA		/* station mode supported */
459 		| IEEE80211_C_IBSS		/* IBSS mode supported */
460 		| IEEE80211_C_HOSTAP		/* Host access point mode */
461 		| IEEE80211_C_MONITOR		/* monitor mode supported */
462 		| IEEE80211_C_AHDEMO		/* adhoc demo mode */
463 		| IEEE80211_C_BGSCAN		/* capable of bg scanning */
464 		| IEEE80211_C_TXFRAG		/* handle tx frags */
465 		| IEEE80211_C_TXPMGT		/* tx power management */
466 		| IEEE80211_C_SHSLOT		/* short slot time supported */
467 		| IEEE80211_C_WPA		/* 802.11i */
468 		| IEEE80211_C_SHPREAMBLE	/* short preamble supported */
469 		| IEEE80211_C_WME		/* 802.11e */
470 		| IEEE80211_C_PMGT		/* Station-side power mgmt */
471 		;
472 
473 	ic->ic_cryptocaps =
474 		  IEEE80211_CRYPTO_AES_CCM;
475 
476 	/*
477 	 * Read in the eeprom and also setup the channels for
478 	 * net80211. We don't set the rates as net80211 does this for us
479 	 */
480 	if ((error = wpi_read_eeprom(sc, ic->ic_macaddr)) != 0) {
481 		device_printf(dev, "could not read EEPROM, error %d\n",
482 		    error);
483 		goto fail;
484 	}
485 
486 #ifdef WPI_DEBUG
487 	if (bootverbose) {
488 		device_printf(sc->sc_dev, "Regulatory Domain: %.4s\n",
489 		    sc->domain);
490 		device_printf(sc->sc_dev, "Hardware Type: %c\n",
491 		    sc->type > 1 ? 'B': '?');
492 		device_printf(sc->sc_dev, "Hardware Revision: %c\n",
493 		    ((sc->rev & 0xf0) == 0xd0) ? 'D': '?');
494 		device_printf(sc->sc_dev, "SKU %s support 802.11a\n",
495 		    supportsa ? "does" : "does not");
496 
497 		/* XXX hw_config uses the PCIDEV for the Hardware rev. Must
498 		   check what sc->rev really represents - benjsc 20070615 */
499 	}
500 #endif
501 
502 	ieee80211_ifattach(ic);
503 	ic->ic_vap_create = wpi_vap_create;
504 	ic->ic_vap_delete = wpi_vap_delete;
505 	ic->ic_parent = wpi_parent;
506 	ic->ic_raw_xmit = wpi_raw_xmit;
507 	ic->ic_transmit = wpi_transmit;
508 	ic->ic_node_alloc = wpi_node_alloc;
509 	sc->sc_node_free = ic->ic_node_free;
510 	ic->ic_node_free = wpi_node_free;
511 	ic->ic_wme.wme_update = wpi_updateedca;
512 	ic->ic_update_promisc = wpi_update_promisc;
513 	ic->ic_update_mcast = wpi_update_mcast;
514 	ic->ic_newassoc = wpi_newassoc;
515 	ic->ic_scan_start = wpi_scan_start;
516 	ic->ic_scan_end = wpi_scan_end;
517 	ic->ic_set_channel = wpi_set_channel;
518 	ic->ic_scan_curchan = wpi_scan_curchan;
519 	ic->ic_scan_mindwell = wpi_scan_mindwell;
520 	ic->ic_getradiocaps = wpi_getradiocaps;
521 	ic->ic_setregdomain = wpi_setregdomain;
522 
523 	sc->sc_update_rx_ring = wpi_update_rx_ring;
524 	sc->sc_update_tx_ring = wpi_update_tx_ring;
525 
526 	wpi_radiotap_attach(sc);
527 
528 	/* Setup Tx status flags (constant). */
529 	sc->sc_txs.flags = IEEE80211_RATECTL_STATUS_PKTLEN |
530 	    IEEE80211_RATECTL_STATUS_SHORT_RETRY |
531 	    IEEE80211_RATECTL_STATUS_LONG_RETRY;
532 
533 	callout_init_mtx(&sc->calib_to, &sc->rxon_mtx, 0);
534 	callout_init_mtx(&sc->scan_timeout, &sc->rxon_mtx, 0);
535 	callout_init_mtx(&sc->tx_timeout, &sc->txq_state_mtx, 0);
536 	callout_init_mtx(&sc->watchdog_rfkill, &sc->sc_mtx, 0);
537 	TASK_INIT(&sc->sc_radiooff_task, 0, wpi_radio_off, sc);
538 	TASK_INIT(&sc->sc_radioon_task, 0, wpi_radio_on, sc);
539 
540 	wpi_sysctlattach(sc);
541 
542 	/*
543 	 * Hook our interrupt after all initialization is complete.
544 	 */
545 	error = bus_setup_intr(dev, sc->irq, INTR_TYPE_NET | INTR_MPSAFE,
546 	    NULL, wpi_intr, sc, &sc->sc_ih);
547 	if (error != 0) {
548 		device_printf(dev, "can't establish interrupt, error %d\n",
549 		    error);
550 		goto fail;
551 	}
552 
553 	if (bootverbose)
554 		ieee80211_announce(ic);
555 
556 #ifdef WPI_DEBUG
557 	if (sc->sc_debug & WPI_DEBUG_HW)
558 		ieee80211_announce_channels(ic);
559 #endif
560 
561 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
562 	return 0;
563 
564 fail:	wpi_detach(dev);
565 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR, __func__);
566 	return error;
567 }
568 
569 /*
570  * Attach the interface to 802.11 radiotap.
571  */
572 static void
573 wpi_radiotap_attach(struct wpi_softc *sc)
574 {
575 	struct wpi_rx_radiotap_header *rxtap = &sc->sc_rxtap;
576 	struct wpi_tx_radiotap_header *txtap = &sc->sc_txtap;
577 
578 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
579 	ieee80211_radiotap_attach(&sc->sc_ic,
580 	    &txtap->wt_ihdr, sizeof(*txtap), WPI_TX_RADIOTAP_PRESENT,
581 	    &rxtap->wr_ihdr, sizeof(*rxtap), WPI_RX_RADIOTAP_PRESENT);
582 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
583 }
584 
585 static void
586 wpi_sysctlattach(struct wpi_softc *sc)
587 {
588 #ifdef WPI_DEBUG
589 	struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->sc_dev);
590 	struct sysctl_oid *tree = device_get_sysctl_tree(sc->sc_dev);
591 
592 	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
593 	    "debug", CTLFLAG_RW, &sc->sc_debug, sc->sc_debug,
594 		"control debugging printfs");
595 #endif
596 }
597 
598 static void
599 wpi_init_beacon(struct wpi_vap *wvp)
600 {
601 	struct wpi_buf *bcn = &wvp->wv_bcbuf;
602 	struct wpi_cmd_beacon *cmd = (struct wpi_cmd_beacon *)&bcn->data;
603 
604 	cmd->id = WPI_ID_BROADCAST;
605 	cmd->ofdm_mask = 0xff;
606 	cmd->cck_mask = 0x0f;
607 	cmd->lifetime = htole32(WPI_LIFETIME_INFINITE);
608 
609 	/*
610 	 * XXX WPI_TX_AUTO_SEQ seems to be ignored - workaround this issue
611 	 * XXX by using WPI_TX_NEED_ACK instead (with some side effects).
612 	 */
613 	cmd->flags = htole32(WPI_TX_NEED_ACK | WPI_TX_INSERT_TSTAMP);
614 
615 	bcn->code = WPI_CMD_SET_BEACON;
616 	bcn->ac = WPI_CMD_QUEUE_NUM;
617 	bcn->size = sizeof(struct wpi_cmd_beacon);
618 }
619 
620 static struct ieee80211vap *
621 wpi_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
622     enum ieee80211_opmode opmode, int flags,
623     const uint8_t bssid[IEEE80211_ADDR_LEN],
624     const uint8_t mac[IEEE80211_ADDR_LEN])
625 {
626 	struct wpi_vap *wvp;
627 	struct ieee80211vap *vap;
628 
629 	if (!TAILQ_EMPTY(&ic->ic_vaps))		/* only one at a time */
630 		return NULL;
631 
632 	wvp = malloc(sizeof(struct wpi_vap), M_80211_VAP, M_WAITOK | M_ZERO);
633 	vap = &wvp->wv_vap;
634 	ieee80211_vap_setup(ic, vap, name, unit, opmode, flags, bssid);
635 
636 	if (opmode == IEEE80211_M_IBSS || opmode == IEEE80211_M_HOSTAP) {
637 		WPI_VAP_LOCK_INIT(wvp);
638 		wpi_init_beacon(wvp);
639 	}
640 
641 	/* Override with driver methods. */
642 	vap->iv_key_set = wpi_key_set;
643 	vap->iv_key_delete = wpi_key_delete;
644 	if (opmode == IEEE80211_M_IBSS) {
645 		wvp->wv_recv_mgmt = vap->iv_recv_mgmt;
646 		vap->iv_recv_mgmt = wpi_ibss_recv_mgmt;
647 	}
648 	wvp->wv_newstate = vap->iv_newstate;
649 	vap->iv_newstate = wpi_newstate;
650 	vap->iv_update_beacon = wpi_update_beacon;
651 	vap->iv_max_aid = WPI_ID_IBSS_MAX - WPI_ID_IBSS_MIN + 1;
652 
653 	ieee80211_ratectl_init(vap);
654 	/* Complete setup. */
655 	ieee80211_vap_attach(vap, ieee80211_media_change,
656 	    ieee80211_media_status, mac);
657 	ic->ic_opmode = opmode;
658 	return vap;
659 }
660 
661 static void
662 wpi_vap_delete(struct ieee80211vap *vap)
663 {
664 	struct wpi_vap *wvp = WPI_VAP(vap);
665 	struct wpi_buf *bcn = &wvp->wv_bcbuf;
666 	enum ieee80211_opmode opmode = vap->iv_opmode;
667 
668 	ieee80211_ratectl_deinit(vap);
669 	ieee80211_vap_detach(vap);
670 
671 	if (opmode == IEEE80211_M_IBSS || opmode == IEEE80211_M_HOSTAP) {
672 		if (bcn->m != NULL)
673 			m_freem(bcn->m);
674 
675 		WPI_VAP_LOCK_DESTROY(wvp);
676 	}
677 
678 	free(wvp, M_80211_VAP);
679 }
680 
681 static int
682 wpi_detach(device_t dev)
683 {
684 	struct wpi_softc *sc = device_get_softc(dev);
685 	struct ieee80211com *ic = &sc->sc_ic;
686 	uint8_t qid;
687 
688 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
689 
690 	if (ic->ic_vap_create == wpi_vap_create) {
691 		ieee80211_draintask(ic, &sc->sc_radioon_task);
692 		ieee80211_draintask(ic, &sc->sc_radiooff_task);
693 
694 		wpi_stop(sc);
695 
696 		callout_drain(&sc->watchdog_rfkill);
697 		callout_drain(&sc->tx_timeout);
698 		callout_drain(&sc->scan_timeout);
699 		callout_drain(&sc->calib_to);
700 		ieee80211_ifdetach(ic);
701 	}
702 
703 	/* Uninstall interrupt handler. */
704 	if (sc->irq != NULL) {
705 		bus_teardown_intr(dev, sc->irq, sc->sc_ih);
706 		bus_release_resource(dev, SYS_RES_IRQ, rman_get_rid(sc->irq),
707 		    sc->irq);
708 		pci_release_msi(dev);
709 	}
710 
711 	if (sc->txq[0].data_dmat) {
712 		/* Free DMA resources. */
713 		for (qid = 0; qid < WPI_DRV_NTXQUEUES; qid++)
714 			wpi_free_tx_ring(sc, &sc->txq[qid]);
715 
716 		wpi_free_rx_ring(sc);
717 		wpi_free_shared(sc);
718 	}
719 
720 	if (sc->fw_dma.tag)
721 		wpi_free_fwmem(sc);
722 
723 	if (sc->mem != NULL)
724 		bus_release_resource(dev, SYS_RES_MEMORY,
725 		    rman_get_rid(sc->mem), sc->mem);
726 
727 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
728 	WPI_TXQ_STATE_LOCK_DESTROY(sc);
729 	WPI_TXQ_LOCK_DESTROY(sc);
730 	WPI_NT_LOCK_DESTROY(sc);
731 	WPI_RXON_LOCK_DESTROY(sc);
732 	WPI_TX_LOCK_DESTROY(sc);
733 	WPI_LOCK_DESTROY(sc);
734 	return 0;
735 }
736 
737 static int
738 wpi_shutdown(device_t dev)
739 {
740 	struct wpi_softc *sc = device_get_softc(dev);
741 
742 	wpi_stop(sc);
743 	return 0;
744 }
745 
746 static int
747 wpi_suspend(device_t dev)
748 {
749 	struct wpi_softc *sc = device_get_softc(dev);
750 	struct ieee80211com *ic = &sc->sc_ic;
751 
752 	ieee80211_suspend_all(ic);
753 	return 0;
754 }
755 
756 static int
757 wpi_resume(device_t dev)
758 {
759 	struct wpi_softc *sc = device_get_softc(dev);
760 	struct ieee80211com *ic = &sc->sc_ic;
761 
762 	/* Clear device-specific "PCI retry timeout" register (41h). */
763 	pci_write_config(dev, 0x41, 0, 1);
764 
765 	ieee80211_resume_all(ic);
766 	return 0;
767 }
768 
769 /*
770  * Grab exclusive access to NIC memory.
771  */
772 static int
773 wpi_nic_lock(struct wpi_softc *sc)
774 {
775 	int ntries;
776 
777 	/* Request exclusive access to NIC. */
778 	WPI_SETBITS(sc, WPI_GP_CNTRL, WPI_GP_CNTRL_MAC_ACCESS_REQ);
779 
780 	/* Spin until we actually get the lock. */
781 	for (ntries = 0; ntries < 1000; ntries++) {
782 		if ((WPI_READ(sc, WPI_GP_CNTRL) &
783 		    (WPI_GP_CNTRL_MAC_ACCESS_ENA | WPI_GP_CNTRL_SLEEP)) ==
784 		    WPI_GP_CNTRL_MAC_ACCESS_ENA)
785 			return 0;
786 		DELAY(10);
787 	}
788 
789 	device_printf(sc->sc_dev, "could not lock memory\n");
790 
791 	return ETIMEDOUT;
792 }
793 
794 /*
795  * Release lock on NIC memory.
796  */
797 static __inline void
798 wpi_nic_unlock(struct wpi_softc *sc)
799 {
800 	WPI_CLRBITS(sc, WPI_GP_CNTRL, WPI_GP_CNTRL_MAC_ACCESS_REQ);
801 }
802 
803 static __inline uint32_t
804 wpi_prph_read(struct wpi_softc *sc, uint32_t addr)
805 {
806 	WPI_WRITE(sc, WPI_PRPH_RADDR, WPI_PRPH_DWORD | addr);
807 	WPI_BARRIER_READ_WRITE(sc);
808 	return WPI_READ(sc, WPI_PRPH_RDATA);
809 }
810 
811 static __inline void
812 wpi_prph_write(struct wpi_softc *sc, uint32_t addr, uint32_t data)
813 {
814 	WPI_WRITE(sc, WPI_PRPH_WADDR, WPI_PRPH_DWORD | addr);
815 	WPI_BARRIER_WRITE(sc);
816 	WPI_WRITE(sc, WPI_PRPH_WDATA, data);
817 }
818 
819 static __inline void
820 wpi_prph_setbits(struct wpi_softc *sc, uint32_t addr, uint32_t mask)
821 {
822 	wpi_prph_write(sc, addr, wpi_prph_read(sc, addr) | mask);
823 }
824 
825 static __inline void
826 wpi_prph_clrbits(struct wpi_softc *sc, uint32_t addr, uint32_t mask)
827 {
828 	wpi_prph_write(sc, addr, wpi_prph_read(sc, addr) & ~mask);
829 }
830 
831 static __inline void
832 wpi_prph_write_region_4(struct wpi_softc *sc, uint32_t addr,
833     const uint32_t *data, uint32_t count)
834 {
835 	for (; count != 0; count--, data++, addr += 4)
836 		wpi_prph_write(sc, addr, *data);
837 }
838 
839 static __inline uint32_t
840 wpi_mem_read(struct wpi_softc *sc, uint32_t addr)
841 {
842 	WPI_WRITE(sc, WPI_MEM_RADDR, addr);
843 	WPI_BARRIER_READ_WRITE(sc);
844 	return WPI_READ(sc, WPI_MEM_RDATA);
845 }
846 
847 static __inline void
848 wpi_mem_read_region_4(struct wpi_softc *sc, uint32_t addr, uint32_t *data,
849     int count)
850 {
851 	for (; count > 0; count--, addr += 4)
852 		*data++ = wpi_mem_read(sc, addr);
853 }
854 
855 static int
856 wpi_read_prom_data(struct wpi_softc *sc, uint32_t addr, void *data, int count)
857 {
858 	uint8_t *out = data;
859 	uint32_t val;
860 	int error, ntries;
861 
862 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
863 
864 	if ((error = wpi_nic_lock(sc)) != 0)
865 		return error;
866 
867 	for (; count > 0; count -= 2, addr++) {
868 		WPI_WRITE(sc, WPI_EEPROM, addr << 2);
869 		for (ntries = 0; ntries < 10; ntries++) {
870 			val = WPI_READ(sc, WPI_EEPROM);
871 			if (val & WPI_EEPROM_READ_VALID)
872 				break;
873 			DELAY(5);
874 		}
875 		if (ntries == 10) {
876 			device_printf(sc->sc_dev,
877 			    "timeout reading ROM at 0x%x\n", addr);
878 			return ETIMEDOUT;
879 		}
880 		*out++= val >> 16;
881 		if (count > 1)
882 			*out ++= val >> 24;
883 	}
884 
885 	wpi_nic_unlock(sc);
886 
887 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
888 
889 	return 0;
890 }
891 
892 static void
893 wpi_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
894 {
895 	if (error != 0)
896 		return;
897 	KASSERT(nsegs == 1, ("too many DMA segments, %d should be 1", nsegs));
898 	*(bus_addr_t *)arg = segs[0].ds_addr;
899 }
900 
901 /*
902  * Allocates a contiguous block of dma memory of the requested size and
903  * alignment.
904  */
905 static int
906 wpi_dma_contig_alloc(struct wpi_softc *sc, struct wpi_dma_info *dma,
907     void **kvap, bus_size_t size, bus_size_t alignment)
908 {
909 	int error;
910 
911 	dma->tag = NULL;
912 	dma->size = size;
913 
914 	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), alignment,
915 	    0, BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, size,
916 	    1, size, 0, NULL, NULL, &dma->tag);
917 	if (error != 0)
918 		goto fail;
919 
920 	error = bus_dmamem_alloc(dma->tag, (void **)&dma->vaddr,
921 	    BUS_DMA_NOWAIT | BUS_DMA_ZERO | BUS_DMA_COHERENT, &dma->map);
922 	if (error != 0)
923 		goto fail;
924 
925 	error = bus_dmamap_load(dma->tag, dma->map, dma->vaddr, size,
926 	    wpi_dma_map_addr, &dma->paddr, BUS_DMA_NOWAIT);
927 	if (error != 0)
928 		goto fail;
929 
930 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
931 
932 	if (kvap != NULL)
933 		*kvap = dma->vaddr;
934 
935 	return 0;
936 
937 fail:	wpi_dma_contig_free(dma);
938 	return error;
939 }
940 
941 static void
942 wpi_dma_contig_free(struct wpi_dma_info *dma)
943 {
944 	if (dma->vaddr != NULL) {
945 		bus_dmamap_sync(dma->tag, dma->map,
946 		    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
947 		bus_dmamap_unload(dma->tag, dma->map);
948 		bus_dmamem_free(dma->tag, dma->vaddr, dma->map);
949 		dma->vaddr = NULL;
950 	}
951 	if (dma->tag != NULL) {
952 		bus_dma_tag_destroy(dma->tag);
953 		dma->tag = NULL;
954 	}
955 }
956 
957 /*
958  * Allocate a shared page between host and NIC.
959  */
960 static int
961 wpi_alloc_shared(struct wpi_softc *sc)
962 {
963 	/* Shared buffer must be aligned on a 4KB boundary. */
964 	return wpi_dma_contig_alloc(sc, &sc->shared_dma,
965 	    (void **)&sc->shared, sizeof (struct wpi_shared), 4096);
966 }
967 
968 static void
969 wpi_free_shared(struct wpi_softc *sc)
970 {
971 	wpi_dma_contig_free(&sc->shared_dma);
972 }
973 
974 /*
975  * Allocate DMA-safe memory for firmware transfer.
976  */
977 static int
978 wpi_alloc_fwmem(struct wpi_softc *sc)
979 {
980 	/* Must be aligned on a 16-byte boundary. */
981 	return wpi_dma_contig_alloc(sc, &sc->fw_dma, NULL,
982 	    WPI_FW_TEXT_MAXSZ + WPI_FW_DATA_MAXSZ, 16);
983 }
984 
985 static void
986 wpi_free_fwmem(struct wpi_softc *sc)
987 {
988 	wpi_dma_contig_free(&sc->fw_dma);
989 }
990 
991 static int
992 wpi_alloc_rx_ring(struct wpi_softc *sc)
993 {
994 	struct wpi_rx_ring *ring = &sc->rxq;
995 	bus_size_t size;
996 	int i, error;
997 
998 	ring->cur = 0;
999 	ring->update = 0;
1000 
1001 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
1002 
1003 	/* Allocate RX descriptors (16KB aligned.) */
1004 	size = WPI_RX_RING_COUNT * sizeof (uint32_t);
1005 	error = wpi_dma_contig_alloc(sc, &ring->desc_dma,
1006 	    (void **)&ring->desc, size, WPI_RING_DMA_ALIGN);
1007 	if (error != 0) {
1008 		device_printf(sc->sc_dev,
1009 		    "%s: could not allocate RX ring DMA memory, error %d\n",
1010 		    __func__, error);
1011 		goto fail;
1012 	}
1013 
1014 	/* Create RX buffer DMA tag. */
1015 	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 1, 0,
1016 	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
1017 	    MJUMPAGESIZE, 1, MJUMPAGESIZE, 0, NULL, NULL, &ring->data_dmat);
1018 	if (error != 0) {
1019 		device_printf(sc->sc_dev,
1020 		    "%s: could not create RX buf DMA tag, error %d\n",
1021 		    __func__, error);
1022 		goto fail;
1023 	}
1024 
1025 	/*
1026 	 * Allocate and map RX buffers.
1027 	 */
1028 	for (i = 0; i < WPI_RX_RING_COUNT; i++) {
1029 		struct wpi_rx_data *data = &ring->data[i];
1030 		bus_addr_t paddr;
1031 
1032 		error = bus_dmamap_create(ring->data_dmat, 0, &data->map);
1033 		if (error != 0) {
1034 			device_printf(sc->sc_dev,
1035 			    "%s: could not create RX buf DMA map, error %d\n",
1036 			    __func__, error);
1037 			goto fail;
1038 		}
1039 
1040 		data->m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, MJUMPAGESIZE);
1041 		if (data->m == NULL) {
1042 			device_printf(sc->sc_dev,
1043 			    "%s: could not allocate RX mbuf\n", __func__);
1044 			error = ENOBUFS;
1045 			goto fail;
1046 		}
1047 
1048 		error = bus_dmamap_load(ring->data_dmat, data->map,
1049 		    mtod(data->m, void *), MJUMPAGESIZE, wpi_dma_map_addr,
1050 		    &paddr, BUS_DMA_NOWAIT);
1051 		if (error != 0 && error != EFBIG) {
1052 			device_printf(sc->sc_dev,
1053 			    "%s: can't map mbuf (error %d)\n", __func__,
1054 			    error);
1055 			goto fail;
1056 		}
1057 
1058 		/* Set physical address of RX buffer. */
1059 		ring->desc[i] = htole32(paddr);
1060 	}
1061 
1062 	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
1063 	    BUS_DMASYNC_PREWRITE);
1064 
1065 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
1066 
1067 	return 0;
1068 
1069 fail:	wpi_free_rx_ring(sc);
1070 
1071 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR, __func__);
1072 
1073 	return error;
1074 }
1075 
1076 static void
1077 wpi_update_rx_ring(struct wpi_softc *sc)
1078 {
1079 	WPI_WRITE(sc, WPI_FH_RX_WPTR, sc->rxq.cur & ~7);
1080 }
1081 
1082 static void
1083 wpi_update_rx_ring_ps(struct wpi_softc *sc)
1084 {
1085 	struct wpi_rx_ring *ring = &sc->rxq;
1086 
1087 	if (ring->update != 0) {
1088 		/* Wait for INT_WAKEUP event. */
1089 		return;
1090 	}
1091 
1092 	WPI_TXQ_LOCK(sc);
1093 	WPI_SETBITS(sc, WPI_GP_CNTRL, WPI_GP_CNTRL_MAC_ACCESS_REQ);
1094 	if (WPI_READ(sc, WPI_GP_CNTRL) & WPI_GP_CNTRL_SLEEP) {
1095 		DPRINTF(sc, WPI_DEBUG_PWRSAVE, "%s: wakeup request\n",
1096 		    __func__);
1097 		ring->update = 1;
1098 	} else {
1099 		wpi_update_rx_ring(sc);
1100 		WPI_CLRBITS(sc, WPI_GP_CNTRL, WPI_GP_CNTRL_MAC_ACCESS_REQ);
1101 	}
1102 	WPI_TXQ_UNLOCK(sc);
1103 }
1104 
1105 static void
1106 wpi_reset_rx_ring(struct wpi_softc *sc)
1107 {
1108 	struct wpi_rx_ring *ring = &sc->rxq;
1109 	int ntries;
1110 
1111 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
1112 
1113 	if (wpi_nic_lock(sc) == 0) {
1114 		WPI_WRITE(sc, WPI_FH_RX_CONFIG, 0);
1115 		for (ntries = 0; ntries < 1000; ntries++) {
1116 			if (WPI_READ(sc, WPI_FH_RX_STATUS) &
1117 			    WPI_FH_RX_STATUS_IDLE)
1118 				break;
1119 			DELAY(10);
1120 		}
1121 		wpi_nic_unlock(sc);
1122 	}
1123 
1124 	ring->cur = 0;
1125 	ring->update = 0;
1126 }
1127 
1128 static void
1129 wpi_free_rx_ring(struct wpi_softc *sc)
1130 {
1131 	struct wpi_rx_ring *ring = &sc->rxq;
1132 	int i;
1133 
1134 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
1135 
1136 	wpi_dma_contig_free(&ring->desc_dma);
1137 
1138 	for (i = 0; i < WPI_RX_RING_COUNT; i++) {
1139 		struct wpi_rx_data *data = &ring->data[i];
1140 
1141 		if (data->m != NULL) {
1142 			bus_dmamap_sync(ring->data_dmat, data->map,
1143 			    BUS_DMASYNC_POSTREAD);
1144 			bus_dmamap_unload(ring->data_dmat, data->map);
1145 			m_freem(data->m);
1146 			data->m = NULL;
1147 		}
1148 		if (data->map != NULL)
1149 			bus_dmamap_destroy(ring->data_dmat, data->map);
1150 	}
1151 	if (ring->data_dmat != NULL) {
1152 		bus_dma_tag_destroy(ring->data_dmat);
1153 		ring->data_dmat = NULL;
1154 	}
1155 }
1156 
1157 static int
1158 wpi_alloc_tx_ring(struct wpi_softc *sc, struct wpi_tx_ring *ring, uint8_t qid)
1159 {
1160 	bus_addr_t paddr;
1161 	bus_size_t size;
1162 	int i, error;
1163 
1164 	ring->qid = qid;
1165 	ring->queued = 0;
1166 	ring->cur = 0;
1167 	ring->pending = 0;
1168 	ring->update = 0;
1169 
1170 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
1171 
1172 	/* Allocate TX descriptors (16KB aligned.) */
1173 	size = WPI_TX_RING_COUNT * sizeof (struct wpi_tx_desc);
1174 	error = wpi_dma_contig_alloc(sc, &ring->desc_dma, (void **)&ring->desc,
1175 	    size, WPI_RING_DMA_ALIGN);
1176 	if (error != 0) {
1177 		device_printf(sc->sc_dev,
1178 		    "%s: could not allocate TX ring DMA memory, error %d\n",
1179 		    __func__, error);
1180 		goto fail;
1181 	}
1182 
1183 	/* Update shared area with ring physical address. */
1184 	sc->shared->txbase[qid] = htole32(ring->desc_dma.paddr);
1185 	bus_dmamap_sync(sc->shared_dma.tag, sc->shared_dma.map,
1186 	    BUS_DMASYNC_PREWRITE);
1187 
1188 	size = WPI_TX_RING_COUNT * sizeof (struct wpi_tx_cmd);
1189 	error = wpi_dma_contig_alloc(sc, &ring->cmd_dma, (void **)&ring->cmd,
1190 	    size, 4);
1191 	if (error != 0) {
1192 		device_printf(sc->sc_dev,
1193 		    "%s: could not allocate TX cmd DMA memory, error %d\n",
1194 		    __func__, error);
1195 		goto fail;
1196 	}
1197 
1198 	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 1, 0,
1199 	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES,
1200 	    WPI_MAX_SCATTER - 1, MCLBYTES, 0, NULL, NULL, &ring->data_dmat);
1201 	if (error != 0) {
1202 		device_printf(sc->sc_dev,
1203 		    "%s: could not create TX buf DMA tag, error %d\n",
1204 		    __func__, error);
1205 		goto fail;
1206 	}
1207 
1208 	paddr = ring->cmd_dma.paddr;
1209 	for (i = 0; i < WPI_TX_RING_COUNT; i++) {
1210 		struct wpi_tx_data *data = &ring->data[i];
1211 
1212 		data->cmd_paddr = paddr;
1213 		paddr += sizeof (struct wpi_tx_cmd);
1214 
1215 		error = bus_dmamap_create(ring->data_dmat, 0, &data->map);
1216 		if (error != 0) {
1217 			device_printf(sc->sc_dev,
1218 			    "%s: could not create TX buf DMA map, error %d\n",
1219 			    __func__, error);
1220 			goto fail;
1221 		}
1222 	}
1223 
1224 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
1225 
1226 	return 0;
1227 
1228 fail:	wpi_free_tx_ring(sc, ring);
1229 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR, __func__);
1230 	return error;
1231 }
1232 
1233 static void
1234 wpi_update_tx_ring(struct wpi_softc *sc, struct wpi_tx_ring *ring)
1235 {
1236 	WPI_WRITE(sc, WPI_HBUS_TARG_WRPTR, ring->qid << 8 | ring->cur);
1237 }
1238 
1239 static void
1240 wpi_update_tx_ring_ps(struct wpi_softc *sc, struct wpi_tx_ring *ring)
1241 {
1242 
1243 	if (ring->update != 0) {
1244 		/* Wait for INT_WAKEUP event. */
1245 		return;
1246 	}
1247 
1248 	WPI_SETBITS(sc, WPI_GP_CNTRL, WPI_GP_CNTRL_MAC_ACCESS_REQ);
1249 	if (WPI_READ(sc, WPI_GP_CNTRL) & WPI_GP_CNTRL_SLEEP) {
1250 		DPRINTF(sc, WPI_DEBUG_PWRSAVE, "%s (%d): requesting wakeup\n",
1251 		    __func__, ring->qid);
1252 		ring->update = 1;
1253 	} else {
1254 		wpi_update_tx_ring(sc, ring);
1255 		WPI_CLRBITS(sc, WPI_GP_CNTRL, WPI_GP_CNTRL_MAC_ACCESS_REQ);
1256 	}
1257 }
1258 
1259 static void
1260 wpi_reset_tx_ring(struct wpi_softc *sc, struct wpi_tx_ring *ring)
1261 {
1262 	int i;
1263 
1264 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
1265 
1266 	for (i = 0; i < WPI_TX_RING_COUNT; i++) {
1267 		struct wpi_tx_data *data = &ring->data[i];
1268 
1269 		if (data->m != NULL) {
1270 			bus_dmamap_sync(ring->data_dmat, data->map,
1271 			    BUS_DMASYNC_POSTWRITE);
1272 			bus_dmamap_unload(ring->data_dmat, data->map);
1273 			m_freem(data->m);
1274 			data->m = NULL;
1275 		}
1276 		if (data->ni != NULL) {
1277 			ieee80211_free_node(data->ni);
1278 			data->ni = NULL;
1279 		}
1280 	}
1281 	/* Clear TX descriptors. */
1282 	memset(ring->desc, 0, ring->desc_dma.size);
1283 	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
1284 	    BUS_DMASYNC_PREWRITE);
1285 	ring->queued = 0;
1286 	ring->cur = 0;
1287 	ring->pending = 0;
1288 	ring->update = 0;
1289 }
1290 
1291 static void
1292 wpi_free_tx_ring(struct wpi_softc *sc, struct wpi_tx_ring *ring)
1293 {
1294 	int i;
1295 
1296 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
1297 
1298 	wpi_dma_contig_free(&ring->desc_dma);
1299 	wpi_dma_contig_free(&ring->cmd_dma);
1300 
1301 	for (i = 0; i < WPI_TX_RING_COUNT; i++) {
1302 		struct wpi_tx_data *data = &ring->data[i];
1303 
1304 		if (data->m != NULL) {
1305 			bus_dmamap_sync(ring->data_dmat, data->map,
1306 			    BUS_DMASYNC_POSTWRITE);
1307 			bus_dmamap_unload(ring->data_dmat, data->map);
1308 			m_freem(data->m);
1309 		}
1310 		if (data->map != NULL)
1311 			bus_dmamap_destroy(ring->data_dmat, data->map);
1312 	}
1313 	if (ring->data_dmat != NULL) {
1314 		bus_dma_tag_destroy(ring->data_dmat);
1315 		ring->data_dmat = NULL;
1316 	}
1317 }
1318 
1319 /*
1320  * Extract various information from EEPROM.
1321  */
1322 static int
1323 wpi_read_eeprom(struct wpi_softc *sc, uint8_t macaddr[IEEE80211_ADDR_LEN])
1324 {
1325 #define WPI_CHK(res) do {		\
1326 	if ((error = res) != 0)		\
1327 		goto fail;		\
1328 } while (0)
1329 	uint8_t i;
1330 	int error;
1331 
1332 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
1333 
1334 	/* Adapter has to be powered on for EEPROM access to work. */
1335 	if ((error = wpi_apm_init(sc)) != 0) {
1336 		device_printf(sc->sc_dev,
1337 		    "%s: could not power ON adapter, error %d\n", __func__,
1338 		    error);
1339 		return error;
1340 	}
1341 
1342 	if ((WPI_READ(sc, WPI_EEPROM_GP) & 0x6) == 0) {
1343 		device_printf(sc->sc_dev, "bad EEPROM signature\n");
1344 		error = EIO;
1345 		goto fail;
1346 	}
1347 	/* Clear HW ownership of EEPROM. */
1348 	WPI_CLRBITS(sc, WPI_EEPROM_GP, WPI_EEPROM_GP_IF_OWNER);
1349 
1350 	/* Read the hardware capabilities, revision and SKU type. */
1351 	WPI_CHK(wpi_read_prom_data(sc, WPI_EEPROM_SKU_CAP, &sc->cap,
1352 	    sizeof(sc->cap)));
1353 	WPI_CHK(wpi_read_prom_data(sc, WPI_EEPROM_REVISION, &sc->rev,
1354 	    sizeof(sc->rev)));
1355 	WPI_CHK(wpi_read_prom_data(sc, WPI_EEPROM_TYPE, &sc->type,
1356 	    sizeof(sc->type)));
1357 
1358 	sc->rev = le16toh(sc->rev);
1359 	DPRINTF(sc, WPI_DEBUG_EEPROM, "cap=%x rev=%x type=%x\n", sc->cap,
1360 	    sc->rev, sc->type);
1361 
1362 	/* Read the regulatory domain (4 ASCII characters.) */
1363 	WPI_CHK(wpi_read_prom_data(sc, WPI_EEPROM_DOMAIN, sc->domain,
1364 	    sizeof(sc->domain)));
1365 
1366 	/* Read MAC address. */
1367 	WPI_CHK(wpi_read_prom_data(sc, WPI_EEPROM_MAC, macaddr,
1368 	    IEEE80211_ADDR_LEN));
1369 
1370 	/* Read the list of authorized channels. */
1371 	for (i = 0; i < WPI_CHAN_BANDS_COUNT; i++)
1372 		WPI_CHK(wpi_read_eeprom_channels(sc, i));
1373 
1374 	/* Read the list of TX power groups. */
1375 	for (i = 0; i < WPI_POWER_GROUPS_COUNT; i++)
1376 		WPI_CHK(wpi_read_eeprom_group(sc, i));
1377 
1378 fail:	wpi_apm_stop(sc);	/* Power OFF adapter. */
1379 
1380 	DPRINTF(sc, WPI_DEBUG_TRACE, error ? TRACE_STR_END_ERR : TRACE_STR_END,
1381 	    __func__);
1382 
1383 	return error;
1384 #undef WPI_CHK
1385 }
1386 
1387 /*
1388  * Translate EEPROM flags to net80211.
1389  */
1390 static uint32_t
1391 wpi_eeprom_channel_flags(struct wpi_eeprom_chan *channel)
1392 {
1393 	uint32_t nflags;
1394 
1395 	nflags = 0;
1396 	if ((channel->flags & WPI_EEPROM_CHAN_ACTIVE) == 0)
1397 		nflags |= IEEE80211_CHAN_PASSIVE;
1398 	if ((channel->flags & WPI_EEPROM_CHAN_IBSS) == 0)
1399 		nflags |= IEEE80211_CHAN_NOADHOC;
1400 	if (channel->flags & WPI_EEPROM_CHAN_RADAR) {
1401 		nflags |= IEEE80211_CHAN_DFS;
1402 		/* XXX apparently IBSS may still be marked */
1403 		nflags |= IEEE80211_CHAN_NOADHOC;
1404 	}
1405 
1406 	/* XXX HOSTAP uses WPI_MODE_IBSS */
1407 	if (nflags & IEEE80211_CHAN_NOADHOC)
1408 		nflags |= IEEE80211_CHAN_NOHOSTAP;
1409 
1410 	return nflags;
1411 }
1412 
1413 static void
1414 wpi_read_eeprom_band(struct wpi_softc *sc, uint8_t n, int maxchans,
1415     int *nchans, struct ieee80211_channel chans[])
1416 {
1417 	struct wpi_eeprom_chan *channels = sc->eeprom_channels[n];
1418 	const struct wpi_chan_band *band = &wpi_bands[n];
1419 	uint32_t nflags;
1420 	uint8_t bands[IEEE80211_MODE_BYTES];
1421 	uint8_t chan, i;
1422 	int error;
1423 
1424 	memset(bands, 0, sizeof(bands));
1425 
1426 	if (n == 0) {
1427 		setbit(bands, IEEE80211_MODE_11B);
1428 		setbit(bands, IEEE80211_MODE_11G);
1429 	} else
1430 		setbit(bands, IEEE80211_MODE_11A);
1431 
1432 	for (i = 0; i < band->nchan; i++) {
1433 		if (!(channels[i].flags & WPI_EEPROM_CHAN_VALID)) {
1434 			DPRINTF(sc, WPI_DEBUG_EEPROM,
1435 			    "Channel Not Valid: %d, band %d\n",
1436 			     band->chan[i],n);
1437 			continue;
1438 		}
1439 
1440 		chan = band->chan[i];
1441 		nflags = wpi_eeprom_channel_flags(&channels[i]);
1442 		error = ieee80211_add_channel(chans, maxchans, nchans,
1443 		    chan, 0, channels[i].maxpwr, nflags, bands);
1444 		if (error != 0)
1445 			break;
1446 
1447 		/* Save maximum allowed TX power for this channel. */
1448 		sc->maxpwr[chan] = channels[i].maxpwr;
1449 
1450 		DPRINTF(sc, WPI_DEBUG_EEPROM,
1451 		    "adding chan %d flags=0x%x maxpwr=%d, offset %d\n",
1452 		    chan, channels[i].flags, sc->maxpwr[chan], *nchans);
1453 	}
1454 }
1455 
1456 /**
1457  * Read the eeprom to find out what channels are valid for the given
1458  * band and update net80211 with what we find.
1459  */
1460 static int
1461 wpi_read_eeprom_channels(struct wpi_softc *sc, uint8_t n)
1462 {
1463 	struct ieee80211com *ic = &sc->sc_ic;
1464 	const struct wpi_chan_band *band = &wpi_bands[n];
1465 	int error;
1466 
1467 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
1468 
1469 	error = wpi_read_prom_data(sc, band->addr, &sc->eeprom_channels[n],
1470 	    band->nchan * sizeof (struct wpi_eeprom_chan));
1471 	if (error != 0) {
1472 		DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR, __func__);
1473 		return error;
1474 	}
1475 
1476 	wpi_read_eeprom_band(sc, n, IEEE80211_CHAN_MAX, &ic->ic_nchans,
1477 	    ic->ic_channels);
1478 
1479 	ieee80211_sort_channels(ic->ic_channels, ic->ic_nchans);
1480 
1481 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
1482 
1483 	return 0;
1484 }
1485 
1486 static struct wpi_eeprom_chan *
1487 wpi_find_eeprom_channel(struct wpi_softc *sc, struct ieee80211_channel *c)
1488 {
1489 	int i, j;
1490 
1491 	for (j = 0; j < WPI_CHAN_BANDS_COUNT; j++)
1492 		for (i = 0; i < wpi_bands[j].nchan; i++)
1493 			if (wpi_bands[j].chan[i] == c->ic_ieee &&
1494 			    ((j == 0) ^ IEEE80211_IS_CHAN_A(c)) == 1)
1495 				return &sc->eeprom_channels[j][i];
1496 
1497 	return NULL;
1498 }
1499 
1500 static void
1501 wpi_getradiocaps(struct ieee80211com *ic,
1502     int maxchans, int *nchans, struct ieee80211_channel chans[])
1503 {
1504 	struct wpi_softc *sc = ic->ic_softc;
1505 	int i;
1506 
1507 	/* Parse the list of authorized channels. */
1508 	for (i = 0; i < WPI_CHAN_BANDS_COUNT && *nchans < maxchans; i++)
1509 		wpi_read_eeprom_band(sc, i, maxchans, nchans, chans);
1510 }
1511 
1512 /*
1513  * Enforce flags read from EEPROM.
1514  */
1515 static int
1516 wpi_setregdomain(struct ieee80211com *ic, struct ieee80211_regdomain *rd,
1517     int nchan, struct ieee80211_channel chans[])
1518 {
1519 	struct wpi_softc *sc = ic->ic_softc;
1520 	int i;
1521 
1522 	for (i = 0; i < nchan; i++) {
1523 		struct ieee80211_channel *c = &chans[i];
1524 		struct wpi_eeprom_chan *channel;
1525 
1526 		channel = wpi_find_eeprom_channel(sc, c);
1527 		if (channel == NULL) {
1528 			ic_printf(ic, "%s: invalid channel %u freq %u/0x%x\n",
1529 			    __func__, c->ic_ieee, c->ic_freq, c->ic_flags);
1530 			return EINVAL;
1531 		}
1532 		c->ic_flags |= wpi_eeprom_channel_flags(channel);
1533 	}
1534 
1535 	return 0;
1536 }
1537 
1538 static int
1539 wpi_read_eeprom_group(struct wpi_softc *sc, uint8_t n)
1540 {
1541 	struct wpi_power_group *group = &sc->groups[n];
1542 	struct wpi_eeprom_group rgroup;
1543 	int i, error;
1544 
1545 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
1546 
1547 	if ((error = wpi_read_prom_data(sc, WPI_EEPROM_POWER_GRP + n * 32,
1548 	    &rgroup, sizeof rgroup)) != 0) {
1549 		DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR, __func__);
1550 		return error;
1551 	}
1552 
1553 	/* Save TX power group information. */
1554 	group->chan   = rgroup.chan;
1555 	group->maxpwr = rgroup.maxpwr;
1556 	/* Retrieve temperature at which the samples were taken. */
1557 	group->temp   = (int16_t)le16toh(rgroup.temp);
1558 
1559 	DPRINTF(sc, WPI_DEBUG_EEPROM,
1560 	    "power group %d: chan=%d maxpwr=%d temp=%d\n", n, group->chan,
1561 	    group->maxpwr, group->temp);
1562 
1563 	for (i = 0; i < WPI_SAMPLES_COUNT; i++) {
1564 		group->samples[i].index = rgroup.samples[i].index;
1565 		group->samples[i].power = rgroup.samples[i].power;
1566 
1567 		DPRINTF(sc, WPI_DEBUG_EEPROM,
1568 		    "\tsample %d: index=%d power=%d\n", i,
1569 		    group->samples[i].index, group->samples[i].power);
1570 	}
1571 
1572 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
1573 
1574 	return 0;
1575 }
1576 
1577 static __inline uint8_t
1578 wpi_add_node_entry_adhoc(struct wpi_softc *sc)
1579 {
1580 	uint8_t newid = WPI_ID_IBSS_MIN;
1581 
1582 	for (; newid <= WPI_ID_IBSS_MAX; newid++) {
1583 		if ((sc->nodesmsk & (1 << newid)) == 0) {
1584 			sc->nodesmsk |= 1 << newid;
1585 			return newid;
1586 		}
1587 	}
1588 
1589 	return WPI_ID_UNDEFINED;
1590 }
1591 
1592 static __inline uint8_t
1593 wpi_add_node_entry_sta(struct wpi_softc *sc)
1594 {
1595 	sc->nodesmsk |= 1 << WPI_ID_BSS;
1596 
1597 	return WPI_ID_BSS;
1598 }
1599 
1600 static __inline int
1601 wpi_check_node_entry(struct wpi_softc *sc, uint8_t id)
1602 {
1603 	if (id == WPI_ID_UNDEFINED)
1604 		return 0;
1605 
1606 	return (sc->nodesmsk >> id) & 1;
1607 }
1608 
1609 static __inline void
1610 wpi_clear_node_table(struct wpi_softc *sc)
1611 {
1612 	sc->nodesmsk = 0;
1613 }
1614 
1615 static __inline void
1616 wpi_del_node_entry(struct wpi_softc *sc, uint8_t id)
1617 {
1618 	sc->nodesmsk &= ~(1 << id);
1619 }
1620 
1621 static struct ieee80211_node *
1622 wpi_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
1623 {
1624 	struct wpi_node *wn;
1625 
1626 	wn = malloc(sizeof (struct wpi_node), M_80211_NODE,
1627 	    M_NOWAIT | M_ZERO);
1628 
1629 	if (wn == NULL)
1630 		return NULL;
1631 
1632 	wn->id = WPI_ID_UNDEFINED;
1633 
1634 	return &wn->ni;
1635 }
1636 
1637 static void
1638 wpi_node_free(struct ieee80211_node *ni)
1639 {
1640 	struct wpi_softc *sc = ni->ni_ic->ic_softc;
1641 	struct wpi_node *wn = WPI_NODE(ni);
1642 
1643 	if (wn->id != WPI_ID_UNDEFINED) {
1644 		WPI_NT_LOCK(sc);
1645 		if (wpi_check_node_entry(sc, wn->id)) {
1646 			wpi_del_node_entry(sc, wn->id);
1647 			wpi_del_node(sc, ni);
1648 		}
1649 		WPI_NT_UNLOCK(sc);
1650 	}
1651 
1652 	sc->sc_node_free(ni);
1653 }
1654 
1655 static __inline int
1656 wpi_check_bss_filter(struct wpi_softc *sc)
1657 {
1658 	return (sc->rxon.filter & htole32(WPI_FILTER_BSS)) != 0;
1659 }
1660 
1661 static void
1662 wpi_ibss_recv_mgmt(struct ieee80211_node *ni, struct mbuf *m, int subtype,
1663     const struct ieee80211_rx_stats *rxs,
1664     int rssi, int nf)
1665 {
1666 	struct ieee80211vap *vap = ni->ni_vap;
1667 	struct wpi_softc *sc = vap->iv_ic->ic_softc;
1668 	struct wpi_vap *wvp = WPI_VAP(vap);
1669 	uint64_t ni_tstamp, rx_tstamp;
1670 
1671 	wvp->wv_recv_mgmt(ni, m, subtype, rxs, rssi, nf);
1672 
1673 	if (vap->iv_state == IEEE80211_S_RUN &&
1674 	    (subtype == IEEE80211_FC0_SUBTYPE_BEACON ||
1675 	    subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)) {
1676 		ni_tstamp = le64toh(ni->ni_tstamp.tsf);
1677 		rx_tstamp = le64toh(sc->rx_tstamp);
1678 
1679 		if (ni_tstamp >= rx_tstamp) {
1680 			DPRINTF(sc, WPI_DEBUG_STATE,
1681 			    "ibss merge, tsf %ju tstamp %ju\n",
1682 			    (uintmax_t)rx_tstamp, (uintmax_t)ni_tstamp);
1683 			(void) ieee80211_ibss_merge(ni);
1684 		}
1685 	}
1686 }
1687 
1688 static void
1689 wpi_restore_node(void *arg, struct ieee80211_node *ni)
1690 {
1691 	struct wpi_softc *sc = arg;
1692 	struct wpi_node *wn = WPI_NODE(ni);
1693 	int error;
1694 
1695 	WPI_NT_LOCK(sc);
1696 	if (wn->id != WPI_ID_UNDEFINED) {
1697 		wn->id = WPI_ID_UNDEFINED;
1698 		if ((error = wpi_add_ibss_node(sc, ni)) != 0) {
1699 			device_printf(sc->sc_dev,
1700 			    "%s: could not add IBSS node, error %d\n",
1701 			    __func__, error);
1702 		}
1703 	}
1704 	WPI_NT_UNLOCK(sc);
1705 }
1706 
1707 static void
1708 wpi_restore_node_table(struct wpi_softc *sc, struct wpi_vap *wvp)
1709 {
1710 	struct ieee80211com *ic = &sc->sc_ic;
1711 
1712 	/* Set group keys once. */
1713 	WPI_NT_LOCK(sc);
1714 	wvp->wv_gtk = 0;
1715 	WPI_NT_UNLOCK(sc);
1716 
1717 	ieee80211_iterate_nodes(&ic->ic_sta, wpi_restore_node, sc);
1718 	ieee80211_crypto_reload_keys(ic);
1719 }
1720 
1721 /**
1722  * Called by net80211 when ever there is a change to 80211 state machine
1723  */
1724 static int
1725 wpi_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
1726 {
1727 	struct wpi_vap *wvp = WPI_VAP(vap);
1728 	struct ieee80211com *ic = vap->iv_ic;
1729 	struct wpi_softc *sc = ic->ic_softc;
1730 	int error = 0;
1731 
1732 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
1733 
1734 	WPI_TXQ_LOCK(sc);
1735 	if (nstate > IEEE80211_S_INIT && sc->sc_running == 0) {
1736 		DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR, __func__);
1737 		WPI_TXQ_UNLOCK(sc);
1738 
1739 		return ENXIO;
1740 	}
1741 	WPI_TXQ_UNLOCK(sc);
1742 
1743 	DPRINTF(sc, WPI_DEBUG_STATE, "%s: %s -> %s\n", __func__,
1744 		ieee80211_state_name[vap->iv_state],
1745 		ieee80211_state_name[nstate]);
1746 
1747 	if (vap->iv_state == IEEE80211_S_RUN && nstate < IEEE80211_S_RUN) {
1748 		if ((error = wpi_set_pslevel(sc, 0, 0, 1)) != 0) {
1749 			device_printf(sc->sc_dev,
1750 			    "%s: could not set power saving level\n",
1751 			    __func__);
1752 			return error;
1753 		}
1754 
1755 		wpi_set_led(sc, WPI_LED_LINK, 1, 0);
1756 	}
1757 
1758 	switch (nstate) {
1759 	case IEEE80211_S_SCAN:
1760 		WPI_RXON_LOCK(sc);
1761 		if (wpi_check_bss_filter(sc) != 0) {
1762 			sc->rxon.filter &= ~htole32(WPI_FILTER_BSS);
1763 			if ((error = wpi_send_rxon(sc, 0, 1)) != 0) {
1764 				device_printf(sc->sc_dev,
1765 				    "%s: could not send RXON\n", __func__);
1766 			}
1767 		}
1768 		WPI_RXON_UNLOCK(sc);
1769 		break;
1770 
1771 	case IEEE80211_S_ASSOC:
1772 		if (vap->iv_state != IEEE80211_S_RUN)
1773 			break;
1774 		/* FALLTHROUGH */
1775 	case IEEE80211_S_AUTH:
1776 		/*
1777 		 * NB: do not optimize AUTH -> AUTH state transmission -
1778 		 * this will break powersave with non-QoS AP!
1779 		 */
1780 
1781 		/*
1782 		 * The node must be registered in the firmware before auth.
1783 		 * Also the associd must be cleared on RUN -> ASSOC
1784 		 * transitions.
1785 		 */
1786 		if ((error = wpi_auth(sc, vap)) != 0) {
1787 			device_printf(sc->sc_dev,
1788 			    "%s: could not move to AUTH state, error %d\n",
1789 			    __func__, error);
1790 		}
1791 		break;
1792 
1793 	case IEEE80211_S_RUN:
1794 		/*
1795 		 * RUN -> RUN transition:
1796 		 * STA mode: Just restart the timers.
1797 		 * IBSS mode: Process IBSS merge.
1798 		 */
1799 		if (vap->iv_state == IEEE80211_S_RUN) {
1800 			if (vap->iv_opmode != IEEE80211_M_IBSS) {
1801 				WPI_RXON_LOCK(sc);
1802 				wpi_calib_timeout(sc);
1803 				WPI_RXON_UNLOCK(sc);
1804 				break;
1805 			} else {
1806 				/*
1807 				 * Drop the BSS_FILTER bit
1808 				 * (there is no another way to change bssid).
1809 				 */
1810 				WPI_RXON_LOCK(sc);
1811 				sc->rxon.filter &= ~htole32(WPI_FILTER_BSS);
1812 				if ((error = wpi_send_rxon(sc, 0, 1)) != 0) {
1813 					device_printf(sc->sc_dev,
1814 					    "%s: could not send RXON\n",
1815 					    __func__);
1816 				}
1817 				WPI_RXON_UNLOCK(sc);
1818 
1819 				/* Restore all what was lost. */
1820 				wpi_restore_node_table(sc, wvp);
1821 
1822 				/* XXX set conditionally? */
1823 				wpi_updateedca(ic);
1824 			}
1825 		}
1826 
1827 		/*
1828 		 * !RUN -> RUN requires setting the association id
1829 		 * which is done with a firmware cmd.  We also defer
1830 		 * starting the timers until that work is done.
1831 		 */
1832 		if ((error = wpi_run(sc, vap)) != 0) {
1833 			device_printf(sc->sc_dev,
1834 			    "%s: could not move to RUN state\n", __func__);
1835 		}
1836 		break;
1837 
1838 	default:
1839 		break;
1840 	}
1841 	if (error != 0) {
1842 		DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR, __func__);
1843 		return error;
1844 	}
1845 
1846 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
1847 
1848 	return wvp->wv_newstate(vap, nstate, arg);
1849 }
1850 
1851 static void
1852 wpi_calib_timeout(void *arg)
1853 {
1854 	struct wpi_softc *sc = arg;
1855 
1856 	if (wpi_check_bss_filter(sc) == 0)
1857 		return;
1858 
1859 	wpi_power_calibration(sc);
1860 
1861 	callout_reset(&sc->calib_to, 60*hz, wpi_calib_timeout, sc);
1862 }
1863 
1864 static __inline uint8_t
1865 rate2plcp(const uint8_t rate)
1866 {
1867 	switch (rate) {
1868 	case 12:	return 0xd;
1869 	case 18:	return 0xf;
1870 	case 24:	return 0x5;
1871 	case 36:	return 0x7;
1872 	case 48:	return 0x9;
1873 	case 72:	return 0xb;
1874 	case 96:	return 0x1;
1875 	case 108:	return 0x3;
1876 	case 2:		return 10;
1877 	case 4:		return 20;
1878 	case 11:	return 55;
1879 	case 22:	return 110;
1880 	default:	return 0;
1881 	}
1882 }
1883 
1884 static __inline uint8_t
1885 plcp2rate(const uint8_t plcp)
1886 {
1887 	switch (plcp) {
1888 	case 0xd:	return 12;
1889 	case 0xf:	return 18;
1890 	case 0x5:	return 24;
1891 	case 0x7:	return 36;
1892 	case 0x9:	return 48;
1893 	case 0xb:	return 72;
1894 	case 0x1:	return 96;
1895 	case 0x3:	return 108;
1896 	case 10:	return 2;
1897 	case 20:	return 4;
1898 	case 55:	return 11;
1899 	case 110:	return 22;
1900 	default:	return 0;
1901 	}
1902 }
1903 
1904 /* Quickly determine if a given rate is CCK or OFDM. */
1905 #define WPI_RATE_IS_OFDM(rate)	((rate) >= 12 && (rate) != 22)
1906 
1907 static void
1908 wpi_rx_done(struct wpi_softc *sc, struct wpi_rx_desc *desc,
1909     struct wpi_rx_data *data)
1910 {
1911 	struct epoch_tracker et;
1912 	struct ieee80211com *ic = &sc->sc_ic;
1913 	struct wpi_rx_ring *ring = &sc->rxq;
1914 	struct wpi_rx_stat *stat;
1915 	struct wpi_rx_head *head;
1916 	struct wpi_rx_tail *tail;
1917 	struct ieee80211_frame *wh;
1918 	struct ieee80211_node *ni;
1919 	struct mbuf *m, *m1;
1920 	bus_addr_t paddr;
1921 	uint32_t flags;
1922 	uint16_t len;
1923 	int error;
1924 
1925 	stat = (struct wpi_rx_stat *)(desc + 1);
1926 
1927 	if (__predict_false(stat->len > WPI_STAT_MAXLEN)) {
1928 		device_printf(sc->sc_dev, "invalid RX statistic header\n");
1929 		goto fail1;
1930 	}
1931 
1932 	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTREAD);
1933 	head = (struct wpi_rx_head *)((caddr_t)(stat + 1) + stat->len);
1934 	len = le16toh(head->len);
1935 	tail = (struct wpi_rx_tail *)((caddr_t)(head + 1) + len);
1936 	flags = le32toh(tail->flags);
1937 
1938 	DPRINTF(sc, WPI_DEBUG_RECV, "%s: idx %d len %d stat len %u rssi %d"
1939 	    " rate %x chan %d tstamp %ju\n", __func__, ring->cur,
1940 	    le32toh(desc->len), len, (int8_t)stat->rssi,
1941 	    head->plcp, head->chan, (uintmax_t)le64toh(tail->tstamp));
1942 
1943 	/* Discard frames with a bad FCS early. */
1944 	if ((flags & WPI_RX_NOERROR) != WPI_RX_NOERROR) {
1945 		DPRINTF(sc, WPI_DEBUG_RECV, "%s: RX flags error %x\n",
1946 		    __func__, flags);
1947 		goto fail1;
1948 	}
1949 	/* Discard frames that are too short. */
1950 	if (len < sizeof (struct ieee80211_frame_ack)) {
1951 		DPRINTF(sc, WPI_DEBUG_RECV, "%s: frame too short: %d\n",
1952 		    __func__, len);
1953 		goto fail1;
1954 	}
1955 
1956 	m1 = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, MJUMPAGESIZE);
1957 	if (__predict_false(m1 == NULL)) {
1958 		DPRINTF(sc, WPI_DEBUG_ANY, "%s: no mbuf to restock ring\n",
1959 		    __func__);
1960 		goto fail1;
1961 	}
1962 	bus_dmamap_unload(ring->data_dmat, data->map);
1963 
1964 	error = bus_dmamap_load(ring->data_dmat, data->map, mtod(m1, void *),
1965 	    MJUMPAGESIZE, wpi_dma_map_addr, &paddr, BUS_DMA_NOWAIT);
1966 	if (__predict_false(error != 0 && error != EFBIG)) {
1967 		device_printf(sc->sc_dev,
1968 		    "%s: bus_dmamap_load failed, error %d\n", __func__, error);
1969 		m_freem(m1);
1970 
1971 		/* Try to reload the old mbuf. */
1972 		error = bus_dmamap_load(ring->data_dmat, data->map,
1973 		    mtod(data->m, void *), MJUMPAGESIZE, wpi_dma_map_addr,
1974 		    &paddr, BUS_DMA_NOWAIT);
1975 		if (error != 0 && error != EFBIG) {
1976 			panic("%s: could not load old RX mbuf", __func__);
1977 		}
1978 		/* Physical address may have changed. */
1979 		ring->desc[ring->cur] = htole32(paddr);
1980 		bus_dmamap_sync(ring->data_dmat, ring->desc_dma.map,
1981 		    BUS_DMASYNC_PREWRITE);
1982 		goto fail1;
1983 	}
1984 
1985 	m = data->m;
1986 	data->m = m1;
1987 	/* Update RX descriptor. */
1988 	ring->desc[ring->cur] = htole32(paddr);
1989 	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
1990 	    BUS_DMASYNC_PREWRITE);
1991 
1992 	/* Finalize mbuf. */
1993 	m->m_data = (caddr_t)(head + 1);
1994 	m->m_pkthdr.len = m->m_len = len;
1995 
1996 	/* Grab a reference to the source node. */
1997 	wh = mtod(m, struct ieee80211_frame *);
1998 
1999 	if ((wh->i_fc[1] & IEEE80211_FC1_PROTECTED) &&
2000 	    (flags & WPI_RX_CIPHER_MASK) == WPI_RX_CIPHER_CCMP) {
2001 		/* Check whether decryption was successful or not. */
2002 		if ((flags & WPI_RX_DECRYPT_MASK) != WPI_RX_DECRYPT_OK) {
2003 			DPRINTF(sc, WPI_DEBUG_RECV,
2004 			    "CCMP decryption failed 0x%x\n", flags);
2005 			goto fail2;
2006 		}
2007 		m->m_flags |= M_WEP;
2008 	}
2009 
2010 	if (len >= sizeof(struct ieee80211_frame_min))
2011 		ni = ieee80211_find_rxnode(ic, (struct ieee80211_frame_min *)wh);
2012 	else
2013 		ni = NULL;
2014 
2015 	sc->rx_tstamp = tail->tstamp;
2016 
2017 	if (ieee80211_radiotap_active(ic)) {
2018 		struct wpi_rx_radiotap_header *tap = &sc->sc_rxtap;
2019 
2020 		tap->wr_flags = 0;
2021 		if (head->flags & htole16(WPI_STAT_FLAG_SHPREAMBLE))
2022 			tap->wr_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
2023 		tap->wr_dbm_antsignal = (int8_t)(stat->rssi + WPI_RSSI_OFFSET);
2024 		tap->wr_dbm_antnoise = WPI_RSSI_OFFSET;
2025 		tap->wr_tsft = tail->tstamp;
2026 		tap->wr_antenna = (le16toh(head->flags) >> 4) & 0xf;
2027 		tap->wr_rate = plcp2rate(head->plcp);
2028 	}
2029 
2030 	WPI_UNLOCK(sc);
2031 	NET_EPOCH_ENTER(et);
2032 
2033 	/* Send the frame to the 802.11 layer. */
2034 	if (ni != NULL) {
2035 		(void)ieee80211_input(ni, m, stat->rssi, WPI_RSSI_OFFSET);
2036 		/* Node is no longer needed. */
2037 		ieee80211_free_node(ni);
2038 	} else
2039 		(void)ieee80211_input_all(ic, m, stat->rssi, WPI_RSSI_OFFSET);
2040 
2041 	NET_EPOCH_EXIT(et);
2042 	WPI_LOCK(sc);
2043 
2044 	return;
2045 
2046 fail2:	m_freem(m);
2047 
2048 fail1:	counter_u64_add(ic->ic_ierrors, 1);
2049 }
2050 
2051 static void
2052 wpi_rx_statistics(struct wpi_softc *sc, struct wpi_rx_desc *desc,
2053     struct wpi_rx_data *data)
2054 {
2055 	/* Ignore */
2056 }
2057 
2058 static void
2059 wpi_tx_done(struct wpi_softc *sc, struct wpi_rx_desc *desc)
2060 {
2061 	struct ieee80211_ratectl_tx_status *txs = &sc->sc_txs;
2062 	struct wpi_tx_ring *ring = &sc->txq[desc->qid & 0x3];
2063 	struct wpi_tx_data *data = &ring->data[desc->idx];
2064 	struct wpi_tx_stat *stat = (struct wpi_tx_stat *)(desc + 1);
2065 	struct mbuf *m;
2066 	struct ieee80211_node *ni;
2067 	uint32_t status = le32toh(stat->status);
2068 
2069 	KASSERT(data->ni != NULL, ("no node"));
2070 	KASSERT(data->m != NULL, ("no mbuf"));
2071 
2072 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
2073 
2074 	DPRINTF(sc, WPI_DEBUG_XMIT, "%s: "
2075 	    "qid %d idx %d retries %d btkillcnt %d rate %x duration %d "
2076 	    "status %x\n", __func__, desc->qid, desc->idx, stat->ackfailcnt,
2077 	    stat->btkillcnt, stat->rate, le32toh(stat->duration), status);
2078 
2079 	/* Unmap and free mbuf. */
2080 	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_POSTWRITE);
2081 	bus_dmamap_unload(ring->data_dmat, data->map);
2082 	m = data->m, data->m = NULL;
2083 	ni = data->ni, data->ni = NULL;
2084 
2085 	/* Restore frame header. */
2086 	KASSERT(M_LEADINGSPACE(m) >= data->hdrlen, ("no frame header!"));
2087 	M_PREPEND(m, data->hdrlen, M_NOWAIT);
2088 	KASSERT(m != NULL, ("%s: m is NULL\n", __func__));
2089 
2090 	/*
2091 	 * Update rate control statistics for the node.
2092 	 */
2093 	txs->pktlen = m->m_pkthdr.len;
2094 	txs->short_retries = stat->rtsfailcnt;
2095 	txs->long_retries = stat->ackfailcnt / WPI_NTRIES_DEFAULT;
2096 	if (!(status & WPI_TX_STATUS_FAIL))
2097 		txs->status = IEEE80211_RATECTL_TX_SUCCESS;
2098 	else {
2099 		switch (status & 0xff) {
2100 		case WPI_TX_STATUS_FAIL_SHORT_LIMIT:
2101 			txs->status = IEEE80211_RATECTL_TX_FAIL_SHORT;
2102 			break;
2103 		case WPI_TX_STATUS_FAIL_LONG_LIMIT:
2104 			txs->status = IEEE80211_RATECTL_TX_FAIL_LONG;
2105 			break;
2106 		case WPI_TX_STATUS_FAIL_LIFE_EXPIRE:
2107 			txs->status = IEEE80211_RATECTL_TX_FAIL_EXPIRED;
2108 			break;
2109 		default:
2110 			txs->status = IEEE80211_RATECTL_TX_FAIL_UNSPECIFIED;
2111 			break;
2112 		}
2113 	}
2114 
2115 	ieee80211_ratectl_tx_complete(ni, txs);
2116 	ieee80211_tx_complete(ni, m, (status & WPI_TX_STATUS_FAIL) != 0);
2117 
2118 	WPI_TXQ_STATE_LOCK(sc);
2119 	if (--ring->queued > 0)
2120 		callout_reset(&sc->tx_timeout, 5*hz, wpi_tx_timeout, sc);
2121 	else
2122 		callout_stop(&sc->tx_timeout);
2123 	WPI_TXQ_STATE_UNLOCK(sc);
2124 
2125 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
2126 }
2127 
2128 /*
2129  * Process a "command done" firmware notification.  This is where we wakeup
2130  * processes waiting for a synchronous command completion.
2131  */
2132 static void
2133 wpi_cmd_done(struct wpi_softc *sc, struct wpi_rx_desc *desc)
2134 {
2135 	struct wpi_tx_ring *ring = &sc->txq[WPI_CMD_QUEUE_NUM];
2136 	struct wpi_tx_data *data;
2137 	struct wpi_tx_cmd *cmd;
2138 
2139 	DPRINTF(sc, WPI_DEBUG_CMD, "cmd notification qid %x idx %d flags %x "
2140 				   "type %s len %d\n", desc->qid, desc->idx,
2141 				   desc->flags, wpi_cmd_str(desc->type),
2142 				   le32toh(desc->len));
2143 
2144 	if ((desc->qid & WPI_RX_DESC_QID_MSK) != WPI_CMD_QUEUE_NUM)
2145 		return;	/* Not a command ack. */
2146 
2147 	KASSERT(ring->queued == 0, ("ring->queued must be 0"));
2148 
2149 	data = &ring->data[desc->idx];
2150 	cmd = &ring->cmd[desc->idx];
2151 
2152 	/* If the command was mapped in an mbuf, free it. */
2153 	if (data->m != NULL) {
2154 		bus_dmamap_sync(ring->data_dmat, data->map,
2155 		    BUS_DMASYNC_POSTWRITE);
2156 		bus_dmamap_unload(ring->data_dmat, data->map);
2157 		m_freem(data->m);
2158 		data->m = NULL;
2159 	}
2160 
2161 	wakeup(cmd);
2162 
2163 	if (desc->type == WPI_CMD_SET_POWER_MODE) {
2164 		struct wpi_pmgt_cmd *pcmd = (struct wpi_pmgt_cmd *)cmd->data;
2165 
2166 		bus_dmamap_sync(ring->data_dmat, ring->cmd_dma.map,
2167 		    BUS_DMASYNC_POSTREAD);
2168 
2169 		WPI_TXQ_LOCK(sc);
2170 		if (le16toh(pcmd->flags) & WPI_PS_ALLOW_SLEEP) {
2171 			sc->sc_update_rx_ring = wpi_update_rx_ring_ps;
2172 			sc->sc_update_tx_ring = wpi_update_tx_ring_ps;
2173 		} else {
2174 			sc->sc_update_rx_ring = wpi_update_rx_ring;
2175 			sc->sc_update_tx_ring = wpi_update_tx_ring;
2176 		}
2177 		WPI_TXQ_UNLOCK(sc);
2178 	}
2179 }
2180 
2181 static void
2182 wpi_notif_intr(struct wpi_softc *sc)
2183 {
2184 	struct ieee80211com *ic = &sc->sc_ic;
2185 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2186 	uint32_t hw;
2187 
2188 	bus_dmamap_sync(sc->shared_dma.tag, sc->shared_dma.map,
2189 	    BUS_DMASYNC_POSTREAD);
2190 
2191 	hw = le32toh(sc->shared->next) & 0xfff;
2192 	hw = (hw == 0) ? WPI_RX_RING_COUNT - 1 : hw - 1;
2193 
2194 	while (sc->rxq.cur != hw) {
2195 		sc->rxq.cur = (sc->rxq.cur + 1) % WPI_RX_RING_COUNT;
2196 
2197 		struct wpi_rx_data *data = &sc->rxq.data[sc->rxq.cur];
2198 		struct wpi_rx_desc *desc;
2199 
2200 		bus_dmamap_sync(sc->rxq.data_dmat, data->map,
2201 		    BUS_DMASYNC_POSTREAD);
2202 		desc = mtod(data->m, struct wpi_rx_desc *);
2203 
2204 		DPRINTF(sc, WPI_DEBUG_NOTIFY,
2205 		    "%s: cur=%d; qid %x idx %d flags %x type %d(%s) len %d\n",
2206 		    __func__, sc->rxq.cur, desc->qid, desc->idx, desc->flags,
2207 		    desc->type, wpi_cmd_str(desc->type), le32toh(desc->len));
2208 
2209 		if (!(desc->qid & WPI_UNSOLICITED_RX_NOTIF)) {
2210 			/* Reply to a command. */
2211 			wpi_cmd_done(sc, desc);
2212 		}
2213 
2214 		switch (desc->type) {
2215 		case WPI_RX_DONE:
2216 			/* An 802.11 frame has been received. */
2217 			wpi_rx_done(sc, desc, data);
2218 
2219 			if (__predict_false(sc->sc_running == 0)) {
2220 				/* wpi_stop() was called. */
2221 				return;
2222 			}
2223 
2224 			break;
2225 
2226 		case WPI_TX_DONE:
2227 			/* An 802.11 frame has been transmitted. */
2228 			wpi_tx_done(sc, desc);
2229 			break;
2230 
2231 		case WPI_RX_STATISTICS:
2232 		case WPI_BEACON_STATISTICS:
2233 			wpi_rx_statistics(sc, desc, data);
2234 			break;
2235 
2236 		case WPI_BEACON_MISSED:
2237 		{
2238 			struct wpi_beacon_missed *miss =
2239 			    (struct wpi_beacon_missed *)(desc + 1);
2240 			uint32_t expected, misses, received, threshold;
2241 
2242 			bus_dmamap_sync(sc->rxq.data_dmat, data->map,
2243 			    BUS_DMASYNC_POSTREAD);
2244 
2245 			misses = le32toh(miss->consecutive);
2246 			expected = le32toh(miss->expected);
2247 			received = le32toh(miss->received);
2248 			threshold = MAX(2, vap->iv_bmissthreshold);
2249 
2250 			DPRINTF(sc, WPI_DEBUG_BMISS,
2251 			    "%s: beacons missed %u(%u) (received %u/%u)\n",
2252 			    __func__, misses, le32toh(miss->total), received,
2253 			    expected);
2254 
2255 			if (misses >= threshold ||
2256 			    (received == 0 && expected >= threshold)) {
2257 				WPI_RXON_LOCK(sc);
2258 				if (callout_pending(&sc->scan_timeout)) {
2259 					wpi_cmd(sc, WPI_CMD_SCAN_ABORT, NULL,
2260 					    0, 1);
2261 				}
2262 				WPI_RXON_UNLOCK(sc);
2263 				if (vap->iv_state == IEEE80211_S_RUN &&
2264 				    (ic->ic_flags & IEEE80211_F_SCAN) == 0)
2265 					ieee80211_beacon_miss(ic);
2266 			}
2267 
2268 			break;
2269 		}
2270 #ifdef WPI_DEBUG
2271 		case WPI_BEACON_SENT:
2272 		{
2273 			struct wpi_tx_stat *stat =
2274 			    (struct wpi_tx_stat *)(desc + 1);
2275 			uint64_t *tsf = (uint64_t *)(stat + 1);
2276 			uint32_t *mode = (uint32_t *)(tsf + 1);
2277 
2278 			bus_dmamap_sync(sc->rxq.data_dmat, data->map,
2279 			    BUS_DMASYNC_POSTREAD);
2280 
2281 			DPRINTF(sc, WPI_DEBUG_BEACON,
2282 			    "beacon sent: rts %u, ack %u, btkill %u, rate %u, "
2283 			    "duration %u, status %x, tsf %ju, mode %x\n",
2284 			    stat->rtsfailcnt, stat->ackfailcnt,
2285 			    stat->btkillcnt, stat->rate, le32toh(stat->duration),
2286 			    le32toh(stat->status), le64toh(*tsf),
2287 			    le32toh(*mode));
2288 
2289 			break;
2290 		}
2291 #endif
2292 		case WPI_UC_READY:
2293 		{
2294 			struct wpi_ucode_info *uc =
2295 			    (struct wpi_ucode_info *)(desc + 1);
2296 
2297 			/* The microcontroller is ready. */
2298 			bus_dmamap_sync(sc->rxq.data_dmat, data->map,
2299 			    BUS_DMASYNC_POSTREAD);
2300 			DPRINTF(sc, WPI_DEBUG_RESET,
2301 			    "microcode alive notification version=%d.%d "
2302 			    "subtype=%x alive=%x\n", uc->major, uc->minor,
2303 			    uc->subtype, le32toh(uc->valid));
2304 
2305 			if (le32toh(uc->valid) != 1) {
2306 				device_printf(sc->sc_dev,
2307 				    "microcontroller initialization failed\n");
2308 				wpi_stop_locked(sc);
2309 				return;
2310 			}
2311 			/* Save the address of the error log in SRAM. */
2312 			sc->errptr = le32toh(uc->errptr);
2313 			break;
2314 		}
2315 		case WPI_STATE_CHANGED:
2316 		{
2317 			bus_dmamap_sync(sc->rxq.data_dmat, data->map,
2318 			    BUS_DMASYNC_POSTREAD);
2319 
2320 			uint32_t *status = (uint32_t *)(desc + 1);
2321 
2322 			DPRINTF(sc, WPI_DEBUG_STATE, "state changed to %x\n",
2323 			    le32toh(*status));
2324 
2325 			if (le32toh(*status) & 1) {
2326 				WPI_NT_LOCK(sc);
2327 				wpi_clear_node_table(sc);
2328 				WPI_NT_UNLOCK(sc);
2329 				ieee80211_runtask(ic,
2330 				    &sc->sc_radiooff_task);
2331 				return;
2332 			}
2333 			break;
2334 		}
2335 #ifdef WPI_DEBUG
2336 		case WPI_START_SCAN:
2337 		{
2338 			bus_dmamap_sync(sc->rxq.data_dmat, data->map,
2339 			    BUS_DMASYNC_POSTREAD);
2340 
2341 			struct wpi_start_scan *scan =
2342 			    (struct wpi_start_scan *)(desc + 1);
2343 			DPRINTF(sc, WPI_DEBUG_SCAN,
2344 			    "%s: scanning channel %d status %x\n",
2345 			    __func__, scan->chan, le32toh(scan->status));
2346 
2347 			break;
2348 		}
2349 #endif
2350 		case WPI_STOP_SCAN:
2351 		{
2352 			bus_dmamap_sync(sc->rxq.data_dmat, data->map,
2353 			    BUS_DMASYNC_POSTREAD);
2354 
2355 			struct wpi_stop_scan *scan =
2356 			    (struct wpi_stop_scan *)(desc + 1);
2357 
2358 			DPRINTF(sc, WPI_DEBUG_SCAN,
2359 			    "scan finished nchan=%d status=%d chan=%d\n",
2360 			    scan->nchan, scan->status, scan->chan);
2361 
2362 			WPI_RXON_LOCK(sc);
2363 			callout_stop(&sc->scan_timeout);
2364 			WPI_RXON_UNLOCK(sc);
2365 			if (scan->status == WPI_SCAN_ABORTED)
2366 				ieee80211_cancel_scan(vap);
2367 			else
2368 				ieee80211_scan_next(vap);
2369 			break;
2370 		}
2371 		}
2372 
2373 		if (sc->rxq.cur % 8 == 0) {
2374 			/* Tell the firmware what we have processed. */
2375 			sc->sc_update_rx_ring(sc);
2376 		}
2377 	}
2378 }
2379 
2380 /*
2381  * Process an INT_WAKEUP interrupt raised when the microcontroller wakes up
2382  * from power-down sleep mode.
2383  */
2384 static void
2385 wpi_wakeup_intr(struct wpi_softc *sc)
2386 {
2387 	int qid;
2388 
2389 	DPRINTF(sc, WPI_DEBUG_PWRSAVE,
2390 	    "%s: ucode wakeup from power-down sleep\n", __func__);
2391 
2392 	/* Wakeup RX and TX rings. */
2393 	if (sc->rxq.update) {
2394 		sc->rxq.update = 0;
2395 		wpi_update_rx_ring(sc);
2396 	}
2397 	WPI_TXQ_LOCK(sc);
2398 	for (qid = 0; qid < WPI_DRV_NTXQUEUES; qid++) {
2399 		struct wpi_tx_ring *ring = &sc->txq[qid];
2400 
2401 		if (ring->update) {
2402 			ring->update = 0;
2403 			wpi_update_tx_ring(sc, ring);
2404 		}
2405 	}
2406 	WPI_CLRBITS(sc, WPI_GP_CNTRL, WPI_GP_CNTRL_MAC_ACCESS_REQ);
2407 	WPI_TXQ_UNLOCK(sc);
2408 }
2409 
2410 /*
2411  * This function prints firmware registers
2412  */
2413 #ifdef WPI_DEBUG
2414 static void
2415 wpi_debug_registers(struct wpi_softc *sc)
2416 {
2417 	size_t i;
2418 	static const uint32_t csr_tbl[] = {
2419 		WPI_HW_IF_CONFIG,
2420 		WPI_INT,
2421 		WPI_INT_MASK,
2422 		WPI_FH_INT,
2423 		WPI_GPIO_IN,
2424 		WPI_RESET,
2425 		WPI_GP_CNTRL,
2426 		WPI_EEPROM,
2427 		WPI_EEPROM_GP,
2428 		WPI_GIO,
2429 		WPI_UCODE_GP1,
2430 		WPI_UCODE_GP2,
2431 		WPI_GIO_CHICKEN,
2432 		WPI_ANA_PLL,
2433 		WPI_DBG_HPET_MEM,
2434 	};
2435 	static const uint32_t prph_tbl[] = {
2436 		WPI_APMG_CLK_CTRL,
2437 		WPI_APMG_PS,
2438 		WPI_APMG_PCI_STT,
2439 		WPI_APMG_RFKILL,
2440 	};
2441 
2442 	DPRINTF(sc, WPI_DEBUG_REGISTER,"%s","\n");
2443 
2444 	for (i = 0; i < nitems(csr_tbl); i++) {
2445 		DPRINTF(sc, WPI_DEBUG_REGISTER, "  %-18s: 0x%08x ",
2446 		    wpi_get_csr_string(csr_tbl[i]), WPI_READ(sc, csr_tbl[i]));
2447 
2448 		if ((i + 1) % 2 == 0)
2449 			DPRINTF(sc, WPI_DEBUG_REGISTER, "\n");
2450 	}
2451 	DPRINTF(sc, WPI_DEBUG_REGISTER, "\n\n");
2452 
2453 	if (wpi_nic_lock(sc) == 0) {
2454 		for (i = 0; i < nitems(prph_tbl); i++) {
2455 			DPRINTF(sc, WPI_DEBUG_REGISTER, "  %-18s: 0x%08x ",
2456 			    wpi_get_prph_string(prph_tbl[i]),
2457 			    wpi_prph_read(sc, prph_tbl[i]));
2458 
2459 			if ((i + 1) % 2 == 0)
2460 				DPRINTF(sc, WPI_DEBUG_REGISTER, "\n");
2461 		}
2462 		DPRINTF(sc, WPI_DEBUG_REGISTER, "\n");
2463 		wpi_nic_unlock(sc);
2464 	} else {
2465 		DPRINTF(sc, WPI_DEBUG_REGISTER,
2466 		    "Cannot access internal registers.\n");
2467 	}
2468 }
2469 #endif
2470 
2471 /*
2472  * Dump the error log of the firmware when a firmware panic occurs.  Although
2473  * we can't debug the firmware because it is neither open source nor free, it
2474  * can help us to identify certain classes of problems.
2475  */
2476 static void
2477 wpi_fatal_intr(struct wpi_softc *sc)
2478 {
2479 	struct wpi_fw_dump dump;
2480 	uint32_t i, offset, count;
2481 
2482 	/* Check that the error log address is valid. */
2483 	if (sc->errptr < WPI_FW_DATA_BASE ||
2484 	    sc->errptr + sizeof (dump) >
2485 	    WPI_FW_DATA_BASE + WPI_FW_DATA_MAXSZ) {
2486 		printf("%s: bad firmware error log address 0x%08x\n", __func__,
2487 		    sc->errptr);
2488 		return;
2489 	}
2490 	if (wpi_nic_lock(sc) != 0) {
2491 		printf("%s: could not read firmware error log\n", __func__);
2492 		return;
2493 	}
2494 	/* Read number of entries in the log. */
2495 	count = wpi_mem_read(sc, sc->errptr);
2496 	if (count == 0 || count * sizeof (dump) > WPI_FW_DATA_MAXSZ) {
2497 		printf("%s: invalid count field (count = %u)\n", __func__,
2498 		    count);
2499 		wpi_nic_unlock(sc);
2500 		return;
2501 	}
2502 	/* Skip "count" field. */
2503 	offset = sc->errptr + sizeof (uint32_t);
2504 	printf("firmware error log (count = %u):\n", count);
2505 	for (i = 0; i < count; i++) {
2506 		wpi_mem_read_region_4(sc, offset, (uint32_t *)&dump,
2507 		    sizeof (dump) / sizeof (uint32_t));
2508 
2509 		printf("  error type = \"%s\" (0x%08X)\n",
2510 		    (dump.desc < nitems(wpi_fw_errmsg)) ?
2511 		        wpi_fw_errmsg[dump.desc] : "UNKNOWN",
2512 		    dump.desc);
2513 		printf("  error data      = 0x%08X\n",
2514 		    dump.data);
2515 		printf("  branch link     = 0x%08X%08X\n",
2516 		    dump.blink[0], dump.blink[1]);
2517 		printf("  interrupt link  = 0x%08X%08X\n",
2518 		    dump.ilink[0], dump.ilink[1]);
2519 		printf("  time            = %u\n", dump.time);
2520 
2521 		offset += sizeof (dump);
2522 	}
2523 	wpi_nic_unlock(sc);
2524 	/* Dump driver status (TX and RX rings) while we're here. */
2525 	printf("driver status:\n");
2526 	WPI_TXQ_LOCK(sc);
2527 	for (i = 0; i < WPI_DRV_NTXQUEUES; i++) {
2528 		struct wpi_tx_ring *ring = &sc->txq[i];
2529 		printf("  tx ring %2d: qid=%-2d cur=%-3d queued=%-3d\n",
2530 		    i, ring->qid, ring->cur, ring->queued);
2531 	}
2532 	WPI_TXQ_UNLOCK(sc);
2533 	printf("  rx ring: cur=%d\n", sc->rxq.cur);
2534 }
2535 
2536 static void
2537 wpi_intr(void *arg)
2538 {
2539 	struct wpi_softc *sc = arg;
2540 	uint32_t r1, r2;
2541 
2542 	WPI_LOCK(sc);
2543 
2544 	/* Disable interrupts. */
2545 	WPI_WRITE(sc, WPI_INT_MASK, 0);
2546 
2547 	r1 = WPI_READ(sc, WPI_INT);
2548 
2549 	if (__predict_false(r1 == 0xffffffff ||
2550 			   (r1 & 0xfffffff0) == 0xa5a5a5a0))
2551 		goto end;	/* Hardware gone! */
2552 
2553 	r2 = WPI_READ(sc, WPI_FH_INT);
2554 
2555 	DPRINTF(sc, WPI_DEBUG_INTR, "%s: reg1=0x%08x reg2=0x%08x\n", __func__,
2556 	    r1, r2);
2557 
2558 	if (r1 == 0 && r2 == 0)
2559 		goto done;	/* Interrupt not for us. */
2560 
2561 	/* Acknowledge interrupts. */
2562 	WPI_WRITE(sc, WPI_INT, r1);
2563 	WPI_WRITE(sc, WPI_FH_INT, r2);
2564 
2565 	if (__predict_false(r1 & (WPI_INT_SW_ERR | WPI_INT_HW_ERR))) {
2566 		struct ieee80211com *ic = &sc->sc_ic;
2567 
2568 		device_printf(sc->sc_dev, "fatal firmware error\n");
2569 #ifdef WPI_DEBUG
2570 		wpi_debug_registers(sc);
2571 #endif
2572 		wpi_fatal_intr(sc);
2573 		DPRINTF(sc, WPI_DEBUG_HW,
2574 		    "(%s)\n", (r1 & WPI_INT_SW_ERR) ? "(Software Error)" :
2575 		    "(Hardware Error)");
2576 		ieee80211_restart_all(ic);
2577 		goto end;
2578 	}
2579 
2580 	if ((r1 & (WPI_INT_FH_RX | WPI_INT_SW_RX)) ||
2581 	    (r2 & WPI_FH_INT_RX))
2582 		wpi_notif_intr(sc);
2583 
2584 	if (r1 & WPI_INT_ALIVE)
2585 		wakeup(sc);	/* Firmware is alive. */
2586 
2587 	if (r1 & WPI_INT_WAKEUP)
2588 		wpi_wakeup_intr(sc);
2589 
2590 done:
2591 	/* Re-enable interrupts. */
2592 	if (__predict_true(sc->sc_running))
2593 		WPI_WRITE(sc, WPI_INT_MASK, WPI_INT_MASK_DEF);
2594 
2595 end:	WPI_UNLOCK(sc);
2596 }
2597 
2598 static void
2599 wpi_free_txfrags(struct wpi_softc *sc, uint16_t ac)
2600 {
2601 	struct wpi_tx_ring *ring;
2602 	struct wpi_tx_data *data;
2603 	uint8_t cur;
2604 
2605 	WPI_TXQ_LOCK(sc);
2606 	ring = &sc->txq[ac];
2607 
2608 	while (ring->pending != 0) {
2609 		ring->pending--;
2610 		cur = (ring->cur + ring->pending) % WPI_TX_RING_COUNT;
2611 		data = &ring->data[cur];
2612 
2613 		bus_dmamap_sync(ring->data_dmat, data->map,
2614 		    BUS_DMASYNC_POSTWRITE);
2615 		bus_dmamap_unload(ring->data_dmat, data->map);
2616 		m_freem(data->m);
2617 		data->m = NULL;
2618 
2619 		ieee80211_node_decref(data->ni);
2620 		data->ni = NULL;
2621 	}
2622 
2623 	WPI_TXQ_UNLOCK(sc);
2624 }
2625 
2626 static int
2627 wpi_cmd2(struct wpi_softc *sc, struct wpi_buf *buf)
2628 {
2629 	struct ieee80211_frame *wh;
2630 	struct wpi_tx_cmd *cmd;
2631 	struct wpi_tx_data *data;
2632 	struct wpi_tx_desc *desc;
2633 	struct wpi_tx_ring *ring;
2634 	struct mbuf *m1;
2635 	bus_dma_segment_t *seg, segs[WPI_MAX_SCATTER];
2636 	uint8_t cur, pad;
2637 	uint16_t hdrlen;
2638 	int error, i, nsegs, totlen, frag;
2639 
2640 	WPI_TXQ_LOCK(sc);
2641 
2642 	KASSERT(buf->size <= sizeof(buf->data), ("buffer overflow"));
2643 
2644 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
2645 
2646 	if (__predict_false(sc->sc_running == 0)) {
2647 		/* wpi_stop() was called */
2648 		error = ENETDOWN;
2649 		goto end;
2650 	}
2651 
2652 	wh = mtod(buf->m, struct ieee80211_frame *);
2653 	hdrlen = ieee80211_anyhdrsize(wh);
2654 	totlen = buf->m->m_pkthdr.len;
2655 	frag = ((buf->m->m_flags & (M_FRAG | M_LASTFRAG)) == M_FRAG);
2656 
2657 	if (__predict_false(totlen < sizeof(struct ieee80211_frame_min))) {
2658 		error = EINVAL;
2659 		goto end;
2660 	}
2661 
2662 	if (hdrlen & 3) {
2663 		/* First segment length must be a multiple of 4. */
2664 		pad = 4 - (hdrlen & 3);
2665 	} else
2666 		pad = 0;
2667 
2668 	ring = &sc->txq[buf->ac];
2669 	cur = (ring->cur + ring->pending) % WPI_TX_RING_COUNT;
2670 	desc = &ring->desc[cur];
2671 	data = &ring->data[cur];
2672 
2673 	/* Prepare TX firmware command. */
2674 	cmd = &ring->cmd[cur];
2675 	cmd->code = buf->code;
2676 	cmd->flags = 0;
2677 	cmd->qid = ring->qid;
2678 	cmd->idx = cur;
2679 
2680 	memcpy(cmd->data, buf->data, buf->size);
2681 
2682 	/* Save and trim IEEE802.11 header. */
2683 	memcpy((uint8_t *)(cmd->data + buf->size), wh, hdrlen);
2684 	m_adj(buf->m, hdrlen);
2685 
2686 	error = bus_dmamap_load_mbuf_sg(ring->data_dmat, data->map, buf->m,
2687 	    segs, &nsegs, BUS_DMA_NOWAIT);
2688 	if (error != 0 && error != EFBIG) {
2689 		device_printf(sc->sc_dev,
2690 		    "%s: can't map mbuf (error %d)\n", __func__, error);
2691 		goto end;
2692 	}
2693 	if (error != 0) {
2694 		/* Too many DMA segments, linearize mbuf. */
2695 		m1 = m_collapse(buf->m, M_NOWAIT, WPI_MAX_SCATTER - 1);
2696 		if (m1 == NULL) {
2697 			device_printf(sc->sc_dev,
2698 			    "%s: could not defrag mbuf\n", __func__);
2699 			error = ENOBUFS;
2700 			goto end;
2701 		}
2702 		buf->m = m1;
2703 
2704 		error = bus_dmamap_load_mbuf_sg(ring->data_dmat, data->map,
2705 		    buf->m, segs, &nsegs, BUS_DMA_NOWAIT);
2706 		if (__predict_false(error != 0)) {
2707 			/* XXX fix this (applicable to the iwn(4) too) */
2708 			/*
2709 			 * NB: Do not return error;
2710 			 * original mbuf does not exist anymore.
2711 			 */
2712 			device_printf(sc->sc_dev,
2713 			    "%s: can't map mbuf (error %d)\n", __func__,
2714 			    error);
2715 			if (ring->qid < WPI_CMD_QUEUE_NUM) {
2716 				if_inc_counter(buf->ni->ni_vap->iv_ifp,
2717 				    IFCOUNTER_OERRORS, 1);
2718 				if (!frag)
2719 					ieee80211_free_node(buf->ni);
2720 			}
2721 			m_freem(buf->m);
2722 			error = 0;
2723 			goto end;
2724 		}
2725 	}
2726 
2727 	KASSERT(nsegs < WPI_MAX_SCATTER,
2728 	    ("too many DMA segments, nsegs (%d) should be less than %d",
2729 	     nsegs, WPI_MAX_SCATTER));
2730 
2731 	data->m = buf->m;
2732 	data->ni = buf->ni;
2733 	data->hdrlen = hdrlen;
2734 
2735 	DPRINTF(sc, WPI_DEBUG_XMIT, "%s: qid %d idx %d len %d nsegs %d\n",
2736 	    __func__, ring->qid, cur, totlen, nsegs);
2737 
2738 	/* Fill TX descriptor. */
2739 	desc->nsegs = WPI_PAD32(totlen + pad) << 4 | (1 + nsegs);
2740 	/* First DMA segment is used by the TX command. */
2741 	desc->segs[0].addr = htole32(data->cmd_paddr);
2742 	desc->segs[0].len  = htole32(4 + buf->size + hdrlen + pad);
2743 	/* Other DMA segments are for data payload. */
2744 	seg = &segs[0];
2745 	for (i = 1; i <= nsegs; i++) {
2746 		desc->segs[i].addr = htole32(seg->ds_addr);
2747 		desc->segs[i].len  = htole32(seg->ds_len);
2748 		seg++;
2749 	}
2750 
2751 	bus_dmamap_sync(ring->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
2752 	bus_dmamap_sync(ring->data_dmat, ring->cmd_dma.map,
2753 	    BUS_DMASYNC_PREWRITE);
2754 	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
2755 	    BUS_DMASYNC_PREWRITE);
2756 
2757 	ring->pending += 1;
2758 
2759 	if (!frag) {
2760 		if (ring->qid < WPI_CMD_QUEUE_NUM) {
2761 			WPI_TXQ_STATE_LOCK(sc);
2762 			ring->queued += ring->pending;
2763 			callout_reset(&sc->tx_timeout, 5*hz, wpi_tx_timeout,
2764 			    sc);
2765 			WPI_TXQ_STATE_UNLOCK(sc);
2766 		}
2767 
2768 		/* Kick TX ring. */
2769 		ring->cur = (ring->cur + ring->pending) % WPI_TX_RING_COUNT;
2770 		ring->pending = 0;
2771 		sc->sc_update_tx_ring(sc, ring);
2772 	} else
2773 		ieee80211_node_incref(data->ni);
2774 
2775 end:	DPRINTF(sc, WPI_DEBUG_TRACE, error ? TRACE_STR_END_ERR : TRACE_STR_END,
2776 	    __func__);
2777 
2778 	WPI_TXQ_UNLOCK(sc);
2779 
2780 	return (error);
2781 }
2782 
2783 /*
2784  * Construct the data packet for a transmit buffer.
2785  */
2786 static int
2787 wpi_tx_data(struct wpi_softc *sc, struct mbuf *m, struct ieee80211_node *ni)
2788 {
2789 	const struct ieee80211_txparam *tp = ni->ni_txparms;
2790 	struct ieee80211vap *vap = ni->ni_vap;
2791 	struct ieee80211com *ic = ni->ni_ic;
2792 	struct wpi_node *wn = WPI_NODE(ni);
2793 	struct ieee80211_frame *wh;
2794 	struct ieee80211_key *k = NULL;
2795 	struct wpi_buf tx_data;
2796 	struct wpi_cmd_data *tx = (struct wpi_cmd_data *)&tx_data.data;
2797 	uint32_t flags;
2798 	uint16_t ac, qos;
2799 	uint8_t tid, type, rate;
2800 	int swcrypt, ismcast, totlen;
2801 
2802 	wh = mtod(m, struct ieee80211_frame *);
2803 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
2804 	ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
2805 	swcrypt = 1;
2806 
2807 	/* Select EDCA Access Category and TX ring for this frame. */
2808 	if (IEEE80211_QOS_HAS_SEQ(wh)) {
2809 		qos = ((const struct ieee80211_qosframe *)wh)->i_qos[0];
2810 		tid = qos & IEEE80211_QOS_TID;
2811 	} else {
2812 		qos = 0;
2813 		tid = 0;
2814 	}
2815 	ac = M_WME_GETAC(m);
2816 
2817 	/* Choose a TX rate index. */
2818 	if (type == IEEE80211_FC0_TYPE_MGT ||
2819 	    type == IEEE80211_FC0_TYPE_CTL ||
2820 	    (m->m_flags & M_EAPOL) != 0)
2821 		rate = tp->mgmtrate;
2822 	else if (ismcast)
2823 		rate = tp->mcastrate;
2824 	else if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE)
2825 		rate = tp->ucastrate;
2826 	else {
2827 		/* XXX pass pktlen */
2828 		(void) ieee80211_ratectl_rate(ni, NULL, 0);
2829 		rate = ni->ni_txrate;
2830 	}
2831 
2832 	/* Encrypt the frame if need be. */
2833 	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
2834 		/* Retrieve key for TX. */
2835 		k = ieee80211_crypto_encap(ni, m);
2836 		if (k == NULL)
2837 			return (ENOBUFS);
2838 
2839 		swcrypt = k->wk_flags & IEEE80211_KEY_SWCRYPT;
2840 
2841 		/* 802.11 header may have moved. */
2842 		wh = mtod(m, struct ieee80211_frame *);
2843 	}
2844 	totlen = m->m_pkthdr.len;
2845 
2846 	if (ieee80211_radiotap_active_vap(vap)) {
2847 		struct wpi_tx_radiotap_header *tap = &sc->sc_txtap;
2848 
2849 		tap->wt_flags = 0;
2850 		tap->wt_rate = rate;
2851 		if (k != NULL)
2852 			tap->wt_flags |= IEEE80211_RADIOTAP_F_WEP;
2853 		if (wh->i_fc[1] & IEEE80211_FC1_MORE_FRAG)
2854 			tap->wt_flags |= IEEE80211_RADIOTAP_F_FRAG;
2855 
2856 		ieee80211_radiotap_tx(vap, m);
2857 	}
2858 
2859 	flags = 0;
2860 	if (!ismcast) {
2861 		/* Unicast frame, check if an ACK is expected. */
2862 		if (!qos || (qos & IEEE80211_QOS_ACKPOLICY) !=
2863 		    IEEE80211_QOS_ACKPOLICY_NOACK)
2864 			flags |= WPI_TX_NEED_ACK;
2865 	}
2866 
2867 	if (!IEEE80211_QOS_HAS_SEQ(wh))
2868 		flags |= WPI_TX_AUTO_SEQ;
2869 	if (wh->i_fc[1] & IEEE80211_FC1_MORE_FRAG)
2870 		flags |= WPI_TX_MORE_FRAG;
2871 
2872 	/* Check if frame must be protected using RTS/CTS or CTS-to-self. */
2873 	if (!ismcast) {
2874 		/* NB: Group frames are sent using CCK in 802.11b/g. */
2875 		if (totlen + IEEE80211_CRC_LEN > vap->iv_rtsthreshold) {
2876 			flags |= WPI_TX_NEED_RTS;
2877 		} else if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
2878 		    WPI_RATE_IS_OFDM(rate)) {
2879 			if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
2880 				flags |= WPI_TX_NEED_CTS;
2881 			else if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
2882 				flags |= WPI_TX_NEED_RTS;
2883 		}
2884 
2885 		if (flags & (WPI_TX_NEED_RTS | WPI_TX_NEED_CTS))
2886 			flags |= WPI_TX_FULL_TXOP;
2887 	}
2888 
2889 	memset(tx, 0, sizeof (struct wpi_cmd_data));
2890 	if (type == IEEE80211_FC0_TYPE_MGT) {
2891 		uint8_t subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
2892 
2893 		/* Tell HW to set timestamp in probe responses. */
2894 		if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
2895 			flags |= WPI_TX_INSERT_TSTAMP;
2896 		if (subtype == IEEE80211_FC0_SUBTYPE_ASSOC_REQ ||
2897 		    subtype == IEEE80211_FC0_SUBTYPE_REASSOC_REQ)
2898 			tx->timeout = htole16(3);
2899 		else
2900 			tx->timeout = htole16(2);
2901 	}
2902 
2903 	if (ismcast || type != IEEE80211_FC0_TYPE_DATA)
2904 		tx->id = WPI_ID_BROADCAST;
2905 	else {
2906 		if (wn->id == WPI_ID_UNDEFINED) {
2907 			device_printf(sc->sc_dev,
2908 			    "%s: undefined node id\n", __func__);
2909 			return (EINVAL);
2910 		}
2911 
2912 		tx->id = wn->id;
2913 	}
2914 
2915 	if (!swcrypt) {
2916 		switch (k->wk_cipher->ic_cipher) {
2917 		case IEEE80211_CIPHER_AES_CCM:
2918 			tx->security = WPI_CIPHER_CCMP;
2919 			break;
2920 
2921 		default:
2922 			break;
2923 		}
2924 
2925 		memcpy(tx->key, k->wk_key, k->wk_keylen);
2926 	}
2927 
2928 	if (wh->i_fc[1] & IEEE80211_FC1_MORE_FRAG) {
2929 		struct mbuf *next = m->m_nextpkt;
2930 
2931 		tx->lnext = htole16(next->m_pkthdr.len);
2932 		tx->fnext = htole32(tx->security |
2933 				    (flags & WPI_TX_NEED_ACK) |
2934 				    WPI_NEXT_STA_ID(tx->id));
2935 	}
2936 
2937 	tx->len = htole16(totlen);
2938 	tx->flags = htole32(flags);
2939 	tx->plcp = rate2plcp(rate);
2940 	tx->tid = tid;
2941 	tx->lifetime = htole32(WPI_LIFETIME_INFINITE);
2942 	tx->ofdm_mask = 0xff;
2943 	tx->cck_mask = 0x0f;
2944 	tx->rts_ntries = 7;
2945 	tx->data_ntries = tp->maxretry;
2946 
2947 	tx_data.ni = ni;
2948 	tx_data.m = m;
2949 	tx_data.size = sizeof(struct wpi_cmd_data);
2950 	tx_data.code = WPI_CMD_TX_DATA;
2951 	tx_data.ac = ac;
2952 
2953 	return wpi_cmd2(sc, &tx_data);
2954 }
2955 
2956 static int
2957 wpi_tx_data_raw(struct wpi_softc *sc, struct mbuf *m,
2958     struct ieee80211_node *ni, const struct ieee80211_bpf_params *params)
2959 {
2960 	struct ieee80211vap *vap = ni->ni_vap;
2961 	struct ieee80211_key *k = NULL;
2962 	struct ieee80211_frame *wh;
2963 	struct wpi_buf tx_data;
2964 	struct wpi_cmd_data *tx = (struct wpi_cmd_data *)&tx_data.data;
2965 	uint32_t flags;
2966 	uint8_t ac, type, rate;
2967 	int swcrypt, totlen;
2968 
2969 	wh = mtod(m, struct ieee80211_frame *);
2970 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
2971 	swcrypt = 1;
2972 
2973 	ac = params->ibp_pri & 3;
2974 
2975 	/* Choose a TX rate index. */
2976 	rate = params->ibp_rate0;
2977 
2978 	flags = 0;
2979 	if (!IEEE80211_QOS_HAS_SEQ(wh))
2980 		flags |= WPI_TX_AUTO_SEQ;
2981 	if ((params->ibp_flags & IEEE80211_BPF_NOACK) == 0)
2982 		flags |= WPI_TX_NEED_ACK;
2983 	if (params->ibp_flags & IEEE80211_BPF_RTS)
2984 		flags |= WPI_TX_NEED_RTS;
2985 	if (params->ibp_flags & IEEE80211_BPF_CTS)
2986 		flags |= WPI_TX_NEED_CTS;
2987 	if (flags & (WPI_TX_NEED_RTS | WPI_TX_NEED_CTS))
2988 		flags |= WPI_TX_FULL_TXOP;
2989 
2990 	/* Encrypt the frame if need be. */
2991 	if (params->ibp_flags & IEEE80211_BPF_CRYPTO) {
2992 		/* Retrieve key for TX. */
2993 		k = ieee80211_crypto_encap(ni, m);
2994 		if (k == NULL)
2995 			return (ENOBUFS);
2996 
2997 		swcrypt = k->wk_flags & IEEE80211_KEY_SWCRYPT;
2998 
2999 		/* 802.11 header may have moved. */
3000 		wh = mtod(m, struct ieee80211_frame *);
3001 	}
3002 	totlen = m->m_pkthdr.len;
3003 
3004 	if (ieee80211_radiotap_active_vap(vap)) {
3005 		struct wpi_tx_radiotap_header *tap = &sc->sc_txtap;
3006 
3007 		tap->wt_flags = 0;
3008 		tap->wt_rate = rate;
3009 		if (params->ibp_flags & IEEE80211_BPF_CRYPTO)
3010 			tap->wt_flags |= IEEE80211_RADIOTAP_F_WEP;
3011 
3012 		ieee80211_radiotap_tx(vap, m);
3013 	}
3014 
3015 	memset(tx, 0, sizeof (struct wpi_cmd_data));
3016 	if (type == IEEE80211_FC0_TYPE_MGT) {
3017 		uint8_t subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
3018 
3019 		/* Tell HW to set timestamp in probe responses. */
3020 		if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
3021 			flags |= WPI_TX_INSERT_TSTAMP;
3022 		if (subtype == IEEE80211_FC0_SUBTYPE_ASSOC_REQ ||
3023 		    subtype == IEEE80211_FC0_SUBTYPE_REASSOC_REQ)
3024 			tx->timeout = htole16(3);
3025 		else
3026 			tx->timeout = htole16(2);
3027 	}
3028 
3029 	if (!swcrypt) {
3030 		switch (k->wk_cipher->ic_cipher) {
3031 		case IEEE80211_CIPHER_AES_CCM:
3032 			tx->security = WPI_CIPHER_CCMP;
3033 			break;
3034 
3035 		default:
3036 			break;
3037 		}
3038 
3039 		memcpy(tx->key, k->wk_key, k->wk_keylen);
3040 	}
3041 
3042 	tx->len = htole16(totlen);
3043 	tx->flags = htole32(flags);
3044 	tx->plcp = rate2plcp(rate);
3045 	tx->id = WPI_ID_BROADCAST;
3046 	tx->lifetime = htole32(WPI_LIFETIME_INFINITE);
3047 	tx->rts_ntries = params->ibp_try1;
3048 	tx->data_ntries = params->ibp_try0;
3049 
3050 	tx_data.ni = ni;
3051 	tx_data.m = m;
3052 	tx_data.size = sizeof(struct wpi_cmd_data);
3053 	tx_data.code = WPI_CMD_TX_DATA;
3054 	tx_data.ac = ac;
3055 
3056 	return wpi_cmd2(sc, &tx_data);
3057 }
3058 
3059 static __inline int
3060 wpi_tx_ring_free_space(struct wpi_softc *sc, uint16_t ac)
3061 {
3062 	struct wpi_tx_ring *ring = &sc->txq[ac];
3063 	int retval;
3064 
3065 	WPI_TXQ_STATE_LOCK(sc);
3066 	retval = WPI_TX_RING_HIMARK - ring->queued;
3067 	WPI_TXQ_STATE_UNLOCK(sc);
3068 
3069 	return retval;
3070 }
3071 
3072 static int
3073 wpi_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
3074     const struct ieee80211_bpf_params *params)
3075 {
3076 	struct ieee80211com *ic = ni->ni_ic;
3077 	struct wpi_softc *sc = ic->ic_softc;
3078 	uint16_t ac;
3079 	int error = 0;
3080 
3081 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
3082 
3083 	ac = M_WME_GETAC(m);
3084 
3085 	WPI_TX_LOCK(sc);
3086 
3087 	/* NB: no fragments here */
3088 	if (sc->sc_running == 0 || wpi_tx_ring_free_space(sc, ac) < 1) {
3089 		error = sc->sc_running ? ENOBUFS : ENETDOWN;
3090 		goto unlock;
3091 	}
3092 
3093 	if (params == NULL) {
3094 		/*
3095 		 * Legacy path; interpret frame contents to decide
3096 		 * precisely how to send the frame.
3097 		 */
3098 		error = wpi_tx_data(sc, m, ni);
3099 	} else {
3100 		/*
3101 		 * Caller supplied explicit parameters to use in
3102 		 * sending the frame.
3103 		 */
3104 		error = wpi_tx_data_raw(sc, m, ni, params);
3105 	}
3106 
3107 unlock:	WPI_TX_UNLOCK(sc);
3108 
3109 	if (error != 0) {
3110 		m_freem(m);
3111 		DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR, __func__);
3112 
3113 		return error;
3114 	}
3115 
3116 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
3117 
3118 	return 0;
3119 }
3120 
3121 static int
3122 wpi_transmit(struct ieee80211com *ic, struct mbuf *m)
3123 {
3124 	struct wpi_softc *sc = ic->ic_softc;
3125 	struct ieee80211_node *ni;
3126 	struct mbuf *mnext;
3127 	uint16_t ac;
3128 	int error, nmbufs;
3129 
3130 	WPI_TX_LOCK(sc);
3131 	DPRINTF(sc, WPI_DEBUG_XMIT, "%s: called\n", __func__);
3132 
3133 	/* Check if interface is up & running. */
3134 	if (__predict_false(sc->sc_running == 0)) {
3135 		error = ENXIO;
3136 		goto unlock;
3137 	}
3138 
3139 	nmbufs = 1;
3140 	for (mnext = m->m_nextpkt; mnext != NULL; mnext = mnext->m_nextpkt)
3141 		nmbufs++;
3142 
3143 	/* Check for available space. */
3144 	ac = M_WME_GETAC(m);
3145 	if (wpi_tx_ring_free_space(sc, ac) < nmbufs) {
3146 		error = ENOBUFS;
3147 		goto unlock;
3148 	}
3149 
3150 	error = 0;
3151 	ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
3152 	do {
3153 		mnext = m->m_nextpkt;
3154 		if (wpi_tx_data(sc, m, ni) != 0) {
3155 			if_inc_counter(ni->ni_vap->iv_ifp, IFCOUNTER_OERRORS,
3156 			    nmbufs);
3157 			wpi_free_txfrags(sc, ac);
3158 			ieee80211_free_mbuf(m);
3159 			ieee80211_free_node(ni);
3160 			break;
3161 		}
3162 	} while((m = mnext) != NULL);
3163 
3164 	DPRINTF(sc, WPI_DEBUG_XMIT, "%s: done\n", __func__);
3165 
3166 unlock:	WPI_TX_UNLOCK(sc);
3167 
3168 	return (error);
3169 }
3170 
3171 static void
3172 wpi_watchdog_rfkill(void *arg)
3173 {
3174 	struct wpi_softc *sc = arg;
3175 	struct ieee80211com *ic = &sc->sc_ic;
3176 
3177 	DPRINTF(sc, WPI_DEBUG_WATCHDOG, "RFkill Watchdog: tick\n");
3178 
3179 	/* No need to lock firmware memory. */
3180 	if ((wpi_prph_read(sc, WPI_APMG_RFKILL) & 0x1) == 0) {
3181 		/* Radio kill switch is still off. */
3182 		callout_reset(&sc->watchdog_rfkill, hz, wpi_watchdog_rfkill,
3183 		    sc);
3184 	} else
3185 		ieee80211_runtask(ic, &sc->sc_radioon_task);
3186 }
3187 
3188 static void
3189 wpi_scan_timeout(void *arg)
3190 {
3191 	struct wpi_softc *sc = arg;
3192 	struct ieee80211com *ic = &sc->sc_ic;
3193 
3194 	ic_printf(ic, "scan timeout\n");
3195 	ieee80211_restart_all(ic);
3196 }
3197 
3198 static void
3199 wpi_tx_timeout(void *arg)
3200 {
3201 	struct wpi_softc *sc = arg;
3202 	struct ieee80211com *ic = &sc->sc_ic;
3203 
3204 	ic_printf(ic, "device timeout\n");
3205 	ieee80211_restart_all(ic);
3206 }
3207 
3208 static void
3209 wpi_parent(struct ieee80211com *ic)
3210 {
3211 	struct wpi_softc *sc = ic->ic_softc;
3212 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3213 
3214 	if (ic->ic_nrunning > 0) {
3215 		if (wpi_init(sc) == 0) {
3216 			ieee80211_notify_radio(ic, 1);
3217 			ieee80211_start_all(ic);
3218 		} else {
3219 			ieee80211_notify_radio(ic, 0);
3220 			ieee80211_stop(vap);
3221 		}
3222 	} else {
3223 		ieee80211_notify_radio(ic, 0);
3224 		wpi_stop(sc);
3225 	}
3226 }
3227 
3228 /*
3229  * Send a command to the firmware.
3230  */
3231 static int
3232 wpi_cmd(struct wpi_softc *sc, uint8_t code, const void *buf, uint16_t size,
3233     int async)
3234 {
3235 	struct wpi_tx_ring *ring = &sc->txq[WPI_CMD_QUEUE_NUM];
3236 	struct wpi_tx_desc *desc;
3237 	struct wpi_tx_data *data;
3238 	struct wpi_tx_cmd *cmd;
3239 	struct mbuf *m;
3240 	bus_addr_t paddr;
3241 	uint16_t totlen;
3242 	int error;
3243 
3244 	WPI_TXQ_LOCK(sc);
3245 
3246 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
3247 
3248 	if (__predict_false(sc->sc_running == 0)) {
3249 		/* wpi_stop() was called */
3250 		if (code == WPI_CMD_SCAN)
3251 			error = ENETDOWN;
3252 		else
3253 			error = 0;
3254 
3255 		goto fail;
3256 	}
3257 
3258 	if (async == 0)
3259 		WPI_LOCK_ASSERT(sc);
3260 
3261 	DPRINTF(sc, WPI_DEBUG_CMD, "%s: cmd %s size %u async %d\n",
3262 	    __func__, wpi_cmd_str(code), size, async);
3263 
3264 	desc = &ring->desc[ring->cur];
3265 	data = &ring->data[ring->cur];
3266 	totlen = 4 + size;
3267 
3268 	if (size > sizeof cmd->data) {
3269 		/* Command is too large to fit in a descriptor. */
3270 		if (totlen > MCLBYTES) {
3271 			error = EINVAL;
3272 			goto fail;
3273 		}
3274 		m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, MJUMPAGESIZE);
3275 		if (m == NULL) {
3276 			error = ENOMEM;
3277 			goto fail;
3278 		}
3279 		cmd = mtod(m, struct wpi_tx_cmd *);
3280 		error = bus_dmamap_load(ring->data_dmat, data->map, cmd,
3281 		    totlen, wpi_dma_map_addr, &paddr, BUS_DMA_NOWAIT);
3282 		if (error != 0) {
3283 			m_freem(m);
3284 			goto fail;
3285 		}
3286 		data->m = m;
3287 	} else {
3288 		cmd = &ring->cmd[ring->cur];
3289 		paddr = data->cmd_paddr;
3290 	}
3291 
3292 	cmd->code = code;
3293 	cmd->flags = 0;
3294 	cmd->qid = ring->qid;
3295 	cmd->idx = ring->cur;
3296 	memcpy(cmd->data, buf, size);
3297 
3298 	desc->nsegs = 1 + (WPI_PAD32(size) << 4);
3299 	desc->segs[0].addr = htole32(paddr);
3300 	desc->segs[0].len  = htole32(totlen);
3301 
3302 	if (size > sizeof cmd->data) {
3303 		bus_dmamap_sync(ring->data_dmat, data->map,
3304 		    BUS_DMASYNC_PREWRITE);
3305 	} else {
3306 		bus_dmamap_sync(ring->data_dmat, ring->cmd_dma.map,
3307 		    BUS_DMASYNC_PREWRITE);
3308 	}
3309 	bus_dmamap_sync(ring->desc_dma.tag, ring->desc_dma.map,
3310 	    BUS_DMASYNC_PREWRITE);
3311 
3312 	/* Kick command ring. */
3313 	ring->cur = (ring->cur + 1) % WPI_TX_RING_COUNT;
3314 	sc->sc_update_tx_ring(sc, ring);
3315 
3316 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
3317 
3318 	WPI_TXQ_UNLOCK(sc);
3319 
3320 	return async ? 0 : mtx_sleep(cmd, &sc->sc_mtx, PCATCH, "wpicmd", hz);
3321 
3322 fail:	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR, __func__);
3323 
3324 	WPI_TXQ_UNLOCK(sc);
3325 
3326 	return error;
3327 }
3328 
3329 /*
3330  * Configure HW multi-rate retries.
3331  */
3332 static int
3333 wpi_mrr_setup(struct wpi_softc *sc)
3334 {
3335 	struct ieee80211com *ic = &sc->sc_ic;
3336 	struct wpi_mrr_setup mrr;
3337 	uint8_t i;
3338 	int error;
3339 
3340 	/* CCK rates (not used with 802.11a). */
3341 	for (i = WPI_RIDX_CCK1; i <= WPI_RIDX_CCK11; i++) {
3342 		mrr.rates[i].flags = 0;
3343 		mrr.rates[i].plcp = wpi_ridx_to_plcp[i];
3344 		/* Fallback to the immediate lower CCK rate (if any.) */
3345 		mrr.rates[i].next =
3346 		    (i == WPI_RIDX_CCK1) ? WPI_RIDX_CCK1 : i - 1;
3347 		/* Try twice at this rate before falling back to "next". */
3348 		mrr.rates[i].ntries = WPI_NTRIES_DEFAULT;
3349 	}
3350 	/* OFDM rates (not used with 802.11b). */
3351 	for (i = WPI_RIDX_OFDM6; i <= WPI_RIDX_OFDM54; i++) {
3352 		mrr.rates[i].flags = 0;
3353 		mrr.rates[i].plcp = wpi_ridx_to_plcp[i];
3354 		/* Fallback to the immediate lower rate (if any.) */
3355 		/* We allow fallback from OFDM/6 to CCK/2 in 11b/g mode. */
3356 		mrr.rates[i].next = (i == WPI_RIDX_OFDM6) ?
3357 		    ((ic->ic_curmode == IEEE80211_MODE_11A) ?
3358 			WPI_RIDX_OFDM6 : WPI_RIDX_CCK2) :
3359 		    i - 1;
3360 		/* Try twice at this rate before falling back to "next". */
3361 		mrr.rates[i].ntries = WPI_NTRIES_DEFAULT;
3362 	}
3363 	/* Setup MRR for control frames. */
3364 	mrr.which = htole32(WPI_MRR_CTL);
3365 	error = wpi_cmd(sc, WPI_CMD_MRR_SETUP, &mrr, sizeof mrr, 0);
3366 	if (error != 0) {
3367 		device_printf(sc->sc_dev,
3368 		    "could not setup MRR for control frames\n");
3369 		return error;
3370 	}
3371 	/* Setup MRR for data frames. */
3372 	mrr.which = htole32(WPI_MRR_DATA);
3373 	error = wpi_cmd(sc, WPI_CMD_MRR_SETUP, &mrr, sizeof mrr, 0);
3374 	if (error != 0) {
3375 		device_printf(sc->sc_dev,
3376 		    "could not setup MRR for data frames\n");
3377 		return error;
3378 	}
3379 	return 0;
3380 }
3381 
3382 static int
3383 wpi_add_node(struct wpi_softc *sc, struct ieee80211_node *ni)
3384 {
3385 	struct ieee80211com *ic = ni->ni_ic;
3386 	struct wpi_vap *wvp = WPI_VAP(ni->ni_vap);
3387 	struct wpi_node *wn = WPI_NODE(ni);
3388 	struct wpi_node_info node;
3389 	int error;
3390 
3391 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
3392 
3393 	if (wn->id == WPI_ID_UNDEFINED)
3394 		return EINVAL;
3395 
3396 	memset(&node, 0, sizeof node);
3397 	IEEE80211_ADDR_COPY(node.macaddr, ni->ni_macaddr);
3398 	node.id = wn->id;
3399 	node.plcp = (ic->ic_curmode == IEEE80211_MODE_11A) ?
3400 	    wpi_ridx_to_plcp[WPI_RIDX_OFDM6] : wpi_ridx_to_plcp[WPI_RIDX_CCK1];
3401 	node.action = htole32(WPI_ACTION_SET_RATE);
3402 	node.antenna = WPI_ANTENNA_BOTH;
3403 
3404 	DPRINTF(sc, WPI_DEBUG_NODE, "%s: adding node %d (%s)\n", __func__,
3405 	    wn->id, ether_sprintf(ni->ni_macaddr));
3406 
3407 	error = wpi_cmd(sc, WPI_CMD_ADD_NODE, &node, sizeof node, 1);
3408 	if (error != 0) {
3409 		device_printf(sc->sc_dev,
3410 		    "%s: wpi_cmd() call failed with error code %d\n", __func__,
3411 		    error);
3412 		return error;
3413 	}
3414 
3415 	if (wvp->wv_gtk != 0) {
3416 		error = wpi_set_global_keys(ni);
3417 		if (error != 0) {
3418 			device_printf(sc->sc_dev,
3419 			    "%s: error while setting global keys\n", __func__);
3420 			return ENXIO;
3421 		}
3422 	}
3423 
3424 	return 0;
3425 }
3426 
3427 /*
3428  * Broadcast node is used to send group-addressed and management frames.
3429  */
3430 static int
3431 wpi_add_broadcast_node(struct wpi_softc *sc, int async)
3432 {
3433 	struct ieee80211com *ic = &sc->sc_ic;
3434 	struct wpi_node_info node;
3435 
3436 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
3437 
3438 	memset(&node, 0, sizeof node);
3439 	IEEE80211_ADDR_COPY(node.macaddr, ieee80211broadcastaddr);
3440 	node.id = WPI_ID_BROADCAST;
3441 	node.plcp = (ic->ic_curmode == IEEE80211_MODE_11A) ?
3442 	    wpi_ridx_to_plcp[WPI_RIDX_OFDM6] : wpi_ridx_to_plcp[WPI_RIDX_CCK1];
3443 	node.action = htole32(WPI_ACTION_SET_RATE);
3444 	node.antenna = WPI_ANTENNA_BOTH;
3445 
3446 	DPRINTF(sc, WPI_DEBUG_NODE, "%s: adding broadcast node\n", __func__);
3447 
3448 	return wpi_cmd(sc, WPI_CMD_ADD_NODE, &node, sizeof node, async);
3449 }
3450 
3451 static int
3452 wpi_add_sta_node(struct wpi_softc *sc, struct ieee80211_node *ni)
3453 {
3454 	struct wpi_node *wn = WPI_NODE(ni);
3455 	int error;
3456 
3457 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
3458 
3459 	wn->id = wpi_add_node_entry_sta(sc);
3460 
3461 	if ((error = wpi_add_node(sc, ni)) != 0) {
3462 		wpi_del_node_entry(sc, wn->id);
3463 		wn->id = WPI_ID_UNDEFINED;
3464 		return error;
3465 	}
3466 
3467 	return 0;
3468 }
3469 
3470 static int
3471 wpi_add_ibss_node(struct wpi_softc *sc, struct ieee80211_node *ni)
3472 {
3473 	struct wpi_node *wn = WPI_NODE(ni);
3474 	int error;
3475 
3476 	KASSERT(wn->id == WPI_ID_UNDEFINED,
3477 	    ("the node %d was added before", wn->id));
3478 
3479 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
3480 
3481 	if ((wn->id = wpi_add_node_entry_adhoc(sc)) == WPI_ID_UNDEFINED) {
3482 		device_printf(sc->sc_dev, "%s: h/w table is full\n", __func__);
3483 		return ENOMEM;
3484 	}
3485 
3486 	if ((error = wpi_add_node(sc, ni)) != 0) {
3487 		wpi_del_node_entry(sc, wn->id);
3488 		wn->id = WPI_ID_UNDEFINED;
3489 		return error;
3490 	}
3491 
3492 	return 0;
3493 }
3494 
3495 static void
3496 wpi_del_node(struct wpi_softc *sc, struct ieee80211_node *ni)
3497 {
3498 	struct wpi_node *wn = WPI_NODE(ni);
3499 	struct wpi_cmd_del_node node;
3500 	int error;
3501 
3502 	KASSERT(wn->id != WPI_ID_UNDEFINED, ("undefined node id passed"));
3503 
3504 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
3505 
3506 	memset(&node, 0, sizeof node);
3507 	IEEE80211_ADDR_COPY(node.macaddr, ni->ni_macaddr);
3508 	node.count = 1;
3509 
3510 	DPRINTF(sc, WPI_DEBUG_NODE, "%s: deleting node %d (%s)\n", __func__,
3511 	    wn->id, ether_sprintf(ni->ni_macaddr));
3512 
3513 	error = wpi_cmd(sc, WPI_CMD_DEL_NODE, &node, sizeof node, 1);
3514 	if (error != 0) {
3515 		device_printf(sc->sc_dev,
3516 		    "%s: could not delete node %u, error %d\n", __func__,
3517 		    wn->id, error);
3518 	}
3519 }
3520 
3521 static int
3522 wpi_updateedca(struct ieee80211com *ic)
3523 {
3524 #define WPI_EXP2(x)	((1 << (x)) - 1)	/* CWmin = 2^ECWmin - 1 */
3525 	struct wpi_softc *sc = ic->ic_softc;
3526 	struct chanAccParams chp;
3527 	struct wpi_edca_params cmd;
3528 	int aci, error;
3529 
3530 	ieee80211_wme_ic_getparams(ic, &chp);
3531 
3532 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
3533 
3534 	memset(&cmd, 0, sizeof cmd);
3535 	cmd.flags = htole32(WPI_EDCA_UPDATE);
3536 	for (aci = 0; aci < WME_NUM_AC; aci++) {
3537 		const struct wmeParams *ac = &chp.cap_wmeParams[aci];
3538 		cmd.ac[aci].aifsn = ac->wmep_aifsn;
3539 		cmd.ac[aci].cwmin = htole16(WPI_EXP2(ac->wmep_logcwmin));
3540 		cmd.ac[aci].cwmax = htole16(WPI_EXP2(ac->wmep_logcwmax));
3541 		cmd.ac[aci].txoplimit =
3542 		    htole16(IEEE80211_TXOP_TO_US(ac->wmep_txopLimit));
3543 
3544 		DPRINTF(sc, WPI_DEBUG_EDCA,
3545 		    "setting WME for queue %d aifsn=%d cwmin=%d cwmax=%d "
3546 		    "txoplimit=%d\n", aci, cmd.ac[aci].aifsn,
3547 		    cmd.ac[aci].cwmin, cmd.ac[aci].cwmax,
3548 		    cmd.ac[aci].txoplimit);
3549 	}
3550 	error = wpi_cmd(sc, WPI_CMD_EDCA_PARAMS, &cmd, sizeof cmd, 1);
3551 
3552 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
3553 
3554 	return error;
3555 #undef WPI_EXP2
3556 }
3557 
3558 static void
3559 wpi_set_promisc(struct wpi_softc *sc)
3560 {
3561 	struct ieee80211com *ic = &sc->sc_ic;
3562 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3563 	uint32_t promisc_filter;
3564 
3565 	promisc_filter = WPI_FILTER_CTL;
3566 	if (vap != NULL && vap->iv_opmode != IEEE80211_M_HOSTAP)
3567 		promisc_filter |= WPI_FILTER_PROMISC;
3568 
3569 	if (ic->ic_promisc > 0)
3570 		sc->rxon.filter |= htole32(promisc_filter);
3571 	else
3572 		sc->rxon.filter &= ~htole32(promisc_filter);
3573 }
3574 
3575 static void
3576 wpi_update_promisc(struct ieee80211com *ic)
3577 {
3578 	struct wpi_softc *sc = ic->ic_softc;
3579 
3580 	WPI_LOCK(sc);
3581 	if (sc->sc_running == 0) {
3582 		WPI_UNLOCK(sc);
3583 		return;
3584 	}
3585 	WPI_UNLOCK(sc);
3586 
3587 	WPI_RXON_LOCK(sc);
3588 	wpi_set_promisc(sc);
3589 
3590 	if (wpi_send_rxon(sc, 1, 1) != 0) {
3591 		device_printf(sc->sc_dev, "%s: could not send RXON\n",
3592 		    __func__);
3593 	}
3594 	WPI_RXON_UNLOCK(sc);
3595 }
3596 
3597 static void
3598 wpi_update_mcast(struct ieee80211com *ic)
3599 {
3600 	/* Ignore */
3601 }
3602 
3603 static void
3604 wpi_set_led(struct wpi_softc *sc, uint8_t which, uint8_t off, uint8_t on)
3605 {
3606 	struct wpi_cmd_led led;
3607 
3608 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
3609 
3610 	led.which = which;
3611 	led.unit = htole32(100000);	/* on/off in unit of 100ms */
3612 	led.off = off;
3613 	led.on = on;
3614 	(void)wpi_cmd(sc, WPI_CMD_SET_LED, &led, sizeof led, 1);
3615 }
3616 
3617 static int
3618 wpi_set_timing(struct wpi_softc *sc, struct ieee80211_node *ni)
3619 {
3620 	struct wpi_cmd_timing cmd;
3621 	uint64_t val, mod;
3622 
3623 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
3624 
3625 	memset(&cmd, 0, sizeof cmd);
3626 	memcpy(&cmd.tstamp, ni->ni_tstamp.data, sizeof (uint64_t));
3627 	cmd.bintval = htole16(ni->ni_intval);
3628 	cmd.lintval = htole16(10);
3629 
3630 	/* Compute remaining time until next beacon. */
3631 	val = (uint64_t)ni->ni_intval * IEEE80211_DUR_TU;
3632 	mod = le64toh(cmd.tstamp) % val;
3633 	cmd.binitval = htole32((uint32_t)(val - mod));
3634 
3635 	DPRINTF(sc, WPI_DEBUG_RESET, "timing bintval=%u tstamp=%ju, init=%u\n",
3636 	    ni->ni_intval, le64toh(cmd.tstamp), (uint32_t)(val - mod));
3637 
3638 	return wpi_cmd(sc, WPI_CMD_TIMING, &cmd, sizeof cmd, 1);
3639 }
3640 
3641 /*
3642  * This function is called periodically (every 60 seconds) to adjust output
3643  * power to temperature changes.
3644  */
3645 static void
3646 wpi_power_calibration(struct wpi_softc *sc)
3647 {
3648 	int temp;
3649 
3650 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
3651 
3652 	/* Update sensor data. */
3653 	temp = (int)WPI_READ(sc, WPI_UCODE_GP2);
3654 	DPRINTF(sc, WPI_DEBUG_TEMP, "Temp in calibration is: %d\n", temp);
3655 
3656 	/* Sanity-check read value. */
3657 	if (temp < -260 || temp > 25) {
3658 		/* This can't be correct, ignore. */
3659 		DPRINTF(sc, WPI_DEBUG_TEMP,
3660 		    "out-of-range temperature reported: %d\n", temp);
3661 		return;
3662 	}
3663 
3664 	DPRINTF(sc, WPI_DEBUG_TEMP, "temperature %d->%d\n", sc->temp, temp);
3665 
3666 	/* Adjust Tx power if need be. */
3667 	if (abs(temp - sc->temp) <= 6)
3668 		return;
3669 
3670 	sc->temp = temp;
3671 
3672 	if (wpi_set_txpower(sc, 1) != 0) {
3673 		/* just warn, too bad for the automatic calibration... */
3674 		device_printf(sc->sc_dev,"could not adjust Tx power\n");
3675 	}
3676 }
3677 
3678 /*
3679  * Set TX power for current channel.
3680  */
3681 static int
3682 wpi_set_txpower(struct wpi_softc *sc, int async)
3683 {
3684 	struct wpi_power_group *group;
3685 	struct wpi_cmd_txpower cmd;
3686 	uint8_t chan;
3687 	int idx, is_chan_5ghz, i;
3688 
3689 	/* Retrieve current channel from last RXON. */
3690 	chan = sc->rxon.chan;
3691 	is_chan_5ghz = (sc->rxon.flags & htole32(WPI_RXON_24GHZ)) == 0;
3692 
3693 	/* Find the TX power group to which this channel belongs. */
3694 	if (is_chan_5ghz) {
3695 		for (group = &sc->groups[1]; group < &sc->groups[4]; group++)
3696 			if (chan <= group->chan)
3697 				break;
3698 	} else
3699 		group = &sc->groups[0];
3700 
3701 	memset(&cmd, 0, sizeof cmd);
3702 	cmd.band = is_chan_5ghz ? WPI_BAND_5GHZ : WPI_BAND_2GHZ;
3703 	cmd.chan = htole16(chan);
3704 
3705 	/* Set TX power for all OFDM and CCK rates. */
3706 	for (i = 0; i <= WPI_RIDX_MAX ; i++) {
3707 		/* Retrieve TX power for this channel/rate. */
3708 		idx = wpi_get_power_index(sc, group, chan, is_chan_5ghz, i);
3709 
3710 		cmd.rates[i].plcp = wpi_ridx_to_plcp[i];
3711 
3712 		if (is_chan_5ghz) {
3713 			cmd.rates[i].rf_gain = wpi_rf_gain_5ghz[idx];
3714 			cmd.rates[i].dsp_gain = wpi_dsp_gain_5ghz[idx];
3715 		} else {
3716 			cmd.rates[i].rf_gain = wpi_rf_gain_2ghz[idx];
3717 			cmd.rates[i].dsp_gain = wpi_dsp_gain_2ghz[idx];
3718 		}
3719 		DPRINTF(sc, WPI_DEBUG_TEMP,
3720 		    "chan %d/ridx %d: power index %d\n", chan, i, idx);
3721 	}
3722 
3723 	return wpi_cmd(sc, WPI_CMD_TXPOWER, &cmd, sizeof cmd, async);
3724 }
3725 
3726 /*
3727  * Determine Tx power index for a given channel/rate combination.
3728  * This takes into account the regulatory information from EEPROM and the
3729  * current temperature.
3730  */
3731 static int
3732 wpi_get_power_index(struct wpi_softc *sc, struct wpi_power_group *group,
3733     uint8_t chan, int is_chan_5ghz, int ridx)
3734 {
3735 /* Fixed-point arithmetic division using a n-bit fractional part. */
3736 #define fdivround(a, b, n)	\
3737 	((((1 << n) * (a)) / (b) + (1 << n) / 2) / (1 << n))
3738 
3739 /* Linear interpolation. */
3740 #define interpolate(x, x1, y1, x2, y2, n)	\
3741 	((y1) + fdivround(((x) - (x1)) * ((y2) - (y1)), (x2) - (x1), n))
3742 
3743 	struct wpi_power_sample *sample;
3744 	int pwr, idx;
3745 
3746 	/* Default TX power is group maximum TX power minus 3dB. */
3747 	pwr = group->maxpwr / 2;
3748 
3749 	/* Decrease TX power for highest OFDM rates to reduce distortion. */
3750 	switch (ridx) {
3751 	case WPI_RIDX_OFDM36:
3752 		pwr -= is_chan_5ghz ?  5 : 0;
3753 		break;
3754 	case WPI_RIDX_OFDM48:
3755 		pwr -= is_chan_5ghz ? 10 : 7;
3756 		break;
3757 	case WPI_RIDX_OFDM54:
3758 		pwr -= is_chan_5ghz ? 12 : 9;
3759 		break;
3760 	}
3761 
3762 	/* Never exceed the channel maximum allowed TX power. */
3763 	pwr = min(pwr, sc->maxpwr[chan]);
3764 
3765 	/* Retrieve TX power index into gain tables from samples. */
3766 	for (sample = group->samples; sample < &group->samples[3]; sample++)
3767 		if (pwr > sample[1].power)
3768 			break;
3769 	/* Fixed-point linear interpolation using a 19-bit fractional part. */
3770 	idx = interpolate(pwr, sample[0].power, sample[0].index,
3771 	    sample[1].power, sample[1].index, 19);
3772 
3773 	/*-
3774 	 * Adjust power index based on current temperature:
3775 	 * - if cooler than factory-calibrated: decrease output power
3776 	 * - if warmer than factory-calibrated: increase output power
3777 	 */
3778 	idx -= (sc->temp - group->temp) * 11 / 100;
3779 
3780 	/* Decrease TX power for CCK rates (-5dB). */
3781 	if (ridx >= WPI_RIDX_CCK1)
3782 		idx += 10;
3783 
3784 	/* Make sure idx stays in a valid range. */
3785 	if (idx < 0)
3786 		return 0;
3787 	if (idx > WPI_MAX_PWR_INDEX)
3788 		return WPI_MAX_PWR_INDEX;
3789 	return idx;
3790 
3791 #undef interpolate
3792 #undef fdivround
3793 }
3794 
3795 /*
3796  * Set STA mode power saving level (between 0 and 5).
3797  * Level 0 is CAM (Continuously Aware Mode), 5 is for maximum power saving.
3798  */
3799 static int
3800 wpi_set_pslevel(struct wpi_softc *sc, uint8_t dtim, int level, int async)
3801 {
3802 	struct wpi_pmgt_cmd cmd;
3803 	const struct wpi_pmgt *pmgt;
3804 	uint32_t max, reg;
3805 	uint8_t skip_dtim;
3806 	int i;
3807 
3808 	DPRINTF(sc, WPI_DEBUG_PWRSAVE,
3809 	    "%s: dtim=%d, level=%d, async=%d\n",
3810 	    __func__, dtim, level, async);
3811 
3812 	/* Select which PS parameters to use. */
3813 	if (dtim <= 10)
3814 		pmgt = &wpi_pmgt[0][level];
3815 	else
3816 		pmgt = &wpi_pmgt[1][level];
3817 
3818 	memset(&cmd, 0, sizeof cmd);
3819 	if (level != 0)	/* not CAM */
3820 		cmd.flags |= htole16(WPI_PS_ALLOW_SLEEP);
3821 	/* Retrieve PCIe Active State Power Management (ASPM). */
3822 	reg = pci_read_config(sc->sc_dev, sc->sc_cap_off + PCIER_LINK_CTL, 1);
3823 	if (!(reg & PCIEM_LINK_CTL_ASPMC_L0S))	/* L0s Entry disabled. */
3824 		cmd.flags |= htole16(WPI_PS_PCI_PMGT);
3825 
3826 	cmd.rxtimeout = htole32(pmgt->rxtimeout * IEEE80211_DUR_TU);
3827 	cmd.txtimeout = htole32(pmgt->txtimeout * IEEE80211_DUR_TU);
3828 
3829 	if (dtim == 0) {
3830 		dtim = 1;
3831 		skip_dtim = 0;
3832 	} else
3833 		skip_dtim = pmgt->skip_dtim;
3834 
3835 	if (skip_dtim != 0) {
3836 		cmd.flags |= htole16(WPI_PS_SLEEP_OVER_DTIM);
3837 		max = pmgt->intval[4];
3838 		if (max == (uint32_t)-1)
3839 			max = dtim * (skip_dtim + 1);
3840 		else if (max > dtim)
3841 			max = rounddown(max, dtim);
3842 	} else
3843 		max = dtim;
3844 
3845 	for (i = 0; i < 5; i++)
3846 		cmd.intval[i] = htole32(MIN(max, pmgt->intval[i]));
3847 
3848 	return wpi_cmd(sc, WPI_CMD_SET_POWER_MODE, &cmd, sizeof cmd, async);
3849 }
3850 
3851 static int
3852 wpi_send_btcoex(struct wpi_softc *sc)
3853 {
3854 	struct wpi_bluetooth cmd;
3855 
3856 	memset(&cmd, 0, sizeof cmd);
3857 	cmd.flags = WPI_BT_COEX_MODE_4WIRE;
3858 	cmd.lead_time = WPI_BT_LEAD_TIME_DEF;
3859 	cmd.max_kill = WPI_BT_MAX_KILL_DEF;
3860 	DPRINTF(sc, WPI_DEBUG_RESET, "%s: configuring bluetooth coexistence\n",
3861 	    __func__);
3862 	return wpi_cmd(sc, WPI_CMD_BT_COEX, &cmd, sizeof(cmd), 0);
3863 }
3864 
3865 static int
3866 wpi_send_rxon(struct wpi_softc *sc, int assoc, int async)
3867 {
3868 	int error;
3869 
3870 	if (async)
3871 		WPI_RXON_LOCK_ASSERT(sc);
3872 
3873 	if (assoc && wpi_check_bss_filter(sc) != 0) {
3874 		struct wpi_assoc rxon_assoc;
3875 
3876 		rxon_assoc.flags = sc->rxon.flags;
3877 		rxon_assoc.filter = sc->rxon.filter;
3878 		rxon_assoc.ofdm_mask = sc->rxon.ofdm_mask;
3879 		rxon_assoc.cck_mask = sc->rxon.cck_mask;
3880 		rxon_assoc.reserved = 0;
3881 
3882 		error = wpi_cmd(sc, WPI_CMD_RXON_ASSOC, &rxon_assoc,
3883 		    sizeof (struct wpi_assoc), async);
3884 		if (error != 0) {
3885 			device_printf(sc->sc_dev,
3886 			    "RXON_ASSOC command failed, error %d\n", error);
3887 			return error;
3888 		}
3889 	} else {
3890 		if (async) {
3891 			WPI_NT_LOCK(sc);
3892 			error = wpi_cmd(sc, WPI_CMD_RXON, &sc->rxon,
3893 			    sizeof (struct wpi_rxon), async);
3894 			if (error == 0)
3895 				wpi_clear_node_table(sc);
3896 			WPI_NT_UNLOCK(sc);
3897 		} else {
3898 			error = wpi_cmd(sc, WPI_CMD_RXON, &sc->rxon,
3899 			    sizeof (struct wpi_rxon), async);
3900 			if (error == 0)
3901 				wpi_clear_node_table(sc);
3902 		}
3903 
3904 		if (error != 0) {
3905 			device_printf(sc->sc_dev,
3906 			    "RXON command failed, error %d\n", error);
3907 			return error;
3908 		}
3909 
3910 		/* Add broadcast node. */
3911 		error = wpi_add_broadcast_node(sc, async);
3912 		if (error != 0) {
3913 			device_printf(sc->sc_dev,
3914 			    "could not add broadcast node, error %d\n", error);
3915 			return error;
3916 		}
3917 	}
3918 
3919 	/* Configuration has changed, set Tx power accordingly. */
3920 	if ((error = wpi_set_txpower(sc, async)) != 0) {
3921 		device_printf(sc->sc_dev,
3922 		    "%s: could not set TX power, error %d\n", __func__, error);
3923 		return error;
3924 	}
3925 
3926 	return 0;
3927 }
3928 
3929 /**
3930  * Configure the card to listen to a particular channel, this transisions the
3931  * card in to being able to receive frames from remote devices.
3932  */
3933 static int
3934 wpi_config(struct wpi_softc *sc)
3935 {
3936 	struct ieee80211com *ic = &sc->sc_ic;
3937 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
3938 	struct ieee80211_channel *c = ic->ic_curchan;
3939 	int error;
3940 
3941 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
3942 
3943 	/* Set power saving level to CAM during initialization. */
3944 	if ((error = wpi_set_pslevel(sc, 0, 0, 0)) != 0) {
3945 		device_printf(sc->sc_dev,
3946 		    "%s: could not set power saving level\n", __func__);
3947 		return error;
3948 	}
3949 
3950 	/* Configure bluetooth coexistence. */
3951 	if ((error = wpi_send_btcoex(sc)) != 0) {
3952 		device_printf(sc->sc_dev,
3953 		    "could not configure bluetooth coexistence\n");
3954 		return error;
3955 	}
3956 
3957 	/* Configure adapter. */
3958 	memset(&sc->rxon, 0, sizeof (struct wpi_rxon));
3959 	IEEE80211_ADDR_COPY(sc->rxon.myaddr, vap->iv_myaddr);
3960 
3961 	/* Set default channel. */
3962 	sc->rxon.chan = ieee80211_chan2ieee(ic, c);
3963 	sc->rxon.flags = htole32(WPI_RXON_TSF | WPI_RXON_CTS_TO_SELF);
3964 	if (IEEE80211_IS_CHAN_2GHZ(c))
3965 		sc->rxon.flags |= htole32(WPI_RXON_AUTO | WPI_RXON_24GHZ);
3966 
3967 	sc->rxon.filter = WPI_FILTER_MULTICAST;
3968 	switch (ic->ic_opmode) {
3969 	case IEEE80211_M_STA:
3970 		sc->rxon.mode = WPI_MODE_STA;
3971 		break;
3972 	case IEEE80211_M_IBSS:
3973 		sc->rxon.mode = WPI_MODE_IBSS;
3974 		sc->rxon.filter |= WPI_FILTER_BEACON;
3975 		break;
3976 	case IEEE80211_M_HOSTAP:
3977 		/* XXX workaround for beaconing */
3978 		sc->rxon.mode = WPI_MODE_IBSS;
3979 		sc->rxon.filter |= WPI_FILTER_ASSOC | WPI_FILTER_PROMISC;
3980 		break;
3981 	case IEEE80211_M_AHDEMO:
3982 		sc->rxon.mode = WPI_MODE_HOSTAP;
3983 		break;
3984 	case IEEE80211_M_MONITOR:
3985 		sc->rxon.mode = WPI_MODE_MONITOR;
3986 		break;
3987 	default:
3988 		device_printf(sc->sc_dev, "unknown opmode %d\n",
3989 		    ic->ic_opmode);
3990 		return EINVAL;
3991 	}
3992 	sc->rxon.filter = htole32(sc->rxon.filter);
3993 	wpi_set_promisc(sc);
3994 	sc->rxon.cck_mask  = 0x0f;	/* not yet negotiated */
3995 	sc->rxon.ofdm_mask = 0xff;	/* not yet negotiated */
3996 
3997 	if ((error = wpi_send_rxon(sc, 0, 0)) != 0) {
3998 		device_printf(sc->sc_dev, "%s: could not send RXON\n",
3999 		    __func__);
4000 		return error;
4001 	}
4002 
4003 	/* Setup rate scalling. */
4004 	if ((error = wpi_mrr_setup(sc)) != 0) {
4005 		device_printf(sc->sc_dev, "could not setup MRR, error %d\n",
4006 		    error);
4007 		return error;
4008 	}
4009 
4010 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
4011 
4012 	return 0;
4013 }
4014 
4015 static uint16_t
4016 wpi_get_active_dwell_time(struct wpi_softc *sc,
4017     struct ieee80211_channel *c, uint8_t n_probes)
4018 {
4019 	/* No channel? Default to 2GHz settings. */
4020 	if (c == NULL || IEEE80211_IS_CHAN_2GHZ(c)) {
4021 		return (WPI_ACTIVE_DWELL_TIME_2GHZ +
4022 		WPI_ACTIVE_DWELL_FACTOR_2GHZ * (n_probes + 1));
4023 	}
4024 
4025 	/* 5GHz dwell time. */
4026 	return (WPI_ACTIVE_DWELL_TIME_5GHZ +
4027 	    WPI_ACTIVE_DWELL_FACTOR_5GHZ * (n_probes + 1));
4028 }
4029 
4030 /*
4031  * Limit the total dwell time.
4032  *
4033  * Returns the dwell time in milliseconds.
4034  */
4035 static uint16_t
4036 wpi_limit_dwell(struct wpi_softc *sc, uint16_t dwell_time)
4037 {
4038 	struct ieee80211com *ic = &sc->sc_ic;
4039 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
4040 	uint16_t bintval = 0;
4041 
4042 	/* bintval is in TU (1.024mS) */
4043 	if (vap != NULL)
4044 		bintval = vap->iv_bss->ni_intval;
4045 
4046 	/*
4047 	 * If it's non-zero, we should calculate the minimum of
4048 	 * it and the DWELL_BASE.
4049 	 *
4050 	 * XXX Yes, the math should take into account that bintval
4051 	 * is 1.024mS, not 1mS..
4052 	 */
4053 	if (bintval > 0) {
4054 		DPRINTF(sc, WPI_DEBUG_SCAN, "%s: bintval=%d\n", __func__,
4055 		    bintval);
4056 		return (MIN(dwell_time, bintval - WPI_CHANNEL_TUNE_TIME * 2));
4057 	}
4058 
4059 	/* No association context? Default. */
4060 	return dwell_time;
4061 }
4062 
4063 static uint16_t
4064 wpi_get_passive_dwell_time(struct wpi_softc *sc, struct ieee80211_channel *c)
4065 {
4066 	uint16_t passive;
4067 
4068 	if (c == NULL || IEEE80211_IS_CHAN_2GHZ(c))
4069 		passive = WPI_PASSIVE_DWELL_BASE + WPI_PASSIVE_DWELL_TIME_2GHZ;
4070 	else
4071 		passive = WPI_PASSIVE_DWELL_BASE + WPI_PASSIVE_DWELL_TIME_5GHZ;
4072 
4073 	/* Clamp to the beacon interval if we're associated. */
4074 	return (wpi_limit_dwell(sc, passive));
4075 }
4076 
4077 static uint32_t
4078 wpi_get_scan_pause_time(uint32_t time, uint16_t bintval)
4079 {
4080 	uint32_t mod = (time % bintval) * IEEE80211_DUR_TU;
4081 	uint32_t nbeacons = time / bintval;
4082 
4083 	if (mod > WPI_PAUSE_MAX_TIME)
4084 		mod = WPI_PAUSE_MAX_TIME;
4085 
4086 	return WPI_PAUSE_SCAN(nbeacons, mod);
4087 }
4088 
4089 /*
4090  * Send a scan request to the firmware.
4091  */
4092 static int
4093 wpi_scan(struct wpi_softc *sc, struct ieee80211_channel *c)
4094 {
4095 	struct ieee80211com *ic = &sc->sc_ic;
4096 	struct ieee80211_scan_state *ss = ic->ic_scan;
4097 	struct ieee80211vap *vap = ss->ss_vap;
4098 	struct wpi_scan_hdr *hdr;
4099 	struct wpi_cmd_data *tx;
4100 	struct wpi_scan_essid *essids;
4101 	struct wpi_scan_chan *chan;
4102 	struct ieee80211_frame *wh;
4103 	struct ieee80211_rateset *rs;
4104 	uint16_t bintval, buflen, dwell_active, dwell_passive;
4105 	uint8_t *buf, *frm, i, nssid;
4106 	int bgscan, error;
4107 
4108 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
4109 
4110 	/*
4111 	 * We are absolutely not allowed to send a scan command when another
4112 	 * scan command is pending.
4113 	 */
4114 	if (callout_pending(&sc->scan_timeout)) {
4115 		device_printf(sc->sc_dev, "%s: called whilst scanning!\n",
4116 		    __func__);
4117 		error = EAGAIN;
4118 		goto fail;
4119 	}
4120 
4121 	bgscan = wpi_check_bss_filter(sc);
4122 	bintval = vap->iv_bss->ni_intval;
4123 	if (bgscan != 0 &&
4124 	    bintval < WPI_QUIET_TIME_DEFAULT + WPI_CHANNEL_TUNE_TIME * 2) {
4125 		error = EOPNOTSUPP;
4126 		goto fail;
4127 	}
4128 
4129 	buf = malloc(WPI_SCAN_MAXSZ, M_DEVBUF, M_NOWAIT | M_ZERO);
4130 	if (buf == NULL) {
4131 		device_printf(sc->sc_dev,
4132 		    "%s: could not allocate buffer for scan command\n",
4133 		    __func__);
4134 		error = ENOMEM;
4135 		goto fail;
4136 	}
4137 	hdr = (struct wpi_scan_hdr *)buf;
4138 
4139 	/*
4140 	 * Move to the next channel if no packets are received within 10 msecs
4141 	 * after sending the probe request.
4142 	 */
4143 	hdr->quiet_time = htole16(WPI_QUIET_TIME_DEFAULT);
4144 	hdr->quiet_threshold = htole16(1);
4145 
4146 	if (bgscan != 0) {
4147 		/*
4148 		 * Max needs to be greater than active and passive and quiet!
4149 		 * It's also in microseconds!
4150 		 */
4151 		hdr->max_svc = htole32(250 * IEEE80211_DUR_TU);
4152 		hdr->pause_svc = htole32(wpi_get_scan_pause_time(100,
4153 		    bintval));
4154 	}
4155 
4156 	hdr->filter = htole32(WPI_FILTER_MULTICAST | WPI_FILTER_BEACON);
4157 
4158 	tx = (struct wpi_cmd_data *)(hdr + 1);
4159 	tx->flags = htole32(WPI_TX_AUTO_SEQ);
4160 	tx->id = WPI_ID_BROADCAST;
4161 	tx->lifetime = htole32(WPI_LIFETIME_INFINITE);
4162 
4163 	if (IEEE80211_IS_CHAN_5GHZ(c)) {
4164 		/* Send probe requests at 6Mbps. */
4165 		tx->plcp = wpi_ridx_to_plcp[WPI_RIDX_OFDM6];
4166 		rs = &ic->ic_sup_rates[IEEE80211_MODE_11A];
4167 	} else {
4168 		hdr->flags = htole32(WPI_RXON_24GHZ | WPI_RXON_AUTO);
4169 		/* Send probe requests at 1Mbps. */
4170 		tx->plcp = wpi_ridx_to_plcp[WPI_RIDX_CCK1];
4171 		rs = &ic->ic_sup_rates[IEEE80211_MODE_11G];
4172 	}
4173 
4174 	essids = (struct wpi_scan_essid *)(tx + 1);
4175 	nssid = MIN(ss->ss_nssid, WPI_SCAN_MAX_ESSIDS);
4176 	for (i = 0; i < nssid; i++) {
4177 		essids[i].id = IEEE80211_ELEMID_SSID;
4178 		essids[i].len = MIN(ss->ss_ssid[i].len, IEEE80211_NWID_LEN);
4179 		memcpy(essids[i].data, ss->ss_ssid[i].ssid, essids[i].len);
4180 #ifdef WPI_DEBUG
4181 		if (sc->sc_debug & WPI_DEBUG_SCAN) {
4182 			printf("Scanning Essid: ");
4183 			ieee80211_print_essid(essids[i].data, essids[i].len);
4184 			printf("\n");
4185 		}
4186 #endif
4187 	}
4188 
4189 	/*
4190 	 * Build a probe request frame.  Most of the following code is a
4191 	 * copy & paste of what is done in net80211.
4192 	 */
4193 	wh = (struct ieee80211_frame *)(essids + WPI_SCAN_MAX_ESSIDS);
4194 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
4195 		IEEE80211_FC0_SUBTYPE_PROBE_REQ;
4196 	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
4197 	IEEE80211_ADDR_COPY(wh->i_addr1, ieee80211broadcastaddr);
4198 	IEEE80211_ADDR_COPY(wh->i_addr2, vap->iv_myaddr);
4199 	IEEE80211_ADDR_COPY(wh->i_addr3, ieee80211broadcastaddr);
4200 
4201 	frm = (uint8_t *)(wh + 1);
4202 	frm = ieee80211_add_ssid(frm, NULL, 0);
4203 	frm = ieee80211_add_rates(frm, rs);
4204 	if (rs->rs_nrates > IEEE80211_RATE_SIZE)
4205 		frm = ieee80211_add_xrates(frm, rs);
4206 
4207 	/* Set length of probe request. */
4208 	tx->len = htole16(frm - (uint8_t *)wh);
4209 
4210 	/*
4211 	 * Construct information about the channel that we
4212 	 * want to scan. The firmware expects this to be directly
4213 	 * after the scan probe request
4214 	 */
4215 	chan = (struct wpi_scan_chan *)frm;
4216 	chan->chan = ieee80211_chan2ieee(ic, c);
4217 	chan->flags = 0;
4218 	if (nssid) {
4219 		hdr->crc_threshold = WPI_SCAN_CRC_TH_DEFAULT;
4220 		chan->flags |= WPI_CHAN_NPBREQS(nssid);
4221 	} else
4222 		hdr->crc_threshold = WPI_SCAN_CRC_TH_NEVER;
4223 
4224 	if (!IEEE80211_IS_CHAN_PASSIVE(c))
4225 		chan->flags |= WPI_CHAN_ACTIVE;
4226 
4227 	/*
4228 	 * Calculate the active/passive dwell times.
4229 	 */
4230 	dwell_active = wpi_get_active_dwell_time(sc, c, nssid);
4231 	dwell_passive = wpi_get_passive_dwell_time(sc, c);
4232 
4233 	/* Make sure they're valid. */
4234 	if (dwell_active > dwell_passive)
4235 		dwell_active = dwell_passive;
4236 
4237 	chan->active = htole16(dwell_active);
4238 	chan->passive = htole16(dwell_passive);
4239 
4240 	chan->dsp_gain = 0x6e;  /* Default level */
4241 
4242 	if (IEEE80211_IS_CHAN_5GHZ(c))
4243 		chan->rf_gain = 0x3b;
4244 	else
4245 		chan->rf_gain = 0x28;
4246 
4247 	DPRINTF(sc, WPI_DEBUG_SCAN, "Scanning %u Passive: %d\n",
4248 	    chan->chan, IEEE80211_IS_CHAN_PASSIVE(c));
4249 
4250 	hdr->nchan++;
4251 
4252 	if (hdr->nchan == 1 && sc->rxon.chan == chan->chan) {
4253 		/* XXX Force probe request transmission. */
4254 		memcpy(chan + 1, chan, sizeof (struct wpi_scan_chan));
4255 
4256 		chan++;
4257 
4258 		/* Reduce unnecessary delay. */
4259 		chan->flags = 0;
4260 		chan->passive = chan->active = hdr->quiet_time;
4261 
4262 		hdr->nchan++;
4263 	}
4264 
4265 	chan++;
4266 
4267 	buflen = (uint8_t *)chan - buf;
4268 	hdr->len = htole16(buflen);
4269 
4270 	DPRINTF(sc, WPI_DEBUG_CMD, "sending scan command nchan=%d\n",
4271 	    hdr->nchan);
4272 	error = wpi_cmd(sc, WPI_CMD_SCAN, buf, buflen, 1);
4273 	free(buf, M_DEVBUF);
4274 
4275 	if (error != 0)
4276 		goto fail;
4277 
4278 	callout_reset(&sc->scan_timeout, 5*hz, wpi_scan_timeout, sc);
4279 
4280 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
4281 
4282 	return 0;
4283 
4284 fail:	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR, __func__);
4285 
4286 	return error;
4287 }
4288 
4289 static int
4290 wpi_auth(struct wpi_softc *sc, struct ieee80211vap *vap)
4291 {
4292 	struct ieee80211com *ic = vap->iv_ic;
4293 	struct ieee80211_node *ni = vap->iv_bss;
4294 	struct ieee80211_channel *c = ni->ni_chan;
4295 	int error;
4296 
4297 	WPI_RXON_LOCK(sc);
4298 
4299 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
4300 
4301 	/* Update adapter configuration. */
4302 	sc->rxon.associd = 0;
4303 	sc->rxon.filter &= ~htole32(WPI_FILTER_BSS);
4304 	IEEE80211_ADDR_COPY(sc->rxon.bssid, ni->ni_bssid);
4305 	sc->rxon.chan = ieee80211_chan2ieee(ic, c);
4306 	sc->rxon.flags = htole32(WPI_RXON_TSF | WPI_RXON_CTS_TO_SELF);
4307 	if (IEEE80211_IS_CHAN_2GHZ(c))
4308 		sc->rxon.flags |= htole32(WPI_RXON_AUTO | WPI_RXON_24GHZ);
4309 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
4310 		sc->rxon.flags |= htole32(WPI_RXON_SHSLOT);
4311 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
4312 		sc->rxon.flags |= htole32(WPI_RXON_SHPREAMBLE);
4313 	if (IEEE80211_IS_CHAN_A(c)) {
4314 		sc->rxon.cck_mask  = 0;
4315 		sc->rxon.ofdm_mask = 0x15;
4316 	} else if (IEEE80211_IS_CHAN_B(c)) {
4317 		sc->rxon.cck_mask  = 0x03;
4318 		sc->rxon.ofdm_mask = 0;
4319 	} else {
4320 		/* Assume 802.11b/g. */
4321 		sc->rxon.cck_mask  = 0x0f;
4322 		sc->rxon.ofdm_mask = 0x15;
4323 	}
4324 
4325 	DPRINTF(sc, WPI_DEBUG_STATE, "rxon chan %d flags %x cck %x ofdm %x\n",
4326 	    sc->rxon.chan, sc->rxon.flags, sc->rxon.cck_mask,
4327 	    sc->rxon.ofdm_mask);
4328 
4329 	if ((error = wpi_send_rxon(sc, 0, 1)) != 0) {
4330 		device_printf(sc->sc_dev, "%s: could not send RXON\n",
4331 		    __func__);
4332 	}
4333 
4334 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
4335 
4336 	WPI_RXON_UNLOCK(sc);
4337 
4338 	return error;
4339 }
4340 
4341 static int
4342 wpi_config_beacon(struct wpi_vap *wvp)
4343 {
4344 	struct ieee80211vap *vap = &wvp->wv_vap;
4345 	struct ieee80211com *ic = vap->iv_ic;
4346 	struct ieee80211_beacon_offsets *bo = &vap->iv_bcn_off;
4347 	struct wpi_buf *bcn = &wvp->wv_bcbuf;
4348 	struct wpi_softc *sc = ic->ic_softc;
4349 	struct wpi_cmd_beacon *cmd = (struct wpi_cmd_beacon *)&bcn->data;
4350 	struct ieee80211_tim_ie *tie;
4351 	struct mbuf *m;
4352 	uint8_t *ptr;
4353 	int error;
4354 
4355 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
4356 
4357 	WPI_VAP_LOCK_ASSERT(wvp);
4358 
4359 	cmd->len = htole16(bcn->m->m_pkthdr.len);
4360 	cmd->plcp = (ic->ic_curmode == IEEE80211_MODE_11A) ?
4361 	    wpi_ridx_to_plcp[WPI_RIDX_OFDM6] : wpi_ridx_to_plcp[WPI_RIDX_CCK1];
4362 
4363 	/* XXX seems to be unused */
4364 	if (*(bo->bo_tim) == IEEE80211_ELEMID_TIM) {
4365 		tie = (struct ieee80211_tim_ie *) bo->bo_tim;
4366 		ptr = mtod(bcn->m, uint8_t *);
4367 
4368 		cmd->tim = htole16(bo->bo_tim - ptr);
4369 		cmd->timsz = tie->tim_len;
4370 	}
4371 
4372 	/* Necessary for recursion in ieee80211_beacon_update(). */
4373 	m = bcn->m;
4374 	bcn->m = m_dup(m, M_NOWAIT);
4375 	if (bcn->m == NULL) {
4376 		device_printf(sc->sc_dev,
4377 		    "%s: could not copy beacon frame\n", __func__);
4378 		error = ENOMEM;
4379 		goto end;
4380 	}
4381 
4382 	if ((error = wpi_cmd2(sc, bcn)) != 0) {
4383 		device_printf(sc->sc_dev,
4384 		    "%s: could not update beacon frame, error %d", __func__,
4385 		    error);
4386 		m_freem(bcn->m);
4387 	}
4388 
4389 	/* Restore mbuf. */
4390 end:	bcn->m = m;
4391 
4392 	return error;
4393 }
4394 
4395 static int
4396 wpi_setup_beacon(struct wpi_softc *sc, struct ieee80211_node *ni)
4397 {
4398 	struct ieee80211vap *vap = ni->ni_vap;
4399 	struct wpi_vap *wvp = WPI_VAP(vap);
4400 	struct wpi_buf *bcn = &wvp->wv_bcbuf;
4401 	struct mbuf *m;
4402 	int error;
4403 
4404 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
4405 
4406 	if (ni->ni_chan == IEEE80211_CHAN_ANYC)
4407 		return EINVAL;
4408 
4409 	m = ieee80211_beacon_alloc(ni);
4410 	if (m == NULL) {
4411 		device_printf(sc->sc_dev,
4412 		    "%s: could not allocate beacon frame\n", __func__);
4413 		return ENOMEM;
4414 	}
4415 
4416 	WPI_VAP_LOCK(wvp);
4417 	if (bcn->m != NULL)
4418 		m_freem(bcn->m);
4419 
4420 	bcn->m = m;
4421 
4422 	error = wpi_config_beacon(wvp);
4423 	WPI_VAP_UNLOCK(wvp);
4424 
4425 	return error;
4426 }
4427 
4428 static void
4429 wpi_update_beacon(struct ieee80211vap *vap, int item)
4430 {
4431 	struct wpi_softc *sc = vap->iv_ic->ic_softc;
4432 	struct wpi_vap *wvp = WPI_VAP(vap);
4433 	struct wpi_buf *bcn = &wvp->wv_bcbuf;
4434 	struct ieee80211_beacon_offsets *bo = &vap->iv_bcn_off;
4435 	struct ieee80211_node *ni = vap->iv_bss;
4436 	int mcast = 0;
4437 
4438 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
4439 
4440 	WPI_VAP_LOCK(wvp);
4441 	if (bcn->m == NULL) {
4442 		bcn->m = ieee80211_beacon_alloc(ni);
4443 		if (bcn->m == NULL) {
4444 			device_printf(sc->sc_dev,
4445 			    "%s: could not allocate beacon frame\n", __func__);
4446 
4447 			DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR,
4448 			    __func__);
4449 
4450 			WPI_VAP_UNLOCK(wvp);
4451 			return;
4452 		}
4453 	}
4454 	WPI_VAP_UNLOCK(wvp);
4455 
4456 	if (item == IEEE80211_BEACON_TIM)
4457 		mcast = 1;	/* TODO */
4458 
4459 	setbit(bo->bo_flags, item);
4460 	ieee80211_beacon_update(ni, bcn->m, mcast);
4461 
4462 	WPI_VAP_LOCK(wvp);
4463 	wpi_config_beacon(wvp);
4464 	WPI_VAP_UNLOCK(wvp);
4465 
4466 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
4467 }
4468 
4469 static void
4470 wpi_newassoc(struct ieee80211_node *ni, int isnew)
4471 {
4472 	struct ieee80211vap *vap = ni->ni_vap;
4473 	struct wpi_softc *sc = ni->ni_ic->ic_softc;
4474 	struct wpi_node *wn = WPI_NODE(ni);
4475 	int error;
4476 
4477 	WPI_NT_LOCK(sc);
4478 
4479 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
4480 
4481 	if (vap->iv_opmode != IEEE80211_M_STA && wn->id == WPI_ID_UNDEFINED) {
4482 		if ((error = wpi_add_ibss_node(sc, ni)) != 0) {
4483 			device_printf(sc->sc_dev,
4484 			    "%s: could not add IBSS node, error %d\n",
4485 			    __func__, error);
4486 		}
4487 	}
4488 	WPI_NT_UNLOCK(sc);
4489 }
4490 
4491 static int
4492 wpi_run(struct wpi_softc *sc, struct ieee80211vap *vap)
4493 {
4494 	struct ieee80211com *ic = vap->iv_ic;
4495 	struct ieee80211_node *ni = vap->iv_bss;
4496 	struct ieee80211_channel *c = ni->ni_chan;
4497 	int error;
4498 
4499 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
4500 
4501 	if (vap->iv_opmode == IEEE80211_M_MONITOR) {
4502 		/* Link LED blinks while monitoring. */
4503 		wpi_set_led(sc, WPI_LED_LINK, 5, 5);
4504 		return 0;
4505 	}
4506 
4507 	/* XXX kernel panic workaround */
4508 	if (c == IEEE80211_CHAN_ANYC) {
4509 		device_printf(sc->sc_dev, "%s: incomplete configuration\n",
4510 		    __func__);
4511 		return EINVAL;
4512 	}
4513 
4514 	if ((error = wpi_set_timing(sc, ni)) != 0) {
4515 		device_printf(sc->sc_dev,
4516 		    "%s: could not set timing, error %d\n", __func__, error);
4517 		return error;
4518 	}
4519 
4520 	/* Update adapter configuration. */
4521 	WPI_RXON_LOCK(sc);
4522 	IEEE80211_ADDR_COPY(sc->rxon.bssid, ni->ni_bssid);
4523 	sc->rxon.associd = htole16(IEEE80211_NODE_AID(ni));
4524 	sc->rxon.chan = ieee80211_chan2ieee(ic, c);
4525 	sc->rxon.flags = htole32(WPI_RXON_TSF | WPI_RXON_CTS_TO_SELF);
4526 	if (IEEE80211_IS_CHAN_2GHZ(c))
4527 		sc->rxon.flags |= htole32(WPI_RXON_AUTO | WPI_RXON_24GHZ);
4528 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
4529 		sc->rxon.flags |= htole32(WPI_RXON_SHSLOT);
4530 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
4531 		sc->rxon.flags |= htole32(WPI_RXON_SHPREAMBLE);
4532 	if (IEEE80211_IS_CHAN_A(c)) {
4533 		sc->rxon.cck_mask  = 0;
4534 		sc->rxon.ofdm_mask = 0x15;
4535 	} else if (IEEE80211_IS_CHAN_B(c)) {
4536 		sc->rxon.cck_mask  = 0x03;
4537 		sc->rxon.ofdm_mask = 0;
4538 	} else {
4539 		/* Assume 802.11b/g. */
4540 		sc->rxon.cck_mask  = 0x0f;
4541 		sc->rxon.ofdm_mask = 0x15;
4542 	}
4543 	sc->rxon.filter |= htole32(WPI_FILTER_BSS);
4544 
4545 	DPRINTF(sc, WPI_DEBUG_STATE, "rxon chan %d flags %x\n",
4546 	    sc->rxon.chan, sc->rxon.flags);
4547 
4548 	if ((error = wpi_send_rxon(sc, 0, 1)) != 0) {
4549 		WPI_RXON_UNLOCK(sc);
4550 		device_printf(sc->sc_dev, "%s: could not send RXON\n",
4551 		    __func__);
4552 		return error;
4553 	}
4554 
4555 	/* Start periodic calibration timer. */
4556 	callout_reset(&sc->calib_to, 60*hz, wpi_calib_timeout, sc);
4557 
4558 	WPI_RXON_UNLOCK(sc);
4559 
4560 	if (vap->iv_opmode == IEEE80211_M_IBSS ||
4561 	    vap->iv_opmode == IEEE80211_M_HOSTAP) {
4562 		if ((error = wpi_setup_beacon(sc, ni)) != 0) {
4563 			device_printf(sc->sc_dev,
4564 			    "%s: could not setup beacon, error %d\n", __func__,
4565 			    error);
4566 			return error;
4567 		}
4568 	}
4569 
4570 	if (vap->iv_opmode == IEEE80211_M_STA) {
4571 		/* Add BSS node. */
4572 		WPI_NT_LOCK(sc);
4573 		error = wpi_add_sta_node(sc, ni);
4574 		WPI_NT_UNLOCK(sc);
4575 		if (error != 0) {
4576 			device_printf(sc->sc_dev,
4577 			    "%s: could not add BSS node, error %d\n", __func__,
4578 			    error);
4579 			return error;
4580 		}
4581 	}
4582 
4583 	/* Link LED always on while associated. */
4584 	wpi_set_led(sc, WPI_LED_LINK, 0, 1);
4585 
4586 	/* Enable power-saving mode if requested by user. */
4587 	if ((vap->iv_flags & IEEE80211_F_PMGTON) &&
4588 	    vap->iv_opmode != IEEE80211_M_IBSS)
4589 		(void)wpi_set_pslevel(sc, 0, 3, 1);
4590 
4591 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
4592 
4593 	return 0;
4594 }
4595 
4596 static int
4597 wpi_load_key(struct ieee80211_node *ni, const struct ieee80211_key *k)
4598 {
4599 	const struct ieee80211_cipher *cip = k->wk_cipher;
4600 	struct ieee80211vap *vap = ni->ni_vap;
4601 	struct wpi_softc *sc = ni->ni_ic->ic_softc;
4602 	struct wpi_node *wn = WPI_NODE(ni);
4603 	struct wpi_node_info node;
4604 	uint16_t kflags;
4605 	int error;
4606 
4607 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
4608 
4609 	if (wpi_check_node_entry(sc, wn->id) == 0) {
4610 		device_printf(sc->sc_dev, "%s: node does not exist\n",
4611 		    __func__);
4612 		return 0;
4613 	}
4614 
4615 	switch (cip->ic_cipher) {
4616 	case IEEE80211_CIPHER_AES_CCM:
4617 		kflags = WPI_KFLAG_CCMP;
4618 		break;
4619 
4620 	default:
4621 		device_printf(sc->sc_dev, "%s: unknown cipher %d\n", __func__,
4622 		    cip->ic_cipher);
4623 		return 0;
4624 	}
4625 
4626 	kflags |= WPI_KFLAG_KID(k->wk_keyix);
4627 	if (k->wk_flags & IEEE80211_KEY_GROUP)
4628 		kflags |= WPI_KFLAG_MULTICAST;
4629 
4630 	memset(&node, 0, sizeof node);
4631 	node.id = wn->id;
4632 	node.control = WPI_NODE_UPDATE;
4633 	node.flags = WPI_FLAG_KEY_SET;
4634 	node.kflags = htole16(kflags);
4635 	memcpy(node.key, k->wk_key, k->wk_keylen);
4636 again:
4637 	DPRINTF(sc, WPI_DEBUG_KEY,
4638 	    "%s: setting %s key id %d for node %d (%s)\n", __func__,
4639 	    (kflags & WPI_KFLAG_MULTICAST) ? "group" : "ucast", k->wk_keyix,
4640 	    node.id, ether_sprintf(ni->ni_macaddr));
4641 
4642 	error = wpi_cmd(sc, WPI_CMD_ADD_NODE, &node, sizeof node, 1);
4643 	if (error != 0) {
4644 		device_printf(sc->sc_dev, "can't update node info, error %d\n",
4645 		    error);
4646 		return !error;
4647 	}
4648 
4649 	if (!(kflags & WPI_KFLAG_MULTICAST) && &vap->iv_nw_keys[0] <= k &&
4650 	    k < &vap->iv_nw_keys[IEEE80211_WEP_NKID]) {
4651 		kflags |= WPI_KFLAG_MULTICAST;
4652 		node.kflags = htole16(kflags);
4653 
4654 		goto again;
4655 	}
4656 
4657 	return 1;
4658 }
4659 
4660 static void
4661 wpi_load_key_cb(void *arg, struct ieee80211_node *ni)
4662 {
4663 	const struct ieee80211_key *k = arg;
4664 	struct ieee80211vap *vap = ni->ni_vap;
4665 	struct wpi_softc *sc = ni->ni_ic->ic_softc;
4666 	struct wpi_node *wn = WPI_NODE(ni);
4667 	int error;
4668 
4669 	if (vap->iv_bss == ni && wn->id == WPI_ID_UNDEFINED)
4670 		return;
4671 
4672 	WPI_NT_LOCK(sc);
4673 	error = wpi_load_key(ni, k);
4674 	WPI_NT_UNLOCK(sc);
4675 
4676 	if (error == 0) {
4677 		device_printf(sc->sc_dev, "%s: error while setting key\n",
4678 		    __func__);
4679 	}
4680 }
4681 
4682 static int
4683 wpi_set_global_keys(struct ieee80211_node *ni)
4684 {
4685 	struct ieee80211vap *vap = ni->ni_vap;
4686 	struct ieee80211_key *wk = &vap->iv_nw_keys[0];
4687 	int error = 1;
4688 
4689 	for (; wk < &vap->iv_nw_keys[IEEE80211_WEP_NKID] && error; wk++)
4690 		if (wk->wk_keyix != IEEE80211_KEYIX_NONE)
4691 			error = wpi_load_key(ni, wk);
4692 
4693 	return !error;
4694 }
4695 
4696 static int
4697 wpi_del_key(struct ieee80211_node *ni, const struct ieee80211_key *k)
4698 {
4699 	struct ieee80211vap *vap = ni->ni_vap;
4700 	struct wpi_softc *sc = ni->ni_ic->ic_softc;
4701 	struct wpi_node *wn = WPI_NODE(ni);
4702 	struct wpi_node_info node;
4703 	uint16_t kflags;
4704 	int error;
4705 
4706 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
4707 
4708 	if (wpi_check_node_entry(sc, wn->id) == 0) {
4709 		DPRINTF(sc, WPI_DEBUG_KEY, "%s: node was removed\n", __func__);
4710 		return 1;	/* Nothing to do. */
4711 	}
4712 
4713 	kflags = WPI_KFLAG_KID(k->wk_keyix);
4714 	if (k->wk_flags & IEEE80211_KEY_GROUP)
4715 		kflags |= WPI_KFLAG_MULTICAST;
4716 
4717 	memset(&node, 0, sizeof node);
4718 	node.id = wn->id;
4719 	node.control = WPI_NODE_UPDATE;
4720 	node.flags = WPI_FLAG_KEY_SET;
4721 	node.kflags = htole16(kflags);
4722 again:
4723 	DPRINTF(sc, WPI_DEBUG_KEY, "%s: deleting %s key %d for node %d (%s)\n",
4724 	    __func__, (kflags & WPI_KFLAG_MULTICAST) ? "group" : "ucast",
4725 	    k->wk_keyix, node.id, ether_sprintf(ni->ni_macaddr));
4726 
4727 	error = wpi_cmd(sc, WPI_CMD_ADD_NODE, &node, sizeof node, 1);
4728 	if (error != 0) {
4729 		device_printf(sc->sc_dev, "can't update node info, error %d\n",
4730 		    error);
4731 		return !error;
4732 	}
4733 
4734 	if (!(kflags & WPI_KFLAG_MULTICAST) && &vap->iv_nw_keys[0] <= k &&
4735 	    k < &vap->iv_nw_keys[IEEE80211_WEP_NKID]) {
4736 		kflags |= WPI_KFLAG_MULTICAST;
4737 		node.kflags = htole16(kflags);
4738 
4739 		goto again;
4740 	}
4741 
4742 	return 1;
4743 }
4744 
4745 static void
4746 wpi_del_key_cb(void *arg, struct ieee80211_node *ni)
4747 {
4748 	const struct ieee80211_key *k = arg;
4749 	struct ieee80211vap *vap = ni->ni_vap;
4750 	struct wpi_softc *sc = ni->ni_ic->ic_softc;
4751 	struct wpi_node *wn = WPI_NODE(ni);
4752 	int error;
4753 
4754 	if (vap->iv_bss == ni && wn->id == WPI_ID_UNDEFINED)
4755 		return;
4756 
4757 	WPI_NT_LOCK(sc);
4758 	error = wpi_del_key(ni, k);
4759 	WPI_NT_UNLOCK(sc);
4760 
4761 	if (error == 0) {
4762 		device_printf(sc->sc_dev, "%s: error while deleting key\n",
4763 		    __func__);
4764 	}
4765 }
4766 
4767 static int
4768 wpi_process_key(struct ieee80211vap *vap, const struct ieee80211_key *k,
4769     int set)
4770 {
4771 	struct ieee80211com *ic = vap->iv_ic;
4772 	struct wpi_softc *sc = ic->ic_softc;
4773 	struct wpi_vap *wvp = WPI_VAP(vap);
4774 	struct ieee80211_node *ni;
4775 	int error, ni_ref = 0;
4776 
4777 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
4778 
4779 	if (k->wk_flags & IEEE80211_KEY_SWCRYPT) {
4780 		/* Not for us. */
4781 		return 1;
4782 	}
4783 
4784 	if (!(k->wk_flags & IEEE80211_KEY_RECV)) {
4785 		/* XMIT keys are handled in wpi_tx_data(). */
4786 		return 1;
4787 	}
4788 
4789 	/* Handle group keys. */
4790 	if (&vap->iv_nw_keys[0] <= k &&
4791 	    k < &vap->iv_nw_keys[IEEE80211_WEP_NKID]) {
4792 		WPI_NT_LOCK(sc);
4793 		if (set)
4794 			wvp->wv_gtk |= WPI_VAP_KEY(k->wk_keyix);
4795 		else
4796 			wvp->wv_gtk &= ~WPI_VAP_KEY(k->wk_keyix);
4797 		WPI_NT_UNLOCK(sc);
4798 
4799 		if (vap->iv_state == IEEE80211_S_RUN) {
4800 			ieee80211_iterate_nodes(&ic->ic_sta,
4801 			    set ? wpi_load_key_cb : wpi_del_key_cb,
4802 			    __DECONST(void *, k));
4803 		}
4804 
4805 		return 1;
4806 	}
4807 
4808 	switch (vap->iv_opmode) {
4809 	case IEEE80211_M_STA:
4810 		ni = vap->iv_bss;
4811 		break;
4812 
4813 	case IEEE80211_M_IBSS:
4814 	case IEEE80211_M_AHDEMO:
4815 	case IEEE80211_M_HOSTAP:
4816 		ni = ieee80211_find_vap_node(&ic->ic_sta, vap, k->wk_macaddr);
4817 		if (ni == NULL)
4818 			return 0;	/* should not happen */
4819 
4820 		ni_ref = 1;
4821 		break;
4822 
4823 	default:
4824 		device_printf(sc->sc_dev, "%s: unknown opmode %d\n", __func__,
4825 		    vap->iv_opmode);
4826 		return 0;
4827 	}
4828 
4829 	WPI_NT_LOCK(sc);
4830 	if (set)
4831 		error = wpi_load_key(ni, k);
4832 	else
4833 		error = wpi_del_key(ni, k);
4834 	WPI_NT_UNLOCK(sc);
4835 
4836 	if (ni_ref)
4837 		ieee80211_node_decref(ni);
4838 
4839 	return error;
4840 }
4841 
4842 static int
4843 wpi_key_set(struct ieee80211vap *vap, const struct ieee80211_key *k)
4844 {
4845 	return wpi_process_key(vap, k, 1);
4846 }
4847 
4848 static int
4849 wpi_key_delete(struct ieee80211vap *vap, const struct ieee80211_key *k)
4850 {
4851 	return wpi_process_key(vap, k, 0);
4852 }
4853 
4854 /*
4855  * This function is called after the runtime firmware notifies us of its
4856  * readiness (called in a process context).
4857  */
4858 static int
4859 wpi_post_alive(struct wpi_softc *sc)
4860 {
4861 	int ntries, error;
4862 
4863 	/* Check (again) that the radio is not disabled. */
4864 	if ((error = wpi_nic_lock(sc)) != 0)
4865 		return error;
4866 
4867 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
4868 
4869 	/* NB: Runtime firmware must be up and running. */
4870 	if (!(wpi_prph_read(sc, WPI_APMG_RFKILL) & 1)) {
4871 		device_printf(sc->sc_dev,
4872 		    "RF switch: radio disabled (%s)\n", __func__);
4873 		wpi_nic_unlock(sc);
4874 		return EPERM;   /* :-) */
4875 	}
4876 	wpi_nic_unlock(sc);
4877 
4878 	/* Wait for thermal sensor to calibrate. */
4879 	for (ntries = 0; ntries < 1000; ntries++) {
4880 		if ((sc->temp = (int)WPI_READ(sc, WPI_UCODE_GP2)) != 0)
4881 			break;
4882 		DELAY(10);
4883 	}
4884 
4885 	if (ntries == 1000) {
4886 		device_printf(sc->sc_dev,
4887 		    "timeout waiting for thermal sensor calibration\n");
4888 		return ETIMEDOUT;
4889 	}
4890 
4891 	DPRINTF(sc, WPI_DEBUG_TEMP, "temperature %d\n", sc->temp);
4892 	return 0;
4893 }
4894 
4895 /*
4896  * The firmware boot code is small and is intended to be copied directly into
4897  * the NIC internal memory (no DMA transfer).
4898  */
4899 static int
4900 wpi_load_bootcode(struct wpi_softc *sc, const uint8_t *ucode, uint32_t size)
4901 {
4902 	int error, ntries;
4903 
4904 	DPRINTF(sc, WPI_DEBUG_HW, "Loading microcode size 0x%x\n", size);
4905 
4906 	size /= sizeof (uint32_t);
4907 
4908 	if ((error = wpi_nic_lock(sc)) != 0)
4909 		return error;
4910 
4911 	/* Copy microcode image into NIC memory. */
4912 	wpi_prph_write_region_4(sc, WPI_BSM_SRAM_BASE,
4913 	    (const uint32_t *)ucode, size);
4914 
4915 	wpi_prph_write(sc, WPI_BSM_WR_MEM_SRC, 0);
4916 	wpi_prph_write(sc, WPI_BSM_WR_MEM_DST, WPI_FW_TEXT_BASE);
4917 	wpi_prph_write(sc, WPI_BSM_WR_DWCOUNT, size);
4918 
4919 	/* Start boot load now. */
4920 	wpi_prph_write(sc, WPI_BSM_WR_CTRL, WPI_BSM_WR_CTRL_START);
4921 
4922 	/* Wait for transfer to complete. */
4923 	for (ntries = 0; ntries < 1000; ntries++) {
4924 		uint32_t status = WPI_READ(sc, WPI_FH_TX_STATUS);
4925 		DPRINTF(sc, WPI_DEBUG_HW,
4926 		    "firmware status=0x%x, val=0x%x, result=0x%x\n", status,
4927 		    WPI_FH_TX_STATUS_IDLE(6),
4928 		    status & WPI_FH_TX_STATUS_IDLE(6));
4929 		if (status & WPI_FH_TX_STATUS_IDLE(6)) {
4930 			DPRINTF(sc, WPI_DEBUG_HW,
4931 			    "Status Match! - ntries = %d\n", ntries);
4932 			break;
4933 		}
4934 		DELAY(10);
4935 	}
4936 	if (ntries == 1000) {
4937 		device_printf(sc->sc_dev, "%s: could not load boot firmware\n",
4938 		    __func__);
4939 		wpi_nic_unlock(sc);
4940 		return ETIMEDOUT;
4941 	}
4942 
4943 	/* Enable boot after power up. */
4944 	wpi_prph_write(sc, WPI_BSM_WR_CTRL, WPI_BSM_WR_CTRL_START_EN);
4945 
4946 	wpi_nic_unlock(sc);
4947 	return 0;
4948 }
4949 
4950 static int
4951 wpi_load_firmware(struct wpi_softc *sc)
4952 {
4953 	struct wpi_fw_info *fw = &sc->fw;
4954 	struct wpi_dma_info *dma = &sc->fw_dma;
4955 	int error;
4956 
4957 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
4958 
4959 	/* Copy initialization sections into pre-allocated DMA-safe memory. */
4960 	memcpy(dma->vaddr, fw->init.data, fw->init.datasz);
4961 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
4962 	memcpy(dma->vaddr + WPI_FW_DATA_MAXSZ, fw->init.text, fw->init.textsz);
4963 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
4964 
4965 	/* Tell adapter where to find initialization sections. */
4966 	if ((error = wpi_nic_lock(sc)) != 0)
4967 		return error;
4968 	wpi_prph_write(sc, WPI_BSM_DRAM_DATA_ADDR, dma->paddr);
4969 	wpi_prph_write(sc, WPI_BSM_DRAM_DATA_SIZE, fw->init.datasz);
4970 	wpi_prph_write(sc, WPI_BSM_DRAM_TEXT_ADDR,
4971 	    dma->paddr + WPI_FW_DATA_MAXSZ);
4972 	wpi_prph_write(sc, WPI_BSM_DRAM_TEXT_SIZE, fw->init.textsz);
4973 	wpi_nic_unlock(sc);
4974 
4975 	/* Load firmware boot code. */
4976 	error = wpi_load_bootcode(sc, fw->boot.text, fw->boot.textsz);
4977 	if (error != 0) {
4978 		device_printf(sc->sc_dev, "%s: could not load boot firmware\n",
4979 		    __func__);
4980 		return error;
4981 	}
4982 
4983 	/* Now press "execute". */
4984 	WPI_WRITE(sc, WPI_RESET, 0);
4985 
4986 	/* Wait at most one second for first alive notification. */
4987 	if ((error = mtx_sleep(sc, &sc->sc_mtx, PCATCH, "wpiinit", hz)) != 0) {
4988 		device_printf(sc->sc_dev,
4989 		    "%s: timeout waiting for adapter to initialize, error %d\n",
4990 		    __func__, error);
4991 		return error;
4992 	}
4993 
4994 	/* Copy runtime sections into pre-allocated DMA-safe memory. */
4995 	memcpy(dma->vaddr, fw->main.data, fw->main.datasz);
4996 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
4997 	memcpy(dma->vaddr + WPI_FW_DATA_MAXSZ, fw->main.text, fw->main.textsz);
4998 	bus_dmamap_sync(dma->tag, dma->map, BUS_DMASYNC_PREWRITE);
4999 
5000 	/* Tell adapter where to find runtime sections. */
5001 	if ((error = wpi_nic_lock(sc)) != 0)
5002 		return error;
5003 	wpi_prph_write(sc, WPI_BSM_DRAM_DATA_ADDR, dma->paddr);
5004 	wpi_prph_write(sc, WPI_BSM_DRAM_DATA_SIZE, fw->main.datasz);
5005 	wpi_prph_write(sc, WPI_BSM_DRAM_TEXT_ADDR,
5006 	    dma->paddr + WPI_FW_DATA_MAXSZ);
5007 	wpi_prph_write(sc, WPI_BSM_DRAM_TEXT_SIZE,
5008 	    WPI_FW_UPDATED | fw->main.textsz);
5009 	wpi_nic_unlock(sc);
5010 
5011 	return 0;
5012 }
5013 
5014 static int
5015 wpi_read_firmware(struct wpi_softc *sc)
5016 {
5017 	const struct firmware *fp;
5018 	struct wpi_fw_info *fw = &sc->fw;
5019 	const struct wpi_firmware_hdr *hdr;
5020 	int error;
5021 
5022 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
5023 
5024 	DPRINTF(sc, WPI_DEBUG_FIRMWARE,
5025 	    "Attempting Loading Firmware from %s module\n", WPI_FW_NAME);
5026 
5027 	WPI_UNLOCK(sc);
5028 	fp = firmware_get(WPI_FW_NAME);
5029 	WPI_LOCK(sc);
5030 
5031 	if (fp == NULL) {
5032 		device_printf(sc->sc_dev,
5033 		    "could not load firmware image '%s'\n", WPI_FW_NAME);
5034 		return EINVAL;
5035 	}
5036 
5037 	sc->fw_fp = fp;
5038 
5039 	if (fp->datasize < sizeof (struct wpi_firmware_hdr)) {
5040 		device_printf(sc->sc_dev,
5041 		    "firmware file too short: %zu bytes\n", fp->datasize);
5042 		error = EINVAL;
5043 		goto fail;
5044 	}
5045 
5046 	fw->size = fp->datasize;
5047 	fw->data = (const uint8_t *)fp->data;
5048 
5049 	/* Extract firmware header information. */
5050 	hdr = (const struct wpi_firmware_hdr *)fw->data;
5051 
5052 	/*     |  RUNTIME FIRMWARE   |    INIT FIRMWARE    | BOOT FW  |
5053 	   |HDR|<--TEXT-->|<--DATA-->|<--TEXT-->|<--DATA-->|<--TEXT-->| */
5054 
5055 	fw->main.textsz = le32toh(hdr->rtextsz);
5056 	fw->main.datasz = le32toh(hdr->rdatasz);
5057 	fw->init.textsz = le32toh(hdr->itextsz);
5058 	fw->init.datasz = le32toh(hdr->idatasz);
5059 	fw->boot.textsz = le32toh(hdr->btextsz);
5060 	fw->boot.datasz = 0;
5061 
5062 	/* Sanity-check firmware header. */
5063 	if (fw->main.textsz > WPI_FW_TEXT_MAXSZ ||
5064 	    fw->main.datasz > WPI_FW_DATA_MAXSZ ||
5065 	    fw->init.textsz > WPI_FW_TEXT_MAXSZ ||
5066 	    fw->init.datasz > WPI_FW_DATA_MAXSZ ||
5067 	    fw->boot.textsz > WPI_FW_BOOT_TEXT_MAXSZ ||
5068 	    (fw->boot.textsz & 3) != 0) {
5069 		device_printf(sc->sc_dev, "invalid firmware header\n");
5070 		error = EINVAL;
5071 		goto fail;
5072 	}
5073 
5074 	/* Check that all firmware sections fit. */
5075 	if (fw->size < sizeof (*hdr) + fw->main.textsz + fw->main.datasz +
5076 	    fw->init.textsz + fw->init.datasz + fw->boot.textsz) {
5077 		device_printf(sc->sc_dev,
5078 		    "firmware file too short: %zu bytes\n", fw->size);
5079 		error = EINVAL;
5080 		goto fail;
5081 	}
5082 
5083 	/* Get pointers to firmware sections. */
5084 	fw->main.text = (const uint8_t *)(hdr + 1);
5085 	fw->main.data = fw->main.text + fw->main.textsz;
5086 	fw->init.text = fw->main.data + fw->main.datasz;
5087 	fw->init.data = fw->init.text + fw->init.textsz;
5088 	fw->boot.text = fw->init.data + fw->init.datasz;
5089 
5090 	DPRINTF(sc, WPI_DEBUG_FIRMWARE,
5091 	    "Firmware Version: Major %d, Minor %d, Driver %d, \n"
5092 	    "runtime (text: %u, data: %u) init (text: %u, data %u) "
5093 	    "boot (text %u)\n", hdr->major, hdr->minor, le32toh(hdr->driver),
5094 	    fw->main.textsz, fw->main.datasz,
5095 	    fw->init.textsz, fw->init.datasz, fw->boot.textsz);
5096 
5097 	DPRINTF(sc, WPI_DEBUG_FIRMWARE, "fw->main.text %p\n", fw->main.text);
5098 	DPRINTF(sc, WPI_DEBUG_FIRMWARE, "fw->main.data %p\n", fw->main.data);
5099 	DPRINTF(sc, WPI_DEBUG_FIRMWARE, "fw->init.text %p\n", fw->init.text);
5100 	DPRINTF(sc, WPI_DEBUG_FIRMWARE, "fw->init.data %p\n", fw->init.data);
5101 	DPRINTF(sc, WPI_DEBUG_FIRMWARE, "fw->boot.text %p\n", fw->boot.text);
5102 
5103 	return 0;
5104 
5105 fail:	wpi_unload_firmware(sc);
5106 	return error;
5107 }
5108 
5109 /**
5110  * Free the referenced firmware image
5111  */
5112 static void
5113 wpi_unload_firmware(struct wpi_softc *sc)
5114 {
5115 	if (sc->fw_fp != NULL) {
5116 		firmware_put(sc->fw_fp, FIRMWARE_UNLOAD);
5117 		sc->fw_fp = NULL;
5118 	}
5119 }
5120 
5121 static int
5122 wpi_clock_wait(struct wpi_softc *sc)
5123 {
5124 	int ntries;
5125 
5126 	/* Set "initialization complete" bit. */
5127 	WPI_SETBITS(sc, WPI_GP_CNTRL, WPI_GP_CNTRL_INIT_DONE);
5128 
5129 	/* Wait for clock stabilization. */
5130 	for (ntries = 0; ntries < 2500; ntries++) {
5131 		if (WPI_READ(sc, WPI_GP_CNTRL) & WPI_GP_CNTRL_MAC_CLOCK_READY)
5132 			return 0;
5133 		DELAY(100);
5134 	}
5135 	device_printf(sc->sc_dev,
5136 	    "%s: timeout waiting for clock stabilization\n", __func__);
5137 
5138 	return ETIMEDOUT;
5139 }
5140 
5141 static int
5142 wpi_apm_init(struct wpi_softc *sc)
5143 {
5144 	uint32_t reg;
5145 	int error;
5146 
5147 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
5148 
5149 	/* Disable L0s exit timer (NMI bug workaround). */
5150 	WPI_SETBITS(sc, WPI_GIO_CHICKEN, WPI_GIO_CHICKEN_DIS_L0S_TIMER);
5151 	/* Don't wait for ICH L0s (ICH bug workaround). */
5152 	WPI_SETBITS(sc, WPI_GIO_CHICKEN, WPI_GIO_CHICKEN_L1A_NO_L0S_RX);
5153 
5154 	/* Set FH wait threshold to max (HW bug under stress workaround). */
5155 	WPI_SETBITS(sc, WPI_DBG_HPET_MEM, 0xffff0000);
5156 
5157 	/* Retrieve PCIe Active State Power Management (ASPM). */
5158 	reg = pci_read_config(sc->sc_dev, sc->sc_cap_off + PCIER_LINK_CTL, 1);
5159 	/* Workaround for HW instability in PCIe L0->L0s->L1 transition. */
5160 	if (reg & PCIEM_LINK_CTL_ASPMC_L1)	/* L1 Entry enabled. */
5161 		WPI_SETBITS(sc, WPI_GIO, WPI_GIO_L0S_ENA);
5162 	else
5163 		WPI_CLRBITS(sc, WPI_GIO, WPI_GIO_L0S_ENA);
5164 
5165 	WPI_SETBITS(sc, WPI_ANA_PLL, WPI_ANA_PLL_INIT);
5166 
5167 	/* Wait for clock stabilization before accessing prph. */
5168 	if ((error = wpi_clock_wait(sc)) != 0)
5169 		return error;
5170 
5171 	if ((error = wpi_nic_lock(sc)) != 0)
5172 		return error;
5173 	/* Cleanup. */
5174 	wpi_prph_write(sc, WPI_APMG_CLK_DIS, 0x00000400);
5175 	wpi_prph_clrbits(sc, WPI_APMG_PS, 0x00000200);
5176 
5177 	/* Enable DMA and BSM (Bootstrap State Machine). */
5178 	wpi_prph_write(sc, WPI_APMG_CLK_EN,
5179 	    WPI_APMG_CLK_CTRL_DMA_CLK_RQT | WPI_APMG_CLK_CTRL_BSM_CLK_RQT);
5180 	DELAY(20);
5181 	/* Disable L1-Active. */
5182 	wpi_prph_setbits(sc, WPI_APMG_PCI_STT, WPI_APMG_PCI_STT_L1A_DIS);
5183 	wpi_nic_unlock(sc);
5184 
5185 	return 0;
5186 }
5187 
5188 static void
5189 wpi_apm_stop_master(struct wpi_softc *sc)
5190 {
5191 	int ntries;
5192 
5193 	/* Stop busmaster DMA activity. */
5194 	WPI_SETBITS(sc, WPI_RESET, WPI_RESET_STOP_MASTER);
5195 
5196 	if ((WPI_READ(sc, WPI_GP_CNTRL) & WPI_GP_CNTRL_PS_MASK) ==
5197 	    WPI_GP_CNTRL_MAC_PS)
5198 		return; /* Already asleep. */
5199 
5200 	for (ntries = 0; ntries < 100; ntries++) {
5201 		if (WPI_READ(sc, WPI_RESET) & WPI_RESET_MASTER_DISABLED)
5202 			return;
5203 		DELAY(10);
5204 	}
5205 	device_printf(sc->sc_dev, "%s: timeout waiting for master\n",
5206 	    __func__);
5207 }
5208 
5209 static void
5210 wpi_apm_stop(struct wpi_softc *sc)
5211 {
5212 	wpi_apm_stop_master(sc);
5213 
5214 	/* Reset the entire device. */
5215 	WPI_SETBITS(sc, WPI_RESET, WPI_RESET_SW);
5216 	DELAY(10);
5217 	/* Clear "initialization complete" bit. */
5218 	WPI_CLRBITS(sc, WPI_GP_CNTRL, WPI_GP_CNTRL_INIT_DONE);
5219 }
5220 
5221 static void
5222 wpi_nic_config(struct wpi_softc *sc)
5223 {
5224 	uint32_t rev;
5225 
5226 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
5227 
5228 	/* voodoo from the Linux "driver".. */
5229 	rev = pci_read_config(sc->sc_dev, PCIR_REVID, 1);
5230 	if ((rev & 0xc0) == 0x40)
5231 		WPI_SETBITS(sc, WPI_HW_IF_CONFIG, WPI_HW_IF_CONFIG_ALM_MB);
5232 	else if (!(rev & 0x80))
5233 		WPI_SETBITS(sc, WPI_HW_IF_CONFIG, WPI_HW_IF_CONFIG_ALM_MM);
5234 
5235 	if (sc->cap == 0x80)
5236 		WPI_SETBITS(sc, WPI_HW_IF_CONFIG, WPI_HW_IF_CONFIG_SKU_MRC);
5237 
5238 	if ((sc->rev & 0xf0) == 0xd0)
5239 		WPI_SETBITS(sc, WPI_HW_IF_CONFIG, WPI_HW_IF_CONFIG_REV_D);
5240 	else
5241 		WPI_CLRBITS(sc, WPI_HW_IF_CONFIG, WPI_HW_IF_CONFIG_REV_D);
5242 
5243 	if (sc->type > 1)
5244 		WPI_SETBITS(sc, WPI_HW_IF_CONFIG, WPI_HW_IF_CONFIG_TYPE_B);
5245 }
5246 
5247 static int
5248 wpi_hw_init(struct wpi_softc *sc)
5249 {
5250 	uint8_t chnl;
5251 	int ntries, error;
5252 
5253 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
5254 
5255 	/* Clear pending interrupts. */
5256 	WPI_WRITE(sc, WPI_INT, 0xffffffff);
5257 
5258 	if ((error = wpi_apm_init(sc)) != 0) {
5259 		device_printf(sc->sc_dev,
5260 		    "%s: could not power ON adapter, error %d\n", __func__,
5261 		    error);
5262 		return error;
5263 	}
5264 
5265 	/* Select VMAIN power source. */
5266 	if ((error = wpi_nic_lock(sc)) != 0)
5267 		return error;
5268 	wpi_prph_clrbits(sc, WPI_APMG_PS, WPI_APMG_PS_PWR_SRC_MASK);
5269 	wpi_nic_unlock(sc);
5270 	/* Spin until VMAIN gets selected. */
5271 	for (ntries = 0; ntries < 5000; ntries++) {
5272 		if (WPI_READ(sc, WPI_GPIO_IN) & WPI_GPIO_IN_VMAIN)
5273 			break;
5274 		DELAY(10);
5275 	}
5276 	if (ntries == 5000) {
5277 		device_printf(sc->sc_dev, "timeout selecting power source\n");
5278 		return ETIMEDOUT;
5279 	}
5280 
5281 	/* Perform adapter initialization. */
5282 	wpi_nic_config(sc);
5283 
5284 	/* Initialize RX ring. */
5285 	if ((error = wpi_nic_lock(sc)) != 0)
5286 		return error;
5287 	/* Set physical address of RX ring. */
5288 	WPI_WRITE(sc, WPI_FH_RX_BASE, sc->rxq.desc_dma.paddr);
5289 	/* Set physical address of RX read pointer. */
5290 	WPI_WRITE(sc, WPI_FH_RX_RPTR_ADDR, sc->shared_dma.paddr +
5291 	    offsetof(struct wpi_shared, next));
5292 	WPI_WRITE(sc, WPI_FH_RX_WPTR, 0);
5293 	/* Enable RX. */
5294 	WPI_WRITE(sc, WPI_FH_RX_CONFIG,
5295 	    WPI_FH_RX_CONFIG_DMA_ENA |
5296 	    WPI_FH_RX_CONFIG_RDRBD_ENA |
5297 	    WPI_FH_RX_CONFIG_WRSTATUS_ENA |
5298 	    WPI_FH_RX_CONFIG_MAXFRAG |
5299 	    WPI_FH_RX_CONFIG_NRBD(WPI_RX_RING_COUNT_LOG) |
5300 	    WPI_FH_RX_CONFIG_IRQ_DST_HOST |
5301 	    WPI_FH_RX_CONFIG_IRQ_TIMEOUT(1));
5302 	(void)WPI_READ(sc, WPI_FH_RSSR_TBL);	/* barrier */
5303 	wpi_nic_unlock(sc);
5304 	WPI_WRITE(sc, WPI_FH_RX_WPTR, (WPI_RX_RING_COUNT - 1) & ~7);
5305 
5306 	/* Initialize TX rings. */
5307 	if ((error = wpi_nic_lock(sc)) != 0)
5308 		return error;
5309 	wpi_prph_write(sc, WPI_ALM_SCHED_MODE, 2);	/* bypass mode */
5310 	wpi_prph_write(sc, WPI_ALM_SCHED_ARASTAT, 1);	/* enable RA0 */
5311 	/* Enable all 6 TX rings. */
5312 	wpi_prph_write(sc, WPI_ALM_SCHED_TXFACT, 0x3f);
5313 	wpi_prph_write(sc, WPI_ALM_SCHED_SBYPASS_MODE1, 0x10000);
5314 	wpi_prph_write(sc, WPI_ALM_SCHED_SBYPASS_MODE2, 0x30002);
5315 	wpi_prph_write(sc, WPI_ALM_SCHED_TXF4MF, 4);
5316 	wpi_prph_write(sc, WPI_ALM_SCHED_TXF5MF, 5);
5317 	/* Set physical address of TX rings. */
5318 	WPI_WRITE(sc, WPI_FH_TX_BASE, sc->shared_dma.paddr);
5319 	WPI_WRITE(sc, WPI_FH_MSG_CONFIG, 0xffff05a5);
5320 
5321 	/* Enable all DMA channels. */
5322 	for (chnl = 0; chnl < WPI_NDMACHNLS; chnl++) {
5323 		WPI_WRITE(sc, WPI_FH_CBBC_CTRL(chnl), 0);
5324 		WPI_WRITE(sc, WPI_FH_CBBC_BASE(chnl), 0);
5325 		WPI_WRITE(sc, WPI_FH_TX_CONFIG(chnl), 0x80200008);
5326 	}
5327 	wpi_nic_unlock(sc);
5328 	(void)WPI_READ(sc, WPI_FH_TX_BASE);	/* barrier */
5329 
5330 	/* Clear "radio off" and "commands blocked" bits. */
5331 	WPI_WRITE(sc, WPI_UCODE_GP1_CLR, WPI_UCODE_GP1_RFKILL);
5332 	WPI_WRITE(sc, WPI_UCODE_GP1_CLR, WPI_UCODE_GP1_CMD_BLOCKED);
5333 
5334 	/* Clear pending interrupts. */
5335 	WPI_WRITE(sc, WPI_INT, 0xffffffff);
5336 	/* Enable interrupts. */
5337 	WPI_WRITE(sc, WPI_INT_MASK, WPI_INT_MASK_DEF);
5338 
5339 	/* _Really_ make sure "radio off" bit is cleared! */
5340 	WPI_WRITE(sc, WPI_UCODE_GP1_CLR, WPI_UCODE_GP1_RFKILL);
5341 	WPI_WRITE(sc, WPI_UCODE_GP1_CLR, WPI_UCODE_GP1_RFKILL);
5342 
5343 	if ((error = wpi_load_firmware(sc)) != 0) {
5344 		device_printf(sc->sc_dev,
5345 		    "%s: could not load firmware, error %d\n", __func__,
5346 		    error);
5347 		return error;
5348 	}
5349 	/* Wait at most one second for firmware alive notification. */
5350 	if ((error = mtx_sleep(sc, &sc->sc_mtx, PCATCH, "wpiinit", hz)) != 0) {
5351 		device_printf(sc->sc_dev,
5352 		    "%s: timeout waiting for adapter to initialize, error %d\n",
5353 		    __func__, error);
5354 		return error;
5355 	}
5356 
5357 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
5358 
5359 	/* Do post-firmware initialization. */
5360 	return wpi_post_alive(sc);
5361 }
5362 
5363 static void
5364 wpi_hw_stop(struct wpi_softc *sc)
5365 {
5366 	uint8_t chnl, qid;
5367 	int ntries;
5368 
5369 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
5370 
5371 	if (WPI_READ(sc, WPI_UCODE_GP1) & WPI_UCODE_GP1_MAC_SLEEP)
5372 		wpi_nic_lock(sc);
5373 
5374 	WPI_WRITE(sc, WPI_RESET, WPI_RESET_NEVO);
5375 
5376 	/* Disable interrupts. */
5377 	WPI_WRITE(sc, WPI_INT_MASK, 0);
5378 	WPI_WRITE(sc, WPI_INT, 0xffffffff);
5379 	WPI_WRITE(sc, WPI_FH_INT, 0xffffffff);
5380 
5381 	/* Make sure we no longer hold the NIC lock. */
5382 	wpi_nic_unlock(sc);
5383 
5384 	if (wpi_nic_lock(sc) == 0) {
5385 		/* Stop TX scheduler. */
5386 		wpi_prph_write(sc, WPI_ALM_SCHED_MODE, 0);
5387 		wpi_prph_write(sc, WPI_ALM_SCHED_TXFACT, 0);
5388 
5389 		/* Stop all DMA channels. */
5390 		for (chnl = 0; chnl < WPI_NDMACHNLS; chnl++) {
5391 			WPI_WRITE(sc, WPI_FH_TX_CONFIG(chnl), 0);
5392 			for (ntries = 0; ntries < 200; ntries++) {
5393 				if (WPI_READ(sc, WPI_FH_TX_STATUS) &
5394 				    WPI_FH_TX_STATUS_IDLE(chnl))
5395 					break;
5396 				DELAY(10);
5397 			}
5398 		}
5399 		wpi_nic_unlock(sc);
5400 	}
5401 
5402 	/* Stop RX ring. */
5403 	wpi_reset_rx_ring(sc);
5404 
5405 	/* Reset all TX rings. */
5406 	for (qid = 0; qid < WPI_DRV_NTXQUEUES; qid++)
5407 		wpi_reset_tx_ring(sc, &sc->txq[qid]);
5408 
5409 	if (wpi_nic_lock(sc) == 0) {
5410 		wpi_prph_write(sc, WPI_APMG_CLK_DIS,
5411 		    WPI_APMG_CLK_CTRL_DMA_CLK_RQT);
5412 		wpi_nic_unlock(sc);
5413 	}
5414 	DELAY(5);
5415 	/* Power OFF adapter. */
5416 	wpi_apm_stop(sc);
5417 }
5418 
5419 static void
5420 wpi_radio_on(void *arg0, int pending)
5421 {
5422 	struct wpi_softc *sc = arg0;
5423 	struct ieee80211com *ic = &sc->sc_ic;
5424 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
5425 
5426 	device_printf(sc->sc_dev, "RF switch: radio enabled\n");
5427 
5428 	WPI_LOCK(sc);
5429 	callout_stop(&sc->watchdog_rfkill);
5430 	WPI_UNLOCK(sc);
5431 
5432 	if (vap != NULL)
5433 		ieee80211_init(vap);
5434 }
5435 
5436 static void
5437 wpi_radio_off(void *arg0, int pending)
5438 {
5439 	struct wpi_softc *sc = arg0;
5440 	struct ieee80211com *ic = &sc->sc_ic;
5441 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
5442 
5443 	device_printf(sc->sc_dev, "RF switch: radio disabled\n");
5444 
5445 	ieee80211_notify_radio(ic, 0);
5446 	wpi_stop(sc);
5447 	if (vap != NULL)
5448 		ieee80211_stop(vap);
5449 
5450 	WPI_LOCK(sc);
5451 	callout_reset(&sc->watchdog_rfkill, hz, wpi_watchdog_rfkill, sc);
5452 	WPI_UNLOCK(sc);
5453 }
5454 
5455 static int
5456 wpi_init(struct wpi_softc *sc)
5457 {
5458 	int error = 0;
5459 
5460 	WPI_LOCK(sc);
5461 
5462 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_BEGIN, __func__);
5463 
5464 	if (sc->sc_running != 0)
5465 		goto end;
5466 
5467 	/* Check that the radio is not disabled by hardware switch. */
5468 	if (!(WPI_READ(sc, WPI_GP_CNTRL) & WPI_GP_CNTRL_RFKILL)) {
5469 		device_printf(sc->sc_dev,
5470 		    "RF switch: radio disabled (%s)\n", __func__);
5471 		callout_reset(&sc->watchdog_rfkill, hz, wpi_watchdog_rfkill,
5472 		    sc);
5473 		error = EINPROGRESS;
5474 		goto end;
5475 	}
5476 
5477 	/* Read firmware images from the filesystem. */
5478 	if ((error = wpi_read_firmware(sc)) != 0) {
5479 		device_printf(sc->sc_dev,
5480 		    "%s: could not read firmware, error %d\n", __func__,
5481 		    error);
5482 		goto end;
5483 	}
5484 
5485 	sc->sc_running = 1;
5486 
5487 	/* Initialize hardware and upload firmware. */
5488 	error = wpi_hw_init(sc);
5489 	wpi_unload_firmware(sc);
5490 	if (error != 0) {
5491 		device_printf(sc->sc_dev,
5492 		    "%s: could not initialize hardware, error %d\n", __func__,
5493 		    error);
5494 		goto fail;
5495 	}
5496 
5497 	/* Configure adapter now that it is ready. */
5498 	if ((error = wpi_config(sc)) != 0) {
5499 		device_printf(sc->sc_dev,
5500 		    "%s: could not configure device, error %d\n", __func__,
5501 		    error);
5502 		goto fail;
5503 	}
5504 
5505 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END, __func__);
5506 
5507 	WPI_UNLOCK(sc);
5508 
5509 	return 0;
5510 
5511 fail:	wpi_stop_locked(sc);
5512 
5513 end:	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_END_ERR, __func__);
5514 	WPI_UNLOCK(sc);
5515 
5516 	return error;
5517 }
5518 
5519 static void
5520 wpi_stop_locked(struct wpi_softc *sc)
5521 {
5522 
5523 	WPI_LOCK_ASSERT(sc);
5524 
5525 	if (sc->sc_running == 0)
5526 		return;
5527 
5528 	WPI_TX_LOCK(sc);
5529 	WPI_TXQ_LOCK(sc);
5530 	sc->sc_running = 0;
5531 	WPI_TXQ_UNLOCK(sc);
5532 	WPI_TX_UNLOCK(sc);
5533 
5534 	WPI_TXQ_STATE_LOCK(sc);
5535 	callout_stop(&sc->tx_timeout);
5536 	WPI_TXQ_STATE_UNLOCK(sc);
5537 
5538 	WPI_RXON_LOCK(sc);
5539 	callout_stop(&sc->scan_timeout);
5540 	callout_stop(&sc->calib_to);
5541 	WPI_RXON_UNLOCK(sc);
5542 
5543 	/* Power OFF hardware. */
5544 	wpi_hw_stop(sc);
5545 }
5546 
5547 static void
5548 wpi_stop(struct wpi_softc *sc)
5549 {
5550 	WPI_LOCK(sc);
5551 	wpi_stop_locked(sc);
5552 	WPI_UNLOCK(sc);
5553 }
5554 
5555 /*
5556  * Callback from net80211 to start a scan.
5557  */
5558 static void
5559 wpi_scan_start(struct ieee80211com *ic)
5560 {
5561 	struct wpi_softc *sc = ic->ic_softc;
5562 
5563 	wpi_set_led(sc, WPI_LED_LINK, 20, 2);
5564 }
5565 
5566 /*
5567  * Callback from net80211 to terminate a scan.
5568  */
5569 static void
5570 wpi_scan_end(struct ieee80211com *ic)
5571 {
5572 	struct wpi_softc *sc = ic->ic_softc;
5573 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
5574 
5575 	if (vap->iv_state == IEEE80211_S_RUN)
5576 		wpi_set_led(sc, WPI_LED_LINK, 0, 1);
5577 }
5578 
5579 /**
5580  * Called by the net80211 framework to indicate to the driver
5581  * that the channel should be changed
5582  */
5583 static void
5584 wpi_set_channel(struct ieee80211com *ic)
5585 {
5586 	const struct ieee80211_channel *c = ic->ic_curchan;
5587 	struct wpi_softc *sc = ic->ic_softc;
5588 	int error;
5589 
5590 	DPRINTF(sc, WPI_DEBUG_TRACE, TRACE_STR_DOING, __func__);
5591 
5592 	WPI_LOCK(sc);
5593 	sc->sc_rxtap.wr_chan_freq = htole16(c->ic_freq);
5594 	sc->sc_rxtap.wr_chan_flags = htole16(c->ic_flags);
5595 	WPI_UNLOCK(sc);
5596 	WPI_TX_LOCK(sc);
5597 	sc->sc_txtap.wt_chan_freq = htole16(c->ic_freq);
5598 	sc->sc_txtap.wt_chan_flags = htole16(c->ic_flags);
5599 	WPI_TX_UNLOCK(sc);
5600 
5601 	/*
5602 	 * Only need to set the channel in Monitor mode. AP scanning and auth
5603 	 * are already taken care of by their respective firmware commands.
5604 	 */
5605 	if (ic->ic_opmode == IEEE80211_M_MONITOR) {
5606 		WPI_RXON_LOCK(sc);
5607 		sc->rxon.chan = ieee80211_chan2ieee(ic, c);
5608 		if (IEEE80211_IS_CHAN_2GHZ(c)) {
5609 			sc->rxon.flags |= htole32(WPI_RXON_AUTO |
5610 			    WPI_RXON_24GHZ);
5611 		} else {
5612 			sc->rxon.flags &= ~htole32(WPI_RXON_AUTO |
5613 			    WPI_RXON_24GHZ);
5614 		}
5615 		if ((error = wpi_send_rxon(sc, 0, 1)) != 0)
5616 			device_printf(sc->sc_dev,
5617 			    "%s: error %d setting channel\n", __func__,
5618 			    error);
5619 		WPI_RXON_UNLOCK(sc);
5620 	}
5621 }
5622 
5623 /**
5624  * Called by net80211 to indicate that we need to scan the current
5625  * channel. The channel is previously be set via the wpi_set_channel
5626  * callback.
5627  */
5628 static void
5629 wpi_scan_curchan(struct ieee80211_scan_state *ss, unsigned long maxdwell)
5630 {
5631 	struct ieee80211vap *vap = ss->ss_vap;
5632 	struct ieee80211com *ic = vap->iv_ic;
5633 	struct wpi_softc *sc = ic->ic_softc;
5634 	int error;
5635 
5636 	WPI_RXON_LOCK(sc);
5637 	error = wpi_scan(sc, ic->ic_curchan);
5638 	WPI_RXON_UNLOCK(sc);
5639 	if (error != 0)
5640 		ieee80211_cancel_scan(vap);
5641 }
5642 
5643 /**
5644  * Called by the net80211 framework to indicate
5645  * the minimum dwell time has been met, terminate the scan.
5646  * We don't actually terminate the scan as the firmware will notify
5647  * us when it's finished and we have no way to interrupt it.
5648  */
5649 static void
5650 wpi_scan_mindwell(struct ieee80211_scan_state *ss)
5651 {
5652 	/* NB: don't try to abort scan; wait for firmware to finish */
5653 }
5654