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