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